Enable your users to accept payments directly

    Facilitate direct payments between other businesses and their own customers.

    Overview

    This guide walks you through how to enable your users to accept payments, move a portion of their earnings into your balance, and pay out the remainder to your users’ bank accounts. We’ll illustrate these concepts with an example of a store builder platform that enables its customers (merchants) to set up their own Internet stores.

    Prerequisites

    1. Register your platform.
    2. Activate your account.
    3. Fill out your platform profile.

    1 Set up Stripe Server-side

    Install Stripe’s official libraries so you can access the API from your application:

    # Available as a gem sudo gem install stripe
    # If you use bundler, you can add this line to your Gemfile gem 'stripe'
    # Install through pip pip install --upgrade stripe
    # Or find the Stripe package on http://pypi.python.org/pypi/stripe/
    # Install the PHP library via Composer composer require stripe/stripe-php
    # Or download the source directly: https://github.com/stripe/stripe-php/releases
    /* For Gradle, add the following dependency to your build.gradle and replace {VERSION} with the version number you want to use from - https://mvnrepository.com/artifact/com.stripe/stripe-java or - https://github.com/stripe/stripe-java/releases/latest */ implementation "com.stripe:stripe-java:{VERSION}"
    <!-- For Maven, add the following dependency to your POM and replace {VERSION} with the version number you want to use from - https://mvnrepository.com/artifact/com.stripe/stripe-java or - https://github.com/stripe/stripe-java/releases/latest --> <dependency> <groupId>com.stripe</groupId> <artifactId>stripe-java</artifactId> <version>{VERSION}</version> </dependency>
    # For other environments, manually install the following JARs: # - The Stripe JAR from https://github.com/stripe/stripe-java/releases/latest # - Google Gson from https://github.com/google/gson
    # Install via npm npm install --save stripe
    # Install via go go get github.com/stripe/stripe-go
    // Then import the package import ( "github.com/stripe/stripe-go" )
    # Install via dotnet dotnet add package Stripe.net dotnet restore
    # Or install via NuGet PM> Install-Package Stripe.net

    2 Create a connected account

    When a user (seller or service provider) signs up on your platform, create a user Account (referred to as a connected account) so you can accept payments and move funds to their bank account. Connected accounts represent your user in Stripe’s API and help facilitate the collection of onboarding requirements so Stripe can verify the user’s identity. In our store builder example, the connected account represents the merchant setting up their Internet store.

    Step 2.1: Add an authentication button Client-side

    Add an OAuth link to your website so the user can sign up for your platform:

    https://connect.stripe.com/oauth/authorize?client_id=ca_32D88BD1qLklliziD7gYQvctJIhWBSQ7&state={STATE_VALUE}&scope=read_write&response_type=code&stripe_user[email]=user@example.com&stripe_user[url]=example.com
    • client_id - This can be found in your platform settings. If you’re testing your integration, enable View test data in the Dashboard.
    • state - Use this argument to prevent CSRF attacks. It should be a unique, not guessable value that’s generated and saved on your server. Stripe passes it back to your redirect after the user finishes the onboarding flow.
    • scope - Set this argument to read_write to allow charges and other writes for the connected account.
    • response_type - Use code to specify that we’ll send you an authorization code back in the redirect.
    • stripe_user - Use these arguments to prefill fields with information that you’ve already collected from the user. For example, if you have collected the merchant’s email and website URL, you can provide this information to Stripe with the stripe_user[email] and stripe_user[url] arguments.

    Click the OAuth link below to see an example flow from the user’s perspective.

    Connect with Stripe

    Step 2.2: Save the account ID Server-side

    In platform settings, specify where the user should be redirected to after they’ve completed the OAuth flow with redirect_uri.

    For example, if your redirect URI is https://www.example.com/connect/oauth, Stripe might redirect to https://www.example.com/connect/oauth?state=s_987654321&authorization_code=ac_123456789.

    Write a GET handler to extract the parameters from the URI, verify the state against the state you saved on your server, and send the token to Stripe’s API:

    curl https://connect.stripe.com/oauth/token \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d code=ac_123456789 \ -d grant_type=authorization_code
    # 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' get '/' do # Display landing page. content_type 'text/html' send_file File.join('./index.html') end get '/connect/oauth' do content_type 'application/json' # Assert the state matches the state you provided in the OAuth link (optional). state = params[:state] if !state_matches?(state) status 403 return {error: 'Incorrect state parameter: ' + state}.to_json end # Send the authorization code to Stripe's API. code = params[:code] begin response = Stripe::OAuth.token({ grant_type: 'authorization_code', code: code, }) rescue Stripe::OAuth::InvalidGrantError status 400 return {error: 'Invalid authorization code: ' + code}.to_json rescue Stripe::StripeError status 500 return {error: 'An unknown error occurred.'}.to_json end connected_account_id = response.stripe_user_id save_account_id(connected_account_id) # Render some HTML or redirect to a different page. status 200 {success: true}.to_json end def state_matches?(state_parameter) # Load the same state value that you randomly generated for your OAuth link. saved_state = '{{ STATE }}' saved_state == state_parameter end def save_account_id(id) # Save the connected account ID from the response to your database. puts 'Connected account ID: ' + id end
    import stripe import json # Using Flask. from flask import ( Flask, render_template, request, ) app = Flask(__name__, static_folder=".", static_url_path="", template_folder=".") @app.route('/', methods=['GET']) def get_example(): # Display landing page. return render_template('index.html') # 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' @app.route("/connect/oauth", methods=["GET"]) def handle_oauth_redirect(): # Assert the state matches the state you provided in the OAuth link (optional). state = request.args.get("state") if not state_matches(state): return json.dumps({"error": "Incorrect state parameter: " + state}), 403 # Send the authorization code to Stripe's API. code = request.args.get("code") try: response = stripe.OAuth.token(grant_type="authorization_code", code=code,) except stripe.oauth_error.OAuthError as e: return json.dumps({"error": "Invalid authorization code: " + code}), 400 except Exception as e: return json.dumps({"error": "An unknown error occurred."}), 500 connected_account_id = response["stripe_user_id"] save_account_id(connected_account_id) # Render some HTML or redirect to a different page. return json.dumps({"success": True}), 200 def state_matches(state_parameter): # Load the same state value that you randomly generated for your OAuth link. saved_state = "{{ STATE }}" return saved_state == state_parameter def save_account_id(id): # Save the connected account ID from the response to your database. print("Connected account ID: ", id) 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'); $app->get('/', function (Request $request, Response $response, array $args) { // Display landing page. return $response->write(file_get_contents('./index.html')); }); $app->get('/connect/oauth', function ($request, $response, $next) { extract($request->getQueryParams()); // Assert the state matches the state you provided in the OAuth link (optional). if (!stateMatches($state)) return $response->withStatus(403)->withJson(array('error' => 'Incorrect state parameter: ' . $state)); // Send the authorization code to Stripe's API. $code = $request->getQueryParam('code'); try { $stripeResponse = \Stripe\OAuth::token([ 'grant_type' => 'authorization_code', 'code' => $code, ]); } catch (\Stripe\Error\OAuth\InvalidGrant $e) { return $response->withStatus(400)->withJson(array('error' => 'Invalid authorization code: ' . $code)); } catch (Exception $e) { return $response->withStatus(500)->withJson(array('error' => 'An unknown error occurred.')); } $connectedAccountId = $stripeResponse->stripe_user_id; saveAccountId($connectedAccountId); // Render some HTML or redirect to a different page. return $response->withStatus(200)->withJson(array('success' => true)); }); function stateMatches($stateParameter) { // Load the same state value that you randomly generated for your OAuth link. $savedState = '{{ STATE }}'; return $savedState == $stateParameter; }; function saveAccountId($id) { // Save the connected account ID from the response to your database. echo 'Connected account ID: ' . $id; }; $app->run();
    // Using Express const express = require('express'); const app = express(); app.use(express.json()); const { resolve } = require("path"); // 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'); app.get("/", (req, res) => { // Display landing page. const path = resolve("./index.html"); res.sendFile(path); }); app.get("/connect/oauth", async (req, res) => { const { code, state } = req.query; // Assert the state matches the state you provided in the OAuth link (optional). if(!stateMatches(state)) { return res.status(403).json({ error: 'Incorrect state parameter: ' + state }); } var error; // Send the authorization code to Stripe's API. stripe.oauth.token({ grant_type: 'authorization_code', code }).then( (response) => { var connected_account_id = response.stripe_user_id; saveAccountId(connected_account_id); // Render some HTML or redirect to a different page. return res.status(200).json({success: true}); }, (err) => { if (err.type === 'StripeInvalidGrantError') { return res.status(400).json({error: 'Invalid authorization code: ' + code}); } else { return res.status(500).json({error: 'An unknown error occurred.'}); } } ); }); const stateMatches = (state_parameter) => { // Load the same state value that you randomly generated for your OAuth link. const saved_state = 'sv_53124'; return saved_state == state_parameter; } const saveAccountId = (id) => { // Save the connected account ID from the response to your database. console.log('Connected account ID: ' + id); } app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
    package com.stripe.sample; import com.google.gson.Gson; import com.stripe.Stripe; import com.stripe.net.OAuth; import com.stripe.model.oauth.TokenResponse; import com.stripe.exception.StripeException; import com.stripe.exception.oauth.InvalidGrantException; import spark.Response; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; // Using Spark. import static spark.Spark.*; import io.github.cdimascio.dotenv.Dotenv; public class Server { private static Gson gson = new Gson(); 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"; staticFiles.externalLocation("../client"); get("/connect/oauth", (request, response) -> { // Assert the state matches the state you provided in the OAuth link (optional). String state = request.queryParams("state"); if (!stateMatches(state)) { return buildResponse( response, 403, "error", "Incorrect state parameter: " + state ); } // Send the authorization code to Stripe's API. String code = request.queryParams("code"); Map<String, Object> params = new HashMap<>(); params.put("grant_type", "authorization_code"); params.put("code", code); try { TokenResponse stripeResponse = OAuth.token(params, null); // Save the connected account ID from the response to your database. String connectedAccountId = stripeResponse.getStripeUserId(); saveAccountId(connectedAccountId); // Render some HTML or redirect to a different page. return buildResponse(response, 200, "success", "Request succeeded."); } catch (InvalidGrantException e) { // There's a problem with the authorization code. return buildResponse( response, 400, "error", "Invalid authorization code: " + code ); } catch (StripeException e) { // All other errors. return buildResponse( response, 500, "error", "An unknown error occurred." ); } }); } private static boolean stateMatches(String parameterState) { // Load the same state value that you randomly generated for your OAuth link. String savedState = "{{ STATE }}"; return savedState.equals(parameterState); } private static void saveAccountId(String id) { System.out.println("Connected account ID: " + id); } private static String buildResponse( Response response, int statusCode, String type, String message ) { response.status(statusCode); Map<String, String> errorResponse = new HashMap<>(); errorResponse.put(type, message); return gson.toJson(errorResponse); } }
    package main import ( "encoding/json" "log" "fmt" "net/http" "github.com/stripe/stripe-go" "github.com/stripe/stripe-go/oauth" "os" ) type CreateOAuthResponse struct { Success bool `json:"success"` } 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" // Display landing page. fs := http.FileServer(http.Dir("static")) http.Handle("/", fs) http.HandleFunc("/connect/oauth", handleOauthRedirect) addr := "localhost:4242" log.Printf("Listening on %s ...", addr) log.Fatal(http.ListenAndServe(addr, nil)) } func handleOauthRedirect(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() // Assert the state matches the state you provided in the OAuth link (optional). state := query.Get("state") if !stateMatches(state, w) { http.Error(w, fmt.Sprintf("Invalid state parameter: %s", state), http.StatusForbidden) return } // Send the authorization code to Stripe's API. code := query.Get("code") params := &stripe.OAuthTokenParams{ GrantType: stripe.String("authorization_code"), Code: &code, } token, err := oauth.New(params) if err != nil { stripeErr := err.(*stripe.Error) if (stripeErr.OAuthError == "invalid_grant") { http.Error(w, fmt.Sprintf("Invalid authorization code: %s", code), http.StatusBadRequest) } else { http.Error(w, "An unknown error occurred.", http.StatusInternalServerError) } return } connectedAccountId := token.StripeUserID saveAccountId(connectedAccountId) // Render some HTML or redirect to a different page. json.NewEncoder(w).Encode(CreateOAuthResponse{ Success: true, }) } func stateMatches(state_parameter string, w http.ResponseWriter) bool { // Load the same state value that you randomly generated for your OAuth link. saved_state := "{{ STATE }}" return saved_state == state_parameter } func saveAccountId(id string) { // Save the connected account ID from the response to your database. log.Println("Connected account ID: " + id) }
    using System; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.AspNetCore.Http; using Stripe; using Newtonsoft.Json; namespace Controllers { public class ConnectController : Controller { private readonly StripeClient client; private readonly IOptions<StripeOptions> options; private readonly ILogger<ConnectController> logger; public ConnectController( IOptions<StripeOptions> options, ILogger<ConnectController> logger, ) { // Set your secret key: remember to switch to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys this.client = new StripeClient("sk_test_4eC39HqLyjWDarjtT1zdp7dc"); this.options = options; this.logger = logger; } [HttpGet("/connect/oauth")] public IActionResult HandleOAuthRedirect( [FromQuery] string state, [FromQuery] string code ) { var service = new OAuthTokenService(client); // Assert the state matches the state you provided in the OAuth link (optional). if (!StateMatches(state)) { return StatusCode( StatusCodes.Status403Forbidden, Json(new { Error = String.Format("Incorrect state parameter: {0}", state) }) ); } // Send the authorization code to Stripe's API. var options = new OAuthTokenCreateOptions { GrantType = "authorization_code", Code = code, }; OAuthToken response = null; try { response = service.Create(options); } catch (StripeException e) { if (e.StripeError != null && e.StripeError.Error == "invalid_grant") { return StatusCode( StatusCodes.Status400BadRequest, Json(new { Error = String.Format("Invalid authorization code: {0}", code) }) ); } else { return StatusCode( StatusCodes.Status500InternalServerError, Json(new { Error = "An unknown error occurred." }) ); } } var connectedAccountId = response.StripeUserId; SaveAccountId(connectedAccountId); // Render some HTML or redirect to a different page. return new OkObjectResult(Json(new { Success = true })); } private bool StateMatches(string stateParameter) { // Load the same state value that you randomly generated for your OAuth link. var savedState = "{{ STATE }}"; return savedState == stateParameter; } private void SaveAccountId(string id) { // Save the connected account ID from the response to your database. logger.LogInformation($"Connected account ID: {id}"); } } }

    Make sure to save the stripe_user_id parameter that’s returned to your database. This is your connected account’s ID and begins with acct_. You will need it later to transfer funds to the account.

    3 Accept a payment

    After you create a connected account for your user, you can accept a payment for them using Checkout, a payment form hosted by Stripe. If you want to build your own payment form, use Stripe Elements for your frontend and refer to the direct charges guide for your backend.

    Step 3.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}}"
    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}}'})
    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}}', )
    $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}}']);
    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);
    (async () => { 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}}', }); })();
    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}}") session, err := session.New(params)
    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 3.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}}' }); stripe.redirectToCheckout({ // Make the id field from the Checkout Session creation API response // available to this file, so you can provide it as parameter here // instead of the {{CHECKOUT_SESSION_ID}} placeholder. sessionId: '{{CHECKOUT_SESSION_ID}}' }).then(function (result) { // If `redirectToCheckout` fails due to a browser or network // error, display the localized error message to your customer // using `result.error.message`. });
    // 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 {error} = await stripe.redirectToCheckout({ // Make the id field from the Checkout Session creation API response // available to this file, so you can provide it as parameter here // instead of the {{CHECKOUT_SESSION_ID}} placeholder. sessionId: '{{CHECKOUT_SESSION_ID}}' }) // If `redirectToCheckout` fails due to a browser or network // error, display the localized error message to your customer // using `error.message`.

    Click Preview Checkout below to see the flow from the user’s perspective. 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.

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

    Step 3.3: Fulfillment Server-side

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

    If you’re using Checkout, 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_checkout_session(connected_account_id, session) end status 200 end def handle_checkout_session(connected_account_id, session) # Fulfill the purchase. puts 'Connected account ID: ' + connected_account_id puts 'Session: ' + session.to_s end
    import stripe import json # Using Flask. from flask import ( Flask, render_template, request, ) 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 HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid Signature. return HttpResponse(status=400) if event["type"] == "checkout.session.completed": session = event["data"]["object"] connected_account_id = event["account"] handle_checkout_session(connected_account_id, session) return json.dumps({"success": True}), 200 def handle_checkout_session(connected_account_id, session): # Fulfill the purchase. print('Connected account ID: ' + connected_account_id) print('Session: ' + 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; handleCheckoutSession($connectedAccountId, $session); } return $response->withStatus(200); }); function handleCheckoutSession($connectedAccountId, $session) { // Fulfill the purchase. echo 'Connected account ID: ' . $connectedAccountId; echo 'Session: ' . $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; handleCheckoutSession(connectedAccountId, session); } response.json({received: true}); }); const handleCheckoutSession = (connectedAccountId, session) => { // Fulfill the purchase. console.log('Connected account ID: ' + connectedAccountId); console.log('Session: ' + 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(); handleCheckoutSession(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 handleCheckoutSession(String connectedAccountId, Session session) { // Fulfill the purchase. System.out.println("Connected account ID: " + connectedAccountId); System.out.println("Session ID: " + session.getId()); } }
    package main import ( "encoding/json" "log" "fmt" "net/http" "io/ioutil" "github.com/stripe/stripe-go" "github.com/stripe/stripe-go/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; handleCheckoutSession(connectedAccountId, session) } w.WriteHeader(http.StatusOK) } func handleCheckoutSession(connectedAccountId string, session stripe.CheckoutSession) { // Fulfill the purchase. log.Println("Connected account ID: " + connectedAccountId) log.Println("Session ID: " + 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; HandleCheckoutSession(connectedAccountId, session); } return Ok(); } catch (Exception e) { logger.LogInformation(e.ToString()); return BadRequest(); } } private void HandleCheckoutSession(string connectedAccountId, Session session) { // Fulfill the purchase. logger.LogInformation($"Connected account ID: {connectedAccountId}"); logger.LogInformation($"Session: {session}"); } } }

    Learn more in our fulfillment guide for Checkout. If you’re not using Checkout, you can use webhooks with different event types to hook into your business logic to fulfill purchases.

    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.

    4 Complete and customize your integration

    You now have a working integration. From your account dashboard, you can view an account and its balance.

    Payouts

    By default, any charge that you create for a connected account accumulates in the connected account’s Stripe balance and is paid out on a daily rolling basis. Standard accounts manage their own payout schedules in their Stripe dashboards at https://dashboard.stripe.com/settings/payouts.

    Testing

    Test your account creation flow by creating accounts and using OAuth. You can use the available test cards to test your payments flow and simulate various payment outcomes.

    Other resources

    You have completed the steps required to build a working Connect integration. Based on your business needs, you can also do the following:

    Manage connected accounts

    Customize payments

    Was this page helpful?

    Feedback about this page?

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

    On this page