Skip to content

Instantly share code, notes, and snippets.

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

abhinavshm95 commented Nov 8, 2022

How did you convert the body into rawBody?

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