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.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
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:
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:
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.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.