Checkout with Stripe in ExpressJS

Checkout with Stripe in ExpressJS

The Stripe checkout process can be implemented in ExpressJS using Stripe's official NPM module.

The Stripe checkout process can be implemented in ExpressJS using Stripe's official NPM module.

First you need to get a session ID from Stripe. This ID is obtained by providing the type or types of payment, the list of products with related information (name, description, price, currency and quantity) and the two URLs to which users will be redirected in case of completion of the order or cancellation of the same.

'use strict';

const app = require('express')();
const stripe = require('stripe')('stripe-private-key');
const PORT =  process.env.PORT ||  3000;

app.get('/checkout', async (req, res, next) => {
    const { products, total } = req.session.cart;
    const url = req.protocol + '://' + req.get('host');
    const stripeParameters = {
        payment_method_types: ['card'],
        line_items: products.map(p => {
          return {
            name: p.name,
            description: p.description,
            amount: p.price * 100,
            currency: 'eur',
            quantity: p.quantity
          };
        }),
        success_url: url + '/thank-you',
        cancel_url: url + '/cancel'
        
    };
    
    try {
       const stripeSession = await stripe.checkout.sessions.create(stripeParameters);
       
       res.render('checkout', {
               sessionId: stripeSession.id,
               total: total
       });
    } catch(err) {
        res.sendStatus(500);
    }
});

app.get('/thank-you', (req, res) => {
    res.render('thank-you');
});

app.get('/cancel', (req, res) => {
    res.redirect('/checkout');
});

app.listen(PORT);

Once the three routes have been defined, one for checkout, one for redirect after completion of the order and the third for deletion, we can use Stripe's JavaScript SDK in the frontend to redirect the user to the checkout page on Stripe's site.

<button id="order-btn" class="btn btn-primary">Order Now<button>

<script src="https://js.stripe.com/v3/"></script>

<script>
const stripe = Stripe('stripe-public-key');
const orderBtn = document.getElementById('order-btn');

orderBtn.addEventListener('click', () => {
    stripe.redirectToCheckout({
        sessionId: '<%= sessionId %>'
    });
}, false);
</script>

We dynamically inserted the session ID value into the view in order to redirect to the Stripe site checkout page using the redirectToCheckout() method of the Stripe SDK.

As you can see, the procedure requires interaction between server-side and client-side code.