Stripe hosted page front-end

  1. Stripe hosted checkout: Front-end

    The frontend receives the sessionID and uses this id to redirect the user to the stripe checkout page.

    The front-end needs to be packaged as follows:

    1. stripe package: npm i @stripe/stripe-js
    2. react stripe: npm i @stripe/react-stripe-js

    Then set the publish key as an environment variable and set REACT_APP_PUBLISHABLE_KEY in .env.


  2. Introduce package, configure Stripe

    In the front-end code, first introduce Elements & loadStripe in the outermost root component src/index.js, and then create stripePromise. After that, wrap <Elements> around the <App/> component and pass in the stripePromise parameter. This way we can use stripe objects in arbitrary components.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import { Elements } from '@stripe/react-stripe-js';
    import { loadStripe } from '@stripe/stripe-js;'

    const stripePromise = loadStripe(process.env.REACT_APP_PUBLISHABLE_KEY)

    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
    <React.StrictMode>
    <Elements stripe={stripePromise}>
    <App />
    </Elements>
    </React.StrictMode>
    );

    After setting, you need to restart the project.


  3. Create checkout component

    We need to complete a checkout component to help users jump to the Stripe hosted checkout page.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    const dataObj = { line_items: line_items, customer_email: "blhxp1@gmail.com", orderId: orderId };
    axios({
    method: 'POST',
    url: '/payment/create-checkout-session',
    data: dataObj
    }).then(response => {
    const { sessionId } = response.data;
    stripe.redirectToCheckout({
    sessionId
    })
    }).catch(err => {
    console.log(err)
    });

  4. Create payment success and payment cancel pages

    We need to create payment success and payment cancel, which are used to help users jump back to our website after completing the payment.

    If we want to carry order information in these two pages, we need to put the data ID into the url from the Stripe backend:

    1
    2
    success_url: `${process.env.DOMAIN}/payment?status=success&orderId=${order_Id}`,
    cancel_url: `${process.env.DOMAIN}/payment?status=failure&orderId=${order_Id}`,

    How the front-end receives the id

    1. For React, the frontend can use useLocation() to receive the id.

    2. For Next.js, the front end can use the SSR method and pass in the context parameter to receive the id.

      1
      2
      3
      export const getServerSideProps: GetServerSideProps = async (context) => {
      const { orderId, status } = context.query;
      }

Share