Checkout
Accept a payment

Accept a payment

Learn how to accept one-time payments with Stripe Checkout.

Accepting payments with Stripe Checkout on your website consists of creating a session for what your customer intends to purchase, and redirecting your customer to a Stripe-hosted payment form to complete their purchase.

What you're building

This sample is running in test mode and won’t create a real charge. Use 4242 4242 4242 4242 as the test card number, any three-digit CVC code, and an expiration date in the future to simulate a successful payment.

Payment flow you’re integrating

1 Set up Stripe Server-side

First, you need a Stripe account. Register now. To use Checkout, ensure that you have set up an account name.

Use our official libraries for access to the Stripe API from your application:

# Available as a gem gem install stripe
# If you use bundler, you can add this line to your Gemfile gem 'stripe'
# Install through pip pip install --upgrade stripe
# Or find the Stripe package on http://pypi.python.org/pypi/stripe/
# Find the version you want to pin: # https://github.com/stripe/stripe-python/blob/master/CHANGELOG.md # Specify that version in your requirements.txt file stripe>=2.48.0,<3.0
# Install the PHP library via Composer composer require stripe/stripe-php
# Or download the source directly: https://github.com/stripe/stripe-php/releases
/* For Gradle, add the following dependency to your build.gradle and replace {VERSION} with the version number you want to use from - https://mvnrepository.com/artifact/com.stripe/stripe-java or - https://github.com/stripe/stripe-java/releases/latest */ implementation "com.stripe:stripe-java:{VERSION}"
<!-- For Maven, add the following dependency to your POM and replace {VERSION} with the version number you want to use from - https://mvnrepository.com/artifact/com.stripe/stripe-java or - https://github.com/stripe/stripe-java/releases/latest --> <dependency> <groupId>com.stripe</groupId> <artifactId>stripe-java</artifactId> <version>{VERSION}</version> </dependency>
# For other environments, manually install the following JARs: # - The Stripe JAR from https://github.com/stripe/stripe-java/releases/latest # - Google Gson from https://github.com/google/gson
# Install via npm npm install --save stripe
# Make sure your project is using Go Modules god mod init # Install stripe-go go get -u github.com/stripe/stripe-go/v71
// Then import the package import ( "github.com/stripe/stripe-go/v71" )
# Install via dotnet dotnet add package Stripe.net dotnet restore
# Or install via NuGet PM> Install-Package Stripe.net

2 Create a Checkout Session Server-side

Create a Session to represent your customer’s checkout flow. Items your customer intends to purchase are represented by line items containing the currency, name, amount to charge, and quantity. You also need to specify:

  • A success_url, a page on your website to redirect your customer after they complete the payment. You can optionally add the ?session_id={CHECKOUT_SESSION_ID} query parameter to the end of the URL. You can then use the Session ID to retrieve details from the Checkout Session (e.g., to display an order confirmation page showing the items purchased).
  • A cancel_url, a page on your website to redirect your customer if they click on your logo in Checkout.
