njt
(Nisa Jt)
1
Hello. I created an HTTPS endpoint with the following function:
// This function is the endpoint's request handler.
exports = async function ({ query, headers, body }, response) {
// Verify the event came from Stripe
const stripe = require("stripe")(context.values.get("stripeKeyTEST"));
const endpointSecret = context.values.get("{ENDPOINT-SECRET}");
const payload = body.text();
const signature = headers['Stripe-Signature'][0];
let event;
try {
event = stripe.webhooks.constructEvent(
payload,
signature,
endpointSecret
);
}
catch (err) {
console.error(err.message);
throw err.message;
}
return "Hello, World!";
};
The function is based on the snippet in @clueless_dev’s reply:
Continuing the discussion from Stripe Webhooks and AWS-S3 function call issue
However, I got the error:
Cannot access member 'length' of undefined
The signature was successfully gotten, so, by process of elimination, I concluded the payload is causing the problem. What can I do to fix this?
Note: Currently, I’m using a REST API endpoint on AWS to handle the Stripe events, but I’d prefer to do that here on Realm instead.
Hmm, can you check whether your endpoint secret is undefined? I ran into this too and supplying a nonempty webhook secret was the fix.
This function looks good to me otherwise
1 Like
I had the same issue. It turns out the problem is with getting the raw body which is needed for stripe to verify the request properly.
body.text()
won’t do. Instead, it can be achieved by using:
Buffer.from(request.body.toBase64(), "base64")
Here’s my full stripe request verification code:
/////////////////////////////
// Verify stripe webhook call
/////////////////////////////
console.log("Verifying request");
const stripeApiKey = context.values.get("stripeApiKey");
const stripeWebhookSecret = context.values.get("stripeWebhookSecret");
const stripe = require("stripe")(stripeApiKey, { apiVersion: "2022-11-15" });
const signature = request.headers["Stripe-Signature"][0];
if (signature == undefined) {
console.error("Missing stripe signature");
throw Error("missing-stripe-signature");
}
var event;
try {
event = stripe.webhooks.constructEvent(Buffer.from(request.body.toBase64(), "base64"), signature, stripeWebhookSecret);
} catch (e) {
console.error(`Stripe event could not be verified. Error: ${e.message}`);
throw Error("invalid-signature");
}
console.log("Request is valid.");
Noor_Ali
(Noor Ali)
4
This doesn’t work anymore. Is there any other way to get the rawBody?