Payments
More payment scenarios
Save a card during payment

Save a card during payment

Learn how to save card details during a payment.

Use the Payment Intents API to save card details from a purchase. There are several use cases:

  • Charge a customer for an e-commerce order and store the details for future purchases
  • Initiate the first payment of a series of recurring payments
  • Charge a deposit and store the details to charge the full amount later

1 Set up Stripe Server-side

First, you need a Stripe account. Register now.

Use our official libraries for access to the Stripe API from your application:

# 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

2 Create a Customer before payment Server-side

To set a card up for future payments, it must be attached to a Customer.

You should create a Customer object when your customer creates an account with your business. If your customer is making a payment as a guest, you can create a Customer object before payment and associate it with your own internal representation of the customer’s account later.

Create or retrieve a Customer to associate with these card details. Include the following code on your server to create a new Customer.

curl https://api.stripe.com/v1/customers \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -X POST
# 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' customer = Stripe::Customer.create
# 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' customer = stripe.Customer.create()
// 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'); $customer = \Stripe\Customer::create();
// 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"; CustomerCreateParams params = CustomerCreateParams.builder() .build(); Customer customer = Customer.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 customer = await stripe.customers.create();
// 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.CustomerParams{} c, _ := customer.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 CustomerCreateOptions{}; var service = new CustomerService(); var customer = service.Create(options);

Associate the ID of the Customer object with your own internal representation of a customer, if you have one.

3 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. 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.

To create a payment, specify the amount, currency and customer.

curl https://api.stripe.com/v1/payment_intents \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d customer="{{CUSTOMER_ID}}" \ -d amount=1099 \ -d currency=usd
# 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::PaymentIntent.create({ amount: 1099, currency: 'usd', customer: customer['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' stripe.PaymentIntent.create( amount=1099, currency='usd', customer=customer['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'); $intent = \Stripe\PaymentIntent::create([ 'amount' => 1099, 'currency' => 'usd', 'customer' => $customer->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"; PaymentIntentCreateParams params = PaymentIntentCreateParams.builder() .setAmount(1099L) .setCurrency("usd") .setCustomer(customer.getId()) .build(); 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 intent = await stripe.paymentIntents.create({ amount: 1099, currency: 'usd', customer: customer.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{ Amount: stripe.Int64(1099), Currency: stripe.String(string(stripe.CurrencyUSD)), Customer: stripe.String(customer.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 options = new PaymentIntentCreateOptions { Amount = 1099, Currency = "usd", Customer = "{{CUSTOMER_ID}}", }; var service = new PaymentIntentService(); var paymentIntent = service.Create(options);

Instead of passing the entire PaymentIntent object to the browser, just pass the 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.

4 Collect card details Client-side

After creating a PaymentIntent on the server and passing its client secret to the browser, you’re ready to collect card information with Stripe Elements on your client. Elements is a set of prebuilt UI components for collecting and validating card number, ZIP code, and expiration date.

Set up Stripe Elements

Include the Stripe.js script by adding it to the head of your checkout page. 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>

Next, create an instance of Elements with the following JavaScript:

// 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 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.

<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>

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 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 details.

Otherwise, combine cardNumber, cardExpiry, and cardCvc Elements for a flexible, multi-input card form.

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 (e.g., postal code validation depends on your customer’s billing country). Use our international test cards to experiment with other postal code formats.

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

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.

5 Submit the payment to Stripe Client-side

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

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].

