Connect
Create a payments page

Create a payments page

Learn how to create a page to accept payments for your users.

You can create a payments page to accept payments for your users. Refer to your platform profile to determine if direct charges or destination charges is recommended for your business.

Use either Stripe Elements or Checkout to create your payments page. Stripe Elements is a set of prebuilt UI components, like inputs and buttons, for building your checkout flow. If you’d rather not build your own payment form, Checkout provides a Stripe-hosted page to accept payments for one-time purchases and subscriptions.

Destination charges

For demonstrative purposes, the platform will represent a home-rental marketplace that’s creating payments for homeowners renting their places. You can use destination charges in other applications as well.

What you're building

Step 1: Create a PaymentIntent Server-side

Stripe uses a PaymentIntent object to represent your intent to collect payment from a customer, tracking charge attempts and payment state changes throughout the process.

Create a PaymentIntent on your server with an amount and currency. Always decide how much to charge on the server side, a trusted environment, as opposed to the client. This prevents malicious customers from being able to choose their own prices.

curl https://api.stripe.com/v1/payment_intents \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d amount=1000 \ -d currency=usd \ -d application_fee_amount=123 \ -d "transfer_data[destination]"="{{CONNECTED_STRIPE_ACCOUNT_ID}}"
# 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' payment_intent = Stripe::PaymentIntent.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, transfer_data: { destination: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, })
# 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' payment_intent = stripe.PaymentIntent.create( payment_method_types=['card'], amount=1000, currency='usd', application_fee_amount=123, transfer_data={ 'destination': '{{CONNECTED_STRIPE_ACCOUNT_ID}}', } )
// 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'); $payment_intent = \Stripe\PaymentIntent::create([ 'payment_method_types' => ['card'], 'amount' => 1000, 'currency' => 'usd', 'application_fee_amount' => 123, 'transfer_data' => [ 'destination' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}', ], ]);
// 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"; ArrayList paymentMethodTypes = new ArrayList(); paymentMethodTypes.add("card"); Map<String, Object> params = new HashMap<>(); params.put("payment_method_types", paymentMethodTypes); params.put("amount", 1000); params.put("currency", "usd"); params.put("application_fee_amount", 123); Map<String, Object> transferDataParams = new HashMap<>(); transferDataParams.put("destination", "{{CONNECTED_STRIPE_ACCOUNT_ID}}"); params.put("transfer_data", transferDataParams); PaymentIntent paymentIntent = PaymentIntent.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 paymentIntent = await stripe.paymentIntents.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, transfer_data: { destination: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, });
// 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.PaymentIntentParams{ PaymentMethodTypes: stripe.StringSlice([]string{ "card", }), Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), ApplicationFeeAmount: stripe.Int64(123), TransferData: &stripe.PaymentIntentTransferDataParams{ Destination: stripe.String("{{CONNECTED_STRIPE_ACCOUNT_ID}}"), }, } pi, _ := paymentintent.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 service = new PaymentIntentService(); var createOptions = new PaymentIntentCreateOptions { PaymentMethodTypes = new List<string> { "card", }, Amount = 2000, Currency = "usd", ApplicationFeeAmount = 123, TransferData = new PaymentIntentTransferDataOptions { Destination = "{{CONNECTED_STRIPE_ACCOUNT_ID}}", }, }; service.Create(createOptions);

In our home-rental example, we want to build an experience where customers pay for rentals by using our platform, and where we pay homeowners for renting to customers. To set this experience up:

  • Indicate the rental is a destination charge with transfer_data[destination].
  • Specify how much of the rental amount will go to the platform with application_fee_amount.

When a rental charge occurs, Stripe transfers the entire amount to the connected account’s pending balance (transfer_data[destination]). Afterward, Stripe transfers the fee amount (application_fee_amount) to the platform’s account, which is the share of the revenue for facilitating the rental. Then, Stripe deducts the Stripe fees from the platform’s fee amount. An illustration of this funds flow is below:

Included in the returned PaymentIntent is a client secret, which is used on the client side to securely complete the payment process instead of passing the entire PaymentIntent object. There are different approaches that you can use to pass the client secret to the client side.

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

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

This example demonstrates how to fetch the client secret with JavaScript on the client side:

