# Embedded form
# Embedded form
Explore a full, working code sample of an integration with [Stripe Checkout](https://docs.stripe.com/payments/checkout.md) that lets your customers pay through an embedded form on your website. The example includes client and server-side code, and an embeddable UI component displays the payment form.
### 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*, setting the [ui_mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-ui_mode) to `embedded`.
The Checkout Session response includes a client secret, which the client uses to mount Checkout. Return the [client_secret](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-client_secret) in your response.
### Create a Checkout Session
Add a [Server Action](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations) to your application that creates a *Checkout Session*, setting the [ui_mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-ui_mode) to `embedded`.
The Checkout Session response includes a client secret, which the client uses to mount Checkout. Return the [client_secret](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-client_secret) from the function.
### Supply a return URL
To define how Stripe redirects your customer after payment, specify the URL of the return page in the [return_url](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-return_url) parameter while creating the Checkout Session. After the payment attempt, Stripe directs your customer to return page hosted on your website.
Include the `{CHECKOUT_SESSION_ID}` template variable in the URL. Before redirecting your customer, Checkout replaces the variable with the Checkout Session ID. You’re responsible for creating and hosting the return page on your website.
### Define a product to sell
Define the products you’re selling when you create the Checkout Session by using [predefined price IDs](https://docs.stripe.com/payments/accept-a-payment.md?platform=web&ui=embedded-form#create-product-prices-upfront).
Always keep sensitive information about your product inventory, such as price and availability, on your server to prevent customer manipulation from the client.
### Choose the 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=embedded-form), switch the `mode` to `subscription`. And for [setting up future payments](https://docs.stripe.com/payments/save-and-reuse.md?platform=web&ui=embedded-form), set the `mode` to `setup`.
### Add Stripe to your React app
To stay *PCI compliant* by ensuring that payment details go directly to Stripe and never reach your server, install [React Stripe.js](https://docs.stripe.com/sdks/stripejs-react.md).
### Load Stripe.js
To configure the Stripe library, call `loadStripe()` with your Stripe publishable API key.
### Load Stripe.js
Use *Stripe.js* to remain *PCI compliant* by ensuring that payment details are sent directly to Stripe without hitting your server. Always load Stripe.js from _js.stripe.com_ to remain compliant. Don’t include the script in a bundle or host it yourself.
### Define the payment form
To securely collect the customer’s information, create an empty placeholder `div`. Stripe inserts an iframe into the `div`.
### Initialize Stripe.js
Initialize Stripe.js with your [publishable API key](https://docs.stripe.com/keys.md#obtain-api-keys).
### Fetch a Checkout Session client secret
Create an asynchronous `fetchClientSecret` function that makes a request to your server to [create a Checkout Session](https://docs.stripe.com/api/checkout/sessions/create.md) and retrieve the client secret.
### Fetch a Checkout Session client secret
Import the Server Action to [create a Checkout Session](https://docs.stripe.com/api/checkout/sessions/create.md) and retrieve the client secret, passing it to the [`fetchClientSecret`](https://docs.stripe.com/js/embedded_checkout/init#embedded_checkout_init-options-fetchClientSecret) parameter.
### Initialize Checkout
Initialize Checkout with your `fetchClientSecret` function and mount it to the placeholder `
` in your payment form. Checkout is rendered in an iframe that securely sends payment information to Stripe over an HTTPS connection.
Avoid placing Checkout within another iframe because some payment methods require redirecting to another page for payment confirmation.
### Initialize Checkout
To allow the child components to access the Stripe service via the embedded Checkout consumer, pass the resulting promise from `loadStripe` and the client secret as an `option` to the embedded Checkout provider.
### Create an endpoint to retrieve a Checkout Session
Add an endpoint to retrieve a Checkout Session status.
### Add a return page
To display order information to your customer, create a return page for the URL you provided as the Checkout Session `return_url`. Stripe redirects to this page after the customer completes the checkout.
### Add a return component
To display order information to your customer, add a new route and return component for the URL you provided as the Checkout Session `return_url`. Stripe redirects to this page after the customer completes the checkout.
### Add a return page
To display order information to your customer, add a file under `pages/` for the URL you provided as the Checkout Session `return_url`. Stripe redirects your customer to this page after they check out.
### Retrieve a Checkout session
As soon as your return page loads, immediately make a request to the endpoint on your server. Use the Checkout Session ID in the URL to retrieve the status of the Checkout Session.
### Handle session
Handle the result of the session by using its status:
- `complete`: The payment succeeded. Use the information from the Checkout Session to render a success page.
- `open`: The payment failed or was canceled. Remount Checkout so that your customer can try again.
### 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).
Each webhook endpoint has a unique signing secret. You can find the secret in the [Webhooks](https://dashboard.stripe.com/webhooks) tab in the Dashboard. If you’re testing locally with the Stripe CLI, you can also obtain it from the CLI output using the command `stripe listen`.
To include a webhook endpoint signing secret to listen to [events](https://docs.stripe.com/event-destinations.md), go to the [Event destinations](https://dashboard.stripe.com/webhooks) tab or use the [Stripe CLI](https://docs.stripe.com/stripe-cli.md).
### 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 pay button to complete the payment, which redirects you to the specified return page.
If you see the return page, and the payment in the list of [successful payments](https://dashboard.stripe.com/test/payments?status%5B0%5D=successful) in the Dashboard, your integration is successfully working. Use any of the following 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](https://docs.stripe.com/payments/checkout/customization.md) the appearance of the embedded form by:
- Adding your color theme and font in your [branding settings](https://dashboard.stripe.com/settings/branding/checkout).
- Using the [Checkout Sessions API](https://docs.stripe.com/api/checkout/sessions/create.md)to activate additional features, like collecting addresses and 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
Change the text of the submit button to `pay`, `donate`, or `book` by setting the [submit_type](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-submit_type). The default text is `pay`.
### 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`, which Checkout displays in a dropdown menu on the page.
### 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';
const YOUR_DOMAIN = 'http://localhost:3000';
app.post('/create-checkout-session', async (req, res) => {
const session = await stripe.checkout.sessions.create({
ui_mode: 'embedded',
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',
return_url: `${YOUR_DOMAIN}/return?session_id={CHECKOUT_SESSION_ID}`,
return_url: `${YOUR_DOMAIN}/return.html?session_id={CHECKOUT_SESSION_ID}`,
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.send({clientSecret: session.client_secret});
});
app.get('/session-status', async (req, res) => {
const session = await stripe.checkout.sessions.retrieve(req.query.session_id);
res.send({
status: session.status,
customer_email: session.customer_details.email
});
});
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'
YOUR_DOMAIN = 'http://localhost:3000'
post '/create-checkout-session' do
content_type 'application/json'
session = Stripe::Checkout::Session.create({
ui_mode: 'embedded',
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',
return_url: YOUR_DOMAIN + '/return.html?session_id={CHECKOUT_SESSION_ID}',
return_url: YOUR_DOMAIN + '/return?session_id={CHECKOUT_SESSION_ID}',
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}}'
})
{clientSecret: session.client_secret}.to_json
end
get '/session-status' do
session = Stripe::Checkout::Session.retrieve(params[:session_id])
{status: session.status, customer_email: session.customer_details.email}.to_json
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, jsonify, redirect, request
import stripe
stripe.api_key = '<>'
app = Flask(__name__,
static_url_path='',
static_folder='public')
YOUR_DOMAIN = 'http://localhost:4242'
YOUR_DOMAIN = 'http://localhost:3000'
@app.route('/create-checkout-session', methods=['POST'])
def create_checkout_session():
try:
session = stripe.checkout.Session.create(
ui_mode = 'embedded',
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',
return_url=YOUR_DOMAIN + '/return.html?session_id={CHECKOUT_SESSION_ID}',
return_url=YOUR_DOMAIN + '/return?session_id={CHECKOUT_SESSION_ID}',
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 jsonify(clientSecret=session.client_secret)
@app.route('/session-status', methods=['GET'])
def session_status():
session = stripe.checkout.Session.retrieve(request.args.get('session_id'))
return jsonify(status=session.status, customer_email=session.customer_details.email)
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
checkout->sessions->create([
'ui_mode' => 'embedded',
'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',
'return_url' => $YOUR_DOMAIN . '/return.html?session_id={CHECKOUT_SESSION_ID}',
'return_url' => $YOUR_DOMAIN . '/return?session_id={CHECKOUT_SESSION_ID}',
'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}}'
]);
echo json_encode(array('clientSecret' => $checkout_session->client_secret));
```
```php
checkout->sessions->retrieve($jsonObj->session_id);
echo json_encode(['status' => $session->status, 'customer_email' => $session->customer_details->email]);
http_response_code(200);
} catch (Error $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
```
```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 domain = "http://localhost:3000";
var options = new SessionCreateOptions
{
UiMode = "embedded",
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",
ReturnUrl = domain + "/return.html?session_id={CHECKOUT_SESSION_ID}",
ReturnUrl = domain + "/return?session_id={CHECKOUT_SESSION_ID}",
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);
return Json(new {clientSecret = session.ClientSecret});
}
}
[Route("session-status")]
[ApiController]
public class SessionStatusController : Controller
{
[HttpGet]
public ActionResult SessionStatus([FromQuery] string session_id)
{
var sessionService = new SessionService();
Session session = sessionService.Get(session_id);
return Json(new {status = session.Status, customer_email = session.CustomerDetails.Email});
}
}
}
```
```
net8.0StripeExampleMajor
```
```go
package main
import (
"bytes"
"encoding/json"
"io"
"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)
http.HandleFunc("/session-status", retrieveCheckoutSession)
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"
domain := "http://localhost:3000"
params := &stripe.CheckoutSessionParams{
UIMode: stripe.String("embedded"),
ReturnURL: stripe.String(domain + "/return.html?session_id={CHECKOUT_SESSION_ID}"),
ReturnURL: stripe.String(domain + "/return?session_id={CHECKOUT_SESSION_ID}"),
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)),
AutomaticTax: &stripe.CheckoutSessionAutomaticTaxParams{Enabled: stripe.Bool(true)},
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)
}
writeJSON(w, struct {
ClientSecret string `json:"clientSecret"`
}{
ClientSecret: s.ClientSecret,
})
}
func retrieveCheckoutSession(w http.ResponseWriter, r *http.Request) {
s, _ := session.Get(r.URL.Query().Get("session_id"), nil)
writeJSON(w, struct {
Status string `json:"status"`
CustomerEmail string `json:"customer_email"`
}{
Status: string(s.Status),
CustomerEmail: string(s.CustomerDetails.Email),
})
}
func writeJSON(w http.ResponseWriter, v interface{}) {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(v); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Printf("json.NewEncoder.Encode: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
if _, err := io.Copy(w, &buf); err != nil {
log.Printf("io.Copy: %v", err)
return
}
}
```
```
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 java.util.Map;
import java.util.HashMap;
import static spark.Spark.post;
import static spark.Spark.get;
import static spark.Spark.port;
import static spark.Spark.staticFiles;
import com.google.gson.Gson;
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());
Gson gson = new Gson();
post("/create-checkout-session", (request, response) -> {
String YOUR_DOMAIN = "http://localhost:4242";
String YOUR_DOMAIN = "http://localhost:3000";
SessionCreateParams params =
SessionCreateParams.builder()
.setUiMode(SessionCreateParams.UiMode.EMBEDDED)
.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)
.setReturnUrl(YOUR_DOMAIN + "/return?session_id={CHECKOUT_SESSION_ID}")
.setReturnUrl(YOUR_DOMAIN + "/return.html?session_id={CHECKOUT_SESSION_ID}")
.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);
Map map = new HashMap();
map.put("clientSecret", session.getRawJsonObject().getAsJsonPrimitive("client_secret").getAsString());
return map;
}, gson::toJson);
get("/session-status", (request, response) -> {
Session session = Session.retrieve(request.queryParams("session_id"));
Map map = new HashMap();
map.put("status", session.getRawJsonObject().getAsJsonPrimitive("status").getAsString());
map.put("customer_email", session.getRawJsonObject().getAsJsonObject("customer_details").getAsJsonPrimitive("email").getAsString());
return map;
}, gson::toJson);
}
}
```
```xml
4.0.0com.stripe.samplestripe-payment1.0.0-SNAPSHOTorg.slf4jslf4j-simple2.0.3com.sparkjavaspark-core2.9.4com.google.code.gsongson2.9.1org.projectlomboklombok1.18.20providedcom.stripestripe-java29.0.0sampleorg.apache.maven.pluginsmaven-compiler-plugin3.10.11.81.8maven-assembly-pluginpackagesinglejar-with-dependenciesServer
```
```html
Accept a payment
)
}
```
```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
import Checkout from './components/checkout'
export default function Page() {
return (
)
}
```
```jsx
import { redirect } from 'next/navigation'
import { stripe } from '../../lib/stripe'
export default async function Return({ 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 'server-only'
import Stripe from 'stripe'
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY)
```
```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 a webhook to fulfill orders after a payment succeeds. Webhooks are the most reliable way to handle business-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