/stripe-guides

How to create a checkout session with Stripe?

Learn how to create a Stripe checkout session step-by-step, from account setup and code examples to testing and going live. Perfect for developers integrating payments.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free consultation

How to create a checkout session with Stripe?

How to Create a Checkout Session with Stripe

 

Step 1: Set up your Stripe account

 

Before you can create a checkout session, you need to have a Stripe account. Visit the Stripe website (https://stripe.com) and sign up for an account if you don't already have one. Once you have registered, navigate to the Developers section to find your API keys.

 

Step 2: Install Stripe library

 

Depending on your programming language, you'll need to install the Stripe library. Here are installation commands for popular languages:

For Node.js:

npm install stripe

For PHP:

composer require stripe/stripe-php

For Python:

pip install stripe

For Ruby:

gem install stripe

 

Step 3: Initialize the Stripe library

 

After installing the library, you need to initialize it with your secret key. Here's how to do it in different languages:

Node.js:

const stripe = require('stripe')('sk_test_YOUR_SECRET_KEY');

PHP:

Python:

import stripe
stripe.api_key = 'sk_test_YOUR_SECRET\_KEY'

Ruby:

require 'stripe'
Stripe.api_key = 'sk_test_YOUR_SECRET\_KEY'

 

Step 4: Create a checkout session

 

Now, let's create a checkout session. Here's how to do it in different languages:

Node.js:

const session = await stripe.checkout.sessions.create({
  payment_method_types: ['card'],
  line\_items: [{
    price\_data: {
      currency: 'usd',
      product\_data: {
        name: 'T-shirt',
        description: 'Comfortable cotton t-shirt',
        images: ['https://example.com/t-shirt.png'],
      },
      unit\_amount: 2000, // $20.00 in cents
    },
    quantity: 1,
  }],
  mode: 'payment',
  success_url: 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
  cancel\_url: 'https://example.com/cancel',
});

PHP:

 ['card'],
  'line\_items' => [[
    'price\_data' => [
      'currency' => 'usd',
      'product\_data' => [
        'name' => 'T-shirt',
        'description' => 'Comfortable cotton t-shirt',
        'images' => ['https://example.com/t-shirt.png'],
      ],
      'unit\_amount' => 2000, // $20.00 in cents
    ],
    'quantity' => 1,
  ]],
  'mode' => 'payment',
  'success_url' => 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
  'cancel\_url' => 'https://example.com/cancel',
]);
?>

Python:

session = stripe.checkout.Session.create(
  payment_method_types=['card'],
  line\_items=[{
    'price\_data': {
      'currency': 'usd',
      'product\_data': {
        'name': 'T-shirt',
        'description': 'Comfortable cotton t-shirt',
        'images': ['https://example.com/t-shirt.png'],
      },
      'unit\_amount': 2000, # $20.00 in cents
    },
    'quantity': 1,
  }],
  mode='payment',
  success_url='https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
  cancel\_url='https://example.com/cancel',
)

Ruby:

session = Stripe::Checkout::Session.create({
  payment_method_types: ['card'],
  line\_items: [{
    price\_data: {
      currency: 'usd',
      product\_data: {
        name: 'T-shirt',
        description: 'Comfortable cotton t-shirt',
        images: ['https://example.com/t-shirt.png'],
      },
      unit\_amount: 2000, # $20.00 in cents
    },
    quantity: 1,
  }],
  mode: 'payment',
  success_url: 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
  cancel\_url: 'https://example.com/cancel',
})

 

Step 5: Redirect the customer to the checkout page

 

After creating the session, you need to redirect the customer to the Stripe-hosted checkout page. Here's how to do it:

Client-side with JavaScript:

// First, include the Stripe.js script in your HTML
// 

// Then in your JavaScript code
const stripe = Stripe('pk_test_YOUR_PUBLISHABLE_KEY');

// When the customer clicks on the "Checkout" button
document.getElementById('checkout-button').addEventListener('click', function() {
  // Redirect to the checkout page
  stripe.redirectToCheckout({
    sessionId: '{{session\_id}}' // Pass the session ID from your server
  }).then(function (result) {
    if (result.error) {
      // Display error to your customer
      console.error(result.error.message);
    }
  });
});

