# Stripe-hosted page # Stripe-hosted page Explore a full, working code sample of an integration with [Stripe Checkout](https://docs.stripe.com/payments/checkout.md) where customers click a button on your site and get redirected to a payment page hosted by Stripe. The example includes client- and server-side code, and the payment page is prebuilt. ### Install the Stripe Node library Install the package and import it in your code. Alternatively, if you’re starting from scratch and need a package.json file, download the project files using the Download link in the code editor. Install the library: Or download the stripe-node library source code directly [from GitHub](https://github.com/stripe/stripe-node). ### Install the Stripe Ruby library Install the Stripe ruby gem and require it in your code. Alternatively, if you’re starting from scratch and need a Gemfile, download the project files using the link in the code editor. Install the gem: Add this line to your Gemfile: Or download the stripe-ruby gem source code directly [from GitHub](https://github.com/stripe/stripe-ruby). ### Install the Stripe Java library Add the dependency to your build and import the library. Alternatively, if you’re starting from scratch and need a sample pom.xml file (for Maven), download the project files using the link in the code editor. Add the following dependency to your POM and replace {VERSION} with the version number you want to use. Add the dependency to your build.gradle file and replace {VERSION} with the version number you want to use. Download the JAR directly [from GitHub](https://github.com/stripe/stripe-java/releases/latest). ### Install the Stripe Python package Install the Stripe package and import it in your code. Alternatively, if you’re starting from scratch and need a requirements.txt file, download the project files using the link in the code editor. Install the package via pip: Download the stripe-python library source code directly [from GitHub](https://github.com/stripe/stripe-python/releases). ### Install the Stripe PHP library Install the library with composer and initialize with your secret API key. Alternatively, if you’re starting from scratch and need a composer.json file, download the files using the link in the code editor. Install the library: Or download the stripe-php library source code directly [from GitHub](https://github.com/stripe/stripe-php). ### Set up your server Add the dependency to your build and import the library. Alternatively, if you’re starting from scratch and need a go.mod file, download the project files using the link in the code editor. Make sure to initialize with Go Modules: Or download the stripe-go module source code directly [from GitHub](https://github.com/stripe/stripe-go). ### Install the Stripe.net library Install the package with .NET or NuGet. Alternatively, if you’re starting from scratch, download the files which contains a configured .csproj file. Install the library: Install the library: Or download the Stripe.net library source code directly [from GitHub](https://github.com/stripe/stripe-dotnet). ### Install the Stripe libraries Install the packages and import them in your code. Alternatively, if you’re starting from scratch and need a `package.json` file, download the project files using the link in the code editor. Install the libraries: ### Create a Checkout Session Add an endpoint on your server that creates a [Checkout Session](https://docs.stripe.com/api/checkout/sessions.md). A Checkout Session controls what your customer sees on the payment page such as line items, the order amount and currency, and acceptable payment methods. We enable cards and other common payment methods for you by default, and you can enable or disable payment methods directly in the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). ### Create a Checkout Session Add a [Route Handler](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) in your application that creates a [Checkout Session](https://docs.stripe.com/api/checkout/sessions.md). A Checkout Session controls what your customer sees on the payment page such as line items, the order amount and currency, and acceptable payment methods. We enable cards and other common payment methods for you by default, and you can enable or disable payment methods directly in the [Stripe Dashboard](https://dashboard.stripe.com/settings/payment_methods). ### Define a product to sell Always keep sensitive information about your product inventory, such as price and availability, on your server to prevent customer manipulation from the client. Define product information when you create the Checkout Session using [predefined price IDs](https://docs.stripe.com/payments/accept-a-payment.md?platform=web&ui=stripe-hosted#create-product-prices-upfront) or on the fly with [price_data](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items-price_data). ### Choose a mode To handle different transaction types, adjust the `mode` parameter. For one-time payments, use `payment`. To initiate recurring payments with [subscriptions](https://docs.stripe.com/billing/subscriptions/build-subscriptions.md?platform=web&ui=stripe-hosted), switch the `mode` to `subscription`. And for [setting up future payments](https://docs.stripe.com/payments/save-and-reuse.md?platform=web&ui=stripe-hosted), set the `mode` to `setup`. ### Supply success and cancel URLs Specify URLs for success and cancel pages—make sure they’re publicly accessible so Stripe can redirect customers to them. You can also handle both the success and canceled states with the same URL. ### Redirect to Checkout After creating the session, redirect your customer to the URL for the Checkout page returned in the response. ### Add a success page Create a success page for the URL you provided as the Checkout Session `success_url` to display order confirmation messaging or order details to your customer. Stripe redirects to this page after the customer successfully completes the checkout. ### Add a canceled page Add another page for `cancel_url`. Stripe redirects to this page when the customer clicks the back button in Checkout. ### Add an order preview page Finally, add a page to show a preview of the customer’s order. Allow them to review or modify their order—as soon as they’re sent to the Checkout page, the order is final and they can’t modify it without creating a new Checkout Session. ### Add an order preview page Add a page to show a preview of the customer’s order. Allow them to review or modify their order—as soon as they’re sent to the Checkout page, the order is final and they can’t modify it without creating a new Checkout Session. ### Add a checkout button Add a button to your order preview page. When your customer clicks this button, they’re redirected to the Stripe-hosted payment page. ### Add a checkout button Add a button to your order preview page. When your customer clicks this button, they’re redirected to the Stripe-hosted payment form. ### Add an order preview page Add a file under `pages/` to create a page showing a preview of the customer’s order. Allow them to review or modify their order—as soon as they’re sent to the Checkout page, the order is final and they can’t modify it without creating a new Checkout Session ### Fetch a Checkout Session Add a button to your order preview page. When your customer clicks it, make a request to the Route Handler to redirect the customer to a new Checkout Session. ### Handle redirect back from Checkout Show a message to your customer when they’re redirected back to your page. Wait to fulfill orders (for example, shipping or sending email receipts) until the payment succeeds. Learn more about [fulfilling orders with Checkout](https://docs.stripe.com/checkout/fulfillment.md). ### Set your environment variables Add your publishable and secret keys to a `.env` file. Next.js automatically loads them into your application as [environment variables](https://nextjs.org/docs/basic-features/environment-variables). If you want to listen to webhooks, also include a webhook secret, which you can create in the [Dashboard](https://dashboard.stripe.com/webhooks) or with the [Stripe CLI](https://docs.stripe.com/stripe-cli.md). ### Before you run the application Add `“proxy”: “”` to your `package.json` file during local development. ### Run the application Start your server and navigate to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) ### Run the application Start your server and navigate to [http://localhost:3000/checkout](http://localhost:3000/checkout) ### Run the application Start your app with `npm run dev` and navigate to [http://localhost:3000](http://localhost:3000) ### Try it out Click the checkout button to be redirected to the Stripe Checkout page. Use any of these test cards to simulate a payment. | Scenario | Card Number | | ------------------------------- | ---------------- | | Payment succeeds | 4242424242424242 | | Payment requires authentication | 4000002500003155 | | Payment is declined | 4000000000009995 | ## Congratulations! You have a basic Checkout integration working. Now learn how to customize the appearance of your checkout page and automate tax collection. ### Customize the checkout page Customize the appearance of the hosted Checkout page by: - Adding your logo and color theme in your [branding settings](https://dashboard.stripe.com/settings/branding). - Using the [Checkout Sessions API](https://docs.stripe.com/api/checkout/sessions/create.md) to activate additional features, like collecting addresses or prefilling customer data. ### Prefill customer data Use [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email) to prefill the customer’s email address in the email input field. You can also pass a [Customer](https://docs.stripe.com/api/customers.md) ID to the `customer` field to prefill the email address field with the email stored on the Customer. ### Pick a submit button Configure the copy displayed on the Checkout submit button by setting the [submit_type](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-submit_type). There are four different submit types. ### Collect billing and shipping details Use [billing_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-billing_address_collection) and [shipping_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection) to collect your customer’s address. [shipping_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection) requires a list of `allowed_countries`. Checkout displays the list of allowed countries in a dropdown menu on the page. ### Preview the customized page Click the checkout button to see a sample Stripe Checkout page with these additional fields. Learn more about all the ways you can [customize Checkout](https://docs.stripe.com/payments/checkout/customization.md). ### Automate tax collection Calculate and collect the right amount of tax on your Stripe transactions. Learn more about [Stripe Tax](https://docs.stripe.com/tax.md) and how to [add it to Checkout](https://docs.stripe.com/tax/checkout.md). ### Set up Stripe Tax in the Dashboard [Activate Stripe Tax](https://dashboard.stripe.com/tax) to monitor your tax obligations, automatically collect tax, and access the reports you need to file returns. ### Add the automatic tax parameter Set the `automatic_tax` parameter to `enabled: true`. ### New and returning customers By default, Checkout only creates [Customers](https://docs.stripe.com/api/customers.md) when one is required (for example, for subscriptions). Otherwise, Checkout uses [guest customers](https://docs.stripe.com/payments/checkout/guest-customers.md) to group payments in the Dashboard. You can optionally configure Checkout to always create a new customer or to specify a returning customer. ### Always create customers To always create customers whenever one isn’t provided, set [customer_creation](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_creation) to `'always'`. ### Specify returning customers To associate a Checkout Session with a customer that already exists, provide the [customer](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) when creating a session. ```javascript const stripe = require('stripe')('<>'); const express = require('express'); const app = express(); app.use(express.static('public')); const YOUR_DOMAIN = 'http://localhost:4242'; app.post('/create-checkout-session', async (req, res) => { const session = await stripe.checkout.sessions.create({ customer_email: 'customer@example.com', submit_type: 'donate', billing_address_collection: 'auto', shipping_address_collection: { allowed_countries: ['US', 'CA'], }, line_items: [ { // Provide the exact Price ID (for example, price_1234) of the product you want to sell price: '{{PRICE_ID}}', quantity: 1, }, ], mode: 'payment', success_url: `${YOUR_DOMAIN}/success.html`, cancel_url: `${YOUR_DOMAIN}/cancel.html`, success_url: `${YOUR_DOMAIN}?success=true`, cancel_url: `${YOUR_DOMAIN}?canceled=true`, automatic_tax: {enabled: true}, customer_creation: 'always', // Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session // customer: '{{CUSTOMER_ID}}' }); res.redirect(303, session.url); }); app.listen(4242, () => console.log('Running on port 4242')); ``` ```json { "name": "stripe-sample", "version": "1.0.0", "description": "A sample Stripe implementation", "main": "server.js", "scripts": { "start": "node server.js" }, "author": "stripe-samples", "license": "ISC", "dependencies": { "express": "^4.17.1", "stripe": "^18.0.0" } } { "name": "stripe-sample", "version": "0.1.0", "dependencies": { "@stripe/react-stripe-js": "^1.0.0", "@stripe/stripe-js": "^1.0.0", "express": "^4.17.1", "react": "^16.9.0", "react-dom": "^16.9.0", "react-scripts": "^3.4.0", "stripe": "^18.0.0" }, "devDependencies": { "concurrently": "4.1.2" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start-client": "react-scripts start", "start-server": "node server.js", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "start": "concurrently \"yarn start-client\" \"yarn start-server\"" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ``` ```ruby require 'stripe' require 'sinatra' Stripe.api_key = '<>' set :static, true set :port, 4242 YOUR_DOMAIN = 'http://localhost:4242' post '/create-checkout-session' do content_type 'application/json' session = Stripe::Checkout::Session.create({ customer_email: 'customer@example.com', submit_type: 'donate', billing_address_collection: 'required', shipping_address_collection: { allowed_countries: ['US', 'CA'], }, line_items: [{ # Provide the exact Price ID (e.g. price_1234) of the product you want to sell price: '{{PRICE_ID}}', quantity: 1, }], mode: 'payment', success_url: YOUR_DOMAIN + '/success.html', cancel_url: YOUR_DOMAIN + '/cancel.html', success_url: YOUR_DOMAIN + '?success=true', cancel_url: YOUR_DOMAIN + '?canceled=true', automatic_tax: {enabled: true}, customer_creation: 'always', # Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session # customer: '{{CUSTOMER_ID}}' }) redirect session.url, 303 end ``` ``` source 'https://rubygems.org/' gem 'sinatra' gem 'stripe' ``` ```python \#! /usr/bin/env python3.6 """ server.py Stripe Sample. Python 3.6 or newer required. """ import os from flask import Flask, redirect, request import stripe stripe.api_key = '<>' app = Flask(__name__, static_url_path='', static_folder='public') YOUR_DOMAIN = 'http://localhost:4242' @app.route('/create-checkout-session', methods=['POST']) def create_checkout_session(): try: checkout_session = stripe.checkout.Session.create( customer_email='customer@example.com', submit_type='donate', billing_address_collection='auto', shipping_address_collection={ 'allowed_countries': ['US', 'CA'], }, line_items=[ { # Provide the exact Price ID (for example, price_1234) of the product you want to sell 'price': '{{PRICE_ID}}', 'quantity': 1, }, ], mode='payment', success_url=YOUR_DOMAIN + '/success.html', cancel_url=YOUR_DOMAIN + '/cancel.html', success_url=YOUR_DOMAIN + '?success=true', cancel_url=YOUR_DOMAIN + '?canceled=true', automatic_tax={'enabled': True}, customer_creation='always', # Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session # customer='{{CUSTOMER_ID}}' ) except Exception as e: return str(e) return redirect(checkout_session.url, code=303) if __name__ == '__main__': app.run(port=4242) ``` ``` certifi==2021.5.30 chardet==4.0.0 Click==8.0.1 Flask==2.0.1 idna==3.2 itsdangerous==2.0.1 Jinja2==3.0.1 MarkupSafe==2.0.1 requests==2.26.0 stripe==12.0.0 toml==0.10.2 Werkzeug==2.0.1 ``` ```php 'customer@example.com', 'submit_type' => 'donate', 'billing_address_collection' => 'required', 'shipping_address_collection' => [ 'allowed_countries' => ['US', 'CA'], ], 'line_items' => [[ # Provide the exact Price ID (e.g. price_1234) of the product you want to sell 'price' => '{{PRICE_ID}}', 'quantity' => 1, ]], 'mode' => 'payment', 'success_url' => $YOUR_DOMAIN . '/success.html', 'cancel_url' => $YOUR_DOMAIN . '/cancel.html', 'success_url' => $YOUR_DOMAIN . '?success=true', 'cancel_url' => $YOUR_DOMAIN . '?canceled=true', 'automatic_tax' => [ 'enabled' => true, ], 'customer_creation' => 'always', # Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session # 'customer' => '{{CUSTOMER_ID}}' ]); header("HTTP/1.1 303 See Other"); header("Location: " . $checkout_session->url); ``` ```php >'; ``` ```json { "require": { "stripe/stripe-php": "^17.0" } } ``` ```csharp using System.Collections.Generic; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Stripe; using Stripe.Checkout; public class StripeOptions { public string option { get; set; } } namespace server.Controllers { public class Program { public static void Main(string[] args) { WebHost.CreateDefaultBuilder(args) .UseUrls("http://0.0.0.0:4242") .UseWebRoot("public") .UseStartup() .Build() .Run(); } } public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddNewtonsoftJson(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { StripeConfiguration.ApiKey = "<>"; if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); app.UseRouting(); app.UseStaticFiles(); app.UseEndpoints(endpoints => endpoints.MapControllers()); } } [Route("create-checkout-session")] [ApiController] public class CheckoutApiController : Controller { [HttpPost] public ActionResult Create() { var domain = "http://localhost:4242"; var options = new SessionCreateOptions { CustomerEmail = "customer@example.com", SubmitType = "donate", BillingAddressCollection = "auto", ShippingAddressCollection = new SessionShippingAddressCollectionOptions { AllowedCountries = new List { "US", "CA", }, }, LineItems = new List { new SessionLineItemOptions { // Provide the exact Price ID (for example, price_1234) of the product you want to sell Price = "{{PRICE_ID}}", Quantity = 1, }, }, Mode = "payment", SuccessUrl = domain + "/success.html", CancelUrl = domain + "/cancel.html", SuccessUrl = domain + "?success=true", CancelUrl = domain + "?canceled=true", AutomaticTax = new SessionAutomaticTaxOptions { Enabled = true }, CustomerCreation = "always", // Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session // Customer="cus_RnhPlBnbBbXapY", }; var service = new SessionService(); Session session = service.Create(options); Response.Headers.Add("Location", session.Url); return new StatusCodeResult(303); } } } ``` ``` net8.0 StripeExample Major ``` ```go package main import ( "log" "net/http" "github.com/stripe/stripe-go/v82" "github.com/stripe/stripe-go/v82/checkout/session" ) func main() { stripe.Key = "<>" http.Handle("/", http.FileServer(http.Dir("public"))) http.HandleFunc("/create-checkout-session", createCheckoutSession) addr := "localhost:4242" log.Printf("Listening on %s", addr) log.Fatal(http.ListenAndServe(addr, nil)) } func createCheckoutSession(w http.ResponseWriter, r *http.Request) { domain := "http://localhost:4242" params := &stripe.CheckoutSessionParams{ CustomerEmail: stripe.String("customer@example.com"), SubmitType: stripe.String("donate"), BillingAddressCollection: stripe.String("auto"), ShippingAddressCollection: &stripe.CheckoutSessionShippingAddressCollectionParams{ AllowedCountries: stripe.StringSlice([]string{ "US", "CA", }), }, LineItems: []*stripe.CheckoutSessionLineItemParams{ &stripe.CheckoutSessionLineItemParams{ // Provide the exact Price ID (for example, price_1234) of the product you want to sell Price: stripe.String("{{PRICE_ID}}"), Quantity: stripe.Int64(1), }, }, Mode: stripe.String(string(stripe.CheckoutSessionModePayment)), SuccessURL: stripe.String(domain + "/success.html"), CancelURL: stripe.String(domain + "/cancel.html"), SuccessURL: stripe.String(domain + "?success=true"), CancelURL: stripe.String(domain + "?canceled=true"), AutomaticTax: &stripe.CheckoutSessionAutomaticTaxParams{Enabled: stripe.Bool(true)}, CreateCustomers: %stripe.CheckoutSessionParams.CustomerCreation.ALWAYS, // Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session // Customer: "cus_RnhPlBnbBbXapY", CustomerCreation: stripe.String(string(stripe.CheckoutSessionCustomerCreationAlways)), // Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session // Customer: stripe.String("{{CUSTOMER_ID}}"), } s, err := session.New(params) if err != nil { log.Printf("session.New: %v", err) } http.Redirect(w, r, s.URL, http.StatusSeeOther) } ``` ``` module stripe.com/docs/payments go 1.13 require github.com/stripe/stripe-go/v82 v82.0.0 ``` ```java package com.stripe.sample; import java.nio.file.Paths; import static spark.Spark.post; import static spark.Spark.port; import static spark.Spark.staticFiles; import com.stripe.Stripe; import com.stripe.model.checkout.Session; import com.stripe.param.checkout.SessionCreateParams; public class Server { public static void main(String[] args) { port(4242); Stripe.apiKey = "<>"; staticFiles.externalLocation( Paths.get("public").toAbsolutePath().toString()); post("/create-checkout-session", (request, response) -> { String YOUR_DOMAIN = "http://localhost:4242"; SessionCreateParams params = SessionCreateParams.builder() .setCustomerEmail("customer@example.com") .setSubmitType(SessionCreateParams.SubmitType.DONATE) .setBillingAddressCollection(SessionCreateParams.BillingAddressCollection.REQUIRED) .setShippingAddressCollection( SessionCreateParams.ShippingAddressCollection.builder() .addAllowedCountry(SessionCreateParams.ShippingAddressCollection.AllowedCountry.CA) .addAllowedCountry(SessionCreateParams.ShippingAddressCollection.AllowedCountry.US) .build()) .setMode(SessionCreateParams.Mode.PAYMENT) .setSuccessUrl(YOUR_DOMAIN + "/success.html") .setCancelUrl(YOUR_DOMAIN + "/cancel.html") .setSuccessUrl(YOUR_DOMAIN + "?success=true") .setCancelUrl(YOUR_DOMAIN + "?canceled=true") .setAutomaticTax( SessionCreateParams.AutomaticTax.builder() .setEnabled(true) .build()) .setCustomerCreation(SessionCreateParams.CustomerCreation.ALWAYS) // Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session // .setCustomer("{{CUSTOMER_ID}}") .addLineItem( SessionCreateParams.LineItem.builder() .setQuantity(1L) // Provide the exact Price ID (for example, price_1234) of the product you want to sell .setPrice("{{PRICE_ID}}") .build()) .build(); Session session = Session.create(params); response.redirect(session.getUrl(), 303); return ""; }); } } ``` ```xml 4.0.0 com.stripe.sample stripe-payment 1.0.0-SNAPSHOT org.slf4j slf4j-simple 2.0.3 com.sparkjava spark-core 2.9.4 com.google.code.gson gson 2.9.1 org.projectlombok lombok 1.18.20 provided com.stripe stripe-java 29.0.0 sample org.apache.maven.plugins maven-compiler-plugin 3.10.1 1.8 1.8 maven-assembly-plugin package single jar-with-dependencies Server ``` ```html Buy cool new product
The cover of Stubborn Attachments

