Stripe Checkout on the Server
checkout.ts
import { stripe } from './';
import Stripe from 'stripe';
/**
* Creates a Stripe Checkout session with line items
*/
export async function createStripeCheckoutSession(
line_items: Stripe.Checkout.SessionCreateParams.LineItem[]
) {
const url = 'http://localhost:3000'; //process.env.WEBAPP_URL;
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items,
success_url: `${url}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${url}/failed`,
});
return session;
}
API Endpoint
api.ts
/**
* Catch async errors when awaiting promises
*/
function runAsync(callback: Function) {
return (req: Request, res: Response, next: NextFunction) => {
callback(req, res, next).catch(next);
};
}
/**
* Checkouts
*/
app.post(
'/checkouts/',
runAsync(async ({ body }: Request, res: Response) => {
res.send(await createStripeCheckoutSession(body.line_items));
})
);