curl https://api.stripe.com/v1/checkout/sessions \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d "line_items[][price_data][currency]"=usd \ -d "line_items[][price_data][product_data][name]"=T-shirt \ -d "line_items[][price_data][unit_amount]"=2000 \ -d "line_items[][quantity]"=1 \ -d mode=payment \ -d success_url="https://example.com/success?session_id={CHECKOUT_SESSION_ID}" \ -d cancel_url="https://example.com/cancel"
# Set your secret key. Remember to switch to your live secret key in production! # See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' session = Stripe::Checkout::Session.create( payment_method_types: ['card'], line_items: [{ price_data: { currency: 'usd', product_data: { name: 'T-shirt', }, unit_amount: 2000, }, quantity: 1, }], mode: 'payment', success_url: 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url: 'https://example.com/cancel', )
# Set your secret key. Remember to switch to your live secret key in production! # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{ 'price_data': { 'currency': 'usd', 'product_data': { 'name': 'T-shirt', }, 'unit_amount': 2000, }, 'quantity': 1, }], mode='payment', success_url='https://example.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url='https://example.com/cancel', )
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys \Stripe\Stripe::setApiKey('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); $session = \Stripe\Checkout\Session::create([ 'payment_method_types' => ['card'], 'line_items' => [[ 'price_data' => [ 'currency' => 'usd', 'product_data' => [ 'name' => 'T-shirt', ], 'unit_amount' => 2000, ], 'quantity' => 1, ]], 'mode' => 'payment', 'success_url' => 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}', 'cancel_url' => 'https://example.com/cancel', ]);
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.apiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; SessionCreateParams params = SessionCreateParams.builder() .addPaymentMethodType(SessionCreateParams.PaymentMethodType.CARD) .setMode(SessionCreateParams.Mode.PAYMENT) .setSuccessUrl("https://example.com/success?session_id={CHECKOUT_SESSION_ID}") .setCancelUrl("https://example.com/cancel") .addLineItem( SessionCreateParams.LineItem.builder() .setQuantity(1L) .setPriceData( SessionCreateParams.LineItem.PriceData.builder() .setCurrency("usd") .setUnitAmount(2000L) .setProductData( SessionCreateParams.LineItem.PriceData.ProductData.builder() .setName("T-shirt") .build()) .build()) .build()) .build(); Session session = Session.create(params);
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys const stripe = require('stripe')('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], line_items: [{ price_data: { currency: 'usd', product_data: { name: 'T-shirt', }, unit_amount: 2000, }, quantity: 1, }], mode: 'payment', success_url: 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url: 'https://example.com/cancel', });
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys stripe.Key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc" params := &stripe.CheckoutSessionParams{ PaymentMethodTypes: stripe.StringSlice([]string{ "card", }), Mode: stripe.String("payment"), LineItems: []*stripe.CheckoutSessionLineItemParams{ &stripe.CheckoutSessionLineItemParams{ PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{ Currency: stripe.String("usd"), ProductData: &stripe.CheckoutSessionLineItemPriceDataProductDataParams{ Name: stripe.String("T-shirt"), }, UnitAmount: stripe.Int64(2000), }, Quantity: stripe.Int64(1), }, }, SuccessURL: stripe.String("https://example.com/success?session_id={CHECKOUT_SESSION_ID}"), CancelURL: stripe.String("https://example.com/cancel"), } session, err := session.New(params)
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys StripeConfiguration.ApiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; var options = new SessionCreateOptions { PaymentMethodTypes = new List<string> { "card", }, LineItems = new List<SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { Currency = "usd", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = "T-shirt", }, UnitAmount = 2000, }, Quantity = 1, }, }, Mode = "payment", SuccessUrl = "https://example.com/success?session_id={CHECKOUT_SESSION_ID}", CancelUrl = "https://example.com/cancel", }; var service = new SessionService(); Session session = service.Create(options);

Specify which payment methods to accept using the payment_method_types attribute. Each line item must have a currency and all line items within a Session must have the same currency (i.e., your customer can’t pay with multiple currencies in Checkout).

The following example demonstrates how to create a Checkout Session that accepts both card and iDEAL payments in EUR for a single item.

