I have made a Stripe webhook and I want to write data to Firebase when a Stripe purchase happens, and it isn't working although the payment always succeeds but the data is not sent to Firebase database.
In Stripe console I'm getting error as:
Webhook error: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing
Following is the code for my webhook:
import { buffer } from "micro";
import * as admin from "firebase-admin";
// Secure a connection to firebase
const serviceAccount = require("../../../permession.json");
const app = !admin.apps.length
? admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
})
: admin.app();
// Stripe
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const endpointSecurit = process.env.STRIPE_SIGNING_SECRET;
const fullfillOrder = async (session) => {
console.log("Fullfilling Order!!!");
return app
.firestore()
.collection("users")
.doc(session.metadata.email)
.collection("orders")
.doc(session.id)
.set({
amount: session.amount_total / 100,
amount_shipping: session.total_details_amount_shipping / 100,
images: JSON.parse(session.metadata.images),
title: JSON.parse(session.metadata.titles),
timestamp: admin.firestore.FieldValue.serverTimestamp(),
})
.then(() => {
console.log(`SUCCESS: Order ${session.id} has been added to DB!`);
});
};
export default async (req, res) => {
if (req.method === "POST") {
const requestBuffer = await buffer(req);
const payload = requestBuffer.toString();
const sig = req.headers["stripe-signature"];
let event;
// Verify (came from stripe)
try {
event = await stripe.webhooks.constructEvent(
payload,
sig,
endpointSecurit
);
} catch (e) {
console.log("ERROR", e.message);
return res.status(400).send({ message: "Webhook error: " + e.message });
}
if (event.type === "checkout.session.completed") {
const session = event.data.object;
// Fullfill the order
return fullfillOrder(session)
.then(() => res.status(200))
.catch((e) =>
res.status(400).send({ message: "WEBHOOK_ERROR: " + e.message })
);
}
}
};
export const config = {
api: {
bodyParser: false,
externalResolver: true,
},
};
Appreciate the help.
const payload = req.rawBody? - Dharmarajconst event = stripe.webhooks.constructEvent(req.rawBody, sig, endpointSecret);This should work. - skull