Server-side redirect (PHP example):

url);
exit();
?>

 

Step 6: Handle the checkout success

 

When a customer completes payment, they will be redirected to your success_url. You can then retrieve the session to confirm payment and fulfill the order:

Node.js:

app.get('/success', async (req, res) => {
  const { session\_id } = req.query;
  
  try {
    // Retrieve the session to verify payment status
    const session = await stripe.checkout.sessions.retrieve(session\_id);
    
    if (session.payment\_status === 'paid') {
      // Fulfill the order here
      // e.g., update database, send confirmation email, etc.
      res.send('Thanks for your order!');
    } else {
      res.send('Payment not completed yet.');
    }
  } catch (error) {
    console.error('Error retrieving session:', error);
    res.status(500).send('Error processing payment');
  }
});

 

Step 7: Set up webhooks to handle payment events (recommended)

 

While the success URL works for simple implementations, using webhooks is more reliable for payment confirmation. Here's how to set up a webhook endpoint:

Node.js:

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

// Use express.raw() for Stripe webhook signatures verification
app.post('/webhook', express.raw({type: 'application/json'}), async (req, res) => {
  const sig = req.headers['stripe-signature'];
  const endpointSecret = 'whsec_YOUR_WEBHOOK\_SECRET';
  
  let event;
  
  try {
    event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
  } catch (err) {
    console.error(`Webhook signature verification failed: ${err.message}`);
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }
  
  // Handle the event
  switch (event.type) {
    case 'checkout.session.completed':
      const session = event.data.object;
      // Fulfill the order
      console.log(`Payment succeeded for session: ${session.id}`);
      break;
    default:
      console.log(`Unhandled event type: ${event.type}`);
  }
  
  // Return a 200 response to acknowledge receipt of the event
  res.status(200).send();
});

 

Step 8: Test your integration

 

You can test your Stripe Checkout integration using test cards provided by Stripe:

  • Card number: 4242 4242 4242 4242
  • Expiration date: Any future date
  • CVC: Any 3 digits
  • ZIP: Any 5 digits

To test different scenarios (like declined payments), Stripe provides various test card numbers in their documentation.

 

Step 9: Go live

 

Once you've thoroughly tested your integration, you need to switch from test mode to live mode:

  1. Go to your Stripe Dashboard
  2. Ensure you have completed the account activation process
  3. Switch your API keys from test keys to live keys
  4. Update your webhook endpoints to use live endpoints

 

Additional Checkout Session Options

 

Stripe Checkout offers many configuration options for more advanced use cases:

const session = await stripe.checkout.sessions.create({
  payment_method_types: ['card'],
  line\_items: [{
    price\_data: {
      currency: 'usd',
      product\_data: {
        name: 'Product',
      },
      unit\_amount: 2000,
    },
    quantity: 1,
  }],
  mode: 'payment', // Can be 'subscription' or 'setup' for other use cases
  
  // Advanced options:
  customer\_email: '[email protected]', // Pre-fill customer email
  client_reference_id: 'order\_123', // Your internal reference
  payment_intent_data: {
    description: 'Order #123',
    receipt\_email: '[email protected]',
  },
  shipping_address_collection: {
    allowed\_countries: ['US', 'CA'], // Collect shipping address
  },
  shipping\_options: [
    {
      shipping_rate_data: {
        type: 'fixed\_amount',
        fixed\_amount: {
          amount: 500,
          currency: 'usd',
        },
        display\_name: 'Standard shipping',
        delivery\_estimate: {
          minimum: {
            unit: 'business\_day',
            value: 3,
          },
          maximum: {
            unit: 'business\_day',
            value: 5,
          },
        },
      },
    },
  ],
  locale: 'auto', // Customer's browser language or a specific locale
  
  success_url: 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
  cancel\_url: 'https://example.com/cancel',
});

This comprehensive tutorial should help you implement Stripe Checkout for your website or application. Remember to review Stripe's documentation for the latest features and best practices.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022