Stubborn Attachments

$20.00
``` ```html Thanks for your order!

We appreciate your business! If you have any questions, please email orders@example.com.

``` ```html Checkout canceled

Forgot to add something to your cart? Shop around then come back to pay!

``` ```css body { display: flex; justify-content: center; align-items: center; background: #242d60; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', 'Ubuntu', sans-serif; height: 100vh; margin: 0; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } section { background: #ffffff; display: flex; flex-direction: column; width: 400px; height: 112px; border-radius: 6px; justify-content: space-between; } .product { display: flex; } .description { display: flex; flex-direction: column; justify-content: center; } p { font-style: normal; font-weight: 500; font-size: 14px; line-height: 20px; letter-spacing: -0.154px; color: #242d60; height: 100%; width: 100%; padding: 0 20px; display: flex; align-items: center; justify-content: center; box-sizing: border-box; } img { border-radius: 6px; margin: 10px; width: 54px; height: 57px; } h3, h5 { font-style: normal; font-weight: 500; font-size: 14px; line-height: 20px; letter-spacing: -0.154px; color: #242d60; margin: 0; } h5 { opacity: 0.5; } button { height: 36px; background: #556cd6; color: white; width: 100%; font-size: 14px; border: 0; font-weight: 500; cursor: pointer; letter-spacing: 0.6; border-radius: 0 0 6px 6px; transition: all 0.2s ease; box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07); } button:hover { opacity: 0.8; } ``` ```json { "name": "stripe-sample", "version": "0.1.0", "dependencies": { "@stripe/react-stripe-js": "^3.5.1", "@stripe/stripe-js": "^6.1.0", "express": "^4.17.1", "react": "^16.9.0", "react-dom": "^16.9.0", "react-scripts": "^3.4.0", "stripe": "^8.202.0" }, "devDependencies": { "concurrently": "4.1.2" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://127.0.0.1:4242", "scripts": { "start-client": "react-scripts start", "start-server": "node server.js", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "start": "concurrently \"yarn start-client\" \"yarn start-server\"" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } { "name": "client", "version": "0.1.0", "private": true, "dependencies": { "@stripe/react-stripe-js": "^3.5.1", "@stripe/stripe-js": "^6.1.0", "react": "^16.9.0", "react-dom": "^16.9.0", "react-scripts": "^3.4.0" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ``` ```jsx import React, { useState, useEffect } from "react"; import "./App.css"; const ProductDisplay = () => (
The cover of Stubborn Attachments

Stubborn Attachments

$20.00
); const Message = ({ message }) => (

{message}

); export default function App() { const [message, setMessage] = useState(""); useEffect(() => { // Check to see if this is a redirect back from Checkout const query = new URLSearchParams(window.location.search); if (query.get("success")) { setMessage("Order placed! You will receive an email confirmation."); } if (query.get("canceled")) { setMessage( "Order canceled -- continue to shop around and checkout when you're ready." ); } }, []); return message ? ( ) : ( ); } ``` ```css body { display: flex; justify-content: center; align-items: center; background: #242d60; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', 'Ubuntu', sans-serif; height: 100vh; margin: 0; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } section { background: #ffffff; display: flex; flex-direction: column; width: 400px; height: 112px; border-radius: 6px; justify-content: space-between; } .product { display: flex; } .description { display: flex; flex-direction: column; justify-content: center; } p { font-style: normal; font-weight: 500; font-size: 14px; line-height: 20px; letter-spacing: -0.154px; color: #242d60; height: 100%; width: 100%; padding: 0 20px; display: flex; align-items: center; justify-content: center; box-sizing: border-box; } img { border-radius: 6px; margin: 10px; width: 54px; height: 57px; } h3, h5 { font-style: normal; font-weight: 500; font-size: 14px; line-height: 20px; letter-spacing: -0.154px; color: #242d60; margin: 0; } h5 { opacity: 0.5; } button { height: 36px; background: #556cd6; color: white; width: 100%; font-size: 14px; border: 0; font-weight: 500; cursor: pointer; letter-spacing: 0.6; border-radius: 0 0 6px 6px; transition: all 0.2s ease; box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07); } button:hover { opacity: 0.8; } ``` ```javascript import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; ReactDOM.render(, document.getElementById("root")); ``` ```html Stripe sample
``` ```json { "name": "stripe-sample", "version": "0.1.0", "dependencies": { "@stripe/react-stripe-js": "^1.0.0", "@stripe/stripe-js": "^1.0.0", "express": "^4.17.1", "react": "^16.9.0", "react-dom": "^16.9.0", "react-scripts": "^3.4.0", "stripe": "^8.202.0" }, "devDependencies": { "concurrently": "4.1.2" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start-client": "react-scripts start", "start-server": "node server.js", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "start": "concurrently \"yarn start-client\" \"yarn start-server\"" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } { "name": "client", "version": "0.1.0", "private": true, "dependencies": { "@stripe/react-stripe-js": "^1.0.0", "@stripe/stripe-js": "^1.0.0", "react": "^16.9.0", "react-dom": "^16.9.0", "react-scripts": "^3.4.0" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ``` ```javascript import { NextResponse } from 'next/server' import { headers } from 'next/headers' import { stripe } from '../../../lib/stripe' export async function POST() { try { const headersList = await headers() const origin = headersList.get('origin') // Create Checkout Sessions from body params. const session = await stripe.checkout.sessions.create({ customer_email: 'customer@example.com', submit_type: 'donate', billing_address_collection: 'auto', shipping_address_collection: { allowed_countries: ['US', 'CA'], }, line_items: [ { // Provide the exact Price ID (for example, price_1234) of the product you want to sell price: '{{PRICE_ID}}', quantity: 1, }, ], mode: 'payment', success_url: `${origin}/success?session_id={CHECKOUT_SESSION_ID}`, cancel_url: `${origin}/?canceled=true`, automatic_tax: {enabled: true}, }); return NextResponse.redirect(session.url, 303) } catch (err) { return NextResponse.json( { error: err.message }, { status: err.statusCode || 500 } ) } } ``` ```bash \# Stripe keys # https://dashboard.stripe.com/apikeys NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_12345 STRIPE_SECRET_KEY=sk_12345 # Set this environment variable to support webhooks — https://stripe.com/docs/webhooks#verify-events # STRIPE_WEBHOOK_SECRET=whsec_12345 ``` ```bash # https://dashboard.stripe.com/apikeys NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=<> STRIPE_SECRET_KEY=<> # Set this environment variable to support webhooks — https://stripe.com/docs/webhooks#verify-events # STRIPE_WEBHOOK_SECRET=whsec_12345 ``` ```bash .DS_Store .vscode # Node files node_modules/ # Next.js .next .vercel .env .env*.local next-env.d.ts ``` ```jsx export default function RootLayout({ children }) { return ( {children} ) } ``` ```json { "name": "stripe-sample", "version": "0.0.0", "description": "Full-stack example using Next.js", "scripts": { "dev": "next", "build": "next build", "start": "next start" }, "dependencies": { "@stripe/react-stripe-js": "^3.1.1", "@stripe/stripe-js": "^5.5.0", "micro": "^10.0.0", "micro-cors": "0.1.1", "next": "15.1.4", "react": "^19.0.0", "react-dom": "^19.0.0", "stripe": "^17.5.0" } } ``` ```jsx export default async function IndexPage({ searchParams }) { const { canceled } = await searchParams if (canceled) { console.log( 'Order canceled -- continue to shop around and checkout when you’re ready.' ) } return (
) } ``` ```javascript import 'server-only' import Stripe from 'stripe' export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY) ``` ```jsx import { redirect } from 'next/navigation' import { stripe } from '../../lib/stripe' export default async function Success({ searchParams }) { const { session_id } = await searchParams if (!session_id) throw new Error('Please provide a valid session_id (`cs_test_...`)') const { status, customer_details: { email: customerEmail } } = await stripe.checkout.sessions.retrieve(session_id, { expand: ['line_items', 'payment_intent'] }) if (status === 'open') { return redirect('/') } if (status === 'complete') { return (

We appreciate your business! A confirmation email will be sent to{' '} {customerEmail}. If you have any questions, please email{' '}

orders@example.com.
) } } ``` ```javascript import { NextResponse } from 'next/server' import { headers } from 'next/headers' import { stripe } from '../../../lib/stripe' export async function POST(req) { let event try { event = stripe.webhooks.constructEvent( await req.text(), (await headers()).get('stripe-signature'), process.env.STRIPE_WEBHOOK_SECRET ) } catch (err) { const errorMessage = err.message // On error, log and return the error message. if (err) console.log(err) console.log(`Error message: ${errorMessage}`) return NextResponse.json( { message: `Webhook Error: ${errorMessage}` }, { status: 400 } ) } const permittedEvents = ['checkout.session.completed'] if (permittedEvents.includes(event.type)) { let data try { switch (event.type) { case 'checkout.session.completed': data = event.data.object console.log(`CheckoutSession status: ${data.payment_status}`) break default: throw new Error(`Unhandled event: ${event.type}`) } } catch (error) { console.log(error) return NextResponse.json( { message: 'Webhook handler failed' }, { status: 500 } ) } } // Return a response to acknowledge receipt of the event. return NextResponse.json({ message: 'Received' }, { status: 200 }) } ``` ```md \# Accept a Payment with Stripe Checkout Stripe Checkout is the fastest way to get started with payments. Included are some basic build and run scripts you can use to start up the application. ## Set Price ID In the back end code, replace `{{PRICE_ID}}` with a Price ID (`price_xxx`) that you created. ## Running the sample 1. Build the server ~~~ pip3 install -r requirements.txt ~~~ 1. Build the server ~~~ bundle install ~~~ 1. Build the server ~~~ composer install ~~~ 1. Build the server ~~~ dotnet restore ~~~ 1. Build the server ~~~ mvn package ~~~ 2. Run the server ~~~ export FLASK_APP=server.py python3 -m flask run --port=4242 ~~~ 2. Run the server ~~~ ruby server.rb -o 0.0.0.0 ~~~ 2. Run the server ~~~ php -S 127.0.0.1:4242 --docroot=public ~~~ 2. Run the server ~~~ dotnet run ~~~ 2. Run the server ~~~ java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ~~~ 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ If you run into an error, when running npm start, try running the following code and starting again: ~~~ export NODE_OPTIONS=--openssl-legacy-provider ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 1. Run the server ~~~ go run server.go ~~~ 2. Build the client app ~~~ npm install ~~~ 3. Run the client app ~~~ npm start ~~~ 4. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 1. Run the server ~~~ go run server.go ~~~ 2. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 1. Build the application ~~~ npm install ~~~ 2. Run the application ~~~ npm start ~~~ 3. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 1. Build the server ~~~ npm install ~~~ 2. Run the server ~~~ npm start ~~~ 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) ### Development 1. Build the application ~~~shell $ npm install ~~~ 2. _Optional_: download and run the [Stripe CLI](https://stripe.com/docs/stripe-cli) ~~~shell $ stripe listen --forward-to localhost:3000/api/webhooks ~~~ 3. Run the application ~~~shell $ STRIPE_WEBHOOK_SECRET=$(stripe listen --print-secret) npm run dev ~~~ 4. Go to [localhost:3000](http://localhost:3000) ### Production 1. Build the application ~~~shell $ npm install $ npm build ~~~ 2. Run the application ~~~shell $ npm start ~~~ ``` ## See Also #### [Fulfill orders](https://docs.stripe.com/checkout/fulfillment.md) Set up an event destination to fulfill orders after a payment succeeds and to handle other critical events. #### [Receive payouts](https://docs.stripe.com/payouts.md) Learn how to move funds out of your Stripe account into your bank account. #### [Refund and cancel payments](https://docs.stripe.com/refunds.md) Handle requests for refunds by using the Stripe API or Dashboard. #### [Customer management](https://docs.stripe.com/customer-management.md) Let your customers self-manage their payment details, invoices, and subscriptions. #### [Adaptive Pricing](https://docs.stripe.com/payments/checkout/adaptive-pricing.md) Automatically present prices in your customer’s local currency.