Skip to content

Instantly share code, notes, and snippets.

@SimonHoiberg
Created June 19, 2020 14:20
Show Gist options
  • Save SimonHoiberg/5562c0cafff263c5794e81e0361827bb to your computer and use it in GitHub Desktop.
Save SimonHoiberg/5562c0cafff263c5794e81e0361827bb 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, invoiceID } = body;
if (!paymentMethodID || !customerID || invoiceID) {
callback(null, {
statusCode: 400,
body: 'Invalid payment method or customer ID',
});
return;
}
try {
// Attach the new payment method
await stripe.paymentMethods.attach(paymentMethodID, {
customer: customerID,
});
// Update default payment method on customer
await stripe.customers.update(customerID, {
invoice_settings: {
default_payment_method: paymentMethodID,
},
});
// Retrieve the invoice
const invoice = await stripe.invoices.retrieve(invoiceID, {
expand: ['payment_intent'],
});
callback(null, {
statusCode: 200,
body: JSON.stringify(invoice),
});
} catch (error) {
callback(error);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment