DEV Community

Hidetaka Okamoto for Stripe

Posted on

How to get the cart item in the Stripe Checkout session

Using Stripe Checkout, we can quickly provide a high-quality checkout page to our customers.
Customers can add additional items at checkout, or modify the number of items that we recommend or modify the number of the items.

Make line item quantities adjustable in Checkout

For the merchant, knowing which items were ordered is vital to fulfilling the order, so we need to get the list of ordered items after completing the checkout session.
We need to get the lists of ordered items after completing the checkout session.

Using the list_line_items API to list the ordered items

In node.js, the following code gets the ordered items:

const items = await stripe.checkout.sessions.listLineItems(sessionId); // cs_xxxx
Enter fullscreen mode Exit fullscreen mode

We mainly use this method in the webhook to listen to the Checkout session event:

const stripe = require('stripe')('YOUR_SECRET_API_KEY');
const express = require('express');
const app = express();

// This is your Stripe CLI webhook secret for testing your endpoint locally.
const endpointSecret = "whsec_xxxxxxx";

app.post('/webhook', express.raw({type: 'application/json'}), async (request, response) => {
  const sig = request.headers['stripe-signature'];

  let event;

  try {
    event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
  } catch (err) {
    response.status(400).send(`Webhook Error: ${(err as Error).message}`);
    return;
  }

  /**
   * Avoiding unrelated events.
   **/
  const data = event.data.object;
  if (
    event.type !== 'checkout.session.completed' &&
    event.type !== 'checkout.session.async_payment_succeeded'
  ) {
    return response.sendStatus(200);
  }

    if (data.payment_status === 'paid') {
    const { items } = await stripe.checkout.sessions.listLineItems(data.id);
    /**
     * TODO: fulfilling the order
     **/
  }

  // Return a 200 response to acknowledge receipt of the event
  response.send();
});

app.listen(4242, () => console.log('Running on port 4242'));

Enter fullscreen mode Exit fullscreen mode

If you want to support an async payment method like a bank transfer or vouchers, please don't forget to handle also the checkout.session.async_payment_succeeded event.

Showing what you ordered on the thanks page

We can get the session ID from the URL query string on the success page.

Creating checkout session

const session = await stripe.checkout.sessions.create({
  success_url: "http://yoursite.com/order/success?session_id={CHECKOUT_SESSION_ID}",
  // other options...,
});
Enter fullscreen mode Exit fullscreen mode

Add a new API to get the items

app.get('/checkout/:session_id/line_items', async (req, res) => {
  const sessionId = req.params['session_id'];
  const items = await stripe.checkout.sessions.listLineItems(sessionId);
  res.status(200).json(items.data);
});
Enter fullscreen mode Exit fullscreen mode

Get the session ID and call the backend API

const url = new URL(window.location);
const sessionId = url.searchParams.get('session_id');
fetch(`https://example.com/checkout/${sessionId}`)
  .then(data => data.json())
  .then(items => {
    console.log(items);
  });
Enter fullscreen mode Exit fullscreen mode

Another use-case

In addition, we also can get the cart item in the session that is not completed.
So if they leave the site before completing the session, we can restore the session if holding the session ID.

Learn more about Stripe Checkout

Japanese version: https://qiita.com/hideokamoto/items/565e3fbba33885be726e

Top comments (0)