Skip to content

Instantly share code, notes, and snippets.

@thomasstep
Created July 2, 2021 15:38
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Stripe webhook handler code for AWS API Gateway and Lambda proxy integration
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;
}
}
@abhinavshm95
Copy link

How did you convert the body into rawBody?

@gmurin08
Copy link

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.

@codercor
Copy link

I am also looking for the answer to the same question.

@notturingtested
Copy link

Me as wel!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment