Skip to content

Instantly share code, notes, and snippets.

@thomasstep
Created July 2, 2021 15:38
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomasstep/31f2a5bb394ee05efc9b987606bdadc9 to your computer and use it in GitHub Desktop.
Save thomasstep/31f2a5bb394ee05efc9b987606bdadc9 to your computer and use it in GitHub Desktop.
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;
}
}
@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