Stripe hosted page back-end

  1. Stripe hosted checkout: Back-end

    Provides a pre-build hosted payment page that can be used for a one-time payment or subscription. The advantage is that there is no need to create a custom integration, stripe already does all the UI. This is the easiest and fastest way.

    However, in this way, it cannot be customized and the ui cannot be changed.


  2. Process

    1. The customer selects the item they want to buy and clicks the checkout button;

    2. Initiate a request to the backend (including information about the item to be purchased) to create a checkout session;

    3. On the backend (for the item to be purchased), create a checkout session through the request Stripe Api;

    4. The Stripe API returns a session object;

    5. The session ID (a single property needed to complete the checkout) is sent to the front end. This session id value is used to redirect the user to the hosted stripe page to complete the checkout process.


    In this way, most of the important tasks are already done by Stripe. For our backend, we need to do a few things to set up the checkout session; for the frontend, we need to get a line items array list, which contains an array of objects, each element is an item the user wants to buy. Without these values, we cannot create a checkout session.

    We will also pre-populate an email address on stripe hosted checkout page. This means we also need the consumer’s mailbox.

    So, our request object needs at least line items. email If not passed in, customers need to enter their own email.


  3. Create Checkout session

    First install the backend stripe package: npm i stripe

    Created with the minimum required parameters. First we need to create a stripe api object on the backend in a separate stripe.js file. In the backend file, we instantiate a new stripe object and pass it a secret key. We can import this file later to use the stripe api to connect to the stripe service.

    1
    2
    const stripeAPI = require('stripe')(process.env.SECRET_KEY);
    module.exports = stripeAPI;

  1. Processing logic

    In another file, api/checkout.js, contains the function to create the checkout session. Include the domain url in the function, because the user will be redirected to the stripe hosted page, and after the checkout is complete, the user will be redirected to your page.

    The parameters for stripeAPI are available in strip api documentation.

    The format of success_url, cancel_url is fixed.

    The res.json only needs to return the sessionID, because just the session id will redirect the user to the stripe hosted page.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    const stripeAPI = require('./stripe');

    async function createCheckoutSession(req, res){
    const domainUrl = process.env.WEB_APP_URL; //domain url, usually localhost3000
    const { line_items, customer_email } = req.body; // session cannot be created without these two parameters

    if(!line_items || !customer_email){
    return res.status(400).json({ error: 'missing required session parameters'})
    }

    let session;
    try { //stripe api doc contains
    session = await stripeAPI.checkout.sessions.create({
    payment_method_types: ['card'],
    mode: 'payment',
    line_items,
    customer_email,
    success_url: `${domainUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${domainUrl}/cancel`,
    shipping_address_collection: { allowed_countries: ['GB', 'US'] }
    });
    res.status(200).json({ sessionId: session.id, })
    } catch (error) {
    console.log(error);
    res.status(400).json({ error: 'an error occurred, unable to create session'});
    }
    }

    module.exports = createCheckoutSession

  1. Postman connection test

    After writing the backend code, use postman to test to see if the session id can be generated. Refer to the official documentation for the format.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    {
    "line_items":
    [
    {
    "quantity": 1,
    "price_data": {
    "currency": "aud",
    "unit_amount": 100,
    "product_data": {
    "name": "canva test 1",
    "description": "court canva designed production, stripe demo",
    "images": ["https://jr-bookinglet-2.s3.ap-southeast-2.amazonaws.com/github/canva.jpg"]
    }
    }
    }
    ],
    "customer_email": "blhxp1@gmail.com"
    }

Share