Set up a subscription

    Use Stripe Checkout to sell products or services requiring recurring payments.

    A Checkout Session represents the details of your customer’s intent to purchase. You create a Session when your customer wants to start a subscription. After redirecting your customer to a Checkout Session, Stripe presents a payment form where your customer can complete their purchase. Once your customer has completed a purchase, they will be redirected back to your site.

    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 sudo 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/
    # 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
    # Install stripe-go go get -u github.com/stripe/stripe-go
    // 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 recurring products and prices

    To use Checkout, you first need to create a Product and a Price. Different physical goods or levels of service should be represented by products. Each product’s pricing is represented by one or more prices.

    For example, you can create a software product that has 4 prices: $10/month, $100/year, €9/month, and €90/year. This allows you to change and add prices without needing to change the details of your underlying products. You can either create a product and price through the API or through the Stripe Dashboard.

    If your price is determined at checkout (e.g. the customer sets a donation amount) or you prefer not to create prices upfront, you can create prices inline at Checkout Session creation.

    Before you start configuring products, make sure you are in test mode by toggling the View test data button at the bottom of the Stripe Dashboard. Next, define the goods and services you plan to sell. To create a new product and price:

    • Navigate to the Products section in the Dashboard
    • Click Add product
    • Select “Recurring” when setting the price
    • Configure the pricing plan

    You can define multiple pricing plans with different parameters for each recurring product. Each price has a generated ID that you can use as a reference during the checkout process.

    To create a basic Product via the API, only the name field is required. The product name, description, and images that you supply are displayed to customers on Checkout.

    curl https://api.stripe.com/v1/products \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d name="Blue banana"
    product = Stripe::Product.create( { name: 'Blue banana', } )
    product = stripe.Product.create( name='Blue banana', )
    $product = \\Stripe\\Product::create([ 'name' => 'Blue banana', ]);
    ProductCreateParams params = ProductCreateParams.builder() .setName("Blue banana") .build(); Product product = Product.create(params);
    const product = await stripe.products.create({ name: 'Blue banana', });
    params := &stripe.ProductParams{ Name: stripe.String("Blue banana"), } p, _ := product.New(params)
    var productService = new ProductService(); var options = new ProductCreateOptions { Name = "Blue banana", }; var product = productService.Create(options);

    Next, create a Price to define how much and how often to charge for your product. This includes how much the product costs, what currency to use, and its billing interval.

    curl https://api.stripe.com/v1/prices \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d product="{{ PRODUCT_ID }}" \ -d unit_amount=1000 \ -d currency=usd \ -d recurring[interval]=month
    stripe post /v1/prices \ -d product={{ PRODUCT_ID }} \ -d unit_amount=1000 \ -d currency=usd \ -d recurring[interval]=month
    price = Stripe::Price.create( { product: '{{ PRODUCT_ID }}', unit_amount: 1000, currency: 'usd', recurring: { interval: 'month', }, } )
    price = stripe.Price.create( product='{{ PRODUCT_ID }}', unit_amount=1000, currency='usd', recurring={ 'interval': 'month', }, )
    $price = \\Stripe\\Price::create([ 'product' => '{{ PRODUCT_ID }}', 'unit_amount' => 1000, 'currency' => 'usd', 'recurring' => [ 'interval' => 'month', ], ]);
    PriceCreateParams params = PriceCreateParams.builder() .setProduct("{{ PRODUCT_ID }}") .setUnitAmount(1000) .setCurrency("usd") .setRecurring( PriceCreateParams.Recurring.builder() .setInterval("month") .build() ) .build(); Price price = Price.create(params);
    const price = await stripe.prices.create({ product: '{{ PRODUCT_ID }}', unit_amount: 1000, currency: 'usd', recurring: { interval: 'month', }, });
    params := &stripe.PriceParams{ Product: stripe.String("{{ PRODUCT_ID }}"), UnitAmount: stripe.Int64(1000), Currency: stripe.String("usd"), Recurring: &stripe.PriceRecurringParams{ Interval: stripe.String("month"), }, } p, _ := price.New(params)
    var priceService = new PriceService(); var options = new PriceCreateOptions { Product = "{{ PRODUCT_ID }}", UnitAmount = 1000, Currency = "usd", Recurring = new PriceRecurringOptions { Interval = "month", }, }; var price = priceService.Create(options);

    This price ID is how you refer to the product when you start the payment process with Checkout.

    3 Create a Checkout Session Server-side

    Create a Session with the ID of an existing Price. Ensure that mode is set to subscription and you pass at least one recurring price. You can add one-time prices in addition to recurring prices.

    When your customer successfully completes their payment, they are redirected to the success_url, a page on your website that informs the customer that their payment was successful.

    When your customer clicks on your logo in a Checkout Session without completing a payment, Checkout redirects them back to your website by navigating to the cancel_url. Typically, this is the page on your website that the customer viewed prior to redirecting to Checkout.

    curl https://api.stripe.com/v1/checkout/sessions \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d "line_items[][price]"="{{PRICE_ID}}" \ -d "line_items[][quantity]"=1 \ -d mode=subscription \ -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: '{{PRICE_ID}}', quantity: 1, }], mode: 'subscription', 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': '{{PRICE_ID}}', 'quantity': 1, }], mode='subscription', 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' => '{{PRICE_ID}}', 'quantity' => 1, ]], 'mode' => 'subscription', '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"; Map<String, Object> params = new HashMap<String, Object>(); ArrayList<String> paymentMethodTypes = new ArrayList<>(); paymentMethodTypes.add("card"); params.put("payment_method_types", paymentMethodTypes); ArrayList<HashMap<String, Object>> lineItems = new ArrayList<>(); HashMap<String, Object> lineItem = new HashMap<String, Object>(); lineItem.put("price", "{{PRICE_ID}}"); lineItem.put("quantity", 1); lineItems.add(lineItem); params.put("line_items", lineItems); params.put("mode", "subscription"); params.put("success_url", "https://example.com/success?session_id={CHECKOUT_SESSION_ID}"); params.put("cancel_url", "https://example.com/cancel"); 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: '{{PRICE_ID}}', quantity: 1, }], mode: 'subscription', 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", }), LineItems: []*stripe.CheckoutSessionLineItemParams{ &stripe.CheckoutSessionLineItemParams{ Price: stripe.String("{{PRICE_ID}}"), Quantity: stripe.Int64(1), }, }, Mode: stripe.String("subscription"), 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 { Price = "{{PRICE_ID}}", Quantity = 1, }, }, Mode = "subscription", SuccessUrl = "https://example.com/success?session_id={CHECKOUT_SESSION_ID}", CancelUrl = "https://example.com/cancel", }; var service = new SessionService(); Session session = service.Create(options);

    Creating a Checkout Session returns a Session id which is important for the following steps. Make the Session ID available on your success page by including the {CHECKOUT_SESSION_ID} template variable in the success_url as in the above example.

    Checkout Sessions expire 24 hours after creation.

    4 Redirect to Checkout Client-side

    Checkout relies on Stripe.js, Stripe’s foundational JavaScript library for building payment flows.

    To get started, 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. See Stripe samples for examples.

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

    Next, create an instance of the Stripe object by providing your publishable API key as the first parameter:

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

    To use Checkout on your website, you must add a snippet of code that includes the Session id from the previous step. When your customer is ready to pay, call redirectToCheckout and provide the Session id as a parameter.

    stripe.redirectToCheckout({ // Make the id field from the Checkout Session creation API response // available to this file, so you can provide it as parameter 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 {error} = await stripe.redirectToCheckout({ // Make the id field from the Checkout Session creation API response // available to this file, so you can provide it as parameter 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`.

    To get started, install the Stripe.js module. 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 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 Session id as a parameter.

    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. const { sessionId } = await fetchCheckoutSession(); // 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 a payment button.

    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.

    6 Confirm the payment is successful

    When your customer completes a payment, Stripe redirects them to the URL that you specified in the success_url parameter. Typically, this is a page on your website that informs your customer that their payment was successful.

    There are several ways you can confirm the payment is successful:

    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.

    When a customer successfully pays for a recurring service, they’re automatically subscribed. Their subscription is recorded as a new entry in the Dashboard’s list of subscriptions.

    Stripe sends the checkout.session.completed event for a successful Checkout payment. The webhook payload includes the Checkout Session object, which contains information about the Customer, PaymentIntent, or Subscription, and optionally the client_reference_id if you provided it when calling redirectToCheckout on the client.

    The checkout.session.completed webhook is sent to your server before your customer is redirected. Your webhook acknowledgement (any 2xx status code) triggers the customer’s redirect to the success_url. If Stripe doesn’t receive successful acknowledgement within 10 seconds of a successful payment, your customer is automatically redirected to the success_url page.

    As the webhook must be acknowledged before redirecting the customer to the success_url​, you can be sure that the order was successful and can safely show a success message to your customer.

    # 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 get information about the customer, payment, or subscription by retrieving the Customer, PaymentIntent, or Subscription objects referenced by the customer, payment_intent, and subscription properties in the webhook payload.

    Retrieving line items from webhook

    By default, Checkout webhooks do not return line_items. To retrieve the items created with the Checkout Session, make an additional request with the Checkout Session id:

    curl https://api.stripe.com/v1/checkout/sessions/{CHECKOUT_SESSION_ID}/line_items \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc:
    stripe get /v1/checkout/sessions/{CHECKOUT_SESSION_ID}/line_items

    Testing webhooks locally

    To test webhooks locally, you can use 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)

    Learn more about setting up webhooks.

    You can periodically check for new payments made via Checkout by polling the /v1/events endpoint for new checkout.session.completed events. You can then execute the code needed to fulfill the purchase when you detect a new checkout.session.completed event.

    Stripe generates the checkout.session.completed event when a Checkout payment is successful. The event payload includes the Checkout Session object, which contains information about the Customer, PaymentIntent, or Subscription, and optionally the client_reference_id if you provided it when calling redirectToCheckout on the client.

    The following example demonstrates how to retrieve all checkout.session.completed events in the last 24 hours:

    # 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' events = Stripe::Event.list({ type: 'checkout.session.completed', created: { # Check for events created in the last 24 hours. gte: Time.now.utc.to_i - 24 * 60 * 60, }, }) events.auto_paging_each do |event| session = event['data']['object'] # Fulfill the purchase... handle_checkout_session(session) 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' events = stripe.Event.list( type='checkout.session.completed', created={ # Check for events created in the last 24 hours. 'gte': int(time.time() - 24 * 60 * 60), }, ) for event in events.auto_paging_iter(): session = event['data']['object'] # Fulfill the purchase... handle_checkout_session(session)
    // 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'); $events = \Stripe\Event::all([ 'type' => 'checkout.session.completed', 'created' => [ // Check for events created in the last 24 hours. 'gte' => time() - 24 * 60 * 60, ], ]); foreach ($events->autoPagingIterator() as $event) { $session = $event->data->object; // Fulfill the purchase... handle_checkout_session($session); }
    // 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"; // Check for events created in the last 24 hours. HashMap<String, Object> createdParams = new HashMap<>(); createdParams.put("gte", (int) ((System.currentTimeMillis() / 1000) - 24 * 60 * 60)); HashMap<String, Object> params = new HashMap<>(); params.put("type", "checkout.session.completed"); params.put("created", createdParams); Iterable<Event> events = Event.list(params).autoPagingIterable(); for (Event event : events) { EventDataObjectDeserializer deserializer = event.getDataObjectDeserializer(); if (deserializer.getObject().isPresent()) { Session session = (Session) deserializer.getObject().get(); // Fulfill the purchase... handleCheckoutSession(session); } }
    // 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 events = stripe.events.list({ type: 'checkout.session.completed', created: { // Check for events created in the last 24 hours. gte: Math.floor((Date.now() - 24 * 60 * 60 * 1000)/1000), }, }); // For older versions of Node, see https://github.com/stripe/stripe-node/#auto-pagination for await (const event of events) { const session = event.data.object; // Fulfill the purchase... handleCheckoutSession(session); }
    // 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.EventListParams{ Type: stripe.String("checkout.session.completed"), CreatedRange: &stripe.RangeQueryParams{ // Check for events created in the last 24 hours. GreaterThan: *stripe.Int64(time.Now().Unix() - 24 * 60 * 60), }, } i := event.List(params) for i.Next() { event := i.Event() var session stripe.CheckoutSession err := json.Unmarshal(event.Data.Raw, &session) if err == nil { // Fulfill the purchase... handleCheckoutSession(session) } }
    // 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 service = new EventService(); var options = new EventListOptions { Type = "checkout.session.completed", Created = new DateRangeOptions { // Check for events created in the last 24 hours. GreaterThan = DateTime.Now.Subtract(new TimeSpan(24, 0, 0)), }, }; foreach (var stripeEvent in service.ListAutoPaging(options)) { var session = stripeEvent.Data.Object as Session; // Fulfill the purchase... handleCheckoutSession(session); }

    You can obtain information about the customer, payment, or subscription by retrieving the Customer, PaymentIntent, or Subscription objects referenced by the customer, payment_intent, and subscription properties in the webhook payload.

    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

    See also

    Was this page helpful?

    Feedback about this page?

    Thank you for helping improve Stripe's documentation. If you need help or have any questions, please consider contacting support.

    On this page