Skip to content

Instantly share code, notes, and snippets.

@SimonHoiberg
Created June 19, 2020 14:14
Show Gist options
  • Save SimonHoiberg/e041b6797612db8993314bb5bcfd3976 to your computer and use it in GitHub Desktop.
Save SimonHoiberg/e041b6797612db8993314bb5bcfd3976 to your computer and use it in GitHub Desktop.
export const handler = async (
event: APIGatewayProxyEvent,
context: any,
callback: (err: Error | null, data: any) => void,
) => {
if (!event.body) {
callback(Error('Invalid body'));
return;
}
const body = JSON.parse(event.body) as IBody;
const { paymentMethodID, customerID } = body;
if (!paymentMethodID || !customerID) {
callback(null, {
statusCode: 400,
body: 'Missing payment method or customer',
});
return;
}
try {
// Attach the payment method
await stripe.paymentMethods.attach(paymentMethodID, {
customer: customerID,
});
// Set the payment method as the 'default' for this customer
await stripe.customers.update(customerID, {
invoice_settings: {
default_payment_method: paymentMethodID,
},
});
// Create the subscription
const subscription = await stripe.subscriptions.create({
customer: customerID,
items: [{ price: process.env.STRIPE_PRICE_ID }],
expand: ['latest_invoice.payment_intent'],
});
callback(null, {
statusCode: 200,
body: JSON.stringify(subscription),
});
} catch (error) {
callback(error);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment