Accept a payment Charges API

    Accept online payments from your U.S. and Canadian customers.

    Overview

    Use Stripe Elements, our prebuilt UI components, to create a payment form that lets you securely collect a customer’s card details without handling the sensitive data. The card details are then converted to a representative Token that you can safely send to your servers. Your server can use that token to create a charge.

    1 Set up Stripe

    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:

    sudo gem install stripe

    If you use bundler, you can add this line:

    gem 'stripe'

    Available through pip:

    pip install --upgrade stripe

    Alternatively, you can also use easy_install:

    easy_install --upgrade stripe

    The PHP library can be installed via Composer:

    composer require stripe/stripe-php

    Alternatively, you can download the source directly.

    For Gradle, add the following dependency to your build.gradle:

    implementation "com.stripe:stripe-java:{VERSION}"
    (Replace {VERSION} with the actual version number you want to use. You can find the most recent version on Maven Repository or GitHub.)

    For Maven, add the following dependency to your POM:

    <dependency> <groupId>com.stripe</groupId> <artifactId>stripe-java</artifactId> <version>{VERSION}</version> </dependency>
    (Replace {VERSION} with the actual version number you want to use. You can find the most recent version on Maven Repository or GitHub.)

    In other environments, manually install the following JARs:

    Install via npm:

    npm install stripe

    Install via go:

    go get github.com/stripe/stripe-go

    Then import the package:

    import ( "github.com/stripe/stripe-go" )

    Install via dotnet:

    dotnet add package Stripe.net dotnet restore

    Or using NuGet:

    PM> Install-Package Stripe.net

    2 Create your payment form Client-side

    To securely collect card details from your customers, Stripe Elements creates UI components for you that are hosted by Stripe. They are then placed into your payment form, rather than you creating them directly. To have Elements available in your webpage, add this script tag in the head of your HTML page:

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

    That script should always be loaded directly from https://js.stripe.com.

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

    // Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/account/apikeys var stripe = Stripe('pk_test_TYooMQauvdEDq54NiTphI7jx'); var elements = stripe.elements();
    // 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 const stripe = Stripe('pk_test_TYooMQauvdEDq54NiTphI7jx'); const elements = stripe.elements();

    Once Elements is loaded, you can create an empty DOM container with a unique ID within your payment form wherever you want Elements to add its input field. We recommend placing that container within a <label> or next to a <label> with a for attribute that matches the unique id of the Element container. By doing so, the Element automatically gains focus when the customer clicks on the corresponding label.

    For example:

    <form action="/charge" method="post" id="payment-form"> <div class="form-row"> <label for="card-element"> Credit or debit card </label> <div id="card-element"> <!-- A Stripe Element will be inserted here. --> </div> <!-- Used to display Element errors. --> <div id="card-errors" role="alert"></div> </div> <button>Submit Payment</button> </form>

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

    // Custom styling can be passed to options when creating an Element. var style = { base: { // Add your base input styles here. For example: fontSize: '16px', color: "#32325d", } }; // Create an instance of the card Element. var card = elements.create('card', {style: style}); // Add an instance of the card Element into the `card-element` <div>. card.mount('#card-element');
    // Custom styling can be passed to options when creating an Element. const style = { base: { // Add your base input styles here. For example: fontSize: '16px', color: "#32325d", }, }; // Create an instance of the card Element. const card = elements.create('card', {style}); // Add an instance of the card Element into the `card-element` <div>. card.mount('#card-element');

    The card Element simplifies the form and minimizes the number of fields required by inserting a single, flexible input field that securely collects all necessary card details. Refer to our Stripe.js reference documentation for a full list of Element types that are supported.

    3 Create a token Client-side

    Add an event listener for when your customer submits their card information and use stripe.createToken(card) to tokenize that information:

    // Create a token or display an error when the form is submitted. var form = document.getElementById('payment-form'); form.addEventListener('submit', function(event) { event.preventDefault(); stripe.createToken(card).then(function(result) { if (result.error) { // Inform the customer that there was an error. var errorElement = document.getElementById('card-errors'); errorElement.textContent = result.error.message; } else { // Send the token to your server. stripeTokenHandler(result.token); } }); });
    // Create a token or display an error when the form is submitted. const form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); const {token, error} = await stripe.createToken(card); if (error) { // Inform the customer that there was an error. const errorElement = document.getElementById('card-errors'); errorElement.textContent = error.message; } else { // Send the token to your server. stripeTokenHandler(token); } });

    createToken also accepts an optional second parameter containing additional card information collected from the customer, which is not used in this example. The function returns a Promise which resolves with a result object. This object has either:

    • result.token: a Token was created successfully.
    • result.error: there was an error. This includes client-side validation errors. Refer to the API reference for all possible errors.

    If the object contains a result.token, send it to your server. Otherwise, show the customer an error.

    4 Submit the token to your server Client-side

    Send the token to your server along with any additional information that has been collected:

    function stripeTokenHandler(token) { // Insert the token ID into the form so it gets submitted to the server var form = document.getElementById('payment-form'); var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeToken'); hiddenInput.setAttribute('value', token.id); form.appendChild(hiddenInput); // Submit the form form.submit(); }
    const stripeTokenHandler = (token) => { // Insert the token ID into the form so it gets submitted to the server const form = document.getElementById('payment-form'); const hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeToken'); hiddenInput.setAttribute('value', token.id); form.appendChild(hiddenInput); // Submit the form form.submit(); }

    5 Create a charge with the token Server-side

    After the client posts the token to your server, you can use it to create a charge. On your server, grab the Stripe token in the POST parameters submitted by your form. From there, it’s one API call to charge the card:

    curl https://api.stripe.com/v1/charges \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d amount=999 \ -d currency=usd \ -d description="Example charge" \ -d source=tok_visa
    # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' # Token is created using Stripe Checkout or Elements! # Get the payment token ID submitted by the form: token = params[:stripeToken] charge = Stripe::Charge.create({ amount: 999, currency: 'usd', description: 'Example charge', source: token, })
    # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' # Token is created using Stripe Checkout or Elements! # Get the payment token ID submitted by the form: token = request.form['stripeToken'] # Using Flask charge = stripe.Charge.create( amount=999, currency='usd', description='Example charge', source=token, )
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys \Stripe\Stripe::setApiKey('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); // Token is created using Stripe Checkout or Elements! // Get the payment token ID submitted by the form: $token = $_POST['stripeToken']; $charge = \Stripe\Charge::create([ 'amount' => 999, 'currency' => 'usd', 'description' => 'Example charge', 'source' => $token, ]);
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.apiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; // Token is created using Stripe Checkout or Elements! // Get the payment token ID submitted by the form: String token = request.getParameter("stripeToken"); Map<String, Object> params = new HashMap<>(); params.put("amount", 999); params.put("currency", "usd"); params.put("description", "Example charge"); params.put("source", token); Charge charge = Charge.create(params);
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys const stripe = require('stripe')('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); // Token is created using Stripe Checkout or Elements! // Get the payment token ID submitted by the form: const token = request.body.stripeToken; // Using Express (async () => { const charge = await stripe.charges.create({ amount: 999, currency: 'usd', description: 'Example charge', source: token, }); })();
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys stripe.Key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc" // Token is created using Stripe Checkout or Elements! // Get the payment token ID submitted by the form: token := r.FormValue("stripeToken") params := &stripe.ChargeParams{ Amount: stripe.Int64(999), Currency: stripe.String(string(stripe.CurrencyUSD)), Description: stripe.String("Example charge"), } params.SetSource(token) ch, _ := charge.New(params)
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys StripeConfiguration.ApiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; // Token is created using Checkout or Elements! // Get the payment token submitted by the form: var token = model.Token; // Using ASP.NET MVC var options = new ChargeCreateOptions { Amount = 999, Currency = "usd", Description = "Example charge", Source = token, }; var service = new ChargeService(); Charge charge = service.Create(options);

    The response from creating a charge will either be a charge or an error with an error code. If the response succeeds, fulfill the customer’s order and show them a success page. Otherwise, show them an error page.

    Test your integration

    If you can reliably enter a test card in your HTML form, submit it to the server, and see that your server created the charge, then your integration is finished.

    Congratulations! You completed a basic payments integration with the Charges API. This API does not support scaling businesses or customers outside of the U.S. and Canada. For more robust and global payments, learn to accept a payment with the Payment Intents API.

    See also

    You can learn more about Elements and how to save cards with the Charges API.

    Overview

    Use our prebuilt card UI component to create a payment form that securely collects a customer’s card details without handling the sensitive data. The card details are then converted to a representative Token that you can safely send to your servers. Your server can use that token to create a charge.

    1 Set up Stripe Client-side Server-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:

    sudo gem install stripe

    If you use bundler, you can add this line:

    gem 'stripe'

    Available through pip:

    pip install --upgrade stripe

    Alternatively, you can also use easy_install:

    easy_install --upgrade stripe

    The PHP library can be installed via Composer:

    composer require stripe/stripe-php

    Alternatively, you can download the source directly.

    For Gradle, add the following dependency to your build.gradle:

    implementation "com.stripe:stripe-java:{VERSION}"
    (Replace {VERSION} with the actual version number you want to use. You can find the most recent version on Maven Repository or GitHub.)

    For Maven, add the following dependency to your POM:

    <dependency> <groupId>com.stripe</groupId> <artifactId>stripe-java</artifactId> <version>{VERSION}</version> </dependency>
    (Replace {VERSION} with the actual version number you want to use. You can find the most recent version on Maven Repository or GitHub.)

    In other environments, manually install the following JARs:

    Install via npm:

    npm install stripe

    Install via go:

    go get github.com/stripe/stripe-go

    Then import the package:

    import ( "github.com/stripe/stripe-go" )

    Install via dotnet:

    dotnet add package Stripe.net dotnet restore

    Or using NuGet:

    PM> Install-Package Stripe.net

    Client-side

    The iOS SDK is open source, fully documented, and compatible with apps supporting iOS 9 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: [UIApplicationLaunchOptionsKey: 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 payment form 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 token Client-side

    When the user taps the pay button, convert the card information collected by STPPaymentCardTextField into a Stripe token. Tokenization ensures that no sensitive card data ever needs to touch your server, so that your integration remains PCI compliant.

    First, create an instance of STPCardParams from the card UI component. Then, pass it to the STPAPIClient createTokenWithCard:completion: and receive an STPToken in the completion block.

    func pay() { // Create an STPCardParams instance let cardParams = STPCardParams() cardParams.number = cardTextField.cardNumber cardParams.expMonth = cardTextField.expirationMonth cardParams.expYear = cardTextField.expirationYear cardParams.cvc = cardTextField.cvc // Pass it to STPAPIClient to create a Token STPAPIClient.shared().createToken(withCard: cardParams) { token, error in guard let token = token else { // Handle the error return } let tokenID = token.tokenId // Send the token identifier to your server... } }
    - (void)pay { // Create an STPCardParams instance STPCardParams *cardParams = [STPCardParams new]; cardParams.number = self.cardTextField.cardNumber; cardParams.expMonth = self.cardTextField.expirationMonth; cardParams.expYear = self.cardTextField.expirationYear; cardParams.cvc = self.cardTextField.cvc; // Pass it to STPAPIClient to create a Token [[STPAPIClient sharedClient] createTokenWithCard:cardParams completion:^(STPToken * _Nullable token, NSError * _Nullable error) { if (token == nil) { // Handle the error return; } NSString *tokenID = token.tokenId; // Send the token identifier to your server... } }

    Send the Token’s identifier to your server from the client.

    4 Create a charge with the token Server-side

    After the client passes the token to your server, pass its identifier as the source to create a charge with one API call:

    curl https://api.stripe.com/v1/charges \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d amount=999 \ -d currency=usd \ -d description="Example charge" \ -d source=tok_visa
    # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' # Token is created using Checkout or Elements! # Get the payment token ID submitted by the form: token = params[:stripeToken] charge = Stripe::Charge.create({ amount: 999, currency: 'usd', description: 'Example charge', source: token, })
    # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' # Token is created using Checkout or Elements! # Get the payment token ID submitted by the form: token = request.form['stripeToken'] # Using Flask charge = stripe.Charge.create( amount=999, currency='usd', description='Example charge', source=token, )
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys \Stripe\Stripe::setApiKey('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); // Token is created using Checkout or Elements! // Get the payment token ID submitted by the form: $token = $_POST['stripeToken']; $charge = \Stripe\Charge::create([ 'amount' => 999, 'currency' => 'usd', 'description' => 'Example charge', 'source' => $token, ]);
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.apiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; // Token is created using Checkout or Elements! // Get the payment token ID submitted by the form: String token = request.getParameter("stripeToken"); Map<String, Object> params = new HashMap<>(); params.put("amount", 999); params.put("currency", "usd"); params.put("description", "Example charge"); params.put("source", token); Charge charge = Charge.create(params);
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys const stripe = require('stripe')('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); // Token is created using Checkout or Elements! // Get the payment token ID submitted by the form: const token = request.body.stripeToken; // Using Express (async () => { const charge = await stripe.charges.create({ amount: 999, currency: 'usd', description: 'Example charge', source: token, }); })();
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys stripe.Key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc" // Token is created using Checkout or Elements! // Get the payment token ID submitted by the form: token := r.FormValue("stripeToken") params := &stripe.ChargeParams{ Amount: stripe.Int64(999), Currency: stripe.String(string(stripe.CurrencyUSD)), Description: stripe.String("Example charge"), } params.SetSource(token) ch, _ := charge.New(params)
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys StripeConfiguration.ApiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; // Token is created using Checkout or Elements! // Get the payment token submitted by the form: var token = model.Token; // Using ASP.NET MVC var options = new ChargeCreateOptions { Amount = 999, Currency = "usd", Description = "Example charge", Source = token, }; var service = new ChargeService(); Charge charge = service.Create(options);

    The response from creating a charge will either be a charge or an error with an error code. If the response succeeds you can fulfill the customer’s order and show them a success screen. Otherwise, you can show them an error.

    Test your integration

    If you can reliably enter a test card in the card element, submit it to the server, and see that your server created the charge, then your integration is finished.

    Congratulations! You created a Charges API integration to start accepting card payments fast. This API does not support scaling businesses or customers outside of the U.S. and Canada. For more robust and global payments, learn to accept a payment with the Payment Intents API.

    See also

    Learn more about how to save cards with the Charges API.

    Overview

    Use our prebuilt card UI component to create a payment form that securely collects a customer’s card details without handling the sensitive data. The card details are then converted to a representative Token that you can safely send to your servers. Your server can use that token to create a charge.

    1 Set up Stripe Client-side Server-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:

    sudo gem install stripe

    If you use bundler, you can add this line:

    gem 'stripe'

    Available through pip:

    pip install --upgrade stripe

    Alternatively, you can also use easy_install:

    easy_install --upgrade stripe

    The PHP library can be installed via Composer:

    composer require stripe/stripe-php

    Alternatively, you can download the source directly.

    For Gradle, add the following dependency to your build.gradle:

    implementation "com.stripe:stripe-java:{VERSION}"
    (Replace {VERSION} with the actual version number you want to use. You can find the most recent version on Maven Repository or GitHub.)

    For Maven, add the following dependency to your POM:

    <dependency> <groupId>com.stripe</groupId> <artifactId>stripe-java</artifactId> <version>{VERSION}</version> </dependency>
    (Replace {VERSION} with the actual version number you want to use. You can find the most recent version on Maven Repository or GitHub.)

    In other environments, manually install the following JARs:

    Install via npm:

    npm install stripe

    Install via go:

    go get github.com/stripe/stripe-go

    Then import the package:

    import ( "github.com/stripe/stripe-go" )

    Install via dotnet:

    dotnet add package Stripe.net dotnet restore

    Or using 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:12.6.0' }

    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"); } }

    2 Create your payment form 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"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/activity_checkout" tools:context=".CheckoutActivity"> <!-- ... --> <com.stripe.android.view.CardInputWidget android:id="@+id/cardInputWidget" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp"/> <Button android:text="Pay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/payButton" android:layout_marginTop="20dp" app:layout_constraintTop_toBottomOf="@+id/cardInputWidget" app:layout_constraintStart_toStartOf="@+id/cardInputWidget" app:layout_constraintEnd_toEndOf="@+id/cardInputWidget"/> <!-- ... --> </androidx.constraintlayout.widget.ConstraintLayout>

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

    3 Create a token Client-side

    When the user taps the pay button, convert the card information collected by CardInputWidget into a Stripe token. Tokenization ensures that no sensitive card data ever needs to touch your server, so that your integration remains PCI compliant.

    The following code shows how to use Stripe#createToken(). The method takes a Card instance as the first parameter. The second parameter is a ApiResultCallback<Token> instance that the client invokes on success or failure. When tokenization completes successfully, send the returned token ID to your server.

    // Hook up the pay button to the card widget and Stripe instance val payButton: Button = findViewById(R.id.payButton) val weakActivity = WeakReference<Activity>(this@CheckoutActivityKotlin) payButton.setOnClickListener { // Get the card details from the card widget val cardInputWidget = findViewById<CardInputWidget>(R.id.cardInputWidget) cardInputWidget.card?.let { card -> // Create a Stripe token from the card details stripe = Stripe(applicationContext, PaymentConfiguration.getInstance(applicationContext).publishableKey) stripe.createToken(card, object: ApiResultCallback<Token> { override fun onSuccess(result: Token) { val tokenID = result.id // Send the Token identifier to the server... } override fun onError(e: java.lang.Exception) { // Handle error } }) } }
    // Hook up the pay button to the card widget and Stripe instance Button payButton = findViewById(R.id.payButton); WeakReference<CheckoutActivityJava> weakActivity = new WeakReference<>(this); payButton.setOnClickListener((View view) -> { // Get the card details from the card widget CardInputWidget cardInputWidget = findViewById(R.id.cardInputWidget); Card card = cardInputWidget.getCard(); if (card != null) { // Create a Stripe token from the card details stripe = new Stripe(getApplicationContext(), PaymentConfiguration.getInstance(getApplicationContext()).getPublishableKey()); stripe.createToken(card, new ApiResultCallback<Token>() { @Override public void onSuccess(@NonNull Token result) { String tokenID = result.getId(); // Send the token identifier to the server... } @Override public void onError(@NonNull Exception e) { // Handle error } }); } });

    Send the Token’s identifier to your server from the client.

    4 Create a charge with the token Server-side

    After the client passes the token to your server, pass its identifier as the source to create a charge with one API call:

    curl https://api.stripe.com/v1/charges \ -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \ -d amount=999 \ -d currency=usd \ -d description="Example charge" \ -d source=tok_visa
    # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' # Token is created using Checkout or Elements! # Get the payment token ID submitted by the form: token = params[:stripeToken] charge = Stripe::Charge.create({ amount: 999, currency: 'usd', description: 'Example charge', source: token, })
    # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' # Token is created using Checkout or Elements! # Get the payment token ID submitted by the form: token = request.form['stripeToken'] # Using Flask charge = stripe.Charge.create( amount=999, currency='usd', description='Example charge', source=token, )
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys \Stripe\Stripe::setApiKey('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); // Token is created using Checkout or Elements! // Get the payment token ID submitted by the form: $token = $_POST['stripeToken']; $charge = \Stripe\Charge::create([ 'amount' => 999, 'currency' => 'usd', 'description' => 'Example charge', 'source' => $token, ]);
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys Stripe.apiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; // Token is created using Checkout or Elements! // Get the payment token ID submitted by the form: String token = request.getParameter("stripeToken"); Map<String, Object> params = new HashMap<>(); params.put("amount", 999); params.put("currency", "usd"); params.put("description", "Example charge"); params.put("source", token); Charge charge = Charge.create(params);
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys const stripe = require('stripe')('sk_test_4eC39HqLyjWDarjtT1zdp7dc'); // Token is created using Checkout or Elements! // Get the payment token ID submitted by the form: const token = request.body.stripeToken; // Using Express (async () => { const charge = await stripe.charges.create({ amount: 999, currency: 'usd', description: 'Example charge', source: token, }); })();
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys stripe.Key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc" // Token is created using Checkout or Elements! // Get the payment token ID submitted by the form: token := r.FormValue("stripeToken") params := &stripe.ChargeParams{ Amount: stripe.Int64(999), Currency: stripe.String(string(stripe.CurrencyUSD)), Description: stripe.String("Example charge"), } params.SetSource(token) ch, _ := charge.New(params)
    // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys StripeConfiguration.ApiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; // Token is created using Checkout or Elements! // Get the payment token submitted by the form: var token = model.Token; // Using ASP.NET MVC var options = new ChargeCreateOptions { Amount = 999, Currency = "usd", Description = "Example charge", Source = token, }; var service = new ChargeService(); Charge charge = service.Create(options);

    The response from creating a charge will either be a charge or an error with an error code. If the response succeeds you can fulfill the customer’s order and show them a success screen. Otherwise, you can show them an error.

    Test your integration

    If you can reliably enter a test card in the card element, submit it to the server, and see that your server created the charge, then your integration is finished.

    Congratulations! You created a Charges API integration to start accepting card payments fast. This API does not support scaling businesses or customers outside of the U.S. and Canada. For more robust and global payments, learn to accept a payment with the Payment Intents API.

    See also

    Learn more about how to save cards with the Charges API.

    Was this page helpful?

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

    On this page