Created
July 2, 2021 15:38
-
-
Save thomasstep/31f2a5bb394ee05efc9b987606bdadc9 to your computer and use it in GitHub Desktop.
Stripe webhook handler code for AWS API Gateway and Lambda proxy integration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); | |
const { | |
updateUserSubscription, | |
deleteUserSubscription, | |
} = require('./database'); | |
exports.handler = async function (event, context, callback) { | |
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET; | |
try { | |
const requestId = event?.requestContext?.requestId; | |
const sig = event?.headers['Stripe-Signature']; | |
const stripeEvent = stripe.webhooks.constructEvent(event.body, sig, webhookSecret); | |
const eventType = stripeEvent.type ? stripeEvent.type : ''; | |
// https://stripe.com/docs/api#event_object | |
const jsonData = JSON.parse(event.body); | |
console.log(`Event Type: ${eventType}`); | |
console.log(jsonData); | |
const subscriptionId = stripeEvent.data.object.id; | |
const customerId = stripeEvent.data.object.customer; | |
const priceId = stripeEvent.data.object.plan?.id; | |
let customerEmail; | |
customerEmail = stripeEvent.data.object['customer_details']?.email; | |
if (!customerEmail) { | |
const customer = await stripe.customers.retrieve(customerId); | |
customerEmail = customer.email; | |
} | |
switch (eventType) { | |
case 'customer.subscription.created': | |
case 'customer.subscription.updated': | |
await updateUserSubscription( | |
customerEmail, | |
subscriptionId, | |
priceId, | |
); | |
break; | |
case 'customer.subscription.deleted': | |
await deleteUserSubscription( | |
customerEmail, | |
); | |
default: | |
console.log('Unhandled event type'); | |
console.log(stripeEvent.data.object); | |
break; | |
} | |
const data = { | |
statusCode: 200, | |
body: JSON.stringify({ | |
received: true, | |
}), | |
}; | |
return data; | |
} catch (uncaughtError) { | |
console.error(uncaughtError); | |
throw uncaughtError; | |
} | |
} |
How did you convert the body into rawBody?
I’m having the same issue. I’ve changed the integration request mapping in api gateway to convert to rawbody but am still getting a parsing error when I send requests to the endpoint.
I am also looking for the answer to the same question.
Me as wel!!
same
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How did you convert the body into rawBody?