var response = fetch('/secret').then(function(response) { return response.json(); }).then(function(responseJson) { var clientSecret = responseJson.client_secret; // Call stripe.confirmCardPayment() with the client secret. });
(async () => { const response = await fetch('/secret'); const {client_secret: clientSecret} = await response.json(); // Call stripe.confirmCardPayment() with the client secret. })();

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

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

Stripe uses a PaymentIntent object to represent your intent to collect payment from a customer, tracking charge attempts and payment state changes throughout the process.

Create a PaymentIntent on your server with an amount and currency. Always decide how much to charge on the server side, a trusted environment, as opposed to the client. This prevents malicious customers from being able to choose their own prices.

curl https://api.stripe.com/v1/payment_intents \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d amount=1000 \ -d currency=usd \ -d application_fee_amount=123 \ -d on_behalf_of="{{CONNECTED_STRIPE_ACCOUNT_ID}}" \ -d "transfer_data[destination]"="{{CONNECTED_STRIPE_ACCOUNT_ID}}"
# 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' payment_intent = Stripe::PaymentIntent.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, on_behalf_of: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', transfer_data: { destination: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, })
# 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' payment_intent = stripe.PaymentIntent.create( payment_method_types=['card'], amount=1000, currency='usd', application_fee_amount=123, on_behalf_of='{{CONNECTED_STRIPE_ACCOUNT_ID}}', transfer_data={ 'destination': '{{CONNECTED_STRIPE_ACCOUNT_ID}}', } )
// 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'); $payment_intent = \Stripe\PaymentIntent::create([ 'payment_method_types' => ['card'], 'amount' => 1000, 'currency' => 'usd', 'application_fee_amount' => 123, 'on_behalf_of' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}', 'transfer_data' => [ 'destination' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}', ], ]);
// 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"; ArrayList paymentMethodTypes = new ArrayList(); paymentMethodTypes.add("card"); Map<String, Object> params = new HashMap<>(); params.put("payment_method_types", paymentMethodTypes); params.put("amount", 1000); params.put("currency", "usd"); params.put("application_fee_amount", 123); params.put("on_behalf_of", "{{CONNECTED_STRIPE_ACCOUNT_ID}}"); Map<String, Object> transferDataParams = new HashMap<>(); transferDataParams.put("destination", "{{CONNECTED_STRIPE_ACCOUNT_ID}}"); params.put("transfer_data", transferDataParams); PaymentIntent paymentIntent = PaymentIntent.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 paymentIntent = await stripe.paymentIntents.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, on_behalf_of: '{{CONNECTED_STRIPE_ACCOUNT_ID}}' transfer_data: { destination: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, });
// 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.PaymentIntentParams{ PaymentMethodTypes: stripe.StringSlice([]string{ "card", }), Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), ApplicationFeeAmount: stripe.Int64(123), OnBehalfOf: stripe.String("{{CONNECTED_STRIPE_ACCOUNT_ID}}"), TransferData: &stripe.PaymentIntentTransferDataParams{ Destination: stripe.String("{{CONNECTED_STRIPE_ACCOUNT_ID}}"), }, } pi, _ := paymentintent.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 service = new PaymentIntentService(); var createOptions = new PaymentIntentCreateOptions { PaymentMethodTypes = new List<string> { "card", }, Amount = 2000, Currency = "usd", ApplicationFeeAmount = 123, OnBehalfOf = "{{CONNECTED_STRIPE_ACCOUNT_ID}}", TransferData = new PaymentIntentTransferDataOptions { Destination = "{{CONNECTED_STRIPE_ACCOUNT_ID}}", }, }; service.Create(createOptions);

Included in the returned PaymentIntent is a client secret, which is used on the client side to securely complete the payment process instead of passing the entire PaymentIntent object. There are different approaches that you can use to pass the client secret to the client side.

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

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

This example demonstrates how to fetch the client secret with JavaScript on the client side:

var response = fetch('/secret').then(function(response) { return response.json(); }).then(function(responseJson) { var clientSecret = responseJson.client_secret; // Call stripe.confirmCardPayment() with the client secret. });
(async () => { const response = await fetch('/secret'); const {client_secret: clientSecret} = await response.json(); // Call stripe.confirmCardPayment() with the client secret. })();

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

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

Step 2: Collect card details Client-side

You’re ready to collect card information on the client with Stripe Elements. Elements is a set of prebuilt UI components for collecting and validating card number, ZIP code, and expiration date.

A Stripe Element contains an iframe that securely sends the payment information to Stripe over a HTTPS connection. The checkout page address must also start with https:// rather than http:// for your integration to work.

You can test your integration without using HTTPS. Enable it when you’re ready to accept live payments.

Set up Stripe Elements

Stripe Elements is automatically available as a feature of Stripe.js. Include the Stripe.js script on your checkout page by adding it to the head of your HTML file. Always load Stripe.js directly from js.stripe.com to remain PCI compliant. Do not include the script in a bundle or host a copy of it yourself.

<head> <title>Checkout</title> <script src="https://js.stripe.com/v3/"></script> </head>

Create an instance of Elements with the following JavaScript on your checkout page:

// Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/account/apikeys var stripe = Stripe('pk_test_TYooMQauvdEDq54NiTphI7jx'); var elements = stripe.elements();

Add Elements to your payment page

Elements needs a place to live in your payment form. Create empty DOM nodes (containers) with unique IDs in your payment form and then pass those IDs to Elements.

<form id="payment-form"> <div id="card-element"> <!-- Elements will create input elements here --> </div> <!-- We'll put the error messages in this element --> <div id="card-errors" role="alert"></div> <button id="submit">Pay</button> </form>

When the form above has loaded, create an instance of an Element and mount it to the Element container:

// Set up Stripe.js and Elements to use in checkout form var elements = stripe.elements(); var style = { base: { color: "#32325d", } }; var card = elements.create("card", { style: style }); card.mount("#card-element");

The card Element simplifies the form and minimizes the number of required fields by inserting a single, flexible input field that securely collects all necessary card and billing details. Otherwise, combine cardNumber, cardExpiry, and cardCvc Elements for a flexible, multi-input card form.

For a full list of supported Element types, refer to our Stripe.js reference documentation.

Elements validates user input as it is typed. To help your customers catch mistakes, listen to change events on the card Element and display any errors:

card.on('change', ({error}) => { const displayError = document.getElementById('card-errors'); if (error) { displayError.textContent = error.message; } else { displayError.textContent = ''; } });
cardElement.on('change', function(event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } });

Postal code validation depends on your customer’s billing country. Use our international test cards to experiment with other postal code formats.

Install React Stripe.js and the Stripe.js loader from the npm public registry.

npm install --save @stripe/react-stripe-js @stripe/stripe-js

We also provide a UMD build for sites that do not use npm or modules.

Include the Stripe.js script, which exports a global Stripe function, and the UMD build of React Stripe.js, which exports a global ReactStripe object. Always load the Stripe.js script directly from js.stripe.com to remain PCI compliant. Do not include the script in a bundle or host a copy of it yourself.

<!-- Stripe.js --> <script src="https://js.stripe.com/v3/"></script> <!-- React Stripe.js development build --> <script src="https://unpkg.com/@stripe/react-stripe-js@latest/dist/react-stripe.umd.js"></script> <!-- When you are ready to deploy your site to production, remove the above development script, and include the following production build. --> <script src="https://unpkg.com/@stripe/react-stripe-js@latest/dist/react-stripe.umd.min.js"></script>

Add Stripe.js and Elements to your page

To use Element components, wrap the root of your React app in an Elements provider. Call loadStripe with your publishable key and pass the returned Promise to the Elements provider.

import React from 'react'; import ReactDOM from 'react-dom'; import {Elements} from '@stripe/react-stripe-js'; import {loadStripe} from '@stripe/stripe-js'; import CheckoutForm from './CheckoutForm'; // 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() { return ( <Elements stripe={stripePromise}> <CheckoutForm /> </Elements> ); }; ReactDOM.render(<App />, document.getElementById('root'));

Add and configure a CardElement component

Use individual Element components, such as CardElement, to build your form.

/** * Use the CSS tab above to style your Element's container. */ import React from 'react'; import {CardElement} from '@stripe/react-stripe-js'; import './CardSectionStyles.css' const CARD_ELEMENT_OPTIONS = { style: { base: { color: "#32325d", fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: "antialiased", fontSize: "16px", "::placeholder": { color: "#aab7c4", }, }, invalid: { color: "#fa755a", iconColor: "#fa755a", }, }, }; function CardSection() { return ( <label> Card details <CardElement options={CARD_ELEMENT_OPTIONS} /> </label> ); }; export default CardSection;
/** * Shows how you can use CSS to style your Element's container. * These classes are added to your Stripe Element by default. * You can override these classNames by using the options passed * to the CardElement component. * https://stripe.com/docs/js/elements_object/create_element?type=card#elements_create-options-classes */ .StripeElement { height: 40px; padding: 10px 12px; width: 100%; color: #32325d; background-color: white; border: 1px solid transparent; border-radius: 4px; box-shadow: 0 1px 3px 0 #e6ebf1; -webkit-transition: box-shadow 150ms ease; transition: box-shadow 150ms ease; } .StripeElement--focus { box-shadow: 0 1px 3px 0 #cfd7df; } .StripeElement--invalid { border-color: #fa755a; } .StripeElement--webkit-autofill { background-color: #fefde5 !important; }

Elements are completely customizable. You can style Elements to match the look and feel of your site, providing a seamless checkout experience for your customers. It’s also possible to style various input states, for example when the Element has focus.

The CardElement simplifies the form and minimizes the number of required fields by inserting a single, flexible input field that securely collects all necessary card and billing details. Otherwise, combine CardNumberElement, CardExpiryElement, and CardCvcElement elements for a flexible, multi-input card form.

Step 3: Submit the payment to Stripe Client-side

Rather than sending the entire PaymentIntent object to the client, use its client secret from Step 1. This is different from your API keys that authenticate Stripe API requests.

The client secret should still be handled carefully because it can complete the charge. Do not log it, embed it in URLs, or expose it to anyone but the customer.

To complete the payment when the user clicks, retrieve the client secret from the PaymentIntent you created in step 1 and call stripe.confirmCardPayment with the client secret.

Pass additional billing details, such as the cardholder name and address, to the billing_details hash. The card Element automatically sends the customer’s postal code information. However, combining cardNumber, cardCvc, and cardExpiry Elements requires you to pass the postal code to billing_details[address][postal_code].

var form = document.getElementById('payment-form'); form.addEventListener('submit', function(ev) { ev.preventDefault(); stripe.confirmCardPayment(clientSecret, { payment_method: { card: card, billing_details: { name: 'Jenny Rosen' } } }).then(function(result) { if (result.error) { // Show error to your customer (e.g., insufficient funds) console.log(result.error.message); } else { // The payment has been processed! if (result.paymentIntent.status === 'succeeded') { // Show a success message to your customer // There's a risk of the customer closing the window before callback // execution. Set up a webhook or plugin to listen for the // payment_intent.succeeded event that handles any business critical // post-payment actions. } } }); });

If the customer must authenticate the card, Stripe.js walks them through that process by showing them a modal. You can see an example of this modal experience by using the test card number 4000 0025 0000 3155 with any CVC, future expiration date, and postal code in the demo at the top of the page.

When the payment completes successfully, the value of the returned PaymentIntent’s status property is succeeded. Check the status of a PaymentIntent in the Dashboard or by inspecting the status property on the object. If the payment is not successful, inspect the returned error to determine the cause.

To complete the payment when the user clicks, retrieve the client secret from the PaymentIntent you created in step two and call stripe.confirmCardPayment with the client secret and the Element. Pass additional billing details, such as the cardholder name and address, to the billing_details hash.

To call stripe.confirmCardPayment from your payment form component, use the useStripe and useElements hooks.

If you prefer traditional class components over hooks, you can instead use an ElementsConsumer.

import React from 'react'; import {useStripe, useElements, CardElement} from '@stripe/react-stripe-js'; import CardSection from './CardSection'; export default function CheckoutForm() { const stripe = useStripe(); const elements = useElements(); const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe || !elements) { // Stripe.js has not yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const result = await stripe.confirmCardPayment('{CLIENT_SECRET}', { payment_method: { card: elements.getElement(CardElement), billing_details: { name: 'Jenny Rosen', }, } }); if (result.error) { // Show error to your customer (e.g., insufficient funds) console.log(result.error.message); } else { // The payment has been processed! if (result.paymentIntent.status === 'succeeded') { // Show a success message to your customer // There's a risk of the customer closing the window before callback // execution. Set up a webhook or plugin to listen for the // payment_intent.succeeded event that handles any business critical // post-payment actions. } } }; return ( <form onSubmit={handleSubmit}> <CardSection /> <button disabled={!stripe}>Confirm order</button> </form> ); }
import React from 'react'; import {ElementsConsumer, CardElement} from '@stripe/react-stripe-js'; import CardSection from './CardSection'; class CheckoutForm extends React.Component { handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); const {stripe, elements} = this.props if (!stripe || !elements) { // Stripe.js has not yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const result = await stripe.confirmCardPayment('{CLIENT_SECRET}', { payment_method: { card: elements.getElement(CardElement), billing_details: { name: 'Jenny Rosen', }, } }); if (result.error) { // Show error to your customer (e.g., insufficient funds) console.log(result.error.message); } else { // The payment has been processed! if (result.paymentIntent.status === 'succeeded') { // Show a success message to your customer // There's a risk of the customer closing the window before callback // execution. Set up a webhook or plugin to listen for the // payment_intent.succeeded event that handles any business critical // post-payment actions. } } }; render() { return ( <form onSubmit={this.handleSubmit}> <CardSection /> <button disabled={!this.props.stripe}>Confirm order</button> </form> ); } } export default function InjectedCheckoutForm() { return ( <ElementsConsumer> {({stripe, elements}) => ( <CheckoutForm stripe={stripe} elements={elements} /> )} </ElementsConsumer> ); }

If the customer must authenticate the card, Stripe.js walks them through that process by showing them a modal. You can see an example of this modal experience by using the test card number 4000 0025 0000 3155 with any CVC, future expiration date, and postal code in the demo at the top of the page.

When the payment completes successfully, the value of the returned PaymentIntent’s status property is succeeded. Check the status of a PaymentIntent in the Dashboard or by inspecting the status property on the object. If the payment is not successful, inspect the returned error to determine the cause.

Step 4: Fulfillment Server-side

After the payment is completed, you’ll need to handle any fulfillment necessary on your end. A home-rental company that requires payment upfront, for instance, would connect the homeowner with the renter after a successful payment.

Configure a webhook endpoint (for events from your account) in your dashboard.

Then create an HTTP endpoint on your server to monitor for completed payments to then enable your sellers or service providers to fulfill purchases.

# Using Sinatra. require 'sinatra' require 'stripe' set :port, 4242 # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' post '/webhook' do payload = request.body.read sig_header = request.env['HTTP_STRIPE_SIGNATURE'] event = nil # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. begin event = Stripe::Webhook.construct_event( payload, sig_header, webhook_secret ) rescue JSON::ParserError => e # Invalid payload. status 400 return rescue Stripe::SignatureVerificationError => e # Invalid Signature. status 400 return end if event['type'] == 'payment_intent.succeeded' payment_intent = event['data']['object'] handle_successful_payment_intent(payment_intent) end status 200 end def handle_successful_payment_intent(payment_intent) # Fulfill the purchase. puts payment_intent.to_s end
import stripe import json # Using Flask. from flask import ( Flask, render_template, request, Response, ) app = Flask(__name__, static_folder=".", static_url_path="", template_folder=".") # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' @app.route("/webhook", methods=["POST"]) def webhook_received(): request_data = json.loads(request.data) signature = request.headers.get("stripe-signature") # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. try: event = stripe.Webhook.construct_event( payload=request.data, sig_header=signature, secret=webhook_secret ) except ValueError as e: # Invalid payload. return Response(status=400) except stripe.error.SignatureVerificationError as e: # Invalid Signature. return Response(status=400) if event["type"] == "payment_intent.succeeded": payment_intent = event["data"]["object"] handle_successful_payment_intent(payment_intent) return json.dumps({"success": True}), 200 def handle_successful_payment_intent(payment_intent): # Fulfill the purchase. print(str( payment_intent)) if __name__ == "__main__": app.run(port=4242)
<?php // Using Slim. use Slim\Http\Request; use Slim\Http\Response; use Stripe\Stripe; require_once('vendor/autoload.php'); $app = new \Slim\App; // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // $webhook_secret = 'whsec_...'; $app->post('/webhook', function ($request, $response, $next) { $payload = $request->getBody(); $sig_header = $request->getHeaderLine('stripe-signature'); $event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { $event = \Stripe\Webhook::constructEvent( $payload, $sig_header, $webhook_secret ); } catch(\UnexpectedValueException $e) { // Invalid payload. return $response->withStatus(400); } catch(\Stripe\Exception\SignatureVerificationException $e) { // Invalid Signature. return $response->withStatus(400); } if ($event->type == 'payment_intent.succeeded') { $paymentIntent = $event->data->object; handleSuccessfulPaymentIntent($paymentIntent); } return $response->withStatus(200); }); function handleSuccessfulPaymentIntent($paymentIntent) { // Fulfill the purchase. echo $paymentIntent; }; $app->run();
// Using Express const express = require('express'); const bodyParser = require("body-parser"); const app = express(); app.use(express.json()); // Use JSON parser for all non-webhook routes app.use((req, res, next) => { if (req.originalUrl === "/webhook") { next(); } else { bodyParser.json()(req, res, next); } }); // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const webhook_secret = 'whsec_...'' app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => { const sig = request.headers['stripe-signature']; let event; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = stripe.webhooks.constructEvent(request.body, sig, webhook_secret); } catch (err) { return response.status(400).send(`Webhook Error: ${err.message}`); } if (event.type === 'payment_intent.succeeded') { const paymentIntent = event.data.object; handleSuccessfulPaymentIntent(paymentIntent); } response.json({received: true}); }); const handleSuccessfulPaymentIntent = (paymentIntent) => { // Fulfill the purchase. console.log(JSON.stringify(paymentIntent)); } app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
package com.stripe.sample; import com.stripe.Stripe; import com.stripe.model.PaymentIntent; import com.stripe.model.Event; import com.stripe.model.EventDataObjectDeserializer; import com.stripe.exception.SignatureVerificationException; import com.stripe.net.Webhook; import com.google.gson.JsonSyntaxException; import spark.Response; // Using Spark. import static spark.Spark.*; public class Server { public static void main(String[] args) { port(4242); // 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"; post("/webhook", (request, response) -> { String payload = request.body(); String sigHeader = request.headers("Stripe-Signature"); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // String webhookSecret = "whsec_..." Event event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = Webhook.constructEvent( payload, sigHeader, webhookSecret ); } catch (JsonSyntaxException e) { // Invalid payload. response.status(400); return ""; } catch (SignatureVerificationException e) { // Invalid Signature. response.status(400); return ""; } if ("payment_intent.succeeded".equals(event.getType())) { // Deserialize the nested object inside the event EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer(); PaymentIntent paymentIntent = null; if (dataObjectDeserializer.getObject().isPresent()) { paymentIntent = (PaymentIntent) dataObjectDeserializer.getObject().get(); handleSuccessfulPaymentIntent(paymentIntent); } else { // Deserialization failed, probably due to an API version mismatch. // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for // instructions on how to handle this case, or return an error here. } } response.status(200); return ""; }); } private static void handleSuccessfulPaymentIntent(PaymentIntent paymentIntent) { // Fulfill the purchase. System.out.println(paymentIntent.getId()); } }
package main import ( "encoding/json" "log" "fmt" "net/http" "io/ioutil" "github.com/stripe/stripe-go/v71" "github.com/stripe/stripe-go/v71/webhook" "os" ) func main() { // 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", handleWebhook) addr := "localhost:4242" log.Printf("Listening on %s ...", addr) log.Fatal(http.ListenAndServe(addr, nil)) } func handleWebhook(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 } // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // webhookSecret := "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. event, err := webhook.ConstructEvent(body, req.Header.Get("Stripe-Signature"), webhookSecret) 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 } if event.Type == "payment_intent.succeeded" { var paymentIntent stripe.PaymentIntent err := json.Unmarshal(event.Data.Raw, &paymentIntent) if err != nil { fmt.Fprintf(os.Stderr, "Error parsing webhook JSON: %v\n", err) w.WriteHeader(http.StatusBadRequest) return } handleSuccessfulPaymentIntent(paymentIntent) } w.WriteHeader(http.StatusOK) } func handleSuccessfulPaymentIntent(paymentIntent stripe.PaymentIntent) { // Fulfill the purchase. log.Println(paymentIntent.ID) }
// 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 System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Stripe; namespace Controllers { public class ConnectController : Controller { private readonly ILogger<ConnectController> logger; public ConnectController( ILogger<ConnectController> logger, ) { this.logger = logger; } [HttpPost("webhook")] public async Task<IActionResult> ProcessWebhookEvent() { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const string webhookSecret = "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], webhookSecret); if (stripeEvent.Type == Events.PaymentIntentSucceeded) { var paymentIntent = stripeEvent.Data.Object as PaymentIntent; HandleSuccessfulPaymentIntent(paymentIntent); } return Ok(); } catch (Exception e) { logger.LogInformation(e.ToString()); return BadRequest(); } } // Fulfill the purchase. private void HandleSuccessfulPaymentIntent(PaymentIntent paymentIntent) { logger.LogInformation($"{paymentIntent}"); } } }

Learn more in our fulfillment guide for payments.

Testing webhooks locally

Testing webhooks locally is easy with the Stripe CLI.

  1. First, install the Stripe CLI on your machine if you haven’t already.

  2. Then, to log in run stripe login in the command line, and follow the instructions.

  3. Finally, to allow your local host to receive a simulated event on your connected account run stripe listen --forward-to localhost:{PORT}/webhook in one terminal window, and run stripe trigger payment_intent.succeeded (or trigger any other supported event) in another.

Step 5: Disputes

As the settlement merchant on charges, your platform is responsible for disputes. Make sure you understand the best practices for responding to disputes.

What you're building

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

Step 1: Create a Checkout session Server-side

On your server, make the following call to Stripe’s API:

curl https://api.stripe.com/v1/checkout/sessions \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d "line_items[][name]"="Kavholm rental" \ -d "line_items[][amount]"=1000 \ -d "line_items[][currency]"=usd \ -d "line_items[][quantity]"=1 \ -d "payment_intent_data[application_fee_amount]"=123 \ -d "payment_intent_data[transfer_data][destination]"="{{CONNECTED_STRIPE_ACCOUNT_ID}}" \ -d success_url="https://example.com/success" \ -d cancel_url="https://example.com/failure"
# 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: [{ name: 'Kavholm rental', amount: 1000, currency: 'usd', quantity: 1, }], payment_intent_data: { application_fee_amount: 123, transfer_data: { destination: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, }, success_url: 'https://example.com/success', cancel_url: 'https://example.com/failure', })
# 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=[{ 'name': 'Kavholm rental', 'amount': 1000, 'currency': 'usd', 'quantity': 1, }], payment_intent_data={ 'application_fee_amount': 123, 'transfer_data': { 'destination': '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, }, success_url='https://example.com/success', cancel_url='https://example.com/failure', )
// 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' => [[ 'name' => 'Kavholm rental', 'amount' => 1000, 'currency' => 'usd', 'quantity' => 1, ]], 'payment_intent_data' => [ 'application_fee_amount' => 123, 'transfer_data' => [ 'destination' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}', ], ], 'success_url' => 'https://example.com/success', 'cancel_url' => 'https://example.com/failure', ]);
// 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: [{ name: 'Kavholm rental', amount: 1000, currency: 'usd', quantity: 1, }], payment_intent_data: { application_fee_amount: 123, transfer_data: { destination: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, }, success_url: 'https://example.com/success', cancel_url: 'https://example.com/failure', });
// 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("name", "Kavholm rental"); lineItem.put("amount", 1000); lineItem.put("currency", "usd"); lineItem.put("quantity", 1); lineItems.add(lineItem); params.put("line_items", lineItems); HashMap<String, Object> paymentIntentData = new HashMap<String, Object>(); paymentIntentData.put("application_fee_amount", 123); HashMap<String, Object> transferData = new HashMap<String, Object>(); transferData.put("destination", "{{CONNECTED_STRIPE_ACCOUNT_ID}}"); paymentIntentData.put("transfer_data", transferData); params.put("payment_intent_data", paymentIntentData); params.put("success_url", "https://example.com/success"); params.put("cancel_url", "https://example.com/failure"); Session session = Session.create(params, requestOptions);
// 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{ Name: stripe.String("Kavholm rental"), Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), Quantity: stripe.Int64(1), }, }, PaymentIntentData: &stripe.CheckoutSessionPaymentIntentDataParams{ ApplicationFeeAmount: stripe.Int64(123), TransferData: &stripe.CheckoutSessionPaymentIntentDataTransferDataParams{ Destination: stripe.String("{{CONNECTED_STRIPE_ACCOUNT_ID}}"), }, }, SuccessURL: stripe.String("https://example.com/success"), CancelURL: stripe.String("https://example.com/failure"), } 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 { Name = "Kavholm rental", Amount = 1000, Currency = "usd", Quantity = 1, }, }, PaymentIntentData = new SessionPaymentIntentDataOptions { ApplicationFeeAmount = 123, TransferData = new SessionPaymentIntentDataTransferDataOptions { Destination = "{{CONNECTED_STRIPE_ACCOUNT_ID}}", }, }, SuccessUrl = "https://example.com/success", CancelUrl = "https://example.com/failure", }; var service = new SessionService(); Session session = service.Create(options);

This returns a Checkout Session object with an id attribute that’s needed on the client side.

  • payment_intent_data[transfer_data][destination] - This argument indicates that this is a destination charge. A destination charge means the charge is processed on the platform and then the funds are immediately and automatically transferred to the connected account’s pending balance. For our home-rental example, we want to build an experience where the customer pays through the platform and the homeowner gets paid by the platform.
  • line_items - This argument represents the items the customer is purchasing. The items are displayed in the Stripe-hosted user interface.
  • success_url - This argument redirects a user after they complete a payment.
  • cancel_url - This argument redirects a user after they click cancel.
  • payment_intent_data[application_fee_amount] - This argument specifies the amount your platform plans to take from the transaction. The full charge amount is immediately transferred from the platform to the connected account that’s specified by transfer_data[destination] after the charge is captured. The application_fee_amount is then transferred back to the platform, and the Stripe fee is deducted from the platform’s amount.

You can also create a destination charge with the on_behalf_of parameter set to the connected account ID (by default, it is the platform). The on_behalf_of parameter determines the settlement merchant, which affects:

  • Whose statement descriptor the end user sees
  • Whose address and phone number the end user sees
  • The settlement currency of the charge

On your server, make the following call to Stripe’s API:

curl https://api.stripe.com/v1/checkout/sessions \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d "line_items[][name]"="Kavholm rental" \ -d "line_items[][amount]"=1000 \ -d "line_items[][currency]"=usd \ -d "line_items[][quantity]"=1 \ -d "payment_intent_data[application_fee_amount]"=123 \ -d "payment_intent_data[on_behalf_of]"="{{CONNECTED_STRIPE_ACCOUNT_ID}}" \ -d "payment_intent_data[transfer_data][destination]"="{{CONNECTED_STRIPE_ACCOUNT_ID}}" \ -d success_url="https://example.com/success" \ -d cancel_url="https://example.com/failure"
# 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: [{ name: 'Kavholm rental', amount: 1000, currency: 'usd', quantity: 1, }], payment_intent_data: { application_fee_amount: 123, on_behalf_of: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', transfer_data: { destination: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, }, success_url: 'https://example.com/success', cancel_url: 'https://example.com/failure', })
# 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=[{ 'name': 'Kavholm rental', 'amount': 1000, 'currency': 'usd', 'quantity': 1, }], payment_intent_data={ 'application_fee_amount': 123, 'on_behalf_of': '{{CONNECTED_STRIPE_ACCOUNT_ID}}', 'transfer_data': { 'destination': '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, }, success_url='https://example.com/success', cancel_url='https://example.com/failure', )
// 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' => [[ 'name' => 'Kavholm rental', 'amount' => 1000, 'currency' => 'usd', 'quantity' => 1, ]], 'payment_intent_data' => [ 'application_fee_amount' => 123, 'on_behalf_of' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}', 'transfer_data' => [ 'destination' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}', ], ], 'success_url' => 'https://example.com/success', 'cancel_url' => 'https://example.com/failure', ]);
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.apiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; SessionCreateParams params = SessionCreateParams.builder() .addPaymentMethodType(SessionCreateParams.PaymentMethodType.CARD) .addLineItem( SessionCreateParams.LineItem.builder() .setName("Kavholm rental") .setAmount(1000L) .setCurrency("usd") .setQuantity(1L) .build()) .setPaymentIntentData( SessionCreateParams.PaymentIntentData.builder() .setApplicationFeeAmount(123L) .setOnBehalfOf("{{CONNECTED_STRIPE_ACCOUNT_ID}}") .setTransferData( SessionCreateParams.PaymentIntentData.TransferData.builder() .setDestination("{{CONNECTED_STRIPE_ACCOUNT_ID}}") .build()) .build()) .setSuccessUrl("https://example.com/success") .setCancelUrl("https://example.com/cancel") .build(); Session session = Session.create(params);
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys const stripe = require('stripe')('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], line_items: [{ name: "Kavholm rental", amount: 1000, currency: 'usd', quantity: 1, }], payment_intent_data: { application_fee_amount: 123, on_behalf_of: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', transfer_data: { destination: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, }, success_url: 'https://example.com/success', cancel_url: 'https://example.com/failure', });
// 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{ Name: stripe.String("Kavholm rental"), Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), Quantity: stripe.Int64(1), }, }, PaymentIntentData: &stripe.CheckoutSessionPaymentIntentDataParams{ ApplicationFeeAmount: stripe.Int64(123), OnBehalfOf: stripe.String("{{CONNECTED_STRIPE_ACCOUNT_ID}}"), TransferData: &stripe.CheckoutSessionPaymentIntentDataTransferDataParams{ Destination: stripe.String("{{CONNECTED_STRIPE_ACCOUNT_ID}}"), }, }, SuccessURL: stripe.String("https://example.com/success"), CancelURL: stripe.String("https://example.com/failure"), } 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 { Name = "Kavholm rental", Amount = 1000, Currency = "usd", Quantity = 1, }, }, PaymentIntentData = new SessionPaymentIntentDataOptions { ApplicationFeeAmount = 123, OnBehalfOf = "{{CONNECTED_STRIPE_ACCOUNT_ID}}", TransferData = new SessionPaymentIntentDataTransferDataOptions { Destination = "{{CONNECTED_STRIPE_ACCOUNT_ID}}", }, }, SuccessUrl = "https://example.com/success", CancelUrl = "https://example.com/failure", }; var service = new SessionService(); Session session = service.Create(options);

This returns a Checkout Session object with an id attribute that’s needed on the client side.

  • payment_intent_data[on_behalf_of] - This argument determines the settlement merchant, which is by default the platform if the parameter isn’t passed in.
  • payment_intent_data[transfer_data][destination] - This argument indicates that this is a destination charge. A destination charge means the charge is processed on the platform and then the funds are immediately and automatically transferred to the connected account’s pending balance. For our ride-hailing example, we want to build an experience where the customer pays through the platform and the driver gets paid by the platform.
  • line_items - This argument represents the items the customer is purchasing. The items are displayed in the Stripe-hosted user interface.
  • success_url - This argument redirects a user after they complete a payment.
  • cancel_url - This argument redirects a user after they click cancel.
  • payment_intent_data[application_fee_amount] - This argument specifies the amount your platform plans to take from the transaction. The full charge amount is immediately transferred from the platform to the connected account that’s specified by transfer_data[destination] after the charge is captured. The application_fee_amount is then transferred back to the platform, and the Stripe fee is deducted from the platform’s amount.

Step 2: Add a checkout button Client-side

On your checkout page, include the Stripe.js script by adding it to the head of your HTML file.

<head> <title>Checkout</title> <script src="https://js.stripe.com/v3/"></script> </head>

Fetch the Session ID from your server. Add a button to your client with a click handler that calls Stripe’s frontend API:

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

You can customize your branding settings.

Step 3: Fulfillment Server-side

After the payment is completed, you’ll need to handle any fulfillment necessary on your end. A home-rental company that requires payment upfront, for instance, would connect the homeowner with the renter after a successful payment.

Configure a webhook endpoint (for events from your account) in your dashboard.

Then create an HTTP endpoint on your server to monitor for completed payments to then enable your sellers or service providers to fulfill purchases.

# Using Sinatra. require 'sinatra' require 'stripe' set :port, 4242 # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' post '/webhook' do payload = request.body.read sig_header = request.env['HTTP_STRIPE_SIGNATURE'] event = nil # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. begin event = Stripe::Webhook.construct_event( payload, sig_header, webhook_secret ) rescue JSON::ParserError => e # Invalid payload. status 400 return rescue Stripe::SignatureVerificationError => e # Invalid Signature. status 400 return end if event['type'] == 'checkout.session.completed' session = event['data']['object'] handle_completed_checkout_session(session) end status 200 end def handle_completed_checkout_session(session) # Fulfill the purchase. puts session.to_s end
import stripe import json # Using Flask. from flask import ( Flask, render_template, request, Response, ) app = Flask(__name__, static_folder=".", static_url_path="", template_folder=".") # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' @app.route("/webhook", methods=["POST"]) def webhook_received(): request_data = json.loads(request.data) signature = request.headers.get("stripe-signature") # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. try: event = stripe.Webhook.construct_event( payload=request.data, sig_header=signature, secret=webhook_secret ) except ValueError as e: # Invalid payload. return Response(status=400) except stripe.error.SignatureVerificationError as e: # Invalid Signature. return Response(status=400) if event["type"] == "checkout.session.completed": session = event["data"]["object"] handle_completed_checkout_session(session) return json.dumps({"success": True}), 200 def handle_completed_checkout_session(session): # Fulfill the purchase. print(str( session)) if __name__ == "__main__": app.run(port=4242)
<?php // Using Slim. use Slim\Http\Request; use Slim\Http\Response; use Stripe\Stripe; require_once('vendor/autoload.php'); $app = new \Slim\App; // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // $webhook_secret = 'whsec_...'; $app->post('/webhook', function ($request, $response, $next) { $payload = $request->getBody(); $sig_header = $request->getHeaderLine('stripe-signature'); $event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { $event = \Stripe\Webhook::constructEvent( $payload, $sig_header, $webhook_secret ); } catch(\UnexpectedValueException $e) { // Invalid payload. return $response->withStatus(400); } catch(\Stripe\Exception\SignatureVerificationException $e) { // Invalid Signature. return $response->withStatus(400); } if ($event->type == 'checkout.session.completed') { $session = $event->data->object; handleCompletedCheckoutSession($session); } return $response->withStatus(200); }); function handleCompletedCheckoutSession($session) { // Fulfill the purchase. echo $session; }; $app->run();
// Using Express const express = require('express'); const bodyParser = require("body-parser"); const app = express(); app.use(express.json()); // Use JSON parser for all non-webhook routes app.use((req, res, next) => { if (req.originalUrl === "/webhook") { next(); } else { bodyParser.json()(req, res, next); } }); // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const webhook_secret = 'whsec_...'' app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => { const sig = request.headers['stripe-signature']; let event; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = stripe.webhooks.constructEvent(request.body, sig, webhook_secret); } catch (err) { return response.status(400).send(`Webhook Error: ${err.message}`); } if (event.type === 'checkout.session.completed') { const session = event.data.object; handleCompletedCheckoutSession(session); } response.json({received: true}); }); const handleCompletedCheckoutSession = (session) => { // Fulfill the purchase. console.log(JSON.stringify(session)); } app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
package com.stripe.sample; import com.stripe.Stripe; import com.stripe.model.checkout.Session; import com.stripe.model.Event; import com.stripe.model.EventDataObjectDeserializer; import com.stripe.exception.SignatureVerificationException; import com.stripe.net.Webhook; import com.google.gson.JsonSyntaxException; import spark.Response; // Using Spark. import static spark.Spark.*; public class Server { public static void main(String[] args) { port(4242); // 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"; post("/webhook", (request, response) -> { String payload = request.body(); String sigHeader = request.headers("Stripe-Signature"); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // String webhookSecret = "whsec_..." Event event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = Webhook.constructEvent( payload, sigHeader, webhookSecret ); } catch (JsonSyntaxException e) { // Invalid payload. response.status(400); return ""; } catch (SignatureVerificationException e) { // Invalid Signature. response.status(400); return ""; } if ("checkout.session.completed".equals(event.getType())) { // Deserialize the nested object inside the event EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer(); Session session = null; if (dataObjectDeserializer.getObject().isPresent()) { session = (Session) dataObjectDeserializer.getObject().get(); handleCompletedCheckoutSession(session); } else { // Deserialization failed, probably due to an API version mismatch. // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for // instructions on how to handle this case, or return an error here. } } response.status(200); return ""; }); } private static void handleCompletedCheckoutSession(Session session) { // Fulfill the purchase. System.out.println(session.getId()); } }
package main import ( "encoding/json" "log" "fmt" "net/http" "io/ioutil" "github.com/stripe/stripe-go/v71" "github.com/stripe/stripe-go/v71/webhook" "os" ) func main() { // 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", handleWebhook) addr := "localhost:4242" log.Printf("Listening on %s ...", addr) log.Fatal(http.ListenAndServe(addr, nil)) } func handleWebhook(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 } // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // webhookSecret := "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. event, err := webhook.ConstructEvent(body, req.Header.Get("Stripe-Signature"), webhookSecret) 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 } 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 } handleCompletedCheckoutSession(session) } w.WriteHeader(http.StatusOK) } func handleCompletedCheckoutSession(session stripe.CheckoutSession) { // Fulfill the purchase. log.Println(session.ID) }
// 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 System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Stripe; using Stripe.Checkout namespace Controllers { public class ConnectController : Controller { private readonly ILogger<ConnectController> logger; public ConnectController( ILogger<ConnectController> logger, ) { this.logger = logger; } [HttpPost("webhook")] public async Task<IActionResult> ProcessWebhookEvent() { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const string webhookSecret = "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], webhookSecret); if (stripeEvent.Type == Events.CheckoutSessionCompleted) { var session = stripeEvent.Data.Object as Session; HandleCompletedCheckoutSession(session); } return Ok(); } catch (Exception e) { logger.LogInformation(e.ToString()); return BadRequest(); } } // Fulfill the purchase. private void HandleCompletedCheckoutSession(Session session) { logger.LogInformation($"{session}"); } } }

Learn more in our fulfillment guide for Checkout.

Testing webhooks locally

Testing webhooks locally is easy with the Stripe CLI.

  1. First, install the Stripe CLI on your machine if you haven’t already.

  2. Then, to log in run stripe login in the command line, and follow the instructions.

  3. Finally, to allow your local host to receive a simulated event on your connected account run stripe listen --forward-to localhost:{PORT}/webhook in one terminal window, and run stripe trigger checkout.session.completed (or trigger any other supported event) in another.

Step 4: Disputes

As the settlement merchant on charges, your platform is responsible for disputes. Make sure you understand the best practices for responding to disputes.

Direct charges

For demonstrative purposes, the platform will represent a store builder platform that allows businesses to create an online store to accept payments from their customers. You can use direct charges in other applications as well.

What you're building

Step 1: Create a PaymentIntent Server-side

Stripe uses a PaymentIntent object to represent your intent to collect payment from a customer, tracking charge attempts and payment state changes throughout the process.

Create a PaymentIntent on your server with an amount and currency. Always decide how much to charge on the server side, a trusted environment, as opposed to the client. This prevents malicious customers from being able to choose their own prices.

curl https://api.stripe.com/v1/payment_intents \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d amount=1000 \ -d currency=usd \ -d application_fee_amount=123 \ -H "Stripe-Account: {{CONNECTED_STRIPE_ACCOUNT_ID}}"
# 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' payment_intent = Stripe::PaymentIntent.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, }, stripe_account: '{{CONNECTED_STRIPE_ACCOUNT_ID}}')
# 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' payment_intent = stripe.PaymentIntent.create( payment_method_types=['card'], amount=1000, currency='usd', application_fee_amount=123, stripe_account='{{CONNECTED_STRIPE_ACCOUNT_ID}}', )
// 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'); $payment_intent = \Stripe\PaymentIntent::create([ 'payment_method_types' => ['card'], 'amount' => 1000, 'currency' => 'usd', 'application_fee_amount' => 123, ], ['stripe_account' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}']);
// 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"; ArrayList paymentMethodTypes = new ArrayList(); paymentMethodTypes.add("card"); Map<String, Object> params = new HashMap<>(); params.put("payment_method_types", paymentMethodTypes); params.put("amount", 1000); params.put("currency", "usd"); params.put("application_fee_amount", 123); RequestOptions requestOptions = RequestOptions.builder().setStripeAccount({{CONNECTED_STRIPE_ACCOUNT_ID}}).build(); PaymentIntent paymentIntent = PaymentIntent.create(params, requestOptions);
// 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 paymentIntent = await stripe.paymentIntents.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, }, { stripeAccount: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', });
// 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.PaymentIntentParams{ PaymentMethodTypes: stripe.StringSlice([]string{ "card", }), Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), ApplicationFeeAmount: stripe.Int64(123), } params.SetStripeAccount("{{CONNECTED_STRIPE_ACCOUNT_ID}}") pi, _ := paymentintent.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 service = new PaymentIntentService(); var createOptions = new PaymentIntentCreateOptions { PaymentMethodTypes = new List<string> { "card", }, Amount = 2000, Currency = "usd", ApplicationFeeAmount = 123, }; var requestOptions = new RequestOptions(); requestOptions.StripeAccount = "{{CONNECTED_STRIPE_ACCOUNT_ID}}"; service.Create(createOptions, requestOptions);

In our store builder example, we want to build an experience where customers pay businesses directly. To set this experience up:

  • Indicate a purchase from the business is a direct charge with the Stripe-Account header.
  • Specify how much of the purchase from the business will go to the platform with application_fee_amount.

When a sale occurs, Stripe transfers the application_fee_amount from the connected account to the platform and deducts the Stripe fee from the connected account’s share. An illustration of this funds flow is below:

Included in the returned PaymentIntent is a client secret, which is used on the client side to securely complete the payment process instead of passing the entire PaymentIntent object. There are different approaches that you can use to pass the client secret to the client side.

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

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

This example demonstrates how to fetch the client secret with JavaScript on the client side:

var response = fetch('/secret').then(function(response) { return response.json(); }).then(function(responseJson) { var clientSecret = responseJson.client_secret; // Call stripe.confirmCardPayment() with the client secret. });
(async () => { const response = await fetch('/secret'); const {client_secret: clientSecret} = await response.json(); // Call stripe.confirmCardPayment() with the client secret. })();

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

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

Step 2: Collect card details Client-side

You’re ready to collect card information on the client with Stripe Elements. Elements is a set of prebuilt UI components for collecting and validating card number, ZIP code, and expiration date.

A Stripe Element contains an iframe that securely sends the payment information to Stripe over a HTTPS connection. The checkout page address must also start with https:// rather than http:// for your integration to work.

You can test your integration without using HTTPS. Enable it when you’re ready to accept live payments.

Set up Stripe Elements

Stripe Elements is automatically available as a feature of Stripe.js. Include the Stripe.js script on your checkout page by adding it to the head of your HTML file. Always load Stripe.js directly from js.stripe.com to remain PCI compliant. Do not include the script in a bundle or host a copy of it yourself.

<head> <title>Checkout</title> <script src="https://js.stripe.com/v3/"></script> </head>

Create an instance of Elements with the following JavaScript on your checkout page:

// Initialize Stripe.js with the same connected account ID used when creating // the PaymentIntent. var stripe = Stripe('pk_test_TYooMQauvdEDq54NiTphI7jx', { stripeAccount: '{{CONNECTED_STRIPE_ACCOUNT_ID}}' });

Add Elements to your payment page

Elements needs a place to live in your payment form. Create empty DOM nodes (containers) with unique IDs in your payment form and then pass those IDs to Elements.

<form id="payment-form"> <div id="card-element"> <!-- Elements will create input elements here --> </div> <!-- We'll put the error messages in this element --> <div id="card-errors" role="alert"></div> <button id="submit">Pay</button> </form>

When the form above has loaded, create an instance of an Element and mount it to the Element container:

// Set up Stripe.js and Elements to use in checkout form var elements = stripe.elements(); var style = { base: { color: "#32325d", } }; var card = elements.create("card", { style: style }); card.mount("#card-element");

The card Element simplifies the form and minimizes the number of required fields by inserting a single, flexible input field that securely collects all necessary card and billing details. Otherwise, combine cardNumber, cardExpiry, and cardCvc Elements for a flexible, multi-input card form.

For a full list of supported Element types, refer to our Stripe.js reference documentation.

Elements validates user input as it is typed. To help your customers catch mistakes, listen to change events on the card Element and display any errors:

card.on('change', ({error}) => { const displayError = document.getElementById('card-errors'); if (error) { displayError.textContent = error.message; } else { displayError.textContent = ''; } });
cardElement.on('change', function(event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } });

Postal code validation depends on your customer’s billing country. Use our international test cards to experiment with other postal code formats.

Install React Stripe.js and the Stripe.js loader from the npm public registry.

npm install --save @stripe/react-stripe-js @stripe/stripe-js

We also provide a UMD build for sites that do not use npm or modules.

Include the Stripe.js script, which exports a global Stripe function, and the UMD build of React Stripe.js, which exports a global ReactStripe object. Always load the Stripe.js script directly from js.stripe.com to remain PCI compliant. Do not include the script in a bundle or host a copy of it yourself.

<!-- Stripe.js --> <script src="https://js.stripe.com/v3/"></script> <!-- React Stripe.js development build --> <script src="https://unpkg.com/@stripe/react-stripe-js@latest/dist/react-stripe.umd.js"></script> <!-- When you are ready to deploy your site to production, remove the above development script, and include the following production build. --> <script src="https://unpkg.com/@stripe/react-stripe-js@latest/dist/react-stripe.umd.min.js"></script>

Add Stripe.js and Elements to your page

To use Element components, wrap the root of your React app in an Elements provider. Call loadStripe with your publishable key and pass the returned Promise to the Elements provider.

import React from 'react'; import ReactDOM from 'react-dom'; import {Elements} from '@stripe/react-stripe-js'; import {loadStripe} from '@stripe/stripe-js'; import CheckoutForm from './CheckoutForm'; // Make sure to call `loadStripe` outside of a component’s render to avoid // recreating the `Stripe` object on every render. // Call `loadStripe` with the same connected account ID used when creating // the PaymentIntent. const stripePromise = loadStripe("pk_test_TYooMQauvdEDq54NiTphI7jx", {stripeAccount: "{{CONNECTED_STRIPE_ACCOUNT_ID}}"}); function App() { return ( <Elements stripe={stripePromise}> <CheckoutForm /> </Elements> ); }; ReactDOM.render(<App />, document.getElementById('root'));

Add and configure a CardElement component

Use individual Element components, such as CardElement, to build your form.

/** * Use the CSS tab above to style your Element's container. */ import React from 'react'; import {CardElement} from '@stripe/react-stripe-js'; import './CardSectionStyles.css' const CARD_ELEMENT_OPTIONS = { style: { base: { color: "#32325d", fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: "antialiased", fontSize: "16px", "::placeholder": { color: "#aab7c4", }, }, invalid: { color: "#fa755a", iconColor: "#fa755a", }, }, }; function CardSection() { return ( <label> Card details <CardElement options={CARD_ELEMENT_OPTIONS} /> </label> ); }; export default CardSection;
/** * Shows how you can use CSS to style your Element's container. * These classes are added to your Stripe Element by default. * You can override these classNames by using the options passed * to the CardElement component. * https://stripe.com/docs/js/elements_object/create_element?type=card#elements_create-options-classes */ .StripeElement { height: 40px; padding: 10px 12px; width: 100%; color: #32325d; background-color: white; border: 1px solid transparent; border-radius: 4px; box-shadow: 0 1px 3px 0 #e6ebf1; -webkit-transition: box-shadow 150ms ease; transition: box-shadow 150ms ease; } .StripeElement--focus { box-shadow: 0 1px 3px 0 #cfd7df; } .StripeElement--invalid { border-color: #fa755a; } .StripeElement--webkit-autofill { background-color: #fefde5 !important; }

Elements are completely customizable. You can style Elements to match the look and feel of your site, providing a seamless checkout experience for your customers. It’s also possible to style various input states, for example when the Element has focus.

The CardElement simplifies the form and minimizes the number of required fields by inserting a single, flexible input field that securely collects all necessary card and billing details. Otherwise, combine CardNumberElement, CardExpiryElement, and CardCvcElement elements for a flexible, multi-input card form.

Step 3: Submit the payment to Stripe Client-side

Rather than sending the entire PaymentIntent object to the client, use its client secret from Step 1. This is different from your API keys that authenticate Stripe API requests.

The client secret should still be handled carefully because it can complete the charge. Do not log it, embed it in URLs, or expose it to anyone but the customer.

To complete the payment when the user clicks, retrieve the client secret from the PaymentIntent you created in step 1 and call stripe.confirmCardPayment with the client secret.

Pass additional billing details, such as the cardholder name and address, to the billing_details hash. The card Element automatically sends the customer’s postal code information. However, combining cardNumber, cardCvc, and cardExpiry Elements requires you to pass the postal code to billing_details[address][postal_code].

var form = document.getElementById('payment-form'); form.addEventListener('submit', function(ev) { ev.preventDefault(); stripe.confirmCardPayment(clientSecret, { payment_method: { card: card, billing_details: { name: 'Jenny Rosen' } } }).then(function(result) { if (result.error) { // Show error to your customer (e.g., insufficient funds) console.log(result.error.message); } else { // The payment has been processed! if (result.paymentIntent.status === 'succeeded') { // Show a success message to your customer // There's a risk of the customer closing the window before callback // execution. Set up a webhook or plugin to listen for the // payment_intent.succeeded event that handles any business critical // post-payment actions. } } }); });

If the customer must authenticate the card, Stripe.js walks them through that process by showing them a modal. You can see an example of this modal experience by using the test card number 4000 0025 0000 3155 with any CVC, future expiration date, and postal code in the demo at the top of the page.

When the payment completes successfully, the value of the returned PaymentIntent’s status property is succeeded. Check the status of a PaymentIntent in the Dashboard or by inspecting the status property on the object. If the payment is not successful, inspect the returned error to determine the cause.

To complete the payment when the user clicks, retrieve the client secret from the PaymentIntent you created in step two and call stripe.confirmCardPayment with the client secret and the Element. Pass additional billing details, such as the cardholder name and address, to the billing_details hash.

To call stripe.confirmCardPayment from your payment form component, use the useStripe and useElements hooks.

If you prefer traditional class components over hooks, you can instead use an ElementsConsumer.

import React from 'react'; import {useStripe, useElements, CardElement} from '@stripe/react-stripe-js'; import CardSection from './CardSection'; export default function CheckoutForm() { const stripe = useStripe(); const elements = useElements(); const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe || !elements) { // Stripe.js has not yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const result = await stripe.confirmCardPayment('{CLIENT_SECRET}', { payment_method: { card: elements.getElement(CardElement), billing_details: { name: 'Jenny Rosen', }, } }); if (result.error) { // Show error to your customer (e.g., insufficient funds) console.log(result.error.message); } else { // The payment has been processed! if (result.paymentIntent.status === 'succeeded') { // Show a success message to your customer // There's a risk of the customer closing the window before callback // execution. Set up a webhook or plugin to listen for the // payment_intent.succeeded event that handles any business critical // post-payment actions. } } }; return ( <form onSubmit={handleSubmit}> <CardSection /> <button disabled={!stripe}>Confirm order</button> </form> ); }
import React from 'react'; import {ElementsConsumer, CardElement} from '@stripe/react-stripe-js'; import CardSection from './CardSection'; class CheckoutForm extends React.Component { handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); const {stripe, elements} = this.props if (!stripe || !elements) { // Stripe.js has not yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const result = await stripe.confirmCardPayment('{CLIENT_SECRET}', { payment_method: { card: elements.getElement(CardElement), billing_details: { name: 'Jenny Rosen', }, } }); if (result.error) { // Show error to your customer (e.g., insufficient funds) console.log(result.error.message); } else { // The payment has been processed! if (result.paymentIntent.status === 'succeeded') { // Show a success message to your customer // There's a risk of the customer closing the window before callback // execution. Set up a webhook or plugin to listen for the // payment_intent.succeeded event that handles any business critical // post-payment actions. } } }; render() { return ( <form onSubmit={this.handleSubmit}> <CardSection /> <button disabled={!this.props.stripe}>Confirm order</button> </form> ); } } export default function InjectedCheckoutForm() { return ( <ElementsConsumer> {({stripe, elements}) => ( <CheckoutForm stripe={stripe} elements={elements} /> )} </ElementsConsumer> ); }

If the customer must authenticate the card, Stripe.js walks them through that process by showing them a modal. You can see an example of this modal experience by using the test card number 4000 0025 0000 3155 with any CVC, future expiration date, and postal code in the demo at the top of the page.

When the payment completes successfully, the value of the returned PaymentIntent’s status property is succeeded. Check the status of a PaymentIntent in the Dashboard or by inspecting the status property on the object. If the payment is not successful, inspect the returned error to determine the cause.

Step 4: Fulfillment Server-side

After payment is completed, you must handle any necessary fulfillment. For example, a store builder must alert the business to send the purchased item to the customer.

Configure a webhook endpoint in your dashboard (for events from your Connect applications).

Then create an HTTP endpoint on your server to monitor for completed payments to then enable your users (connected accounts) to fulfill purchases.

# Using Sinatra. require 'sinatra' require 'stripe' set :port, 4242 # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' post '/webhook' do payload = request.body.read sig_header = request.env['HTTP_STRIPE_SIGNATURE'] event = nil # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. begin event = Stripe::Webhook.construct_event( payload, sig_header, webhook_secret ) rescue JSON::ParserError => e # Invalid payload. status 400 return rescue Stripe::SignatureVerificationError => e # Invalid Signature. status 400 return end if event['type'] == 'payment_intent.succeeded' payment_intent = event['data']['object'] connected_account_id = event['account'] handle_successful_payment_intent(connected_account_id, payment_intent) end status 200 end def handle_successful_payment_intent(connected_account_id, payment_intent) # Fulfill the purchase. puts 'Connected account ID: ' + connected_account_id puts payment_intent.to_s end
import stripe import json # Using Flask. from flask import ( Flask, render_template, request, Response, ) app = Flask(__name__, static_folder=".", static_url_path="", template_folder=".") # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' @app.route("/webhook", methods=["POST"]) def webhook_received(): request_data = json.loads(request.data) signature = request.headers.get("stripe-signature") # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. try: event = stripe.Webhook.construct_event( payload=request.data, sig_header=signature, secret=webhook_secret ) except ValueError as e: # Invalid payload. return Response(status=400) except stripe.error.SignatureVerificationError as e: # Invalid Signature. return Response(status=400) if event["type"] == "payment_intent.succeeded": payment_intent = event["data"]["object"] connected_account_id = event["account"] handle_successful_payment_intent(connected_account_id, payment_intent) return json.dumps({"success": True}), 200 def handle_successful_payment_intent(connected_account_id, payment_intent): # Fulfill the purchase. print('Connected account ID: ' + connected_account_id) print(str( payment_intent)) if __name__ == "__main__": app.run(port=4242)
<?php // Using Slim. use Slim\Http\Request; use Slim\Http\Response; use Stripe\Stripe; require_once('vendor/autoload.php'); $app = new \Slim\App; // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // $webhook_secret = 'whsec_...'; $app->post('/webhook', function ($request, $response, $next) { $payload = $request->getBody(); $sig_header = $request->getHeaderLine('stripe-signature'); $event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { $event = \Stripe\Webhook::constructEvent( $payload, $sig_header, $webhook_secret ); } catch(\UnexpectedValueException $e) { // Invalid payload. return $response->withStatus(400); } catch(\Stripe\Exception\SignatureVerificationException $e) { // Invalid Signature. return $response->withStatus(400); } if ($event->type == 'payment_intent.succeeded') { $paymentIntent = $event->data->object; $connectedAccountId = $event->account; handleSuccessfulPaymentIntent($connectedAccountId, $paymentIntent); } return $response->withStatus(200); }); function handleSuccessfulPaymentIntent($connectedAccountId, $paymentIntent) { // Fulfill the purchase. echo 'Connected account ID: ' . $connectedAccountId; echo $paymentIntent; }; $app->run();
// Using Express const express = require('express'); const bodyParser = require("body-parser"); const app = express(); app.use(express.json()); // Use JSON parser for all non-webhook routes app.use((req, res, next) => { if (req.originalUrl === "/webhook") { next(); } else { bodyParser.json()(req, res, next); } }); // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const webhook_secret = 'whsec_...'' app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => { const sig = request.headers['stripe-signature']; let event; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = stripe.webhooks.constructEvent(request.body, sig, webhook_secret); } catch (err) { return response.status(400).send(`Webhook Error: ${err.message}`); } if (event.type === 'payment_intent.succeeded') { const paymentIntent = event.data.object; const connectedAccountId = event.account; handleSuccessfulPaymentIntent(connectedAccountId, paymentIntent); } response.json({received: true}); }); const handleSuccessfulPaymentIntent = (connectedAccountId, paymentIntent) => { // Fulfill the purchase. console.log('Connected account ID: ' + connectedAccountId); console.log(JSON.stringify(paymentIntent)); } app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
package com.stripe.sample; import com.stripe.Stripe; import com.stripe.model.PaymentIntent; import com.stripe.model.Event; import com.stripe.model.EventDataObjectDeserializer; import com.stripe.exception.SignatureVerificationException; import com.stripe.net.Webhook; import com.google.gson.JsonSyntaxException; import spark.Response; // Using Spark. import static spark.Spark.*; public class Server { public static void main(String[] args) { port(4242); // 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"; post("/webhook", (request, response) -> { String payload = request.body(); String sigHeader = request.headers("Stripe-Signature"); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // String webhookSecret = "whsec_..." Event event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = Webhook.constructEvent( payload, sigHeader, webhookSecret ); } catch (JsonSyntaxException e) { // Invalid payload. response.status(400); return ""; } catch (SignatureVerificationException e) { // Invalid Signature. response.status(400); return ""; } if ("payment_intent.succeeded".equals(event.getType())) { // Deserialize the nested object inside the event EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer(); PaymentIntent paymentIntent = null; if (dataObjectDeserializer.getObject().isPresent()) { paymentIntent = (PaymentIntent) dataObjectDeserializer.getObject().get(); String connectedAccountId = event.getAccount(); handleSuccessfulPaymentIntent(connectedAccountId, paymentIntent); } else { // Deserialization failed, probably due to an API version mismatch. // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for // instructions on how to handle this case, or return an error here. } } response.status(200); return ""; }); } private static void handleSuccessfulPaymentIntent(String connectedAccountId, PaymentIntent paymentIntent) { // Fulfill the purchase. System.out.println("Connected account ID: " + connectedAccountId); System.out.println(paymentIntent.getId()); } }
package main import ( "encoding/json" "log" "fmt" "net/http" "io/ioutil" "github.com/stripe/stripe-go/v71" "github.com/stripe/stripe-go/v71/webhook" "os" ) func main() { // 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", handleWebhook) addr := "localhost:4242" log.Printf("Listening on %s ...", addr) log.Fatal(http.ListenAndServe(addr, nil)) } func handleWebhook(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 } // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // webhookSecret := "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. event, err := webhook.ConstructEvent(body, req.Header.Get("Stripe-Signature"), webhookSecret) 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 } if event.Type == "payment_intent.succeeded" { var paymentIntent stripe.PaymentIntent err := json.Unmarshal(event.Data.Raw, &paymentIntent) if err != nil { fmt.Fprintf(os.Stderr, "Error parsing webhook JSON: %v\n", err) w.WriteHeader(http.StatusBadRequest) return } var connectedAccountId = event.Account; handleSuccessfulPaymentIntent(connectedAccountId, paymentIntent) } w.WriteHeader(http.StatusOK) } func handleSuccessfulPaymentIntent(connectedAccountId string, paymentIntent stripe.PaymentIntent) { // Fulfill the purchase. log.Println("Connected account ID: " + connectedAccountId) log.Println(paymentIntent.ID) }
// 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 System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Stripe; namespace Controllers { public class ConnectController : Controller { private readonly ILogger<ConnectController> logger; public ConnectController( ILogger<ConnectController> logger, ) { this.logger = logger; } [HttpPost("webhook")] public async Task<IActionResult> ProcessWebhookEvent() { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const string webhookSecret = "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], webhookSecret); if (stripeEvent.Type == Events.PaymentIntentSucceeded) { var paymentIntent = stripeEvent.Data.Object as PaymentIntent; var connectedAccountId = stripeEvent.Account; HandleSuccessfulPaymentIntent(connectedAccountId, paymentIntent); } return Ok(); } catch (Exception e) { logger.LogInformation(e.ToString()); return BadRequest(); } } private void HandleSuccessfulPaymentIntent(string connectedAccountId, PaymentIntent paymentIntent) { // Fulfill the purchase. logger.LogInformation($"Connected account ID: {connectedAccountId}"); logger.LogInformation($"{paymentIntent}"); } } }

Learn more in our fulfillment guide for payments.

Testing webhooks locally

Testing webhooks locally is easy with the Stripe CLI.

  1. First, install the Stripe CLI on your machine if you haven’t already.

  2. Then, to log in run stripe login in the command line, and follow the instructions.

  3. Finally, to allow your local host to receive a simulated event on your connected account run stripe listen --forward-connect-to localhost:{PORT}/webhook in one terminal window, and run stripe trigger --stripe-account={{CONNECTED_STRIPE_ACCOUNT_ID}} payment_intent.succeeded (or trigger any other supported event) in another.

What you're building

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

Step 1: Create a Checkout session Server-side

On your server, make the following call to Stripe’s API:

curl https://api.stripe.com/v1/checkout/sessions \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d "line_items[][name]"="Stainless Steel Water Bottle" \ -d "line_items[][amount]"=1000 \ -d "line_items[][currency]"=usd \ -d "line_items[][quantity]"=1 \ -d "payment_intent_data[application_fee_amount]"=123 \ -d success_url="https://example.com/success" \ -d cancel_url="https://example.com/cancel" \ -H "Stripe-Account: {{CONNECTED_STRIPE_ACCOUNT_ID}}"
# 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: [{ name: 'Stainless Steel Water Bottle', amount: 1000, currency: 'usd', quantity: 1, }], payment_intent_data: { application_fee_amount: 123, }, success_url: 'https://example.com/success', cancel_url: 'https://example.com/cancel', }, {stripe_account: '{{CONNECTED_STRIPE_ACCOUNT_ID}}'})
# 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=[{ 'name': 'Stainless Steel Water Bottle', 'amount': 1000, 'currency': 'usd', 'quantity': 1, }], payment_intent_data={ 'application_fee_amount': 123, }, success_url='https://example.com/success', cancel_url='https://example.com/cancel', stripe_account='{{CONNECTED_STRIPE_ACCOUNT_ID}}', )
// 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' => [[ 'name' => 'Stainless Steel Water Bottle', 'amount' => 1000, 'currency' => 'usd', 'quantity' => 1, ]], 'payment_intent_data' => [ 'application_fee_amount' => 123, ], 'success_url' => 'https://example.com/success', 'cancel_url' => 'https://example.com/cancel', ], ['stripe_account' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}']);
// 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("name", "Stainless Steel Water Bottle"); lineItem.put("amount", 1000); lineItem.put("currency", "usd"); lineItem.put("quantity", 1); lineItems.add(lineItem); params.put("line_items", lineItems); HashMap<String, Object> paymentIntentData = new HashMap<String, Object>(); paymentIntentData.put("application_fee_amount", 123); params.put("payment_intent_data", paymentIntentData); params.put("success_url", "https://example.com/success"); params.put("cancel_url", "https://example.com/cancel"); RequestOptions requestOptions = RequestOptions.builder().setStripeAccount("{{CONNECTED_STRIPE_ACCOUNT_ID}}").build(); Session session = Session.create(params, requestOptions);
// 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: [{ name: 'Stainless Steel Water Bottle', amount: 1000, currency: 'usd', quantity: 1, }], payment_intent_data: { application_fee_amount: 123, }, success_url: 'https://example.com/success', cancel_url: 'https://example.com/cancel', }, { stripeAccount: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', });
// 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{ Name: stripe.String("Stainless Steel Water Bottle"), Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), Quantity: stripe.Int64(1), }, }, PaymentIntentData: &stripe.CheckoutSessionPaymentIntentDataParams{ ApplicationFeeAmount: stripe.Int64(123), }, SuccessURL: stripe.String("https://example.com/success"), CancelURL: stripe.String("https://example.com/cancel"), } params.SetStripeAccount("{{CONNECTED_STRIPE_ACCOUNT_ID}}") s, _ := 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 { Name = "Stainless Steel Water Bottle", Amount = 1000, Currency = "usd", Quantity = 1, }, }, PaymentIntentData = new SessionPaymentIntentDataOptions { ApplicationFeeAmount = 123, }, SuccessUrl = "https://example.com/success", CancelUrl = "https://example.com/cancel", }; var requestOptions = new RequestOptions { StripeAccount = "{{CONNECTED_STRIPE_ACCOUNT_ID}}", }; var service = new SessionService(); Session session = service.Create(options, requestOptions);

This returns a Checkout Session object with an id attribute that’s needed on the client side.

  • Stripe-Account - This header indicates a direct charge for your connected account. With direct charges, the connected account is responsible for Stripe fees, refunds, and chargebacks. The connected account’s branding is used in Checkout, which allows their customers to feel like they’re interacting directly with the merchant instead of your platform.
  • line_items - This argument represents items that your customer is purchasing and that will show up in the hosted user interface.
  • success_url - This argument redirects a user after they complete a payment.
  • cancel_url - This argument redirects a user after they click cancel.
  • (Optional) payment_intent_data[application_fee_amount] - This argument specifies the amount your platform plans to take from the transaction. After the payment is processed on the connected account, the application_fee_amount is transferred to the platform and the Stripe fee is deducted from the connected account’s balance.

Step 2: Add a checkout button Client-side

On your checkout page, include the Stripe.js script by adding it to the head of your HTML file.

<head> <title>Checkout</title> <script src="https://js.stripe.com/v3/"></script> </head>

Fetch the Session ID from your server. Add a button to your client with a click handler that calls Stripe’s frontend API:

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

Your connected accounts can set up their branding settings at: https://dashboard.stripe.com/account/branding.

Step 3: Fulfillment Server-side

After payment is completed, you must handle any necessary fulfillment. For example, a store builder must alert the business to send the purchased item to the customer.

Configure a webhook endpoint in your dashboard (for events from your Connect applications).

Then create an HTTP endpoint on your server to monitor for completed payments to then enable your users (connected accounts) to fulfill purchases.

# Using Sinatra. require 'sinatra' require 'stripe' set :port, 4242 # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' post '/webhook' do payload = request.body.read sig_header = request.env['HTTP_STRIPE_SIGNATURE'] event = nil # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. begin event = Stripe::Webhook.construct_event( payload, sig_header, webhook_secret ) rescue JSON::ParserError => e # Invalid payload. status 400 return rescue Stripe::SignatureVerificationError => e # Invalid Signature. status 400 return end if event['type'] == 'checkout.session.completed' session = event['data']['object'] connected_account_id = event['account'] handle_completed_checkout_session(connected_account_id, session) end status 200 end def handle_completed_checkout_session(connected_account_id, session) # Fulfill the purchase. puts 'Connected account ID: ' + connected_account_id puts session.to_s end
import stripe import json # Using Flask. from flask import ( Flask, render_template, request, Response, ) app = Flask(__name__, static_folder=".", static_url_path="", template_folder=".") # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' @app.route("/webhook", methods=["POST"]) def webhook_received(): request_data = json.loads(request.data) signature = request.headers.get("stripe-signature") # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. try: event = stripe.Webhook.construct_event( payload=request.data, sig_header=signature, secret=webhook_secret ) except ValueError as e: # Invalid payload. return Response(status=400) except stripe.error.SignatureVerificationError as e: # Invalid Signature. return Response(status=400) if event["type"] == "checkout.session.completed": session = event["data"]["object"] connected_account_id = event["account"] handle_completed_checkout_session(connected_account_id, session) return json.dumps({"success": True}), 200 def handle_completed_checkout_session(connected_account_id, session): # Fulfill the purchase. print('Connected account ID: ' + connected_account_id) print(str( session)) if __name__ == "__main__": app.run(port=4242)
<?php // Using Slim. use Slim\Http\Request; use Slim\Http\Response; use Stripe\Stripe; require_once('vendor/autoload.php'); $app = new \Slim\App; // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // $webhook_secret = 'whsec_...'; $app->post('/webhook', function ($request, $response, $next) { $payload = $request->getBody(); $sig_header = $request->getHeaderLine('stripe-signature'); $event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { $event = \Stripe\Webhook::constructEvent( $payload, $sig_header, $webhook_secret ); } catch(\UnexpectedValueException $e) { // Invalid payload. return $response->withStatus(400); } catch(\Stripe\Exception\SignatureVerificationException $e) { // Invalid Signature. return $response->withStatus(400); } if ($event->type == 'checkout.session.completed') { $session = $event->data->object; $connectedAccountId = $event->account; handleCompletedCheckoutSession($connectedAccountId, $session); } return $response->withStatus(200); }); function handleCompletedCheckoutSession($connectedAccountId, $session) { // Fulfill the purchase. echo 'Connected account ID: ' . $connectedAccountId; echo $session; }; $app->run();
// Using Express const express = require('express'); const bodyParser = require("body-parser"); const app = express(); app.use(express.json()); // Use JSON parser for all non-webhook routes app.use((req, res, next) => { if (req.originalUrl === "/webhook") { next(); } else { bodyParser.json()(req, res, next); } }); // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const webhook_secret = 'whsec_...'' app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => { const sig = request.headers['stripe-signature']; let event; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = stripe.webhooks.constructEvent(request.body, sig, webhook_secret); } catch (err) { return response.status(400).send(`Webhook Error: ${err.message}`); } if (event.type === 'checkout.session.completed') { const session = event.data.object; const connectedAccountId = event.account; handleCompletedCheckoutSession(connectedAccountId, session); } response.json({received: true}); }); const handleCompletedCheckoutSession = (connectedAccountId, session) => { // Fulfill the purchase. console.log('Connected account ID: ' + connectedAccountId); console.log(JSON.stringify(session)); } app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
package com.stripe.sample; import com.stripe.Stripe; import com.stripe.model.checkout.Session; import com.stripe.model.Event; import com.stripe.model.EventDataObjectDeserializer; import com.stripe.exception.SignatureVerificationException; import com.stripe.net.Webhook; import com.google.gson.JsonSyntaxException; import spark.Response; // Using Spark. import static spark.Spark.*; public class Server { public static void main(String[] args) { port(4242); // 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"; post("/webhook", (request, response) -> { String payload = request.body(); String sigHeader = request.headers("Stripe-Signature"); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // String webhookSecret = "whsec_..." Event event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = Webhook.constructEvent( payload, sigHeader, webhookSecret ); } catch (JsonSyntaxException e) { // Invalid payload. response.status(400); return ""; } catch (SignatureVerificationException e) { // Invalid Signature. response.status(400); return ""; } if ("checkout.session.completed".equals(event.getType())) { // Deserialize the nested object inside the event EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer(); Session session = null; if (dataObjectDeserializer.getObject().isPresent()) { session = (Session) dataObjectDeserializer.getObject().get(); String connectedAccountId = event.getAccount(); handleCompletedCheckoutSession(connectedAccountId, session); } else { // Deserialization failed, probably due to an API version mismatch. // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for // instructions on how to handle this case, or return an error here. } } response.status(200); return ""; }); } private static void handleCompletedCheckoutSession(String connectedAccountId, Session session) { // Fulfill the purchase. System.out.println("Connected account ID: " + connectedAccountId); System.out.println(session.getId()); } }
package main import ( "encoding/json" "log" "fmt" "net/http" "io/ioutil" "github.com/stripe/stripe-go/v71" "github.com/stripe/stripe-go/v71/webhook" "os" ) func main() { // 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", handleWebhook) addr := "localhost:4242" log.Printf("Listening on %s ...", addr) log.Fatal(http.ListenAndServe(addr, nil)) } func handleWebhook(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 } // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // webhookSecret := "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. event, err := webhook.ConstructEvent(body, req.Header.Get("Stripe-Signature"), webhookSecret) 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 } 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 } var connectedAccountId = event.Account; handleCompletedCheckoutSession(connectedAccountId, session) } w.WriteHeader(http.StatusOK) } func handleCompletedCheckoutSession(connectedAccountId string, session stripe.CheckoutSession) { // Fulfill the purchase. log.Println("Connected account ID: " + connectedAccountId) log.Println(session.ID) }
// 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 System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Stripe; using Stripe.Checkout namespace Controllers { public class ConnectController : Controller { private readonly ILogger<ConnectController> logger; public ConnectController( ILogger<ConnectController> logger, ) { this.logger = logger; } [HttpPost("webhook")] public async Task<IActionResult> ProcessWebhookEvent() { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const string webhookSecret = "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], webhookSecret); if (stripeEvent.Type == Events.CheckoutSessionCompleted) { var session = stripeEvent.Data.Object as Session; var connectedAccountId = stripeEvent.Account; HandleCompletedCheckoutSession(connectedAccountId, session); } return Ok(); } catch (Exception e) { logger.LogInformation(e.ToString()); return BadRequest(); } } private void HandleCompletedCheckoutSession(string connectedAccountId, Session session) { // Fulfill the purchase. logger.LogInformation($"Connected account ID: {connectedAccountId}"); logger.LogInformation($"{session}"); } } }

Learn more in our fulfillment guide for Checkout.

Testing webhooks locally

Testing webhooks locally is easy with the Stripe CLI.

  1. First, install the Stripe CLI on your machine if you haven’t already.

  2. Then, to log in run stripe login in the command line, and follow the instructions.

  3. Finally, to allow your local host to receive a simulated event on your connected account run stripe listen --forward-connect-to localhost:{PORT}/webhook in one terminal window, and run stripe trigger --stripe-account={{CONNECTED_STRIPE_ACCOUNT_ID}} checkout.session.completed (or trigger any other supported event) in another.

Separate charges and transfers

For demonstrative purposes, the platform will represent a food delivery platform that’s paying restaurants and delivery people separately. You can use separate charges and transfers in other applications as well.

What you're building

Step 1: Create a PaymentIntent Server-side

Stripe uses a PaymentIntent object to represent your intent to collect payment from a customer, tracking charge attempts and payment state changes throughout the process.

Create a PaymentIntent on your server with an amount and currency. Always decide how much to charge on the server side, a trusted environment, as opposed to the client. This prevents malicious customers from being able to choose their own prices.

curl https://api.stripe.com/v1/payment_intents \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d amount=1000 \ -d currency=usd \ -d transfer_group="{ORDER10}"
# 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' payment_intent = Stripe::PaymentIntent.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', transfer_group: '{ORDER10}', })
# 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' payment_intent = stripe.PaymentIntent.create( payment_method_types=['card'], amount=1000, currency='usd', transfer_group='{ORDER10}', })
// 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'); $payment_intent = \Stripe\PaymentIntent::create([ 'payment_method_types' => ['card'], 'amount' => 1000, 'currency' => 'usd', 'transfer_group' => '{ORDER10}', ])
// 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"; ArrayList paymentMethodTypes = new ArrayList(); paymentMethodTypes.add("card"); Map<String, Object> params = new HashMap<>(); params.put("payment_method_types", paymentMethodTypes); params.put("amount", 1000); params.put("currency", "usd"); params.put("transfer_group", "{ORDER10}"); PaymentIntent paymentIntent = PaymentIntent.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 paymentIntent = await stripe.paymentIntents.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', transfer_group: '{ORDER10}' });
// 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.PaymentIntentParams{ PaymentMethodTypes: stripe.StringSlice([]string{ "card", }), Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), TransferGroup: stripe.String("{ORDER10}"), } params.SetStripeAccount("{{CONNECTED_STRIPE_ACCOUNT_ID}}") pi, _ := paymentintent.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 service = new PaymentIntentService(); var createOptions = new PaymentIntentCreateOptions { PaymentMethodTypes = new List<string> { "card", }, Amount = 2000, Currency = "usd", TransferGroup: "{ORDER10}", }; service.Create(createOptions);

Included in the returned PaymentIntent is a client secret, which is used on the client side to securely complete the payment process instead of passing the entire PaymentIntent object. There are different approaches that you can use to pass the client secret to the client side.

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

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

This example demonstrates how to fetch the client secret with JavaScript on the client side:

var response = fetch('/secret').then(function(response) { return response.json(); }).then(function(responseJson) { var clientSecret = responseJson.client_secret; // Call stripe.confirmCardPayment() with the client secret. });
(async () => { const response = await fetch('/secret'); const {client_secret: clientSecret} = await response.json(); // Call stripe.confirmCardPayment() with the client secret. })();

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

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

Step 2: Collect card details Client-side

You’re ready to collect card information on the client with Stripe Elements. Elements is a set of prebuilt UI components for collecting and validating card number, ZIP code, and expiration date.

A Stripe Element contains an iframe that securely sends the payment information to Stripe over a HTTPS connection. The checkout page address must also start with https:// rather than http:// for your integration to work.

You can test your integration without using HTTPS. Enable it when you’re ready to accept live payments.

Set up Stripe Elements

Stripe Elements is automatically available as a feature of Stripe.js. Include the Stripe.js script on your checkout page by adding it to the head of your HTML file. Always load Stripe.js directly from js.stripe.com to remain PCI compliant. Do not include the script in a bundle or host a copy of it yourself.

<head> <title>Checkout</title> <script src="https://js.stripe.com/v3/"></script> </head>

Create an instance of Elements with the following JavaScript on your checkout page:

// Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/account/apikeys var stripe = Stripe('pk_test_TYooMQauvdEDq54NiTphI7jx'); var elements = stripe.elements();

Add Elements to your payment page

Elements needs a place to live in your payment form. Create empty DOM nodes (containers) with unique IDs in your payment form and then pass those IDs to Elements.

<form id="payment-form"> <div id="card-element"> <!-- Elements will create input elements here --> </div> <!-- We'll put the error messages in this element --> <div id="card-errors" role="alert"></div> <button id="submit">Pay</button> </form>

When the form above has loaded, create an instance of an Element and mount it to the Element container:

// Set up Stripe.js and Elements to use in checkout form var elements = stripe.elements(); var style = { base: { color: "#32325d", } }; var card = elements.create("card", { style: style }); card.mount("#card-element");

The card Element simplifies the form and minimizes the number of required fields by inserting a single, flexible input field that securely collects all necessary card and billing details. Otherwise, combine cardNumber, cardExpiry, and cardCvc Elements for a flexible, multi-input card form.

For a full list of supported Element types, refer to our Stripe.js reference documentation.

Elements validates user input as it is typed. To help your customers catch mistakes, listen to change events on the card Element and display any errors:

card.on('change', ({error}) => { const displayError = document.getElementById('card-errors'); if (error) { displayError.textContent = error.message; } else { displayError.textContent = ''; } });
cardElement.on('change', function(event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } });

Postal code validation depends on your customer’s billing country. Use our international test cards to experiment with other postal code formats.

Install React Stripe.js and the Stripe.js loader from the npm public registry.

npm install --save @stripe/react-stripe-js @stripe/stripe-js

We also provide a UMD build for sites that do not use npm or modules.

Include the Stripe.js script, which exports a global Stripe function, and the UMD build of React Stripe.js, which exports a global ReactStripe object. Always load the Stripe.js script directly from js.stripe.com to remain PCI compliant. Do not include the script in a bundle or host a copy of it yourself.

<!-- Stripe.js --> <script src="https://js.stripe.com/v3/"></script> <!-- React Stripe.js development build --> <script src="https://unpkg.com/@stripe/react-stripe-js@latest/dist/react-stripe.umd.js"></script> <!-- When you are ready to deploy your site to production, remove the above development script, and include the following production build. --> <script src="https://unpkg.com/@stripe/react-stripe-js@latest/dist/react-stripe.umd.min.js"></script>

Add Stripe.js and Elements to your page

To use Element components, wrap the root of your React app in an Elements provider. Call loadStripe with your publishable key and pass the returned Promise to the Elements provider.

import React from 'react'; import ReactDOM from 'react-dom'; import {Elements} from '@stripe/react-stripe-js'; import {loadStripe} from '@stripe/stripe-js'; import CheckoutForm from './CheckoutForm'; // 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() { return ( <Elements stripe={stripePromise}> <CheckoutForm /> </Elements> ); }; ReactDOM.render(<App />, document.getElementById('root'));

Add and configure a CardElement component

Use individual Element components, such as CardElement, to build your form.

/** * Use the CSS tab above to style your Element's container. */ import React from 'react'; import {CardElement} from '@stripe/react-stripe-js'; import './CardSectionStyles.css' const CARD_ELEMENT_OPTIONS = { style: { base: { color: "#32325d", fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: "antialiased", fontSize: "16px", "::placeholder": { color: "#aab7c4", }, }, invalid: { color: "#fa755a", iconColor: "#fa755a", }, }, }; function CardSection() { return ( <label> Card details <CardElement options={CARD_ELEMENT_OPTIONS} /> </label> ); }; export default CardSection;
/** * Shows how you can use CSS to style your Element's container. * These classes are added to your Stripe Element by default. * You can override these classNames by using the options passed * to the CardElement component. * https://stripe.com/docs/js/elements_object/create_element?type=card#elements_create-options-classes */ .StripeElement { height: 40px; padding: 10px 12px; width: 100%; color: #32325d; background-color: white; border: 1px solid transparent; border-radius: 4px; box-shadow: 0 1px 3px 0 #e6ebf1; -webkit-transition: box-shadow 150ms ease; transition: box-shadow 150ms ease; } .StripeElement--focus { box-shadow: 0 1px 3px 0 #cfd7df; } .StripeElement--invalid { border-color: #fa755a; } .StripeElement--webkit-autofill { background-color: #fefde5 !important; }

Elements are completely customizable. You can style Elements to match the look and feel of your site, providing a seamless checkout experience for your customers. It’s also possible to style various input states, for example when the Element has focus.

The CardElement simplifies the form and minimizes the number of required fields by inserting a single, flexible input field that securely collects all necessary card and billing details. Otherwise, combine CardNumberElement, CardExpiryElement, and CardCvcElement elements for a flexible, multi-input card form.

Step 3: Submit the payment to Stripe Client-side

Rather than sending the entire PaymentIntent object to the client, use its client secret from Step 1. This is different from your API keys that authenticate Stripe API requests.

The client secret should still be handled carefully because it can complete the charge. Do not log it, embed it in URLs, or expose it to anyone but the customer.

To complete the payment when the user clicks, retrieve the client secret from the PaymentIntent you created in step 1 and call stripe.confirmCardPayment with the client secret.

Pass additional billing details, such as the cardholder name and address, to the billing_details hash. The card Element automatically sends the customer’s postal code information. However, combining cardNumber, cardCvc, and cardExpiry Elements requires you to pass the postal code to billing_details[address][postal_code].

var form = document.getElementById('payment-form'); form.addEventListener('submit', function(ev) { ev.preventDefault(); stripe.confirmCardPayment(clientSecret, { payment_method: { card: card, billing_details: { name: 'Jenny Rosen' } } }).then(function(result) { if (result.error) { // Show error to your customer (e.g., insufficient funds) console.log(result.error.message); } else { // The payment has been processed! if (result.paymentIntent.status === 'succeeded') { // Show a success message to your customer // There's a risk of the customer closing the window before callback // execution. Set up a webhook or plugin to listen for the // payment_intent.succeeded event that handles any business critical // post-payment actions. } } }); });

If the customer must authenticate the card, Stripe.js walks them through that process by showing them a modal. You can see an example of this modal experience by using the test card number 4000 0025 0000 3155 with any CVC, future expiration date, and postal code in the demo at the top of the page.

When the payment completes successfully, the value of the returned PaymentIntent’s status property is succeeded. Check the status of a PaymentIntent in the Dashboard or by inspecting the status property on the object. If the payment is not successful, inspect the returned error to determine the cause.

To complete the payment when the user clicks, retrieve the client secret from the PaymentIntent you created in step two and call stripe.confirmCardPayment with the client secret and the Element. Pass additional billing details, such as the cardholder name and address, to the billing_details hash.

To call stripe.confirmCardPayment from your payment form component, use the useStripe and useElements hooks.

If you prefer traditional class components over hooks, you can instead use an ElementsConsumer.

import React from 'react'; import {useStripe, useElements, CardElement} from '@stripe/react-stripe-js'; import CardSection from './CardSection'; export default function CheckoutForm() { const stripe = useStripe(); const elements = useElements(); const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe || !elements) { // Stripe.js has not yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const result = await stripe.confirmCardPayment('{CLIENT_SECRET}', { payment_method: { card: elements.getElement(CardElement), billing_details: { name: 'Jenny Rosen', }, } }); if (result.error) { // Show error to your customer (e.g., insufficient funds) console.log(result.error.message); } else { // The payment has been processed! if (result.paymentIntent.status === 'succeeded') { // Show a success message to your customer // There's a risk of the customer closing the window before callback // execution. Set up a webhook or plugin to listen for the // payment_intent.succeeded event that handles any business critical // post-payment actions. } } }; return ( <form onSubmit={handleSubmit}> <CardSection /> <button disabled={!stripe}>Confirm order</button> </form> ); }
import React from 'react'; import {ElementsConsumer, CardElement} from '@stripe/react-stripe-js'; import CardSection from './CardSection'; class CheckoutForm extends React.Component { handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); const {stripe, elements} = this.props if (!stripe || !elements) { // Stripe.js has not yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const result = await stripe.confirmCardPayment('{CLIENT_SECRET}', { payment_method: { card: elements.getElement(CardElement), billing_details: { name: 'Jenny Rosen', }, } }); if (result.error) { // Show error to your customer (e.g., insufficient funds) console.log(result.error.message); } else { // The payment has been processed! if (result.paymentIntent.status === 'succeeded') { // Show a success message to your customer // There's a risk of the customer closing the window before callback // execution. Set up a webhook or plugin to listen for the // payment_intent.succeeded event that handles any business critical // post-payment actions. } } }; render() { return ( <form onSubmit={this.handleSubmit}> <CardSection /> <button disabled={!this.props.stripe}>Confirm order</button> </form> ); } } export default function InjectedCheckoutForm() { return ( <ElementsConsumer> {({stripe, elements}) => ( <CheckoutForm stripe={stripe} elements={elements} /> )} </ElementsConsumer> ); }

If the customer must authenticate the card, Stripe.js walks them through that process by showing them a modal. You can see an example of this modal experience by using the test card number 4000 0025 0000 3155 with any CVC, future expiration date, and postal code in the demo at the top of the page.

When the payment completes successfully, the value of the returned PaymentIntent’s status property is succeeded. Check the status of a PaymentIntent in the Dashboard or by inspecting the status property on the object. If the payment is not successful, inspect the returned error to determine the cause.

Step 4: Fulfillment Server-side

After payment is completed, you must handle any necessary fulfillment. For example, once a customer pays on the food delivery platform, the platform must alert the restaurant to prepare the order and the food delivery person to deliver the order.

Configure a webhook endpoint in your dashboard (for events from your account).

Then create an HTTP endpoint on your server to monitor for completed payments to then enable your users (connected accounts) to fulfill purchases.

# Using Sinatra. require 'sinatra' require 'stripe' set :port, 4242 # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' post '/webhook' do payload = request.body.read sig_header = request.env['HTTP_STRIPE_SIGNATURE'] event = nil # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. begin event = Stripe::Webhook.construct_event( payload, sig_header, webhook_secret ) rescue JSON::ParserError => e # Invalid payload. status 400 return rescue Stripe::SignatureVerificationError => e # Invalid Signature. status 400 return end if event['type'] == 'payment_intent.succeeded' payment_intent = event['data']['object'] handle_successful_payment_intent(payment_intent) end status 200 end def handle_successful_payment_intent(payment_intent) # Fulfill the purchase. puts payment_intent.to_s end
import stripe import json # Using Flask. from flask import ( Flask, render_template, request, Response, ) app = Flask(__name__, static_folder=".", static_url_path="", template_folder=".") # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' @app.route("/webhook", methods=["POST"]) def webhook_received(): request_data = json.loads(request.data) signature = request.headers.get("stripe-signature") # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. try: event = stripe.Webhook.construct_event( payload=request.data, sig_header=signature, secret=webhook_secret ) except ValueError as e: # Invalid payload. return Response(status=400) except stripe.error.SignatureVerificationError as e: # Invalid Signature. return Response(status=400) if event["type"] == "payment_intent.succeeded": payment_intent = event["data"]["object"] handle_successful_payment_intent(payment_intent) return json.dumps({"success": True}), 200 def handle_successful_payment_intent(payment_intent): # Fulfill the purchase. print(str( payment_intent)) if __name__ == "__main__": app.run(port=4242)
<?php // Using Slim. use Slim\Http\Request; use Slim\Http\Response; use Stripe\Stripe; require_once('vendor/autoload.php'); $app = new \Slim\App; // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // $webhook_secret = 'whsec_...'; $app->post('/webhook', function ($request, $response, $next) { $payload = $request->getBody(); $sig_header = $request->getHeaderLine('stripe-signature'); $event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { $event = \Stripe\Webhook::constructEvent( $payload, $sig_header, $webhook_secret ); } catch(\UnexpectedValueException $e) { // Invalid payload. return $response->withStatus(400); } catch(\Stripe\Exception\SignatureVerificationException $e) { // Invalid Signature. return $response->withStatus(400); } if ($event->type == 'payment_intent.succeeded') { $paymentIntent = $event->data->object; handleSuccessfulPaymentIntent($paymentIntent); } return $response->withStatus(200); }); function handleSuccessfulPaymentIntent($paymentIntent) { // Fulfill the purchase. echo $paymentIntent; }; $app->run();
// Using Express const express = require('express'); const bodyParser = require("body-parser"); const app = express(); app.use(express.json()); // Use JSON parser for all non-webhook routes app.use((req, res, next) => { if (req.originalUrl === "/webhook") { next(); } else { bodyParser.json()(req, res, next); } }); // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const webhook_secret = 'whsec_...'' app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => { const sig = request.headers['stripe-signature']; let event; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = stripe.webhooks.constructEvent(request.body, sig, webhook_secret); } catch (err) { return response.status(400).send(`Webhook Error: ${err.message}`); } if (event.type === 'payment_intent.succeeded') { const paymentIntent = event.data.object; handleSuccessfulPaymentIntent(paymentIntent); } response.json({received: true}); }); const handleSuccessfulPaymentIntent = (paymentIntent) => { // Fulfill the purchase. console.log(JSON.stringify(paymentIntent)); } app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
package com.stripe.sample; import com.stripe.Stripe; import com.stripe.model.PaymentIntent; import com.stripe.model.Event; import com.stripe.model.EventDataObjectDeserializer; import com.stripe.exception.SignatureVerificationException; import com.stripe.net.Webhook; import com.google.gson.JsonSyntaxException; import spark.Response; // Using Spark. import static spark.Spark.*; public class Server { public static void main(String[] args) { port(4242); // 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"; post("/webhook", (request, response) -> { String payload = request.body(); String sigHeader = request.headers("Stripe-Signature"); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // String webhookSecret = "whsec_..." Event event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = Webhook.constructEvent( payload, sigHeader, webhookSecret ); } catch (JsonSyntaxException e) { // Invalid payload. response.status(400); return ""; } catch (SignatureVerificationException e) { // Invalid Signature. response.status(400); return ""; } if ("payment_intent.succeeded".equals(event.getType())) { // Deserialize the nested object inside the event EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer(); PaymentIntent paymentIntent = null; if (dataObjectDeserializer.getObject().isPresent()) { paymentIntent = (PaymentIntent) dataObjectDeserializer.getObject().get(); handleSuccessfulPaymentIntent(paymentIntent); } else { // Deserialization failed, probably due to an API version mismatch. // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for // instructions on how to handle this case, or return an error here. } } response.status(200); return ""; }); } private static void handleSuccessfulPaymentIntent(PaymentIntent paymentIntent) { // Fulfill the purchase. System.out.println(paymentIntent.getId()); } }
package main import ( "encoding/json" "log" "fmt" "net/http" "io/ioutil" "github.com/stripe/stripe-go/v71" "github.com/stripe/stripe-go/v71/webhook" "os" ) func main() { // 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", handleWebhook) addr := "localhost:4242" log.Printf("Listening on %s ...", addr) log.Fatal(http.ListenAndServe(addr, nil)) } func handleWebhook(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 } // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // webhookSecret := "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. event, err := webhook.ConstructEvent(body, req.Header.Get("Stripe-Signature"), webhookSecret) 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 } if event.Type == "payment_intent.succeeded" { var paymentIntent stripe.PaymentIntent err := json.Unmarshal(event.Data.Raw, &paymentIntent) if err != nil { fmt.Fprintf(os.Stderr, "Error parsing webhook JSON: %v\n", err) w.WriteHeader(http.StatusBadRequest) return } handleSuccessfulPaymentIntent(paymentIntent) } w.WriteHeader(http.StatusOK) } func handleSuccessfulPaymentIntent(paymentIntent stripe.PaymentIntent) { // Fulfill the purchase. log.Println(paymentIntent.ID) }
// 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 System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Stripe; namespace Controllers { public class ConnectController : Controller { private readonly ILogger<ConnectController> logger; public ConnectController( ILogger<ConnectController> logger, ) { this.logger = logger; } [HttpPost("webhook")] public async Task<IActionResult> ProcessWebhookEvent() { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const string webhookSecret = "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], webhookSecret); if (stripeEvent.Type == Events.PaymentIntentSucceeded) { var paymentIntent = stripeEvent.Data.Object as PaymentIntent; HandleSuccessfulPaymentIntent(paymentIntent); } return Ok(); } catch (Exception e) { logger.LogInformation(e.ToString()); return BadRequest(); } } // Fulfill the purchase. private void HandleSuccessfulPaymentIntent(PaymentIntent paymentIntent) { logger.LogInformation($"{paymentIntent}"); } } }

Learn more in our fulfillment guide for payments.

Testing webhooks locally

Testing webhooks locally is easy with the Stripe CLI.

  1. First, install the Stripe CLI on your machine if you haven’t already.

  2. Then, to log in run stripe login in the command line, and follow the instructions.

  3. Finally, to allow your local host to receive a simulated event on your connected account run stripe listen --forward-connect-to localhost:{PORT}/webhook in one terminal window, and run stripe trigger --stripe-account={{CONNECTED_STRIPE_ACCOUNT_ID}} payment_intent.succeeded (or trigger any other supported event) in another.

Step 5: Transfer Server-side

Transfer to your connected accounts using the same transfer_group from Step 1 to tie the transfer to the PaymentIntent you created. You can create multiple transfers with the same transfer_group to different connected accounts.

curl https://api.stripe.com/v1/transfers \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d amount=1000 \ -d currency=usd \ -d transfer_group="{ORDER10}" \ -d destination="{{CONNECTED_STRIPE_ACCOUNT_ID}}"
# 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' transfer = Stripe::Transfer.create({ amount: 900, currency: "usd", transfer_group: "{ORDER10}", destination: "{{CONNECTED_STRIPE_ACCOUNT_ID}}", })
# 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' transfer = stripe.Transfer.create( amount=1000, currency="usd", transfer_group="{ORDER10}", destination="{{CONNECTED_STRIPE_ACCOUNT_ID}}", )
// 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'); $transfer = \Stripe\Transfer::create([ "amount" => 1000, "currency" => "usd", "transfer_group=" => "{ORDER10}", "destination" => "{{CONNECTED_STRIPE_ACCOUNT_ID}}", ]);
// 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<>(); params.put("amount", 1000); params.put("currency", "usd"); params.put("transfer_group", "{ORDER10}"); params.put("destination", "{{CONNECTED_STRIPE_ACCOUNT_ID}}"); Transfer transfer = Transfer.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 transfer = await stripe.transfers.create({ amount: 1000, currency: "usd", transfer_group: "{ORDER10}", destination: "{{CONNECTED_STRIPE_ACCOUNT_ID}}", });
// 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.TransferParams{ Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), TransferGroup: stripe.String("{ORDER10}"), Destination: stripe.String("{{CONNECTED_STRIPE_ACCOUNT_ID}}"), } tr, _ := transfer.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 TransferCreateOptions { Amount = 1000, Currency = "usd", TransferGroup = "{ORDER10}", Destination = "{{CONNECTED_STRIPE_ACCOUNT_ID}}" }; var service = new TransferService(); var Transfer = service.Create(options);

What you're building

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

Step 1: Create a Checkout session Server-side

On your server, make the following call to Stripe’s API:

curl https://api.stripe.com/v1/checkout/sessions \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d "line_items[][name]"="Miso soup" \ -d "line_items[][amount]"=1000 \ -d "line_items[][currency]"=usd \ -d "line_items[][quantity]"=1 \ -d "payment_intent_data[application_fee_amount]"=123 \ -d success_url="https://example.com/success" \ -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: [{ name: 'Miso soup', amount: 1000, currency: 'usd', quantity: 1, }], success_url: 'https://example.com/success', 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=[{ 'name': 'Miso soup', 'amount': 1000, 'currency': 'usd', 'quantity': 1, }], payment_intent_data={ 'application_fee_amount': 123, }, success_url='https://example.com/success', 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' => [[ 'name' => 'Miso soup', 'amount' => 1000, 'currency' => 'usd', 'quantity' => 1, ]], 'success_url' => 'https://example.com/success', '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("name", "Miso soup"); lineItem.put("amount", 1000); lineItem.put("currency", "usd"); lineItem.put("quantity", 1); lineItems.add(lineItem); params.put("line_items", lineItems); params.put("success_url", "https://example.com/success"); params.put("cancel_url", "https://example.com/cancel"); RequestOptions requestOptions = RequestOptions.builder().build(); Session session = Session.create(params, requestOptions);
// 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: [{ name: 'Miso soup', amount: 1000, currency: 'usd', quantity: 1, }], success_url: 'https://example.com/success', 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{ Name: stripe.String("Miso soup"), Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), Quantity: stripe.Int64(1), }, }, SuccessURL: stripe.String("https://example.com/success"), CancelURL: stripe.String("https://example.com/cancel"), } s, _ := 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 { Name = "Miso soup", Amount = 1000, Currency = "usd", Quantity = 1, }, }, SuccessUrl = "https://example.com/success", CancelUrl = "https://example.com/cancel", }; var service = new SessionService(); Session session = service.Create(options);

This returns a Checkout Session object with an id attribute that’s needed on the client side.

  • line_items - This argument represents items that your customer is purchasing and that will show up in the hosted user interface.
  • success_url - This argument redirects a user after they complete a payment.
  • cancel_url - This argument redirects a user after they click cancel.

Step 2: Add a checkout button Client-side

On your checkout page, include the Stripe.js script by adding it to the head of your HTML file.

<head> <title>Checkout</title> <script src="https://js.stripe.com/v3/"></script> </head>

Fetch the Session ID from your server. Add a button to your client with a click handler that calls Stripe’s frontend API:

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

Your connected accounts can set up their branding settings at: https://dashboard.stripe.com/account/branding.

Step 3: Fulfillment Server-side

After payment is completed, you must handle any necessary fulfillment. For example, once a customer pays on the food delivery platform, the platform must alert the restaurant to prepare the order and the food delivery person to deliver the order.

Configure a webhook endpoint in your dashboard (for events from your account).

Then create an HTTP endpoint on your server to monitor for completed payments to then enable your users (connected accounts) to fulfill purchases.

# Using Sinatra. require 'sinatra' require 'stripe' set :port, 4242 # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' post '/webhook' do payload = request.body.read sig_header = request.env['HTTP_STRIPE_SIGNATURE'] event = nil # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. begin event = Stripe::Webhook.construct_event( payload, sig_header, webhook_secret ) rescue JSON::ParserError => e # Invalid payload. status 400 return rescue Stripe::SignatureVerificationError => e # Invalid Signature. status 400 return end if event['type'] == 'checkout.session.completed' session = event['data']['object'] handle_completed_checkout_session(session) end status 200 end def handle_completed_checkout_session(session) # Fulfill the purchase. puts session.to_s end
import stripe import json # Using Flask. from flask import ( Flask, render_template, request, Response, ) app = Flask(__name__, static_folder=".", static_url_path="", template_folder=".") # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' @app.route("/webhook", methods=["POST"]) def webhook_received(): request_data = json.loads(request.data) signature = request.headers.get("stripe-signature") # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. try: event = stripe.Webhook.construct_event( payload=request.data, sig_header=signature, secret=webhook_secret ) except ValueError as e: # Invalid payload. return Response(status=400) except stripe.error.SignatureVerificationError as e: # Invalid Signature. return Response(status=400) if event["type"] == "checkout.session.completed": session = event["data"]["object"] handle_completed_checkout_session(session) return json.dumps({"success": True}), 200 def handle_completed_checkout_session(session): # Fulfill the purchase. print(str( session)) if __name__ == "__main__": app.run(port=4242)
<?php // Using Slim. use Slim\Http\Request; use Slim\Http\Response; use Stripe\Stripe; require_once('vendor/autoload.php'); $app = new \Slim\App; // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // $webhook_secret = 'whsec_...'; $app->post('/webhook', function ($request, $response, $next) { $payload = $request->getBody(); $sig_header = $request->getHeaderLine('stripe-signature'); $event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { $event = \Stripe\Webhook::constructEvent( $payload, $sig_header, $webhook_secret ); } catch(\UnexpectedValueException $e) { // Invalid payload. return $response->withStatus(400); } catch(\Stripe\Exception\SignatureVerificationException $e) { // Invalid Signature. return $response->withStatus(400); } if ($event->type == 'checkout.session.completed') { $session = $event->data->object; handleCompletedCheckoutSession($session); } return $response->withStatus(200); }); function handleCompletedCheckoutSession($session) { // Fulfill the purchase. echo $session; }; $app->run();
// Using Express const express = require('express'); const bodyParser = require("body-parser"); const app = express(); app.use(express.json()); // Use JSON parser for all non-webhook routes app.use((req, res, next) => { if (req.originalUrl === "/webhook") { next(); } else { bodyParser.json()(req, res, next); } }); // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const webhook_secret = 'whsec_...'' app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => { const sig = request.headers['stripe-signature']; let event; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = stripe.webhooks.constructEvent(request.body, sig, webhook_secret); } catch (err) { return response.status(400).send(`Webhook Error: ${err.message}`); } if (event.type === 'checkout.session.completed') { const session = event.data.object; handleCompletedCheckoutSession(session); } response.json({received: true}); }); const handleCompletedCheckoutSession = (session) => { // Fulfill the purchase. console.log(JSON.stringify(session)); } app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
package com.stripe.sample; import com.stripe.Stripe; import com.stripe.model.checkout.Session; import com.stripe.model.Event; import com.stripe.model.EventDataObjectDeserializer; import com.stripe.exception.SignatureVerificationException; import com.stripe.net.Webhook; import com.google.gson.JsonSyntaxException; import spark.Response; // Using Spark. import static spark.Spark.*; public class Server { public static void main(String[] args) { port(4242); // 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"; post("/webhook", (request, response) -> { String payload = request.body(); String sigHeader = request.headers("Stripe-Signature"); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // String webhookSecret = "whsec_..." Event event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = Webhook.constructEvent( payload, sigHeader, webhookSecret ); } catch (JsonSyntaxException e) { // Invalid payload. response.status(400); return ""; } catch (SignatureVerificationException e) { // Invalid Signature. response.status(400); return ""; } if ("checkout.session.completed".equals(event.getType())) { // Deserialize the nested object inside the event EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer(); Session session = null; if (dataObjectDeserializer.getObject().isPresent()) { session = (Session) dataObjectDeserializer.getObject().get(); handleCompletedCheckoutSession(session); } else { // Deserialization failed, probably due to an API version mismatch. // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for // instructions on how to handle this case, or return an error here. } } response.status(200); return ""; }); } private static void handleCompletedCheckoutSession(Session session) { // Fulfill the purchase. System.out.println(session.getId()); } }
package main import ( "encoding/json" "log" "fmt" "net/http" "io/ioutil" "github.com/stripe/stripe-go/v71" "github.com/stripe/stripe-go/v71/webhook" "os" ) func main() { // 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", handleWebhook) addr := "localhost:4242" log.Printf("Listening on %s ...", addr) log.Fatal(http.ListenAndServe(addr, nil)) } func handleWebhook(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 } // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // webhookSecret := "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. event, err := webhook.ConstructEvent(body, req.Header.Get("Stripe-Signature"), webhookSecret) 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 } 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 } handleCompletedCheckoutSession(session) } w.WriteHeader(http.StatusOK) } func handleCompletedCheckoutSession(session stripe.CheckoutSession) { // Fulfill the purchase. log.Println(session.ID) }
// 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 System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Stripe; using Stripe.Checkout namespace Controllers { public class ConnectController : Controller { private readonly ILogger<ConnectController> logger; public ConnectController( ILogger<ConnectController> logger, ) { this.logger = logger; } [HttpPost("webhook")] public async Task<IActionResult> ProcessWebhookEvent() { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const string webhookSecret = "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], webhookSecret); if (stripeEvent.Type == Events.CheckoutSessionCompleted) { var session = stripeEvent.Data.Object as Session; HandleCompletedCheckoutSession(session); } return Ok(); } catch (Exception e) { logger.LogInformation(e.ToString()); return BadRequest(); } } // Fulfill the purchase. private void HandleCompletedCheckoutSession(Session session) { logger.LogInformation($"{session}"); } } }

Learn more in our fulfillment guide for Checkout.

Testing webhooks locally

Testing webhooks locally is easy with the Stripe CLI.

  1. First, install the Stripe CLI on your machine if you haven’t already.

  2. Then, to log in run stripe login in the command line, and follow the instructions.

  3. Finally, to allow your local host to receive a simulated event on your connected account run stripe listen --forward-connect-to localhost:{PORT}/webhook in one terminal window, and run stripe trigger --stripe-account={{CONNECTED_STRIPE_ACCOUNT_ID}} checkout.session.completed (or trigger any other supported event) in another.

Step 4: Transfer Server-side

Transfer to your connected accounts using a source_transaction to tie the transfer to the PaymentIntent created by the Checkout Session. You can create multiple transfers with the same source_transaction to different connected accounts. The transfer will succeed regardless of balance, and the transfer will occur once the charge’s funds are available.

curl https://api.stripe.com/v1/transfers \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d amount=1000 \ -d currency=usd \ -d source_transaction="{CHARGE_ID}" \ -d destination="{{CONNECTED_STRIPE_ACCOUNT_ID}}"
# 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' transfer = Stripe::Transfer.create({ amount: 900, currency: "usd", source_transaction: "{CHARGE_ID}", destination: "{{CONNECTED_STRIPE_ACCOUNT_ID}}", })
# 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' transfer = stripe.Transfer.create( amount=1000, currency="usd", source_transaction="{CHARGE_ID}", destination="{{CONNECTED_STRIPE_ACCOUNT_ID}}", )
// 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'); $transfer = \Stripe\Transfer::create([ "amount" => 1000, "currency" => "usd", "source_transaction" => "{CHARGE_ID}", "destination" => "{{CONNECTED_STRIPE_ACCOUNT_ID}}", ]);
// 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<>(); params.put("amount", 1000); params.put("currency", "usd"); params.put("source_transaction", "{CHARGE_ID}"); params.put("destination", "{{CONNECTED_STRIPE_ACCOUNT_ID}}"); Transfer transfer = Transfer.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 transfer = await stripe.transfers.create({ amount: 1000, currency: "usd", source_transaction: "{CHARGE_ID}", destination: "{{CONNECTED_STRIPE_ACCOUNT_ID}}", });
// 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.TransferParams{ Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), SourceTransaction: stripe.String("{CHARGE_ID}"), Destination: stripe.String("{{CONNECTED_STRIPE_ACCOUNT_ID}}"), } tr, _ := transfer.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 TransferCreateOptions { Amount = 1000, Currency = "usd", SourceTransaction = "{CHARGE_ID}", Destination = "{{CONNECTED_STRIPE_ACCOUNT_ID}}" }; var service = new TransferService(); var Transfer = service.Create(options);

Subscriptions

You can create a recurring payment on a connected account with subscriptions. Subscriptions are created with direct charges. Optionally, specify an application_fee_percent to direct a percentage of each invoice payment to your platform.

The Checkout page is branded using the business name, icon, logo, and color of the connected account.

Step 1: Create a Checkout session Server-side

On your server, make the following call to Stripe’s API:

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 "subscription_data[application_fee_percent]"=10 \ -d mode=subscription \ -d success_url="https://example.com/success" \ -d cancel_url="https://example.com/cancel" \ -H "Stripe-Account: {{CONNECTED_STRIPE_ACCOUNT_ID}}"
# 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, }], subscription_data: { application_fee_percent: 10, }, mode: 'subscription', success_url: 'https://example.com/success', cancel_url: 'https://example.com/cancel', }, {stripe_account: '{{CONNECTED_STRIPE_ACCOUNT_ID}}'})
# 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, }], subscription_data={ 'application_fee_percent': 10, }, mode='subscription', success_url='https://example.com/success', cancel_url='https://example.com/cancel', stripe_account='{{CONNECTED_STRIPE_ACCOUNT_ID}}', )
// 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, ]], 'subscription_data' => [ 'application_fee_percent' => 10, ], 'mode' => 'subscription', 'success_url' => 'https://example.com/success', 'cancel_url' => 'https://example.com/cancel', ], ['stripe_account' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}']);
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.apiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; SessionCreateParams params = SessionCreateParams.builder() .addPaymentMethodType(SessionCreateParams.PaymentMethodType.CARD) .addLineItem( SessionCreateParams.LineItem.builder() .setPrice("{{PRICE_ID}}") .setQuantity(1L) .build()) .setSubscriptionData( SessionCreateParams.SubscriptionData.builder() .setApplicationFeePercent(new BigDecimal(10)) .build()) .setMode(SessionCreateParams.Mode.SUBSCRIPTION) .setSuccessUrl("https://example.com/success") .setCancelUrl("https://example.com/cancel") .build(); RequestOptions requestOptions = RequestOptions.builder().setStripeAccount("{{CONNECTED_STRIPE_ACCOUNT_ID}}").build(); Session session = Session.create(params, requestOptions);
// 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'], lineItems: [{ price: '{{PRICE_ID}}', quantity: 1, }], mode: 'subscription', subscription_data: { application_fee_percent: 10, }, success_url: 'https://example.com/success', cancel_url: 'https://example.com/cancel', }, { stripeAccount: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', });
// 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.CheckoutSessionLineItemsParams{ &stripe.CheckoutSessionLineItemsParams{ Price: stripe.String("{{PRICE_ID}}"), Quantity: stripe.Int64(1), }, }, Mode: stripe.String("subscription"), SubscriptionData: &stripe.CheckoutSessionSubscriptionDataParams{ ApplicationFeePercent: stripe.Int64(10), }, SuccessURL: stripe.String("https://example.com/success"), CancelURL: stripe.String("https://example.com/cancel"), } params.SetStripeAccount("{{CONNECTED_STRIPE_ACCOUNT_ID}}") s, _ := 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", SubscriptionData = new SessionSubscriptionDataOptions { ApplicationFeePercent = 10, }, SuccessUrl = "https://example.com/success", CancelUrl = "https://example.com/cancel", }; var requestOptions = new RequestOptions { StripeAccount = "{{CONNECTED_STRIPE_ACCOUNT_ID}}", }; var service = new SessionService(); var session = service.Create(options, requestOptions);

Step 2: Add a checkout button Client-side

On your checkout page, include the Stripe.js script by adding it to the head of your HTML file.

<head> <title>Checkout</title> <script src="https://js.stripe.com/v3/"></script> </head>

Fetch the Session ID from your server. Add a button to your client with a click handler that calls Stripe’s frontend API:

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

Branding

Your platform and Standard connected accounts can use the Branding settings in the Dashboard to customize branding on the payments page. Destination charges will use the platform’s branding. For direct charges, platforms can use the Accounts API to configure the branding settings for Express and Custom accounts.

The account update API accepts the following parameters for branding:

  • icon - Displayed next to the business name in the header of the Checkout page.
  • logo- If specified, displayed instead of the icon and business name in the header of the Checkout page.
  • primary_color - Used as the background color on the Checkout page.
  • secondary_color Used as the button color on the Checkout page.
curl https://api.stripe.com/v1/accounts/{{CONNECTED_STRIPE_ACCOUNT_ID}} \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "settings[branding][icon]"=file_123 \ -d "settings[branding][logo]"=file_456 \ -d "settings[branding][primary_color]"="#663399" \ -d "settings[branding][secondary_color]"="#4BB543"
# 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' Stripe::Account.update( '{{CONNECTED_STRIPE_ACCOUNT_ID}}', { settings: { branding: { icon: 'file_123', logo: 'file_456', primary_color: '#663399', }, }, } )
# 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' stripe.Account.modify( '{{CONNECTED_STRIPE_ACCOUNT_ID}}', settings={ 'branding': { 'icon': 'file_123', 'logo': 'file_456', 'primary_color': '#663399', }, }, )
// 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'); \Stripe\Account::update( '{{CONNECTED_STRIPE_ACCOUNT_ID}}', [ 'settings' => [ 'branding' => [ 'icon' => 'file_123', 'logo' => 'file_456', 'primary_color' => '#663399', ], ], ] );
// 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"; Account account = Account.retrieve("{{CONNECTED_STRIPE_ACCOUNT_ID}}"); HashMap<String, Object> params = new HashMap<String, Object>(); HashMap<String, Object> settings = new HashMap<String, Object>(); HashMap<String, Object> branding = new HashMap<String, Object>(); branding.put("icon", "file_123"); branding.put("logo", "file_456"); branding.put("primary_color", "#663399"); settings.put("branding", branding); params.put("settings", settings); account.update(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'); stripe.accounts.update( '{{CONNECTED_STRIPE_ACCOUNT_ID}}', { settings: { branding: { icon: 'file_123', logo: 'file_456', primary_color: '#663399', }, }, }, )
// 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.AccountParams{ Settings: &stripe.AccountSettingsParams{ Branding: &stripe.AccountSettingsBrandingParams{ Icon: stripe.String("file_123"), Logo: stripe.String("file_456"), PrimaryColor: stripe.String("#663399"), }, }, } account.Update("{{CONNECTED_STRIPE_ACCOUNT_ID}}", 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 AccountUpdateOptions { Settings = new AccountSettingsOptions { Branding = new AccountSettingsBrandingOptions { Icon = "file_123", Logo = "file_456", PrimaryColor = "#663399", }, }, }; var accountService = new AccountService(); accountService.Update("{{CONNECTED_STRIPE_ACCOUNT_ID}}", options);

Collecting payments in your iOS app consists of creating an object to track a payment on your server, collecting card information in your app, and submitting the payment to Stripe for processing.

Stripe uses this payment object, called a PaymentIntent, to track and handle all the states of the payment until it’s completed—even when the bank requires customer intervention, like two-factor authentication.

1 Set up Stripe Server-side Client-side

First, you need a Stripe account. Register now.

Server-side

This integration requires endpoints on your server that talk to the Stripe API. Use our official libraries for access to the Stripe API from your server:

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

Client-side

The iOS SDK is open source, fully documented, and compatible with apps supporting iOS 10 or above.

  1. If you haven't already, install the latest version of CocoaPods.
  2. If you don't have an existing Podfile, run the following command to create one:
    pod init
  3. Add this line to your Podfile:
    pod 'Stripe'
  4. Run the following command:
    pod install
  5. Don't forget to use the .xcworkspace file to open your project in Xcode, instead of the .xcodeproj file, from here on out.
  6. In the future, to update to the latest version of the SDK, just run:
    pod update Stripe
  1. If you haven't already, install the latest version of Carthage.
  2. Add this line to your Cartfile:
    github "stripe/stripe-ios"
  3. Follow the Carthage installation instructions.
  4. In the future, to update to the latest version of the SDK, run the following command:
    carthage update stripe-ios --platform ios
  1. Head to our GitHub releases page and download and unzip Stripe.framework.zip.
  2. Drag Stripe.framework to the "Embedded Binaries" section of your Xcode project's "General" settings. Make sure to select "Copy items if needed".
  3. Head to the "Build Phases" section of your Xcode project settings, and create a new "Run Script Build Phase". Paste the following snippet into the text field:
    bash "${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/Stripe.framework/integrate-dynamic-framework.sh"
  4. In the future, to update to the latest version of our SDK, just repeat steps 1 and 2.

When your app starts, configure the SDK with your Stripe publishable key so that it can make requests to the Stripe API.

import UIKit import Stripe @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { Stripe.setDefaultPublishableKey("pk_test_TYooMQauvdEDq54NiTphI7jx") // do any other necessary launch configuration return true } }
#import "AppDelegate.h" #import <Stripe/Stripe.h> @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [Stripe setDefaultPublishableKey:@"pk_test_TYooMQauvdEDq54NiTphI7jx"]; // do any other necessary launch configuration return YES; } @end

2 Create your checkout page Client-side

Securely collect card information on the client with STPPaymentCardTextField, a drop-in UI component provided by the SDK.

STPPaymentCardTextField performs on-the-fly validation and formatting.

Create an instance of the card component and a Pay button with the following code:

import UIKit import Stripe class CheckoutViewController: UIViewController { lazy var cardTextField: STPPaymentCardTextField = { let cardTextField = STPPaymentCardTextField() return cardTextField }() lazy var payButton: UIButton = { let button = UIButton(type: .custom) button.layer.cornerRadius = 5 button.backgroundColor = .systemBlue button.titleLabel?.font = UIFont.systemFont(ofSize: 22) button.setTitle("Pay", for: .normal) button.addTarget(self, action: #selector(pay), for: .touchUpInside) return button }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let stackView = UIStackView(arrangedSubviews: [cardTextField, payButton]) stackView.axis = .vertical stackView.spacing = 20 stackView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(stackView) NSLayoutConstraint.activate([ stackView.leftAnchor.constraint(equalToSystemSpacingAfter: view.leftAnchor, multiplier: 2), view.rightAnchor.constraint(equalToSystemSpacingAfter: stackView.rightAnchor, multiplier: 2), stackView.topAnchor.constraint(equalToSystemSpacingBelow: view.topAnchor, multiplier: 2), ]) } @objc func pay() { // ... } }
#import "CheckoutViewController.h" #import <Stripe/Stripe.h> @interface CheckoutViewController () @property (weak) STPPaymentCardTextField *cardTextField; @property (weak) UIButton *payButton; @end @implementation CheckoutViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; STPPaymentCardTextField *cardTextField = [[STPPaymentCardTextField alloc] init]; self.cardTextField = cardTextField; UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.layer.cornerRadius = 5; button.backgroundColor = [UIColor systemBlueColor]; button.titleLabel.font = [UIFont systemFontOfSize:22]; [button setTitle:@"Pay" forState:UIControlStateNormal]; [button addTarget:self action:@selector(pay) forControlEvents:UIControlEventTouchUpInside]; self.payButton = button; UIStackView *stackView = [[UIStackView alloc] initWithArrangedSubviews:@[cardTextField, button]]; stackView.axis = UILayoutConstraintAxisVertical; stackView.translatesAutoresizingMaskIntoConstraints = NO; stackView.spacing = 20; [self.view addSubview:stackView]; [NSLayoutConstraint activateConstraints:@[ [stackView.leftAnchor constraintEqualToSystemSpacingAfterAnchor:self.view.leftAnchor multiplier:2], [self.view.rightAnchor constraintEqualToSystemSpacingAfterAnchor:stackView.rightAnchor multiplier:2], [stackView.topAnchor constraintEqualToSystemSpacingBelowAnchor:self.view.topAnchor multiplier:2], ]]; } - (void)pay { // ... } @end

Run your app, and make sure your checkout page shows the card component and pay button.

3 Create a PaymentIntent Server-side Client-side

You can create a payments page to accept payments for your users. Refer to your platform profile to determine if direct charges or destination charges is recommended for your business.

Stripe uses a PaymentIntent object to represent your intent to collect payment from a customer, tracking your charge attempts and payment state changes throughout the process.

Server-side

On your server, make an endpoint that creates a PaymentIntent with an amount and currency. Always decide how much to charge on the server side, a trusted environment, as opposed to the client. This prevents malicious customers from being able to choose their own prices.

curl https://api.stripe.com/v1/payment_intents \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d amount=1000 \ -d currency=usd \ -d application_fee_amount=123 \ -d "transfer_data[destination]"="{{CONNECTED_STRIPE_ACCOUNT_ID}}"
# 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' payment_intent = Stripe::PaymentIntent.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, transfer_data: { destination: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, }) client_secret = payment_intent['client_secret'] # Pass the client secret to the client
# 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' payment_intent = stripe.PaymentIntent.create( payment_method_types=['card'], amount=1000, currency='usd', application_fee_amount=123, transfer_data={ 'destination': '{{CONNECTED_STRIPE_ACCOUNT_ID}}', } ) client_secret = intent.client_secret # Pass the client secret to the client
// 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'); $payment_intent = \Stripe\PaymentIntent::create([ 'payment_method_types' => ['card'], 'amount' => 1000, 'currency' => 'usd', 'application_fee_amount' => 123, 'transfer_data' => [ 'destination' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}', ], ]); $client_secret = $intent->client_secret; // Pass the client secret to the client
// 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"; ArrayList paymentMethodTypes = new ArrayList(); paymentMethodTypes.add("card"); Map<String, Object> params = new HashMap<>(); params.put("payment_method_types", paymentMethodTypes); params.put("amount", 1000); params.put("currency", "usd"); params.put("application_fee_amount", 123); Map<String, Object> transferDataParams = new HashMap<>(); transferDataParams.put("destination", "{{CONNECTED_STRIPE_ACCOUNT_ID}}"); params.put("transfer_data", transferDataParams); PaymentIntent paymentIntent = PaymentIntent.create(params); PaymentIntent intent = PaymentIntent.create(params); String clientSecret = intent.getClientSecret(); // Pass the client secret to the client
// 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 paymentIntent = await stripe.paymentIntents.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, transfer_data: { destination: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, }); const clientSecret = paymentIntent.client_secret;
// 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.PaymentIntentParams{ PaymentMethodTypes: stripe.StringSlice([]string{ "card", }), Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), ApplicationFeeAmount: stripe.Int64(123), TransferData: &stripe.PaymentIntentTransferDataParams{ Destination: stripe.String("{{CONNECTED_STRIPE_ACCOUNT_ID}}"), }, } pi, _ := paymentintent.New(params) // Pass the client secret to the client
// 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 PaymentIntentService(); var createOptions = new PaymentIntentCreateOptions { PaymentMethodTypes = new List<string> { "card", }, Amount = 2000, Currency = "usd", ApplicationFeeAmount = 123, TransferData = new PaymentIntentTransferDataOptions { Destination = "{{CONNECTED_STRIPE_ACCOUNT_ID}}", }, }; service.Create(createOptions); // Pass the client secret to the client

In our home-rental example, we want to build an experience where customers pay for rentals by using our platform, and where we pay homeowners for renting to customers. To set this experience up:

  • Indicate the rental is a destination charge with transfer_data[destination].
  • Specify how much of the rental amount will go to the platform with application_fee_amount.

When a rental charge occurs, Stripe transfers the entire amount to the connected account’s pending balance (transfer_data[destination]). Afterward, Stripe transfers the fee amount (application_fee_amount) to the platform’s account, which is the share of the revenue for facilitating the rental. Then, Stripe deducts the Stripe fees from the platform’s fee amount. An illustration of this funds flow is below:

Instead of passing the entire PaymentIntent object to your app, just return its client secret. The PaymentIntent’s client secret is a unique key that lets you confirm the payment and update card details on the client, without allowing manipulation of sensitive information, like payment amount.

Client-side

On the client, request a PaymentIntent from your server and store its client secret.

class CheckoutViewController: UIViewController { var paymentIntentClientSecret: String? // ...continued from previous step override func viewDidLoad() { // ...continued from previous step startCheckout() } func startCheckout() { // Request a PaymentIntent from your server and store its client secret // Click Open on GitHub to see a full implementation } }
@interface CheckoutViewController () // ...continued from previous step @property (strong) NSString *paymentIntentClientSecret; @end @implementation CheckoutViewController - (void)viewDidLoad { [super viewDidLoad]; // ...continued from previous step [self startCheckout]; } - (void)startCheckout { // Request a PaymentIntent from your server and store its client secret // Click Open on GitHub to see a full implementation } @end

Stripe uses a PaymentIntent object to represent your intent to collect payment from a customer, tracking your charge attempts and payment state changes throughout the process.

Server-side

On your server, make an endpoint that creates a PaymentIntent with an amount and currency. Always decide how much to charge on the server side, a trusted environment, as opposed to the client. This prevents malicious customers from being able to choose their own prices.

curl https://api.stripe.com/v1/payment_intents \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d amount=1000 \ -d currency=usd \ -d application_fee_amount=123 \ -H "Stripe-Account: {{CONNECTED_STRIPE_ACCOUNT_ID}}"
# 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' payment_intent = Stripe::PaymentIntent.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, }, stripe_account: '{{CONNECTED_STRIPE_ACCOUNT_ID}}') client_secret = payment_intent['client_secret'] # Pass the client secret to the client
# 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' payment_intent = stripe.PaymentIntent.create( payment_method_types=['card'], amount=1000, currency='usd', application_fee_amount=123, stripe_account='{{CONNECTED_STRIPE_ACCOUNT_ID}}', ) client_secret = intent.client_secret # Pass the client secret to the client
// 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'); $payment_intent = \Stripe\PaymentIntent::create([ 'payment_method_types' => ['card'], 'amount' => 1000, 'currency' => 'usd', 'application_fee_amount' => 123, ], ['stripe_account' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}']); $client_secret = $intent->client_secret; // Pass the client secret to the client
// 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"; ArrayList paymentMethodTypes = new ArrayList(); paymentMethodTypes.add("card"); Map<String, Object> params = new HashMap<>(); params.put("payment_method_types", paymentMethodTypes); params.put("amount", 1000); params.put("currency", "usd"); params.put("application_fee_amount", 123); RequestOptions requestOptions = RequestOptions.builder().setStripeAccount({{CONNECTED_STRIPE_ACCOUNT_ID}}).build(); PaymentIntent paymentIntent = PaymentIntent.create(params, requestOptions); PaymentIntent intent = PaymentIntent.create(params); String clientSecret = intent.getClientSecret(); // Pass the client secret to the client
// 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 paymentIntent = await stripe.paymentIntents.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, }, { stripeAccount: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }); const clientSecret = paymentIntent.client_secret;
// 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.PaymentIntentParams{ PaymentMethodTypes: stripe.StringSlice([]string{ "card", }), Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), ApplicationFeeAmount: stripe.Int64(123), } params.SetStripeAccount("{{CONNECTED_STRIPE_ACCOUNT_ID}}") pi, _ := paymentintent.New(params) // Pass the client secret to the client
// 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 PaymentIntentService(); var createOptions = new PaymentIntentCreateOptions { PaymentMethodTypes = new List<string> { "card", }, Amount = 2000, Currency = "usd", ApplicationFeeAmount = 123, }; var requestOptions = new RequestOptions(); requestOptions.StripeAccount = "{{CONNECTED_STRIPE_ACCOUNT_ID}}"; service.Create(createOptions, requestOptions); // Pass the client secret to the client

In our store builder example, we want to build an experience where customers pay businesses directly. To set this experience up:

  • Indicate a purchase from the business is a direct charge with the Stripe-Account header.
  • Specify how much of the purchase from the business will go to the platform with application_fee_amount.

When a sale occurs, Stripe transfers the application_fee_amount from the connected account to the platform and deducts the Stripe fee from the connected account’s share. An illustration of this funds flow is below:

Instead of passing the entire PaymentIntent object to your app, just return its client secret. The PaymentIntent’s client secret is a unique key that lets you confirm the payment and update card details on the client, without allowing manipulation of sensitive information, like payment amount.

Client-side

Set the connected account id as an argument to the client application in the client-side libraries.

import UIKit import Stripe @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { Stripe.setDefaultPublishableKey("{{PLATFORM_PUBLISHABLE_KEY}}") STPAPIClient.shared().stripeAccount = "{{CONNECTED_STRIPE_ACCOUNT_ID}}" // For SDK versions < v19.0.0, set this too: STPPaymentConfiguration.shared().stripeAccount = "{{CONNECTED_STRIPE_ACCOUNT_ID}}" return true } }
#import "AppDelegate.h" #import <Stripe/Stripe.h> @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [Stripe setDefaultPublishableKey:@"{{PLATFORM_PUBLISHABLE_KEY}}"]; [STPAPIClient sharedClient] setStripeAccount:@"{{CONNECTED_STRIPE_ACCOUNT_ID}}"]; // For SDK versions < v19.0.0, set this too: [[STPPaymentConfiguration sharedConfiguration] setStripeAccount:@"{{CONNECTED_STRIPE_ACCOUNT_ID}}"]; return YES; } @end

On the client, request a PaymentIntent from your server and store its client secret.

class CheckoutViewController: UIViewController { var paymentIntentClientSecret: String? // ...continued from previous step override func viewDidLoad() { // ...continued from previous step startCheckout() } func startCheckout() { // Request a PaymentIntent from your server and store its client secret // Click Open on GitHub to see a full implementation } }
@interface CheckoutViewController () // ...continued from previous step @property (strong) NSString *paymentIntentClientSecret; @end @implementation CheckoutViewController - (void)viewDidLoad { [super viewDidLoad]; // ...continued from previous step [self startCheckout]; } - (void)startCheckout { // Request a PaymentIntent from your server and store its client secret // Click Open on GitHub to see a full implementation } @end

4 Submit the payment to Stripe Client-side

When the customer taps the Pay button, confirm the PaymentIntent to complete the payment.

First, assemble a STPPaymentIntentParams object with:

  1. The card text field’s payment method details
  2. The PaymentIntent client secret from your server

Rather than sending the entire PaymentIntent object to the client, use its client secret. This is different from your API keys that authenticate Stripe API requests. The client secret is a string that lets your app access important fields from the PaymentIntent (e.g., status) while hiding sensitive ones (e.g., customer).

The client secret should still be handled carefully because it can complete the charge. Do not log it, embed it in URLs, or expose it to anyone but the customer.

Next, complete the payment by calling the STPPaymentHandler confirmPayment method.

class CheckoutViewController: UIViewController { // ... @objc func pay() { guard let paymentIntentClientSecret = paymentIntentClientSecret else { return; } // Collect card details let cardParams = cardTextField.cardParams let paymentMethodParams = STPPaymentMethodParams(card: cardParams, billingDetails: nil, metadata: nil) let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret) paymentIntentParams.paymentMethodParams = paymentMethodParams // Submit the payment let paymentHandler = STPPaymentHandler.shared() paymentHandler.confirmPayment(withParams: paymentIntentParams, authenticationContext: self) { (status, paymentIntent, error) in switch (status) { case .failed: self.displayAlert(title: "Payment failed", message: error?.localizedDescription ?? "") break case .canceled: self.displayAlert(title: "Payment canceled", message: error?.localizedDescription ?? "") break case .succeeded: self.displayAlert(title: "Payment succeeded", message: paymentIntent?.description ?? "", restartDemo: true) break @unknown default: fatalError() break } } } } extension CheckoutViewController: STPAuthenticationContext { func authenticationPresentingViewController() -> UIViewController { return self } }
@interface CheckoutViewController () <STPAuthenticationContext> // ... @end @implementation CheckoutViewController // ... - (void)pay { if (!self.paymentIntentClientSecret) { NSLog(@"PaymentIntent hasn't been created"); return; } // Collect card details STPPaymentMethodCardParams *cardParams = self.cardTextField.cardParams; STPPaymentMethodParams *paymentMethodParams = [STPPaymentMethodParams paramsWithCard:cardParams billingDetails:nil metadata:nil]; STPPaymentIntentParams *paymentIntentParams = [[STPPaymentIntentParams alloc] initWithClientSecret:self.paymentIntentClientSecret]; paymentIntentParams.paymentMethodParams = paymentMethodParams; // Submit the payment STPPaymentHandler *paymentHandler = [STPPaymentHandler sharedHandler]; [paymentHandler confirmPayment:paymentIntentParams withAuthenticationContext:self completion:^(STPPaymentHandlerActionStatus status, STPPaymentIntent *paymentIntent, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ switch (status) { case STPPaymentHandlerActionStatusFailed: { [self displayAlertWithTitle:@"Payment failed" message:error.localizedDescription ?: @"" restartDemo:NO]; break; } case STPPaymentHandlerActionStatusCanceled: { [self displayAlertWithTitle:@"Payment canceled" message:error.localizedDescription ?: @"" restartDemo:NO]; break; } case STPPaymentHandlerActionStatusSucceeded: { [self displayAlertWithTitle:@"Payment succeeded" message:paymentIntent.description ?: @"" restartDemo:YES]; break; } default: break; } }); }]; } # pragma mark STPAuthenticationContext - (UIViewController *)authenticationPresentingViewController { return self; } @end

If authentication is required by regulation such as Strong Customer Authentication, STPPaymentHandler presents view controllers using the STPAuthenticationContext passed in and walks the customer through that process. See Supporting 3D Secure Authentication on iOS to learn more.

If the payment succeeds, the completion handler is called with a status of .succeeded. If it fails, the status is .failed and you can display the error.localizedDescription to the user.

You can also check the status of a PaymentIntent in the Dashboard or by inspecting the status property on the object.

5 Test the integration

By this point you should have a basic card integration that collects card details and makes a payment.

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

Number Description
4242424242424242 Succeeds and immediately processes the payment.
4000002500003155 Requires authentication. Stripe will trigger a modal asking for the customer to authenticate.
4000000000009995 Always fails with a decline code of insufficient_funds.

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

6 Handle post-payment events

Fulfillment

After payment is completed, you must handle any necessary fulfillment. Stripe sends a payment_intent.succeeded event when the payment completes. Use the Dashboard, a custom webhook, or a partner solution to receive these events and run actions.

Create an HTTP endpoint on your server to monitor for completed payments to then enable your users (connected accounts) to fulfill purchases.

# Using Sinatra. require 'sinatra' require 'stripe' set :port, 4242 # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' post '/webhook' do payload = request.body.read sig_header = request.env['HTTP_STRIPE_SIGNATURE'] event = nil # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. begin event = Stripe::Webhook.construct_event( payload, sig_header, webhook_secret ) rescue JSON::ParserError => e # Invalid payload. status 400 return rescue Stripe::SignatureVerificationError => e # Invalid Signature. status 400 return end if event['type'] == 'payment_intent.succeeded' payment_intent = event['data']['object'] connected_account_id = event['account'] handle_successful_payment_intent(connected_account_id, payment_intent) end status 200 end def handle_successful_payment_intent(connected_account_id, payment_intent) # Fulfill the purchase. puts 'Connected account ID: ' + connected_account_id puts payment_intent.to_s end
import stripe import json # Using Flask. from flask import ( Flask, render_template, request, Response, ) app = Flask(__name__, static_folder=".", static_url_path="", template_folder=".") # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' @app.route("/webhook", methods=["POST"]) def webhook_received(): request_data = json.loads(request.data) signature = request.headers.get("stripe-signature") # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. try: event = stripe.Webhook.construct_event( payload=request.data, sig_header=signature, secret=webhook_secret ) except ValueError as e: # Invalid payload. return Response(status=400) except stripe.error.SignatureVerificationError as e: # Invalid Signature. return Response(status=400) if event["type"] == "payment_intent.succeeded": payment_intent = event["data"]["object"] connected_account_id = event["account"] handle_successful_payment_intent(connected_account_id, payment_intent) return json.dumps({"success": True}), 200 def handle_successful_payment_intent(connected_account_id, payment_intent): # Fulfill the purchase. print('Connected account ID: ' + connected_account_id) print(str( payment_intent)) if __name__ == "__main__": app.run(port=4242)
<?php // Using Slim. use Slim\Http\Request; use Slim\Http\Response; use Stripe\Stripe; require_once('vendor/autoload.php'); $app = new \Slim\App; // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // $webhook_secret = 'whsec_...'; $app->post('/webhook', function ($request, $response, $next) { $payload = $request->getBody(); $sig_header = $request->getHeaderLine('stripe-signature'); $event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { $event = \Stripe\Webhook::constructEvent( $payload, $sig_header, $webhook_secret ); } catch(\UnexpectedValueException $e) { // Invalid payload. return $response->withStatus(400); } catch(\Stripe\Exception\SignatureVerificationException $e) { // Invalid Signature. return $response->withStatus(400); } if ($event->type == 'payment_intent.succeeded') { $paymentIntent = $event->data->object; $connectedAccountId = $event->account; handleSuccessfulPaymentIntent($connectedAccountId, $paymentIntent); } return $response->withStatus(200); }); function handleSuccessfulPaymentIntent($connectedAccountId, $paymentIntent) { // Fulfill the purchase. echo 'Connected account ID: ' . $connectedAccountId; echo $paymentIntent; }; $app->run();
// Using Express const express = require('express'); const bodyParser = require("body-parser"); const app = express(); app.use(express.json()); // Use JSON parser for all non-webhook routes app.use((req, res, next) => { if (req.originalUrl === "/webhook") { next(); } else { bodyParser.json()(req, res, next); } }); // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const webhook_secret = 'whsec_...'' app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => { const sig = request.headers['stripe-signature']; let event; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = stripe.webhooks.constructEvent(request.body, sig, webhook_secret); } catch (err) { return response.status(400).send(`Webhook Error: ${err.message}`); } if (event.type === 'payment_intent.succeeded') { const paymentIntent = event.data.object; const connectedAccountId = event.account; handleSuccessfulPaymentIntent(connectedAccountId, paymentIntent); } response.json({received: true}); }); const handleSuccessfulPaymentIntent = (connectedAccountId, paymentIntent) => { // Fulfill the purchase. console.log('Connected account ID: ' + connectedAccountId); console.log(JSON.stringify(paymentIntent)); } app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
package com.stripe.sample; import com.stripe.Stripe; import com.stripe.model.PaymentIntent; import com.stripe.model.Event; import com.stripe.model.EventDataObjectDeserializer; import com.stripe.exception.SignatureVerificationException; import com.stripe.net.Webhook; import com.google.gson.JsonSyntaxException; import spark.Response; // Using Spark. import static spark.Spark.*; public class Server { public static void main(String[] args) { port(4242); // 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"; post("/webhook", (request, response) -> { String payload = request.body(); String sigHeader = request.headers("Stripe-Signature"); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // String webhookSecret = "whsec_..." Event event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = Webhook.constructEvent( payload, sigHeader, webhookSecret ); } catch (JsonSyntaxException e) { // Invalid payload. response.status(400); return ""; } catch (SignatureVerificationException e) { // Invalid Signature. response.status(400); return ""; } if ("payment_intent.succeeded".equals(event.getType())) { // Deserialize the nested object inside the event EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer(); PaymentIntent paymentIntent = null; if (dataObjectDeserializer.getObject().isPresent()) { paymentIntent = (PaymentIntent) dataObjectDeserializer.getObject().get(); String connectedAccountId = event.getAccount(); handleSuccessfulPaymentIntent(connectedAccountId, paymentIntent); } else { // Deserialization failed, probably due to an API version mismatch. // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for // instructions on how to handle this case, or return an error here. } } response.status(200); return ""; }); } private static void handleSuccessfulPaymentIntent(String connectedAccountId, PaymentIntent paymentIntent) { // Fulfill the purchase. System.out.println("Connected account ID: " + connectedAccountId); System.out.println(paymentIntent.getId()); } }
package main import ( "encoding/json" "log" "fmt" "net/http" "io/ioutil" "github.com/stripe/stripe-go/v71" "github.com/stripe/stripe-go/v71/webhook" "os" ) func main() { // 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", handleWebhook) addr := "localhost:4242" log.Printf("Listening on %s ...", addr) log.Fatal(http.ListenAndServe(addr, nil)) } func handleWebhook(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 } // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // webhookSecret := "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. event, err := webhook.ConstructEvent(body, req.Header.Get("Stripe-Signature"), webhookSecret) 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 } if event.Type == "payment_intent.succeeded" { var paymentIntent stripe.PaymentIntent err := json.Unmarshal(event.Data.Raw, &paymentIntent) if err != nil { fmt.Fprintf(os.Stderr, "Error parsing webhook JSON: %v\n", err) w.WriteHeader(http.StatusBadRequest) return } var connectedAccountId = event.Account; handleSuccessfulPaymentIntent(connectedAccountId, paymentIntent) } w.WriteHeader(http.StatusOK) } func handleSuccessfulPaymentIntent(connectedAccountId string, paymentIntent stripe.PaymentIntent) { // Fulfill the purchase. log.Println("Connected account ID: " + connectedAccountId) log.Println(paymentIntent.ID) }
// 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 System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Stripe; namespace Controllers { public class ConnectController : Controller { private readonly ILogger<ConnectController> logger; public ConnectController( ILogger<ConnectController> logger, ) { this.logger = logger; } [HttpPost("webhook")] public async Task<IActionResult> ProcessWebhookEvent() { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const string webhookSecret = "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], webhookSecret); if (stripeEvent.Type == Events.PaymentIntentSucceeded) { var paymentIntent = stripeEvent.Data.Object as PaymentIntent; var connectedAccountId = stripeEvent.Account; HandleSuccessfulPaymentIntent(connectedAccountId, paymentIntent); } return Ok(); } catch (Exception e) { logger.LogInformation(e.ToString()); return BadRequest(); } } private void HandleSuccessfulPaymentIntent(string connectedAccountId, PaymentIntent paymentIntent) { // Fulfill the purchase. logger.LogInformation($"Connected account ID: {connectedAccountId}"); logger.LogInformation($"{paymentIntent}"); } } }

Learn more in our fulfillment guide for payments.

Disputes

As the settlement merchant on charges, your platform is responsible for disputes. Make sure you understand the best practices for responding to disputes.

Collecting payments in your Android app consists of creating an object to track a payment on your server, collecting card information in your app, and submitting the payment to Stripe for processing.

Stripe uses this payment object, called a PaymentIntent, to track and handle all the states of the payment until it’s completed—even when the bank requires customer intervention, like two-factor authentication.

1 Set up Stripe Server-side Client-side

First, you need a Stripe account. Register now.

Server-side

This integration requires endpoints on your server that talk to the Stripe API. Use our official libraries for access to the Stripe API from your server:

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

Client-side

The Android SDK is open source and fully documented.

To install the SDK, add stripe-android to the dependencies block of your app/build.gradle file:

apply plugin: 'com.android.application' android { ... } dependencies { // ... // Stripe Android SDK implementation 'com.stripe:stripe-android:16.0.1' }

Configure the SDK with your Stripe publishable key so that it can make requests to the Stripe API, such as in your Application subclass:

import com.stripe.android.PaymentConfiguration class MyApp : Application() { override fun onCreate() { super.onCreate() PaymentConfiguration.init( applicationContext, "pk_test_TYooMQauvdEDq54NiTphI7jx" ) } }
import com.stripe.android.PaymentConfiguration; public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); PaymentConfiguration.init( getApplicationContext(), "pk_test_TYooMQauvdEDq54NiTphI7jx" ); } }

Our code samples also use OkHttp and GSON to make HTTP requests to a server.

2 Create your checkout page Client-side

Securely collect card information on the client with CardInputWidget, a drop-in UI component provided by the SDK.

CardInputWidget performs on-the-fly validation and formatting.

Create an instance of the card component and a Pay button by adding the following to your checkout page’s layout:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="20dp" tools:context=".CheckoutActivityKotlin" tools:showIn="@layout/activity_checkout"> <!-- ... --> <com.stripe.android.view.CardInputWidget android:id="@+id/cardInputWidget" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:text="@string/pay" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/payButton" android:layout_marginTop="20dp" android:backgroundTint="@android:color/holo_green_light"/> <!-- ... --> </LinearLayout>

Run your app, and make sure your checkout page shows the card component and pay button.

3 Create a PaymentIntent Server-side Client-side

Stripe uses a PaymentIntent object to represent your intent to collect payment from a customer, tracking your charge attempts and payment state changes throughout the process.

Server-side

On your server, make an endpoint that creates a PaymentIntent with an amount and currency. Always decide how much to charge on the server side, a trusted environment, as opposed to the client. This prevents malicious customers from being able to choose their own prices.

curl https://api.stripe.com/v1/payment_intents \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d amount=1000 \ -d currency=usd \ -d application_fee_amount=123 \ -d "transfer_data[destination]"="{{CONNECTED_STRIPE_ACCOUNT_ID}}"
# 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' payment_intent = Stripe::PaymentIntent.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, transfer_data: { destination: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, }) client_secret = payment_intent['client_secret'] # Pass the client secret to the client
# 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' payment_intent = stripe.PaymentIntent.create( payment_method_types=['card'], amount=1000, currency='usd', application_fee_amount=123, transfer_data={ 'destination': '{{CONNECTED_STRIPE_ACCOUNT_ID}}', } ) client_secret = intent.client_secret # Pass the client secret to the client
// 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'); $payment_intent = \Stripe\PaymentIntent::create([ 'payment_method_types' => ['card'], 'amount' => 1000, 'currency' => 'usd', 'application_fee_amount' => 123, 'transfer_data' => [ 'destination' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}', ], ]); $client_secret = $intent->client_secret; // Pass the client secret to the client
// 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"; ArrayList paymentMethodTypes = new ArrayList(); paymentMethodTypes.add("card"); Map<String, Object> params = new HashMap<>(); params.put("payment_method_types", paymentMethodTypes); params.put("amount", 1000); params.put("currency", "usd"); params.put("application_fee_amount", 123); Map<String, Object> transferDataParams = new HashMap<>(); transferDataParams.put("destination", "{{CONNECTED_STRIPE_ACCOUNT_ID}}"); params.put("transfer_data", transferDataParams); PaymentIntent paymentIntent = PaymentIntent.create(params); PaymentIntent intent = PaymentIntent.create(params); String clientSecret = intent.getClientSecret(); // Pass the client secret to the client
// 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 paymentIntent = await stripe.paymentIntents.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, transfer_data: { destination: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }, }); const clientSecret = paymentIntent.client_secret;
// 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.PaymentIntentParams{ PaymentMethodTypes: stripe.StringSlice([]string{ "card", }), Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), ApplicationFeeAmount: stripe.Int64(123), TransferData: &stripe.PaymentIntentTransferDataParams{ Destination: stripe.String("{{CONNECTED_STRIPE_ACCOUNT_ID}}"), }, } pi, _ := paymentintent.New(params) // Pass the client secret to the client
// 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 PaymentIntentService(); var createOptions = new PaymentIntentCreateOptions { PaymentMethodTypes = new List<string> { "card", }, Amount = 2000, Currency = "usd", ApplicationFeeAmount = 123, TransferData = new PaymentIntentTransferDataOptions { Destination = "{{CONNECTED_STRIPE_ACCOUNT_ID}}", }, }; service.Create(createOptions); // Pass the client secret to the client

In our home-rental example, we want to build an experience where customers pay for rentals by using our platform, and where we pay homeowners for renting to customers. To set this experience up:

  • Indicate the rental is a destination charge with transfer_data[destination].
  • Specify how much of the rental amount will go to the platform with application_fee_amount.

When a rental charge occurs, Stripe transfers the entire amount to the connected account’s pending balance (transfer_data[destination]). Afterward, Stripe transfers the fee amount (application_fee_amount) to the platform’s account, which is the share of the revenue for facilitating the rental. Then, Stripe deducts the Stripe fees from the platform’s fee amount. An illustration of this funds flow is below:

Instead of passing the entire PaymentIntent object to your app, just return its client secret. The PaymentIntent’s client secret is a unique key that lets you confirm the payment and update card details on the client, without allowing manipulation of sensitive information, like payment amount.

Client-side

On the client, request a PaymentIntent from your server and store its client secret.

class CheckoutActivity : AppCompatActivity() { private lateinit var paymentIntentClientSecret: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... startCheckout() } private fun startCheckout() { // Request a PaymentIntent from your server and store its client secret in paymentIntentClientSecret // Click Open on GitHub to see a full implementation } }
public class CheckoutActivity extends AppCompatActivity { private String paymentIntentClientSecret; @Override public void onCreate(Bundle savedInstanceState) { // ... startCheckout(); } private void startCheckout() { // Request a PaymentIntent from your server and store its client secret in paymentIntentClientSecret // Click Open on GitHub to see a full implementation } }

Stripe uses a PaymentIntent object to represent your intent to collect payment from a customer, tracking your charge attempts and payment state changes throughout the process.

Server-side

On your server, make an endpoint that creates a PaymentIntent with an amount and currency. Always decide how much to charge on the server side, a trusted environment, as opposed to the client. This prevents malicious customers from being able to choose their own prices.

curl https://api.stripe.com/v1/payment_intents \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d "payment_method_types[]"=card \ -d amount=1000 \ -d currency=usd \ -d application_fee_amount=123 \ -H "Stripe-Account: {{CONNECTED_STRIPE_ACCOUNT_ID}}"
# 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' payment_intent = Stripe::PaymentIntent.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, }, stripe_account: '{{CONNECTED_STRIPE_ACCOUNT_ID}}') client_secret = payment_intent['client_secret'] # Pass the client secret to the client
# 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' payment_intent = stripe.PaymentIntent.create( payment_method_types=['card'], amount=1000, currency='usd', application_fee_amount=123, stripe_account='{{CONNECTED_STRIPE_ACCOUNT_ID}}', ) client_secret = intent.client_secret # Pass the client secret to the client
// 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'); $payment_intent = \Stripe\PaymentIntent::create([ 'payment_method_types' => ['card'], 'amount' => 1000, 'currency' => 'usd', 'application_fee_amount' => 123, ], ['stripe_account' => '{{CONNECTED_STRIPE_ACCOUNT_ID}}']); $client_secret = $intent->client_secret; // Pass the client secret to the client
// 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"; ArrayList paymentMethodTypes = new ArrayList(); paymentMethodTypes.add("card"); Map<String, Object> params = new HashMap<>(); params.put("payment_method_types", paymentMethodTypes); params.put("amount", 1000); params.put("currency", "usd"); params.put("application_fee_amount", 123); RequestOptions requestOptions = RequestOptions.builder().setStripeAccount({{CONNECTED_STRIPE_ACCOUNT_ID}}).build(); PaymentIntent paymentIntent = PaymentIntent.create(params, requestOptions); PaymentIntent intent = PaymentIntent.create(params); String clientSecret = intent.getClientSecret(); // Pass the client secret to the client
// 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 paymentIntent = await stripe.paymentIntents.create({ payment_method_types: ['card'], amount: 1000, currency: 'usd', application_fee_amount: 123, }, { stripeAccount: '{{CONNECTED_STRIPE_ACCOUNT_ID}}', }); const clientSecret = paymentIntent.client_secret;
// 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.PaymentIntentParams{ PaymentMethodTypes: stripe.StringSlice([]string{ "card", }), Amount: stripe.Int64(1000), Currency: stripe.String(string(stripe.CurrencyUSD)), ApplicationFeeAmount: stripe.Int64(123), } params.SetStripeAccount("{{CONNECTED_STRIPE_ACCOUNT_ID}}") pi, _ := paymentintent.New(params) // Pass the client secret to the client
// 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 PaymentIntentService(); var createOptions = new PaymentIntentCreateOptions { PaymentMethodTypes = new List<string> { "card", }, Amount = 2000, Currency = "usd", ApplicationFeeAmount = 123, }; var requestOptions = new RequestOptions(); requestOptions.StripeAccount = "{{CONNECTED_STRIPE_ACCOUNT_ID}}"; service.Create(createOptions, requestOptions); // Pass the client secret to the client

In our store builder example, we want to build an experience where customers pay businesses directly. To set this experience up:

  • Indicate a purchase from the business is a direct charge with the Stripe-Account header.
  • Specify how much of the purchase from the business will go to the platform with application_fee_amount.

When a sale occurs, Stripe transfers the application_fee_amount from the connected account to the platform and deducts the Stripe fee from the connected account’s share. An illustration of this funds flow is below:

Instead of passing the entire PaymentIntent object to your app, just return its client secret. The PaymentIntent’s client secret is a unique key that lets you confirm the payment and update card details on the client, without allowing manipulation of sensitive information, like payment amount.

Client-side

Set the connected account id as an argument to the client application in the client-side libraries.

import com.stripe.android.PaymentConfiguration class MyActivity: Activity() { private lateinit var stripe: Stripe override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) stripe = Stripe( this, PaymentConfiguration.getInstance(this).publishableKey, "{{CONNECTED_STRIPE_ACCOUNT_ID}}" ) } }
import com.stripe.android.PaymentConfiguration; public class MyActivity extends Activity { private Stripe stripe; @Override public void onCreate(@Nullable Bundle savedInstancedState) { super.onCreate(savedInstancedState); stripe = new Stripe( this, PaymentConfiguration.getInstance(this).getPublishableKey(), "{{CONNECTED_STRIPE_ACCOUNT_ID}}" ); } }

On the client, request a PaymentIntent from your server and store its client secret.

class CheckoutActivity : AppCompatActivity() { private lateinit var paymentIntentClientSecret: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... startCheckout() } private fun startCheckout() { // Request a PaymentIntent from your server and store its client secret in paymentIntentClientSecret // Click Open on GitHub to see a full implementation } }
public class CheckoutActivity extends AppCompatActivity { private String paymentIntentClientSecret; @Override public void onCreate(Bundle savedInstanceState) { // ... startCheckout(); } private void startCheckout() { // Request a PaymentIntent from your server and store its client secret in paymentIntentClientSecret // Click Open on GitHub to see a full implementation } }

4 Submit the payment to Stripe Client-side

When the customer taps the Pay button, confirm the PaymentIntent to complete the payment.

First, assemble a ConfirmPaymentIntentParams object with:

  1. The card component’s payment method details
  2. The PaymentIntent client secret from your server

Rather than sending the entire PaymentIntent object to the client, use its client secret. This is different from your API keys that authenticate Stripe API requests. The client secret is a string that lets your app access important fields from the PaymentIntent (e.g., status) while hiding sensitive ones (e.g., customer).

The client secret should still be handled carefully because it can complete the charge. Do not log it, embed it in URLs, or expose it to anyone but the customer.

Next, complete the payment by calling the stripe confirmPayment method.

class CheckoutActivity : AppCompatActivity() { // ... private lateinit var paymentIntentClientSecret: String private lateinit var stripe: Stripe private fun startCheckout() { // ... // Hook up the pay button to the card widget and stripe instance val payButton: Button = findViewById(R.id.payButton) payButton.setOnClickListener { val params = cardInputWidget.paymentMethodCreateParams if (params != null) { val confirmParams = ConfirmPaymentIntentParams .createWithPaymentMethodCreateParams(params, paymentIntentClientSecret) stripe = Stripe(applicationContext, PaymentConfiguration.getInstance(applicationContext).publishableKey) stripe.confirmPayment(this, confirmParams) } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) val weakActivity = WeakReference<Activity>(this) // Handle the result of stripe.confirmPayment stripe.onPaymentResult(requestCode, data, object : ApiResultCallback<PaymentIntentResult> { override fun onSuccess(result: PaymentIntentResult) { val paymentIntent = result.intent val status = paymentIntent.status if (status == StripeIntent.Status.Succeeded) { val gson = GsonBuilder().setPrettyPrinting().create() displayAlert(weakActivity.get(), "Payment succeeded", gson.toJson(paymentIntent), restartDemo = true) } else { displayAlert(weakActivity.get(), "Payment failed", paymentIntent.lastPaymentError?.message ?: "") } } override fun onError(e: Exception) { displayAlert(weakActivity.get(), "Payment failed", e.toString()) } }) } }
public class CheckoutActivity extends AppCompatActivity { // ... private String paymentIntentClientSecret; private Stripe stripe; private void startCheckout() { // ... // Hook up the pay button to the card widget and stripe instance Button payButton = findViewById(R.id.payButton); payButton.setOnClickListener((View view) -> { PaymentMethodCreateParams params = cardInputWidget.getPaymentMethodCreateParams(); if (params != null) { ConfirmPaymentIntentParams confirmParams = ConfirmPaymentIntentParams .createWithPaymentMethodCreateParams(params, paymentIntentClientSecret); final Context context = getApplicationContext(); stripe = new Stripe( context, PaymentConfiguration.getInstance(context).getPublishableKey() ); stripe.confirmPayment(this, confirmParams); } }); } // ... @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); // Handle the result of stripe.confirmPayment stripe.onPaymentResult(requestCode, data, new PaymentResultCallback(this)); } // ... private static final class PaymentResultCallback implements ApiResultCallback<PaymentIntentResult> { @NonNull private final WeakReference<CheckoutActivity> activityRef; PaymentResultCallback(@NonNull CheckoutActivity activity) { activityRef = new WeakReference<>(activity); } @Override public void onSuccess(@NonNull PaymentIntentResult result) { final CheckoutActivity activity = activityRef.get(); if (activity == null) { return; } PaymentIntent paymentIntent = result.getIntent(); PaymentIntent.Status status = paymentIntent.getStatus(); if (status == PaymentIntent.Status.Succeeded) { // Payment completed successfully Gson gson = new GsonBuilder().setPrettyPrinting().create(); activity.displayAlert( "Payment completed", gson.toJson(paymentIntent), true ); } else if (status == PaymentIntent.Status.RequiresPaymentMethod) { // Payment failed activity.displayAlert( "Payment failed", Objects.requireNonNull(paymentIntent.getLastPaymentError()).getMessage(), false ); } } @Override public void onError(@NonNull Exception e) { final CheckoutActivity activity = activityRef.get(); if (activity == null) { return; } // Payment request failed – allow retrying using the same payment method activity.displayAlert("Error", e.toString(), false); } } }

If authentication is required by regulation such as Strong Customer Authentication, the SDK presents additional activities and walks the customer through that process. See Supporting 3D Secure Authentication on Android to learn more.

When the payment completes, onSuccess is called and the value of the returned PaymentIntent’s status is Succeeded. Any other value indicates the payment was not successful. Inspect lastPaymentError to determine the cause.

You can also check the status of a PaymentIntent in the Dashboard or by inspecting the status property on the object.

5 Test the integration

By this point you should have a basic card integration that collects card details and makes a payment.

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

Number Description
4242424242424242 Succeeds and immediately processes the payment.
4000002500003155 Requires authentication. Stripe will trigger a modal asking for the customer to authenticate.
4000000000009995 Always fails with a decline code of insufficient_funds.

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

6 Handle post-payment events

Fulfillment

After payment is completed, you must handle any necessary fulfillment. Stripe sends a payment_intent.succeeded event when the payment completes. Use the Dashboard, a custom webhook, or a partner solution to receive these events and run actions.

Create an HTTP endpoint on your server to monitor for completed payments to then enable your users (connected accounts) to fulfill purchases.

# Using Sinatra. require 'sinatra' require 'stripe' set :port, 4242 # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' post '/webhook' do payload = request.body.read sig_header = request.env['HTTP_STRIPE_SIGNATURE'] event = nil # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. begin event = Stripe::Webhook.construct_event( payload, sig_header, webhook_secret ) rescue JSON::ParserError => e # Invalid payload. status 400 return rescue Stripe::SignatureVerificationError => e # Invalid Signature. status 400 return end if event['type'] == 'payment_intent.succeeded' payment_intent = event['data']['object'] connected_account_id = event['account'] handle_successful_payment_intent(connected_account_id, payment_intent) end status 200 end def handle_successful_payment_intent(connected_account_id, payment_intent) # Fulfill the purchase. puts 'Connected account ID: ' + connected_account_id puts payment_intent.to_s end
import stripe import json # Using Flask. from flask import ( Flask, render_template, request, Response, ) app = Flask(__name__, static_folder=".", static_url_path="", template_folder=".") # 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' # Uncomment and replace with a real secret. You can find your endpoint's # secret in your webhook settings. # webhook_secret = 'whsec_...' @app.route("/webhook", methods=["POST"]) def webhook_received(): request_data = json.loads(request.data) signature = request.headers.get("stripe-signature") # Verify webhook signature and extract the event. # See https://stripe.com/docs/webhooks/signatures for more information. try: event = stripe.Webhook.construct_event( payload=request.data, sig_header=signature, secret=webhook_secret ) except ValueError as e: # Invalid payload. return Response(status=400) except stripe.error.SignatureVerificationError as e: # Invalid Signature. return Response(status=400) if event["type"] == "payment_intent.succeeded": payment_intent = event["data"]["object"] connected_account_id = event["account"] handle_successful_payment_intent(connected_account_id, payment_intent) return json.dumps({"success": True}), 200 def handle_successful_payment_intent(connected_account_id, payment_intent): # Fulfill the purchase. print('Connected account ID: ' + connected_account_id) print(str( payment_intent)) if __name__ == "__main__": app.run(port=4242)
<?php // Using Slim. use Slim\Http\Request; use Slim\Http\Response; use Stripe\Stripe; require_once('vendor/autoload.php'); $app = new \Slim\App; // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // $webhook_secret = 'whsec_...'; $app->post('/webhook', function ($request, $response, $next) { $payload = $request->getBody(); $sig_header = $request->getHeaderLine('stripe-signature'); $event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { $event = \Stripe\Webhook::constructEvent( $payload, $sig_header, $webhook_secret ); } catch(\UnexpectedValueException $e) { // Invalid payload. return $response->withStatus(400); } catch(\Stripe\Exception\SignatureVerificationException $e) { // Invalid Signature. return $response->withStatus(400); } if ($event->type == 'payment_intent.succeeded') { $paymentIntent = $event->data->object; $connectedAccountId = $event->account; handleSuccessfulPaymentIntent($connectedAccountId, $paymentIntent); } return $response->withStatus(200); }); function handleSuccessfulPaymentIntent($connectedAccountId, $paymentIntent) { // Fulfill the purchase. echo 'Connected account ID: ' . $connectedAccountId; echo $paymentIntent; }; $app->run();
// Using Express const express = require('express'); const bodyParser = require("body-parser"); const app = express(); app.use(express.json()); // Use JSON parser for all non-webhook routes app.use((req, res, next) => { if (req.originalUrl === "/webhook") { next(); } else { bodyParser.json()(req, res, next); } }); // 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'); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const webhook_secret = 'whsec_...'' app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => { const sig = request.headers['stripe-signature']; let event; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = stripe.webhooks.constructEvent(request.body, sig, webhook_secret); } catch (err) { return response.status(400).send(`Webhook Error: ${err.message}`); } if (event.type === 'payment_intent.succeeded') { const paymentIntent = event.data.object; const connectedAccountId = event.account; handleSuccessfulPaymentIntent(connectedAccountId, paymentIntent); } response.json({received: true}); }); const handleSuccessfulPaymentIntent = (connectedAccountId, paymentIntent) => { // Fulfill the purchase. console.log('Connected account ID: ' + connectedAccountId); console.log(JSON.stringify(paymentIntent)); } app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
package com.stripe.sample; import com.stripe.Stripe; import com.stripe.model.PaymentIntent; import com.stripe.model.Event; import com.stripe.model.EventDataObjectDeserializer; import com.stripe.exception.SignatureVerificationException; import com.stripe.net.Webhook; import com.google.gson.JsonSyntaxException; import spark.Response; // Using Spark. import static spark.Spark.*; public class Server { public static void main(String[] args) { port(4242); // 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"; post("/webhook", (request, response) -> { String payload = request.body(); String sigHeader = request.headers("Stripe-Signature"); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // String webhookSecret = "whsec_..." Event event = null; // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { event = Webhook.constructEvent( payload, sigHeader, webhookSecret ); } catch (JsonSyntaxException e) { // Invalid payload. response.status(400); return ""; } catch (SignatureVerificationException e) { // Invalid Signature. response.status(400); return ""; } if ("payment_intent.succeeded".equals(event.getType())) { // Deserialize the nested object inside the event EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer(); PaymentIntent paymentIntent = null; if (dataObjectDeserializer.getObject().isPresent()) { paymentIntent = (PaymentIntent) dataObjectDeserializer.getObject().get(); String connectedAccountId = event.getAccount(); handleSuccessfulPaymentIntent(connectedAccountId, paymentIntent); } else { // Deserialization failed, probably due to an API version mismatch. // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for // instructions on how to handle this case, or return an error here. } } response.status(200); return ""; }); } private static void handleSuccessfulPaymentIntent(String connectedAccountId, PaymentIntent paymentIntent) { // Fulfill the purchase. System.out.println("Connected account ID: " + connectedAccountId); System.out.println(paymentIntent.getId()); } }
package main import ( "encoding/json" "log" "fmt" "net/http" "io/ioutil" "github.com/stripe/stripe-go/v71" "github.com/stripe/stripe-go/v71/webhook" "os" ) func main() { // 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", handleWebhook) addr := "localhost:4242" log.Printf("Listening on %s ...", addr) log.Fatal(http.ListenAndServe(addr, nil)) } func handleWebhook(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 } // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // webhookSecret := "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. event, err := webhook.ConstructEvent(body, req.Header.Get("Stripe-Signature"), webhookSecret) 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 } if event.Type == "payment_intent.succeeded" { var paymentIntent stripe.PaymentIntent err := json.Unmarshal(event.Data.Raw, &paymentIntent) if err != nil { fmt.Fprintf(os.Stderr, "Error parsing webhook JSON: %v\n", err) w.WriteHeader(http.StatusBadRequest) return } var connectedAccountId = event.Account; handleSuccessfulPaymentIntent(connectedAccountId, paymentIntent) } w.WriteHeader(http.StatusOK) } func handleSuccessfulPaymentIntent(connectedAccountId string, paymentIntent stripe.PaymentIntent) { // Fulfill the purchase. log.Println("Connected account ID: " + connectedAccountId) log.Println(paymentIntent.ID) }
// 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 System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Stripe; namespace Controllers { public class ConnectController : Controller { private readonly ILogger<ConnectController> logger; public ConnectController( ILogger<ConnectController> logger, ) { this.logger = logger; } [HttpPost("webhook")] public async Task<IActionResult> ProcessWebhookEvent() { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); // Uncomment and replace with a real secret. You can find your endpoint's // secret in your webhook settings. // const string webhookSecret = "whsec_..." // Verify webhook signature and extract the event. // See https://stripe.com/docs/webhooks/signatures for more information. try { var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], webhookSecret); if (stripeEvent.Type == Events.PaymentIntentSucceeded) { var paymentIntent = stripeEvent.Data.Object as PaymentIntent; var connectedAccountId = stripeEvent.Account; HandleSuccessfulPaymentIntent(connectedAccountId, paymentIntent); } return Ok(); } catch (Exception e) { logger.LogInformation(e.ToString()); return BadRequest(); } } private void HandleSuccessfulPaymentIntent(string connectedAccountId, PaymentIntent paymentIntent) { // Fulfill the purchase. logger.LogInformation($"Connected account ID: {connectedAccountId}"); logger.LogInformation($"{paymentIntent}"); } } }

Learn more in our fulfillment guide for payments.

Disputes

As the settlement merchant on charges, your platform is responsible for disputes. Make sure you understand the best practices for responding to disputes.

Was this page helpful?
Questions? Contact us.
Developer tutorials on YouTube.