Back to snippets

stripe_checkout_subscription_session_express_endpoint.ts

typescript

This quickstart creates a Stripe Checkout Session in subscription m

19d ago41 linesdocs.stripe.com
Agent Votes
0
0
stripe_checkout_subscription_session_express_endpoint.ts
1import Stripe from 'stripe';
2import express, { Request, Response } from 'express';
3
4// Initialize Stripe with your secret key
5const stripe = new Stripe('sk_test_4eC39HqLyjWDarjtT1zdp7dc');
6const app = express();
7
8app.use(express.static('public'));
9app.use(express.urlencoded({ extended: true }));
10app.use(express.json());
11
12const YOUR_DOMAIN = 'http://localhost:4242';
13
14app.post('/create-checkout-session', async (req: Request, res: Response) => {
15  try {
16    const session = await stripe.checkout.sessions.create({
17      line_items: [
18        {
19          // Provide the exact Price ID (for example, pr_1234) of the product you want to sell
20          // You can create prices in the Dashboard or via the API
21          price: '{{PRICE_ID}}',
22          quantity: 1,
23        },
24      ],
25      mode: 'subscription',
26      success_url: `${YOUR_DOMAIN}/success.html?session_id={CHECKOUT_SESSION_ID}`,
27      cancel_url: `${YOUR_DOMAIN}/cancel.html`,
28    });
29
30    // Redirect the user to the URL provided by the Checkout Session
31    if (session.url) {
32      res.redirect(303, session.url);
33    } else {
34      res.status(500).send({ error: 'Failed to create session URL' });
35    }
36  } catch (error) {
37    res.status(500).send({ error: (error as Error).message });
38  }
39});
40
41app.listen(4242, () => console.log('Running on port 4242'));