stripe.confirmCardPayment(clientSecret, { payment_method: { card: card, billing_details: { name: 'Jenny Rosen' } }, setup_future_usage: 'off_session' }).then(function(result) { if (result.error) { // Show error to your customer console.log(result.error.message); } else { 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 // to save the card to a Customer // The PaymentMethod ID can be found on result.paymentIntent.payment_method } } });

The client secret can be used to complete the payment process with the amount specified on the PaymentIntent. It should not be logged, embedded in URLs, or exposed to anyone other than the customer.

The setup_future_usage parameter helps optimize future payments made with the same card. When both setup_future_usage and a customer are provided on a PaymentIntent, the payment’s card details are automatically saved to the customer once the payment is confirmed. You can also supply this parameter when creating the PaymentIntent on your server.

Supplying an appropriate setup_future_usage value for your application may require your customer to complete additional authentication steps, but reduces the chance of future payments being rejected by the bank. See Optimizing cards for future payments to determine which value you should use for your application.

When the payment completes successfully, the value of the returned PaymentIntent’s status property is succeeded. If the payment was not successful, you can inspect the returned error to determine the cause.

If the payment completed successfully, the payment’s card is saved to the payment’s customer. This is reflected on the PaymentMethod’s customer field. At this point, associate the ID of the Customer object with your own internal representation of a customer, if you have one. Now you can use the stored PaymentMethod object to collect payments from your customer in the future without prompting them for their payment details again.

6 Charge the saved card later Server-side

When you are ready to charge your customer off-session, use the Customer and PaymentMethod IDs to create a PaymentIntent.

To find a card to charge, list the PaymentMethods associated with your Customer.

curl https://api.stripe.com/v1/payment_methods \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d customer="{{CUSTOMER_ID}}" \ -d type=card \ -G
# 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::PaymentMethod.list({ customer: '{{CUSTOMER_ID}}', type: 'card', })
# 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.PaymentMethod.list( customer="{{CUSTOMER_ID}}", type="card", )
// 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\PaymentMethod::all([ 'customer' => '{{CUSTOMER_ID}}', 'type' => 'card', ]);
// 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"; PaymentMethodListParams params = PaymentMethodListParams.builder() .setCustomer("{{CUSTOMER_ID}}") .setType(PaymentMethodListParams.Type.CARD) .build(); PaymentMethodCollection paymentMethods = PaymentMethod.list(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 paymentMethods = await stripe.paymentMethods.list({ customer: '{{CUSTOMER_ID}}', type: 'card', });
// 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.PaymentMethodListParams{ Customer: stripe.String("{{CUSTOMER_ID}}"), Type: stripe.String(string(stripe.PaymentMethodTypeCard)), } i := paymentmethod.List(params) for i.Next() { pm := i.PaymentMethod() }
// 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 PaymentMethodListOptions { Customer = "{{CUSTOMER_ID}}", Type = "card", }; var service = new PaymentMethodService(); var paymentMethods = service.List(options);

When you have the Customer and PaymentMethod IDs, create a PaymentIntent with the amount and currency of the payment. Set a few other parameters to make the off-session payment:

  • Set off_session to true to indicate that the customer is not in your checkout flow during this payment attempt. This causes the PaymentIntent to throw an error if authentication is required.
  • Set the value of the PaymentIntent’s confirm property to true, which causes confirmation to occur immediately when the PaymentIntent is created.
  • Set payment_method to the ID of the PaymentMethod and customer to the ID of the Customer.
curl https://api.stripe.com/v1/payment_intents \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d amount=1099 \ -d currency=usd \ -d customer="{{CUSTOMER_ID}}" \ -d payment_method="{{PAYMENT_METHOD_ID}}" \ -d off_session=true \ -d confirm=true
# 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' begin intent = Stripe::PaymentIntent.create({ amount: 1099, currency: 'usd', customer: '{{CUSTOMER_ID}}', payment_method: '{{PAYMENT_METHOD_ID}}', off_session: true, confirm: true, }) rescue Stripe::CardError => e # Error code will be authentication_required if authentication is needed puts "Error is: #{e.error.code}" payment_intent_id = e.error.payment_intent.id payment_intent = Stripe::PaymentIntent.retrieve(payment_intent_id) puts payment_intent.id end
# Set your secret key. Remember to switch to your live secret key in production! # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' try: stripe.PaymentIntent.create( amount=1099, currency='usd', customer='{{CUSTOMER_ID}}', payment_method='{{PAYMENT_METHOD_ID}}', off_session=True, confirm=True, ) except stripe.error.CardError as e: err = e.error # Error code will be authentication_required if authentication is needed print("Code is: %s" % err.code) payment_intent_id = err.payment_intent['id'] payment_intent = stripe.PaymentIntent.retrieve(payment_intent_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'); try { \Stripe\PaymentIntent::create([ 'amount' => 1099, 'currency' => 'usd', 'customer' => '{{CUSTOMER_ID}}', 'payment_method' => '{{PAYMENT_METHOD_ID}}', 'off_session' => true, 'confirm' => true, ]); } catch (\Stripe\Exception\CardException $e) { // Error code will be authentication_required if authentication is needed echo 'Error code is:' . $e->getError()->code; $payment_intent_id = $e->getError()->payment_intent->id; $payment_intent = \Stripe\PaymentIntent::retrieve($payment_intent_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"; PaymentIntentCreateParams params = PaymentIntentCreateParams.builder() .setCurrency("usd") .setAmount(1099) .setPaymentMethod("{{PAYMENT_METHOD_ID}}") .setCustomer("{{CUSTOMER_ID}}") .setConfirm(true) .setOffSession(true) .build(); try { PaymentIntent.create(params); } catch (CardException err) { // Error code will be authentication_required if authentication is needed System.out.println("Error code is : " + e.getCode()); String paymentIntentId = e.getStripeError().getPaymentIntent().getId(); PaymentIntent paymentIntent = PaymentIntent.retrieve(paymentIntentId); System.out.println(paymentIntent.getId()); }
// 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'); try { const paymentIntent = await stripe.paymentIntents.create({ amount: 1099, currency: 'usd', customer: '{{CUSTOMER_ID}}', payment_method: '{{PAYMENT_METHOD_ID}}', off_session: true, confirm: true, }); } catch (err) { // Error code will be authentication_required if authentication is needed console.log('Error code is: ', err.code); const paymentIntentRetrieved = await stripe.paymentIntents.retrieve(err.raw.payment_intent.id); console.log('PI retrieved: ', paymentIntentRetrieved.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{ Amount: stripe.Int64(1099), Currency: stripe.String(string(stripe.CurrencyUSD)), Customer: stripe.String("{{CUSTOMER_ID}}"), PaymentMethod: stripe.String("{{PAYMENT_METHOD_ID}}"), Confirm: stripe.Bool(true), OffSession: stripe.Bool(true), } _, err := paymentintent.New(params) if err != nil { if stripeErr, ok := err.(*stripe.Error); ok { // Error code will be authentication_required if authentication is needed fmt.Printf("Error code: %v", stripeErr.Code) paymentIntentID := stripeErr.PaymentIntent.ID paymentIntent, _ := paymentintent.Get(paymentIntentID, nil) fmt.Printf("PI: %v", 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"; try { var service = new PaymentIntentService(); var options = new PaymentIntentCreateOptions { Amount = 1099, Currency = "usd", Customer = "{{CUSTOMER_ID}}", PaymentMethod = "{{PAYMENT_METHOD_ID}}", Confirm = true, OffSession = true, }; service.Create(options); } catch (StripeException e) { switch (e.StripeError.ErrorType) { case "card_error": // Error code will be authentication_required if authentication is needed Console.WriteLine("Error code: " + e.StripeError.Code); var paymentIntentId = e.StripeError.PaymentIntent.Id; var service = new PaymentIntentService(); var paymentIntent = service.Get(paymentIntentId); Console.WriteLine(paymentIntent.Id); break; default: break; } }

When a payment attempt fails, the request also fails with a 402 HTTP status code and the status of the PaymentIntent is requires_payment_method. You need to notify your customer to return to your application (e.g., by sending an email or in-app notification) to complete the payment. Check the code of the Error raised by the Stripe API library or check the last_payment_error.decline_code on the PaymentIntent to inspect why the card issuer declined the payment.

If the payment failed due to an authentication_required decline code, use the declined PaymentIntent’s client secret and payment method with confirmCardPayment to allow the customer to authenticate the payment.

// Pass the failed PaymentIntent to your client from your server stripe.confirmCardPayment(intent.client_secret, { payment_method: intent.last_payment_error.payment_method.id }).then(function(result) { if (result.error) { // Show error to your customer console.log(result.error.message); } else { if (result.paymentIntent.status === 'succeeded') { // The payment is complete! } } });

If the payment failed for other reasons, such as insufficient funds on the card, send your customer to a payment page to enter a new card. You can reuse the existing PaymentIntent to attempt the payment again with the new card details.

7 Test the integration

By this point you should have an integration that:

  1. Collects card details and makes a payment
  2. Saves the card details to a Customer
  3. Charges the card off-session and has a recovery flow to handle declines and authentication requests

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

Number Description
4242424242424242 Succeeds and immediately processes the payment.
4000002500003155 Requires authentication for the initial purchase, but succeeds for subsequent payments (including off-session ones) as long as the card is setup with setup_future_usage.
4000002760003184 Requires authentication for the initial purchase, and fails for subsequent payments (including off-session ones) with an authentication_required decline code.
4000008260003178 Requires authentication for the initial purchase, but fails for subsequent payments (including off-session ones) with an insufficient_funds decline code.
4000000000009995 Always fails (including the initial purchase) with a decline code of insufficient_funds.

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

Use the Payment Intents API to save card details from a purchase. There are several use cases:

  • Charge a customer for an e-commerce order and store the details for future purchases
  • Initiate the first payment of a series of recurring payments
  • Charge a deposit and store the details to charge the full amount later

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 11 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 Customer before payment Server-side

To set a card up for future payments, it must be attached to a Customer.

You should create a Customer object when your customer creates an account with your business. If your customer is making a payment as a guest, you can create a Customer object before payment and associate it with your own internal representation of the customer’s account later.

Create or retrieve a Customer to associate with these card details. Include the following code on your server to create a new Customer.

curl https://api.stripe.com/v1/customers \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -X POST
# 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' customer = Stripe::Customer.create
# 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' customer = stripe.Customer.create()
// 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'); $customer = \Stripe\Customer::create();
// 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"; CustomerCreateParams params = CustomerCreateParams.builder() .build(); Customer customer = Customer.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 customer = await stripe.customers.create();
// 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.CustomerParams{} c, _ := customer.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 CustomerCreateOptions{}; var service = new CustomerService(); var customer = service.Create(options);

Associate the ID of the Customer object with your own internal representation of a customer, if you have one.

4 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, currency, and customer. 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 customer="{{CUSTOMER_ID}}" \ -d amount=1099 \ -d currency=usd
# 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::PaymentIntent.create({ amount: 1099, currency: 'usd', customer: customer['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' stripe.PaymentIntent.create( amount=1099, currency='usd', customer=customer['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'); $intent = \Stripe\PaymentIntent::create([ 'amount' => 1099, 'currency' => 'usd', 'customer' => $customer->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"; PaymentIntentCreateParams params = PaymentIntentCreateParams.builder() .setAmount(1099L) .setCurrency("usd") .setCustomer(customer.getId()) .build(); 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 intent = await stripe.paymentIntents.create({ amount: 1099, currency: 'usd', customer: customer.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{ Amount: stripe.Int64(1099), Currency: stripe.String(string(stripe.CurrencyUSD)), Customer: stripe.String(customer.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 options = new PaymentIntentCreateOptions { Amount = 1099, Currency = "usd", Customer = "{{CUSTOMER_ID}}", }; var service = new PaymentIntentService(); var paymentIntent = service.Create(options);

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

5 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
  3. A value for setupFutureUsage indicating how you plan to use the card in the future

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 paymentIntentParams.setupFutureUsage = NSNumber(value: STPPaymentIntentSetupFutureUsage.offSession.rawValue) // 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; paymentIntentParams.setupFutureUsage = @(STPPaymentIntentSetupFutureUsageOffSession); // 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

The setupFutureUsage parameter helps optimize future payments made with the same card. When both setupFutureUsage and a customer are provided on a PaymentIntent, the payment’s card details are automatically saved to the customer once the payment is confirmed. You can also supply this parameter when creating the PaymentIntent on your server.

Supplying an appropriate setupFutureUsage value for your application may require your customer to complete additional authentication steps, but reduces the chance of future payments being rejected by the bank. See Optimizing cards for future payments to determine which value you should use for your application.

How you intend to use the card setup_future_usage enum value to use
On-session payments only STPPaymentIntentSetupFutureUsageOnSession
Off-session payments only STPPaymentIntentSetupFutureUsageOffSession
Both on and off-session payments STPPaymentIntentSetupFutureUsageOffSession

A card set up for on-session payments can still be used to make off-session payments, but there’s a higher likelihood that the bank will reject the off-session payment and require authentication from the cardholder.

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.

If the payment completed successfully, the payment’s card is saved to the payment’s customer. This is reflected on the PaymentMethod’s customer field. At this point, associate the ID of the Customer object with your own internal representation of a customer, if you have one. Now you can use the stored PaymentMethod object to collect payments from your customer in the future without prompting them for their payment details again.

6 Charge the card off-session Server-side

When you are ready to charge your customer off-session, use the Customer and PaymentMethod IDs to create a PaymentIntent.

To find a card to charge, list the PaymentMethods associated with your Customer.

curl https://api.stripe.com/v1/payment_methods \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d customer="{{CUSTOMER_ID}}" \ -d type=card \ -G
# 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::PaymentMethod.list({ customer: '{{CUSTOMER_ID}}', type: 'card', })
# 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.PaymentMethod.list( customer="{{CUSTOMER_ID}}", type="card", )
// 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\PaymentMethod::all([ 'customer' => '{{CUSTOMER_ID}}', 'type' => 'card', ]);
// 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"; PaymentMethodListParams params = PaymentMethodListParams.builder() .setCustomer("{{CUSTOMER_ID}}") .setType(PaymentMethodListParams.Type.CARD) .build(); PaymentMethodCollection paymentMethods = PaymentMethod.list(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 paymentMethods = await stripe.paymentMethods.list({ customer: '{{CUSTOMER_ID}}', type: 'card', });
// 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.PaymentMethodListParams{ Customer: stripe.String("{{CUSTOMER_ID}}"), Type: stripe.String(string(stripe.PaymentMethodTypeCard)), } i := paymentmethod.List(params) for i.Next() { pm := i.PaymentMethod() }
// 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 PaymentMethodListOptions { Customer = "{{CUSTOMER_ID}}", Type = "card", }; var service = new PaymentMethodService(); var paymentMethods = service.List(options);

When you have the Customer and PaymentMethod IDs, create a PaymentIntent with the amount and currency of the payment. Set a few other parameters to make the off-session payment:

  • Set off_session to true to indicate that the customer is not in your checkout flow during this payment attempt. This causes the PaymentIntent to throw an error if authentication is required.
  • Set the value of the PaymentIntent’s confirm property to true, which causes confirmation to occur immediately when the PaymentIntent is created.
  • Set payment_method to the ID of the PaymentMethod and customer to the ID of the Customer.
curl https://api.stripe.com/v1/payment_intents \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d amount=1099 \ -d currency=usd \ -d customer="{{CUSTOMER_ID}}" \ -d payment_method="{{PAYMENT_METHOD_ID}}" \ -d off_session=true \ -d confirm=true
# 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' begin intent = Stripe::PaymentIntent.create({ amount: 1099, currency: 'usd', customer: '{{CUSTOMER_ID}}', payment_method: '{{PAYMENT_METHOD_ID}}', off_session: true, confirm: true, }) rescue Stripe::CardError => e # Error code will be authentication_required if authentication is needed puts "Error is: #{e.error.code}" payment_intent_id = e.error.payment_intent.id payment_intent = Stripe::PaymentIntent.retrieve(payment_intent_id) puts payment_intent.id end
# Set your secret key. Remember to switch to your live secret key in production! # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' try: stripe.PaymentIntent.create( amount=1099, currency='usd', customer='{{CUSTOMER_ID}}', payment_method='{{PAYMENT_METHOD_ID}}', off_session=True, confirm=True, ) except stripe.error.CardError as e: err = e.error # Error code will be authentication_required if authentication is needed print("Code is: %s" % err.code) payment_intent_id = err.payment_intent['id'] payment_intent = stripe.PaymentIntent.retrieve(payment_intent_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'); try { \Stripe\PaymentIntent::create([ 'amount' => 1099, 'currency' => 'usd', 'customer' => '{{CUSTOMER_ID}}', 'payment_method' => '{{PAYMENT_METHOD_ID}}', 'off_session' => true, 'confirm' => true, ]); } catch (\Stripe\Exception\CardException $e) { // Error code will be authentication_required if authentication is needed echo 'Error code is:' . $e->getError()->code; $payment_intent_id = $e->getError()->payment_intent->id; $payment_intent = \Stripe\PaymentIntent::retrieve($payment_intent_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"; PaymentIntentCreateParams params = PaymentIntentCreateParams.builder() .setCurrency("usd") .setAmount(1099) .setPaymentMethod("{{PAYMENT_METHOD_ID}}") .setCustomer("{{CUSTOMER_ID}}") .setConfirm(true) .setOffSession(true) .build(); try { PaymentIntent.create(params); } catch (CardException err) { // Error code will be authentication_required if authentication is needed System.out.println("Error code is : " + e.getCode()); String paymentIntentId = e.getStripeError().getPaymentIntent().getId(); PaymentIntent paymentIntent = PaymentIntent.retrieve(paymentIntentId); System.out.println(paymentIntent.getId()); }
// 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'); try { const paymentIntent = await stripe.paymentIntents.create({ amount: 1099, currency: 'usd', customer: '{{CUSTOMER_ID}}', payment_method: '{{PAYMENT_METHOD_ID}}', off_session: true, confirm: true, }); } catch (err) { // Error code will be authentication_required if authentication is needed console.log('Error code is: ', err.code); const paymentIntentRetrieved = await stripe.paymentIntents.retrieve(err.raw.payment_intent.id); console.log('PI retrieved: ', paymentIntentRetrieved.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{ Amount: stripe.Int64(1099), Currency: stripe.String(string(stripe.CurrencyUSD)), Customer: stripe.String("{{CUSTOMER_ID}}"), PaymentMethod: stripe.String("{{PAYMENT_METHOD_ID}}"), Confirm: stripe.Bool(true), OffSession: stripe.Bool(true), } _, err := paymentintent.New(params) if err != nil { if stripeErr, ok := err.(*stripe.Error); ok { // Error code will be authentication_required if authentication is needed fmt.Printf("Error code: %v", stripeErr.Code) paymentIntentID := stripeErr.PaymentIntent.ID paymentIntent, _ := paymentintent.Get(paymentIntentID, nil) fmt.Printf("PI: %v", 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"; try { var service = new PaymentIntentService(); var options = new PaymentIntentCreateOptions { Amount = 1099, Currency = "usd", Customer = "{{CUSTOMER_ID}}", PaymentMethod = "{{PAYMENT_METHOD_ID}}", Confirm = true, OffSession = true, }; service.Create(options); } catch (StripeException e) { switch (e.StripeError.ErrorType) { case "card_error": // Error code will be authentication_required if authentication is needed Console.WriteLine("Error code: " + e.StripeError.Code); var paymentIntentId = e.StripeError.PaymentIntent.Id; var service = new PaymentIntentService(); var paymentIntent = service.Get(paymentIntentId); Console.WriteLine(paymentIntent.Id); break; default: break; } }

7 Handle declines or authentication requests

Inspect the status property of the PaymentIntent to confirm that the payment completed successfully. If the payment attempt succeeded, the PaymentIntent’s status is succeeded and the off-session payment is complete.

Start a recovery flow

If the PaymentIntent has any other status, the payment did not succeed and the request fails. Notify your customer to return to your application (e.g., by email, text, push notification) to complete the payment. We recommend creating a recovery flow in your app that shows why the payment failed initially and lets your customer retry.

In your recovery flow, retrieve the PaymentIntent via its client secret. Check the PaymentIntent’s lastPaymentError to inspect why the payment attempt failed. For card errors, you can show the user the last payment error’s message. Otherwise, you can show a generic failure message.

func startRecoveryFlow(clientSecret: String) { // Retrieve the PaymentIntent STPAPIClient.shared().retrievePaymentIntent(withClientSecret: clientSecret) { (paymentIntent, error) in guard error == nil, let lastPaymentError = paymentIntent?.lastPaymentError else { // Handle error (e.g. allow your customer to retry) return } var failureReason = "Payment failed, try again." // Default to a generic error message if lastPaymentError.type == .card { failureReason = lastPaymentError.message } // Display the failure reason to your customer // ... } }
- (void)startRecoveryFlow:(NSString *)clientSecret { // Retrieve the PaymentIntent [[STPAPIClient sharedClient] retrievePaymentIntentWithClientSecret:clientSecret completion:^(STPPaymentIntent * _Nullable paymentIntent, NSError * _Nullable error) { if (error || paymentIntent.status == STPPaymentIntentStatusSucceeded) { // Handle error (e.g. allow your customer to retry) return; } NSString *failureReason = @"Payment failed, try again."; // Default to a generic error message if (paymentIntent.lastPaymentError.type == STPPaymentIntentLastPaymentErrorTypeCard) { // For card errors, the error's message can be shown to your customer failureReason = paymentIntent.lastPaymentError.message; } // Display the failure reason to your customer // ... }]; }

Let your customer try again

Give the customer the option to update or remove their saved card and try payment again in your recovery flow. Follow the same steps you did to accept their initial payment with one difference—confirm the original, failed PaymentIntent by reusing its client secret instead of creating a new one.

If the payment failed because it requires authentication, try again with the existing PaymentMethod instead of creating a new one.

func startRecoveryFlow(clientSecret: String) { // ...continued from previous step // Reuse the existing PaymentIntent's client secret let paymentIntentParams = STPPaymentIntentParams(clientSecret: clientSecret) if paymentIntent.lastPaymentError.code == STPPaymentIntentLastPaymentErrorCodeAuthenticationFailure { // Payment failed because authentication is required, reuse the PaymentMethod paymentIntentParams.paymentMethodId = paymentIntent.lastPaymentError.paymentMethod.stripeId } else { // Collect a new PaymentMethod from the customer... } // Submit the payment... }
- (void)startRecoveryFlow:(NSString *)clientSecret { // ...continued from previous step // Reuse the existing PaymentIntent's client secret STPPaymentIntentParams *paymentIntentParams = [STPPaymentIntentParams alloc] initWithClientSecret:clientSecret] if ([paymentIntent.lastPaymentError.code isEqualToString:STPPaymentIntentLastPaymentErrorCodeAuthenticationFailure]) { // Payment failed because authentication is required, reuse the PaymentMethod paymentIntentParams.paymentMethodId = paymentIntent.lastPaymentError.paymentMethod.stripeId; } else { // Collect a new PaymentMethod from the customer... } // Submit the payment... }

8 Test the integration

By this point you should have an integration that:

  1. Collects card details and makes a payment
  2. Saves the card details to a Customer
  3. Charges the card off-session and has a recovery flow to handle declines and authentication requests

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

Number Description
4242424242424242 Succeeds and immediately processes the payment.
4000002500003155 Requires authentication for the initial purchase, but succeeds for subsequent payments (including off-session ones) as long as the card is setup with setup_future_usage.
4000002760003184 Requires authentication for the initial purchase, and fails for subsequent payments (including off-session ones) with an authentication_required decline code.
4000008260003178 Requires authentication for the initial purchase, but fails for subsequent payments (including off-session ones) with an insufficient_funds decline code.
4000000000009995 Always fails (including the initial purchase) with a decline code of insufficient_funds.

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

Use the Payment Intents API to save card details from a purchase. There are several use cases:

  • Charge a customer for an e-commerce order and store the details for future purchases
  • Initiate the first payment of a series of recurring payments
  • Charge a deposit and store the details to charge the full amount later

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 Customer before payment Server-side

To set a card up for future payments, it must be attached to a Customer.

You should create a Customer object when your customer creates an account with your business. If your customer is making a payment as a guest, you can create a Customer object before payment and associate it with your own internal representation of the customer’s account later.

Create or retrieve a Customer to associate with these card details. Include the following code on your server to create a new Customer.

curl https://api.stripe.com/v1/customers \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -X POST
# 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' customer = Stripe::Customer.create
# 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' customer = stripe.Customer.create()
// 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'); $customer = \Stripe\Customer::create();
// 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"; CustomerCreateParams params = CustomerCreateParams.builder() .build(); Customer customer = Customer.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 customer = await stripe.customers.create();
// 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.CustomerParams{} c, _ := customer.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 CustomerCreateOptions{}; var service = new CustomerService(); var customer = service.Create(options);

Associate the ID of the Customer object with your own internal representation of a customer, if you have one.

4 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, currency, and customer. 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 customer="{{CUSTOMER_ID}}" \ -d amount=1099 \ -d currency=usd
# 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::PaymentIntent.create({ amount: 1099, currency: 'usd', customer: customer['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' stripe.PaymentIntent.create( amount=1099, currency='usd', customer=customer['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'); $intent = \Stripe\PaymentIntent::create([ 'amount' => 1099, 'currency' => 'usd', 'customer' => $customer->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"; PaymentIntentCreateParams params = PaymentIntentCreateParams.builder() .setAmount(1099L) .setCurrency("usd") .setCustomer(customer.getId()) .build(); 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 intent = await stripe.paymentIntents.create({ amount: 1099, currency: 'usd', customer: customer.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{ Amount: stripe.Int64(1099), Currency: stripe.String(string(stripe.CurrencyUSD)), Customer: stripe.String(customer.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 options = new PaymentIntentCreateOptions { Amount = 1099, Currency = "usd", Customer = "{{CUSTOMER_ID}}", }; var service = new PaymentIntentService(); var paymentIntent = service.Create(options);

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 } }

5 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
  3. A value for setup_future_usage indicating how you plan to use the card in the future

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, null, false, mapOf("setup_future_usage" to "off_session")) 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) { Map<String, String> extraParams = new HashMap<>(); extraParams.put("setup_future_usage", "off_session"); ConfirmPaymentIntentParams confirmParams = ConfirmPaymentIntentParams .createWithPaymentMethodCreateParams(params, paymentIntentClientSecret, null, false, extraParams); stripe = Stripe(applicationContext, PaymentConfiguration.getInstance(applicationContext).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); } } }

The setup_future_usage parameter helps optimize future payments made with the same card. When both setup_future_usage and a customer are provided on a PaymentIntent, the payment’s card details are automatically saved to the customer once the payment is confirmed. You can also supply this parameter when creating the PaymentIntent on your server.

Supplying an appropriate setup_future_usage value for your application may require your customer to complete additional authentication steps, but reduces the chance of future payments being rejected by the bank. See Optimizing cards for future payments to determine which value you should use for your application.

How you intend to use the card setup_future_usage enum value to use
On-session payments only on_session
Off-session payments only off_session
Both on and off-session payments off_session

A card set up for on-session payments can still be used to make off-session payments, but there’s a higher likelihood that the bank will reject the off-session payment and require authentication from the cardholder.

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.

If the payment completed successfully, the payment’s card is saved to the payment’s customer. This is reflected on the PaymentMethod’s customer field. At this point, associate the ID of the Customer object with your own internal representation of a customer, if you have one. Now you can use the stored PaymentMethod object to collect payments from your customer in the future without prompting them for their payment details again.

6 Charge the card off-session Server-side

When you are ready to charge your customer off-session, use the Customer and PaymentMethod IDs to create a PaymentIntent.

To find a card to charge, list the PaymentMethods associated with your Customer.

curl https://api.stripe.com/v1/payment_methods \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d customer="{{CUSTOMER_ID}}" \ -d type=card \ -G
# 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::PaymentMethod.list({ customer: '{{CUSTOMER_ID}}', type: 'card', })
# 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.PaymentMethod.list( customer="{{CUSTOMER_ID}}", type="card", )
// 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\PaymentMethod::all([ 'customer' => '{{CUSTOMER_ID}}', 'type' => 'card', ]);
// 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"; PaymentMethodListParams params = PaymentMethodListParams.builder() .setCustomer("{{CUSTOMER_ID}}") .setType(PaymentMethodListParams.Type.CARD) .build(); PaymentMethodCollection paymentMethods = PaymentMethod.list(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 paymentMethods = await stripe.paymentMethods.list({ customer: '{{CUSTOMER_ID}}', type: 'card', });
// 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.PaymentMethodListParams{ Customer: stripe.String("{{CUSTOMER_ID}}"), Type: stripe.String(string(stripe.PaymentMethodTypeCard)), } i := paymentmethod.List(params) for i.Next() { pm := i.PaymentMethod() }
// 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 PaymentMethodListOptions { Customer = "{{CUSTOMER_ID}}", Type = "card", }; var service = new PaymentMethodService(); var paymentMethods = service.List(options);

When you have the Customer and PaymentMethod IDs, create a PaymentIntent with the amount and currency of the payment. Set a few other parameters to make the off-session payment:

  • Set off_session to true to indicate that the customer is not in your checkout flow during this payment attempt. This causes the PaymentIntent to throw an error if authentication is required.
  • Set the value of the PaymentIntent’s confirm property to true, which causes confirmation to occur immediately when the PaymentIntent is created.
  • Set payment_method to the ID of the PaymentMethod and customer to the ID of the Customer.
curl https://api.stripe.com/v1/payment_intents \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d amount=1099 \ -d currency=usd \ -d customer="{{CUSTOMER_ID}}" \ -d payment_method="{{PAYMENT_METHOD_ID}}" \ -d off_session=true \ -d confirm=true
# 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' begin intent = Stripe::PaymentIntent.create({ amount: 1099, currency: 'usd', customer: '{{CUSTOMER_ID}}', payment_method: '{{PAYMENT_METHOD_ID}}', off_session: true, confirm: true, }) rescue Stripe::CardError => e # Error code will be authentication_required if authentication is needed puts "Error is: #{e.error.code}" payment_intent_id = e.error.payment_intent.id payment_intent = Stripe::PaymentIntent.retrieve(payment_intent_id) puts payment_intent.id end
# Set your secret key. Remember to switch to your live secret key in production! # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' try: stripe.PaymentIntent.create( amount=1099, currency='usd', customer='{{CUSTOMER_ID}}', payment_method='{{PAYMENT_METHOD_ID}}', off_session=True, confirm=True, ) except stripe.error.CardError as e: err = e.error # Error code will be authentication_required if authentication is needed print("Code is: %s" % err.code) payment_intent_id = err.payment_intent['id'] payment_intent = stripe.PaymentIntent.retrieve(payment_intent_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'); try { \Stripe\PaymentIntent::create([ 'amount' => 1099, 'currency' => 'usd', 'customer' => '{{CUSTOMER_ID}}', 'payment_method' => '{{PAYMENT_METHOD_ID}}', 'off_session' => true, 'confirm' => true, ]); } catch (\Stripe\Exception\CardException $e) { // Error code will be authentication_required if authentication is needed echo 'Error code is:' . $e->getError()->code; $payment_intent_id = $e->getError()->payment_intent->id; $payment_intent = \Stripe\PaymentIntent::retrieve($payment_intent_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"; PaymentIntentCreateParams params = PaymentIntentCreateParams.builder() .setCurrency("usd") .setAmount(1099) .setPaymentMethod("{{PAYMENT_METHOD_ID}}") .setCustomer("{{CUSTOMER_ID}}") .setConfirm(true) .setOffSession(true) .build(); try { PaymentIntent.create(params); } catch (CardException err) { // Error code will be authentication_required if authentication is needed System.out.println("Error code is : " + e.getCode()); String paymentIntentId = e.getStripeError().getPaymentIntent().getId(); PaymentIntent paymentIntent = PaymentIntent.retrieve(paymentIntentId); System.out.println(paymentIntent.getId()); }
// 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'); try { const paymentIntent = await stripe.paymentIntents.create({ amount: 1099, currency: 'usd', customer: '{{CUSTOMER_ID}}', payment_method: '{{PAYMENT_METHOD_ID}}', off_session: true, confirm: true, }); } catch (err) { // Error code will be authentication_required if authentication is needed console.log('Error code is: ', err.code); const paymentIntentRetrieved = await stripe.paymentIntents.retrieve(err.raw.payment_intent.id); console.log('PI retrieved: ', paymentIntentRetrieved.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{ Amount: stripe.Int64(1099), Currency: stripe.String(string(stripe.CurrencyUSD)), Customer: stripe.String("{{CUSTOMER_ID}}"), PaymentMethod: stripe.String("{{PAYMENT_METHOD_ID}}"), Confirm: stripe.Bool(true), OffSession: stripe.Bool(true), } _, err := paymentintent.New(params) if err != nil { if stripeErr, ok := err.(*stripe.Error); ok { // Error code will be authentication_required if authentication is needed fmt.Printf("Error code: %v", stripeErr.Code) paymentIntentID := stripeErr.PaymentIntent.ID paymentIntent, _ := paymentintent.Get(paymentIntentID, nil) fmt.Printf("PI: %v", 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"; try { var service = new PaymentIntentService(); var options = new PaymentIntentCreateOptions { Amount = 1099, Currency = "usd", Customer = "{{CUSTOMER_ID}}", PaymentMethod = "{{PAYMENT_METHOD_ID}}", Confirm = true, OffSession = true, }; service.Create(options); } catch (StripeException e) { switch (e.StripeError.ErrorType) { case "card_error": // Error code will be authentication_required if authentication is needed Console.WriteLine("Error code: " + e.StripeError.Code); var paymentIntentId = e.StripeError.PaymentIntent.Id; var service = new PaymentIntentService(); var paymentIntent = service.Get(paymentIntentId); Console.WriteLine(paymentIntent.Id); break; default: break; } }

7 Handle declines or authentication requests

Inspect the status property of the PaymentIntent to confirm that the payment completed successfully. If the payment attempt succeeded, the PaymentIntent’s status is succeeded and the off-session payment is complete.

Start a recovery flow

If the PaymentIntent has any other status, the payment did not succeed and the request fails. Notify your customer to return to your application (e.g., by email, text, push notification) to complete the payment. We recommend creating a recovery flow in your app that shows why the payment failed initially and lets your customer retry.

In your recovery flow, retrieve the PaymentIntent via its client secret. Check the PaymentIntent’s lastPaymentError to inspect why the payment attempt failed. For card errors, you can show the user the last payment error’s message. Otherwise, you can show a generic failure message.

fun startRecoveryFlow(clientSecret: String) { AsyncTask.execute { val stripe = Stripe(applicationContext, PaymentConfiguration.getInstance(applicationContext).publishableKey) val paymentIntent = stripe.retrievePaymentIntentSynchronous(clientSecret) var failureReason = "Payment failed, try again" // Default to a generic error message paymentIntent?.lastPaymentError?.let { lastPaymentError -> if (lastPaymentError.type == PaymentIntent.Error.Type.CardError) { lastPaymentError.message?.let { errorMessage -> failureReason = errorMessage } } } // Display the failure reason to your customer } }
public void startRecoveryFlow(@NonNull String clientSecret) { AsyncTask.execute(new Runnable() { @Override public void run() { final Stripe stripe = new Stripe( getApplicationContext(), PaymentConfiguration.getInstance(this).getPublishableKey() ); try { final PaymentIntent paymentIntent = stripe.retrievePaymentIntentSynchronous(clientSecret); final PaymentIntent.Error lastPaymentError = paymentIntent != null ? paymentIntent.getLastPaymentError() : null; final String failureReason; if (lastPaymentError != null && PaymentIntent.Error.Type.CardError.equals(lastPaymentError.getType())) { failureReason = lastPaymentError.getMessage(); } else { failureReason = "Payment failed, try again"; // Default to a generic error message } // Display the failure reason to your customer } catch (Exception e) { // Handle error } } }); }

Let your customer try again

Give the customer the option to update or remove their saved card and try payment again in your recovery flow. Follow the same steps you did to accept their initial payment with one difference—confirm the original, failed PaymentIntent by reusing its client secret instead of creating a new one.

If the payment failed because it requires authentication, try again with the existing PaymentMethod instead of creating a new one.

fun startRecoveryFlow(clientSecret: String) { // ...continued from previous step val lastPaymentError = paymentIntent.lastPaymentError val lastPaymentMethodId = lastPaymentError.paymentMethod?.id if (lastPaymentError?.code == "authentication_required" && lastPaymentMethodId != null) { // Payment failed because authentication is required, reuse the PaymentMethod val paymentIntentParams = ConfirmPaymentIntentParams.createWithPaymentMethodId( lastPaymentMethodId, clientSecret // Reuse the existing PaymentIntent ) // Submit the payment... stripe.confirmPayment(this, paymentIntentParams) } else { // Collect a new PaymentMethod from the customer... } }
private void startRecoveryFlow(@NonNull String clientSecret) { // ...continued from previous step final String lastPaymentMethodId; if (lastPaymentError != null && lastPaymentError.getPaymentMethod() != null) { lastPaymentMethodId = lastPaymentError.getPaymentMethod().id; } else { lastPaymentMethodId = null; } if (lastPaymentError != null && "authentication_required".equals(lastPaymentError.getCode()) && lastPaymentMethodId != null) { // Payment failed because authentication is required, reuse the PaymentMethod final ConfirmPaymentIntentParams params = ConfirmPaymentIntentParams.createWithPaymentMethodId( lastPaymentMethodId, clientSecret // Reuse the existing PaymentIntent ); // Submit the payment... stripe.confirmPayment(this, params); } else { // Collect a new PaymentMethod from the customer... } } }

8 Test the integration

By this point you should have an integration that:

  1. Collects card details and makes a payment
  2. Saves the card details to a Customer
  3. Charges the card off-session and has a recovery flow to handle declines and authentication requests

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

Number Description
4242424242424242 Succeeds and immediately processes the payment.
4000002500003155 Requires authentication for the initial purchase, but succeeds for subsequent payments (including off-session ones) as long as the card is setup with setup_future_usage.
4000002760003184 Requires authentication for the initial purchase, and fails for subsequent payments (including off-session ones) with an authentication_required decline code.
4000008260003178 Requires authentication for the initial purchase, but fails for subsequent payments (including off-session ones) with an insufficient_funds decline code.
4000000000009995 Always fails (including the initial purchase) with a decline code of insufficient_funds.

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

See also

Now that you have a working integration, learn about handling post-payment events:

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