curl https://api.stripe.com/v1/checkout/sessions \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d "payment_method_types[]"=ideal \ -d "line_items[][price_data][currency]"=eur \ -d "line_items[][price_data][product_data][name]"=T-shirt \ -d "line_items[][price_data][unit_amount]"=2000 \ -d "line_items[][quantity]"=1 \ -d mode=payment \ -d success_url="https://example.com/success?session_id={CHECKOUT_SESSION_ID}" \ -d cancel_url="https://example.com/cancel"
# Set your secret key. Remember to switch to your live secret key in production! # See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' session = Stripe::Checkout::Session.create( payment_method_types: ['card', 'ideal'], line_items: [{ price_data: { currency: 'eur', product_data: { name: 'T-shirt', }, unit_amount: 2000, }, quantity: 1, }], mode: 'payment', success_url: 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url: 'https://example.com/cancel', )
# Set your secret key. Remember to switch to your live secret key in production! # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' session = stripe.checkout.Session.create( payment_method_types=['card', 'ideal'], line_items=[{ 'price_data': { 'currency': 'eur', 'product_data': { 'name': 'T-shirt', }, 'unit_amount': 2000, }, 'quantity': 1, }], mode='payment', success_url='https://example.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url='https://example.com/cancel', )
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys \Stripe\Stripe::setApiKey('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); $session = \Stripe\Checkout\Session::create([ 'payment_method_types' => ['card', 'ideal'], 'line_items' => [[ 'price_data' => [ 'currency' => 'eur', 'product_data' => [ 'name' => 'T-shirt', ], 'unit_amount' => 2000, ], 'quantity' => 1, ]], 'mode' => 'payment', 'success_url' => 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}', 'cancel_url' => 'https://example.com/cancel', ]);
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.apiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; SessionCreateParams params = SessionCreateParams.builder() .addPaymentMethodType(SessionCreateParams.PaymentMethodType.CARD) .addPaymentMethodType(SessionCreateParams.PaymentMethodType.IDEAL) .setMode(SessionCreateParams.Mode.PAYMENT) .setSuccessUrl("https://example.com/success?session_id={CHECKOUT_SESSION_ID}") .setCancelUrl("https://example.com/cancel") .addLineItem( SessionCreateParams.LineItem.builder() .setQuantity(1L) .setPriceData( SessionCreateParams.LineItem.PriceData.builder() .setCurrency("eur") .setUnitAmount(2000L) .setProductData( SessionCreateParams.LineItem.PriceData.ProductData.builder() .setName("T-shirt") .build()) .build()) .build()) .build(); Session session = Session.create(params);
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys const stripe = require('stripe')('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); const session = await stripe.checkout.sessions.create({ payment_method_types: ['card', 'ideal'], line_items: [{ price_data: { currency: 'eur', product_data: { name: 'T-shirt', }, unit_amount: 2000, }, quantity: 1, }], mode: 'payment', success_url: 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url: 'https://example.com/cancel', });
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys stripe.Key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc" params := &stripe.CheckoutSessionParams{ PaymentMethodTypes: stripe.StringSlice([]string{ "card", "ideal", }), LineItems: []*stripe.CheckoutSessionLineItemParams{ &stripe.CheckoutSessionLineItemParams{ PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{ Currency: stripe.String("stripe.String(stripe.CurrencyEUR)"), ProductData: &stripe.CheckoutSessionLineItemPriceDataProductDataParams{ Name: stripe.String("T-shirt"), }, UnitAmount: stripe.Int64(2000), }, Quantity: stripe.Int64(1), }, }, Mode: stripe.String("payment"), SuccessURL: stripe.String("https://example.com/success?session_id={CHECKOUT_SESSION_ID}"), CancelURL: stripe.String("https://example.com/cancel"), } session, err := session.New(params)
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys StripeConfiguration.ApiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; var options = new SessionCreateOptions { PaymentMethodTypes = new List<string> { "card", "ideal", }, LineItems = new List<SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { Currency = "eur", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = "T-shirt", }, UnitAmount = 2000, }, Quantity = 1, }, }, Mode = "payment", SuccessUrl = "https://example.com/success?session_id={CHECKOUT_SESSION_ID}", CancelUrl = "https://example.com/cancel", }; var service = new SessionService(); Session session = service.Create(options);

Pass the Session ID

Creating a Checkout Session returns a Session object. This object contains a Session ID that you need to pass to your client to redirect your customer to their session. There are different approaches you can use to pass the Session ID to your client.

You can retrieve the Session ID from an endpoint on your server using the browser’s fetch function on the client side. This approach is generally most suitable when your client side is a single-page application, particularly one built with a modern frontend framework such as React. This example shows how to create the server endpoint that serves the client secret:

get '/id' do session = # ... Create or retrieve the Checkout Session {session_id: session.id}.to_json end
from flask import jsonify @app.route('/id') def secret(): session = # ... Create or retrieve the Checkout Session return jsonify(session_id=session.id)
<?php $session = # ... Create or retrieve the Checkout Session echo json_encode(array('session_id' => $session->id)); ?>
import java.util.HashMap; import java.util.Map; import com.stripe.model.checkout.Session; import com.google.gson.Gson; import static spark.Spark.get; public class StripeJavaQuickStart { public static void main(String[] args) { Gson gson = new Gson(); get("/id", (request, response) -> { Session session = // ... Fetch or create the Checkout Session Map<String, String> map = new HashMap(); map.put("session_id", session.getSessionID()); return map; }, gson::toJson); } }
const express = require('express'); const app = express(); app.get('/id', async (req, res) => { const session = // ... Fetch or create the Checkout Session res.json({session_id: session.id}); }); app.listen(3000, () => { console.log('Running on port 3000'); });
package main import ( "encoding/json" "net/http" stripe "github.com/stripe/stripe-go/v71" ) type CheckoutData struct { SessionID string `json:"id"` } func main() { http.HandleFunc("/id", func(w http.ResponseWriter, r *http.Request) { intent := // ... Fetch or create the Checkout Session data := CheckoutData{ SessionID: session.id, } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(data) }) http.ListenAndServe(":3000", nil) }
using System; using Microsoft.AspNetCore.Mvc; using Stripe; namespace StripeExampleApi.Controllers { [Route("id")] [ApiController] public class CheckoutApiController : Controller { [HttpGet] public ActionResult Get() { var session = // ... Fetch or create the Checkout Session return Json(new {session_id = session.id}); } } }

You can then fetch the Session ID with JavaScript on the client side:

var response = fetch('/id').then(function(response) { return response.json(); }).then(function(responseJson) { var sessionID = responseJson.session_id; // Call stripe.redirectToCheckout() with the Session ID. });
(async () => { const response = await fetch('/id'); const {session_id: sessionID} = await response.json(); // Call stripe.redirectToCheckout() with the Session ID. })();

If your application uses server-side rendering, you can use your template framework to embed the Session ID in the HTML output of your checkout page during rendering. You can embed it in a data attribute or in a hidden HTML element and then extract it with JavaScript in order to use it to complete the payment.

<button id="checkout-button" data-secret="<%= @session.id %>"> Checkout </button>
get '/checkout' do @session = # ... Fetch or create the Checkout Session erb :checkout end
<button id="checkout-button" data-secret="{{ session_id }}"> Checkout </button>
@app.route('/checkout') def checkout(): session = # ... Fetch or create the Checkout Session return render_template('checkout.html', session_id=session.id)
<?php $session = # ... Fetch or create the Checkout Session; ?> ... <button id="checkout-button" data-secret="<?= $session->id ?>"> Checkout </button> ...
<button id="checkout-button" data-secret="{{ session_id }}"> Checkout </button>
import java.util.HashMap; import java.util.Map; import com.stripe.model.checkout.Session; import spark.ModelAndView; import static spark.Spark.get; public class StripeJavaQuickStart { public static void main(String[] args) { get("/checkout", (request, response) -> { Session session = // ... Fetch or create the Checkout Session Map map = new HashMap(); map.put("session_id", session.getSessionID()); return new ModelAndView(map, "checkout.hbs"); }, new HandlebarsTemplateEngine()); } }
<button id="checkout-button" data-secret="{{ session_id }}"> Checkout </button>
const express = require('express'); const expressHandlebars = require('express-handlebars'); const app = express(); app.engine('.hbs', expressHandlebars({ extname: '.hbs' })); app.set('view engine', '.hbs'); app.set('views', './views'); app.get('/checkout', async (req, res) => { const session = // ... Fetch or create the Checkout Session res.render('checkout', { session_id: session.id }); }); app.listen(3000, () => { console.log('Running on port 3000'); });
<button id="checkout-button" data-secret="{{ .SessionId }}"> Checkout </button>
package main import ( "html/template" "net/http" stripe "github.com/stripe/stripe-go/v71" ) type CheckoutData struct { SessionId string } func main() { checkoutTmpl := template.Must(template.ParseFiles("views/checkout.html")) http.HandleFunc("/checkout", func(w http.ResponseWriter, r *http.Request) { session := // ... Fetch or create the Checkout Session data := CheckoutData{ SessionId: session.id, } checkoutTmpl.Execute(w, data) }) http.ListenAndServe(":3000", nil) }
<button id="checkout-button" data-secret="@ViewData["SessionID"]"> Checkout </button>
using System; using Microsoft.AspNetCore.Mvc; using Stripe; namespace StripeExampleApi.Controllers { [Route("/[controller]")] public class CheckoutController : Controller { public IActionResult Index() { var session = // ... Fetch or create the Checkout Session ViewData["SessionID"] = session.id; return View(); } } }

3 Add a checkout button Client-side

Next, add a checkout button to your website. When your customer clicks this button, it should redirect to the Stripe-hosted payment form referencing their Checkout Session through the Session ID.

Checkout relies on Stripe.js, Stripe’s foundational JavaScript library for collecting sensitive payment information and advanced fraud detection. Include the following script tag on your website—always load it directly from https://js.stripe.com. You cannot include it in a bundle or host it yourself.

<script src="https://js.stripe.com/v3/"></script>
npm install @stripe/stripe-js

Create a checkout button:

<button id="checkout-button">Checkout</button>

Create an instance of the Stripe object with your publishable API key:

var stripe = Stripe('pk_test_TYooMQauvdEDq54NiTphI7jx');
import {loadStripe} from '@stripe/stripe-js'; const stripe = await loadStripe('pk_test_TYooMQauvdEDq54NiTphI7jx');

When your customer is ready to pay, call redirectToCheckout and provide the Checkout Session ID from the previous step as an argument.

var checkoutButton = document.getElementById('checkout-button'); checkoutButton.addEventListener('click', function() { stripe.redirectToCheckout({ // Make the id field from the Checkout Session creation API response // available to this file, so you can provide it as argument here // instead of the {{CHECKOUT_SESSION_ID}} placeholder. sessionId: '{{CHECKOUT_SESSION_ID}}' }).then(function (result) { // If `redirectToCheckout` fails due to a browser or network // error, display the localized error message to your customer // using `result.error.message`. }); });
const checkoutButton = document.getElementById('checkout-button'); checkoutButton.addEventListener('click', () => { stripe.redirectToCheckout({ // Make the id field from the Checkout Session creation API response // available to this file, so you can provide it as argument here // instead of the {{CHECKOUT_SESSION_ID}} placeholder. sessionId: '{{CHECKOUT_SESSION_ID}}' }) // If `redirectToCheckout` fails due to a browser or network // error, display the localized error message to your customer // using `error.message`. });

Checkout relies on Stripe.js, Stripe’s foundational JavaScript library for collecting sensitive payment information and advanced fraud detection. Install the Stripe.js module with the following command. Always load Stripe.js directly from https://js.stripe.com. You cannot include it in a bundle or host it yourself.

npm install @stripe/stripe-js

Add Stripe.js to your page

Call loadStripe with your publishable API key. It returns a Promise that resolves with the Stripe object once Stripe.js has loaded.

When your customer is ready to pay, call redirectToCheckout and provide the Checkout Session ID from the previous step as an argument.

import React from 'react'; import ReactDOM from 'react-dom'; import { loadStripe } from '@stripe/stripe-js'; // Make sure to call `loadStripe` outside of a component’s render to avoid // recreating the `Stripe` object on every render. const stripePromise = loadStripe('pk_test_TYooMQauvdEDq54NiTphI7jx'); function App() { const handleClick = async (event) => { // Call your backend to create the Checkout Session—see previous step const { sessionId } = await createCheckoutSession(); // When the customer clicks on the button, redirect them to Checkout. const stripe = await stripePromise; const { error } = await stripe.redirectToCheckout({ sessionId, }); // If `redirectToCheckout` fails due to a browser or network // error, display the localized error message to your customer // using `error.message`. }; return ( <button role="link" onClick={handleClick}> Checkout </button> ); } ReactDOM.render(<App />, document.getElementById('root'));

This code is typically invoked from an event handler that triggers in response to an action taken by your customer, such as clicking on the checkout button.

4 Confirm the payment is successful

When your customer completes a payment, they’re redirected to the URL that you specified as the success_url. This is typically a page on your website that informs your customer that their payment was successful.

Use the Dashboard, a custom webhook, or a third-party plugin to handle post-payment events like sending an order confirmation email to your customer, logging the sale in a database, or starting a shipping workflow.

Successful payments appear in the Dashboard’s list of payments. When you click a payment, it takes you to the payment detail page. The Checkout summary section contains billing information and the list of items purchased, which you can use to manually fulfill the order.

Set up webhooks to programmatically handle post-payment events. The quickest way to develop and test webhooks locally is with the Stripe CLI. Once you have it installed, you can forward events to your server:

stripe listen --forward-to localhost:4242/webhook Ready! Your webhook signing secret is '{{WEBHOOK_SIGNING_SECRET}}' (^C to quit)

When your customer completes a payment, Stripe sends the checkout.session.completed event. This event includes the Checkout Session object, which contains details about your customer and their payment.

With a webhook endpoint, your customer is redirected to the success_url when you acknowledged you received the event. In scenarios where your endpoint is down or the event isn’t acknowledged properly, your customer is redirected to the success_url 10 seconds after a successful payment.

The following example endpoint demonstrates how to acknowledge and handle events.

# Set your secret key. Remember to switch to your live secret key in production! # See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' # You can find your endpoint's secret in your webhook settings endpoint_secret = 'whsec_...' # Using Sinatra post '/webhook' do payload = request.body.read event = nil # Verify webhook signature and extract the event # See https://stripe.com/docs/webhooks/signatures for more information. sig_header = request.env['HTTP_STRIPE_SIGNATURE'] begin event = Stripe::Webhook.construct_event( payload, sig_header, endpoint_secret ) rescue JSON::ParserError => e # Invalid payload status 400 return rescue Stripe::SignatureVerificationError => e # Invalid signature status 400 return end # Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed' session = event['data']['object'] # Fulfill the purchase... handle_checkout_session(session) end status 200 end
# Set your secret key. Remember to switch to your live secret key in production! # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' # Using Django from django.http import HttpResponse # You can find your endpoint's secret in your webhook settings endpoint_secret = 'whsec_...' @csrf_exempt def my_webhook_view(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) # Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed': session = event['data']['object'] # Fulfill the purchase... handle_checkout_session(session) return HttpResponse(status=200)
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys \Stripe\Stripe::setApiKey('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); // You can find your endpoint's secret in your webhook settings $endpoint_secret = 'whsec_...'; $payload = @file_get_contents('php://input'); $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE']; $event = null; try { $event = \Stripe\Webhook::constructEvent( $payload, $sig_header, $endpoint_secret ); } catch(\UnexpectedValueException $e) { // Invalid payload http_response_code(400); exit(); } catch(\Stripe\Exception\SignatureVerificationException $e) { // Invalid signature http_response_code(400); exit(); } // Handle the checkout.session.completed event if ($event->type == 'checkout.session.completed') { $session = $event->data->object; // Fulfill the purchase... handle_checkout_session($session); } http_response_code(200);
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.apiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; // You can find your endpoint's secret in your webhook settings String endpointSecret = "whsec_..."; // Using the Spark framework (http://sparkjava.com) public Object handle(Request request, Response response) { String payload = request.body(); String sigHeader = request.headers("Stripe-Signature"); Event event = null; try { event = Webhook.constructEvent( payload, sigHeader, endpointSecret ); } catch (JsonSyntaxException e) { // Invalid payload response.status(400); return ""; } catch (SignatureVerificationException e) { // Invalid signature response.status(400); return ""; } // Handle the checkout.session.completed event if ("checkout.session.completed".equals(event.getType())) { Session session = (Session) event.getDataObjectDeserializer().getObject(); // Fulfill the purchase... handleCheckoutSession(session); } response.status(200); return ""; }
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys const stripe = require('stripe')('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); // Find your endpoint's secret in your Dashboard's webhook settings const endpointSecret = 'whsec_...'; // Using Express const app = require('express')(); // Use body-parser to retrieve the raw body as a buffer const bodyParser = require('body-parser'); // Match the raw body to content type application/json app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => { const sig = request.headers['stripe-signature']; let event; try { event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret); } catch (err) { return response.status(400).send(`Webhook Error: ${err.message}`); } // Handle the checkout.session.completed event if (event.type === 'checkout.session.completed') { const session = event.data.object; // Fulfill the purchase... handleCheckoutSession(session); } // Return a response to acknowledge receipt of the event response.json({received: true}); }); app.listen(8000, () => console.log('Running on port 8000'));
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys stripe.Key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc" http.HandleFunc("/webhook", func(w http.ResponseWriter, req *http.Request) { const MaxBodyBytes = int64(65536) req.Body = http.MaxBytesReader(w, req.Body, MaxBodyBytes) body, err := ioutil.ReadAll(req.Body) if err != nil { fmt.Fprintf(os.Stderr, "Error reading request body: %v\n", err) w.WriteHeader(http.StatusServiceUnavailable) return } // Pass the request body & Stripe-Signature header to ConstructEvent, along with the webhook signing key // You can find your endpoint's secret in your webhook settings endpointSecret := "whsec_..."; event, err := webhook.ConstructEvent(body, req.Header.Get("Stripe-Signature"), endpointSecret) if err != nil { fmt.Fprintf(os.Stderr, "Error verifying webhook signature: %v\n", err) w.WriteHeader(http.StatusBadRequest) // Return a 400 error on a bad signature return } // Handle the checkout.session.completed event if event.Type == "checkout.session.completed" { var session stripe.CheckoutSession err := json.Unmarshal(event.Data.Raw, &session) if err != nil { fmt.Fprintf(os.Stderr, "Error parsing webhook JSON: %v\n", err) w.WriteHeader(http.StatusBadRequest) return } // Fulfill the purchase... handleCheckoutSession(session) } w.WriteHeader(http.StatusOK) })
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys StripeConfiguration.ApiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; using System; using System.IO; using Microsoft.AspNetCore.Mvc; using Stripe; namespace workspace.Controllers { [Route("api/[controller]")] public class StripeWebHook : Controller { // You can find your endpoint's secret in your webhook settings const string secret = "whsec_..."; [HttpPost] public async Task<IActionResult> Index() { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); try { var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], secret); // Handle the checkout.session.completed event if (stripeEvent.Type == Events.CheckoutSessionCompleted) { var session = stripeEvent.Data.Object as Checkout.Session; // Fulfill the purchase... HandleCheckoutSession(session); } else { return Ok() } } catch (StripeException e) { return BadRequest(); } } } }

You can use plugins like Zapier to automate updating your purchase fulfillment systems with information from Stripe payments.

Some examples of automation supported by plugins include:

  • Updating spreadsheets used for order tracking in response to successful payments
  • Updating inventory management systems in response to successful payments
  • Triggering notifications to internal customer service teams using email or chat applications

5 Test the integration

There are several test cards you can use to make sure your integration is ready for production. Use them with any CVC, postal code, and future expiration date.

Number Description
4242424242424242 Succeeds and immediately processes the payment.
4000000000003220 3D Secure 2 authentication must be completed for a successful payment.
4000000000009995 Always fails with a decline code of insufficient_funds.

For the full list of test cards see our guide on testing.

For other payment methods, enter any email address and name. Click on Pay to redirect to a Stripe-hosted test payment page where you can either authorize or fail the test payment.

See also

Was this page helpful?
Questions? Contact us.
Developer tutorials on YouTube.
You can unsubscribe at any time. Read our privacy policy.