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

    2 Create 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.

    Set up Stripe Elements

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

    Refer to our Stripe.js reference documentation for a full list of supported Element types.

    Install @stripe/react-stripe-js and @stripe/stripe-js:

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

    Add Stripe.js and Elements to your page

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

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

    Add and configure a CardElement component

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

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

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

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

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

    Tokenize the users card information when the user submits the payment form. Use the useStripe and useElements hooks to call stripe.createToken with the Element.

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

    import React from 'react'; import {useStripe, useElements, CardElement} from '@stripe/react-stripe-js'; import CardSection from './CardSection'; export default function CheckoutForm() { const stripe = useStripe(); const elements = useElements(); const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe || !elements) { // Stripe.js has not yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const card = elements.getElement(CardElement); const result = await stripe.createToken(card); if (result.error) { // Show error to your customer. console.log(result.error.message); } else { // Send the token to your server. // This function does not exist yet; we will define it in the next step. stripeTokenHandler(result.token); } }; return ( <form onSubmit={handleSubmit}> <CardSection /> <button disabled={!stripe}>Confirm order</button> </form> ); }
    import React from 'react'; import {ElementsConsumer, CardElement} from '@stripe/react-stripe-js'; import CardSection from './CardSection'; class CheckoutForm extends React.Component { handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); const {stripe, elements} = this.props if (!stripe || !elements) { // Stripe.js has not yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const card = elements.getElement(CardElement); const result = await stripe.createToken(card); if (result.error) { // Show error to your customer. console.log(result.error.message); } else { // Send the token to your server. // This function does not exist yet; we will define it in the next step. stripeTokenHandler(result.token); } }; render() { return ( <form onSubmit={this.handleSubmit}> <CardSection /> <button disabled={!this.props.stripe}>Confirm order</button> </form> ); } } export default function InjectedCheckoutForm() { return ( <ElementsConsumer> {({stripe, elements}) => ( <CheckoutForm stripe={stripe} elements={elements} /> )} </ElementsConsumer> ); }

    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(); }
    function stripeTokenHandler(token) { const paymentData = {token: token.id}; // Use fetch to send the token ID and any other payment data to your server. // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch const response = await fetch('/charge', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(paymentData), }); // Return and display the result of the charge. return response.json(); }

    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 switch 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 switch 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 switch 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 switch 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 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'); // Token is created using Stripe Checkout or Elements! // Get the payment token ID submitted by the form: const token = request.body.stripeToken; // Using Express const charge = await stripe.charges.create({ amount: 999, currency: 'usd', description: 'Example charge', source: token, });
    // 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" // 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 switch 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(); var 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 to your Gemfile gem 'stripe'
    # Install through pip pip install --upgrade stripe
    # Or find the Stripe package on http://pypi.python.org/pypi/stripe/
    # Install the PHP library via Composer composer require stripe/stripe-php
    # Or download the source directly: https://github.com/stripe/stripe-php/releases
    /* For Gradle, add the following dependency to your build.gradle and replace {VERSION} with the version number you want to use from - https://mvnrepository.com/artifact/com.stripe/stripe-java or - https://github.com/stripe/stripe-java/releases/latest */ implementation "com.stripe:stripe-java:{VERSION}"
    <!-- For Maven, add the following dependency to your POM and replace {VERSION} with the version number you want to use from - https://mvnrepository.com/artifact/com.stripe/stripe-java or - https://github.com/stripe/stripe-java/releases/latest --> <dependency> <groupId>com.stripe</groupId> <artifactId>stripe-java</artifactId> <version>{VERSION}</version> </dependency>
    # For other environments, manually install the following JARs: # - The Stripe JAR from https://github.com/stripe/stripe-java/releases/latest # - Google Gson from https://github.com/google/gson
    # Install via npm npm install --save stripe
    # Install via go go get github.com/stripe/stripe-go
    // Then import the package import ( "github.com/stripe/stripe-go" )
    # Install via dotnet dotnet add package Stripe.net dotnet restore
    # Or install via NuGet PM> Install-Package Stripe.net

    Client-side

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

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

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

    import UIKit import Stripe @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [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 switch 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 switch 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 switch 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 switch 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 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'); // 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 switch 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 switch 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(); var 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 to your Gemfile gem 'stripe'
    # Install through pip pip install --upgrade stripe
    # Or find the Stripe package on http://pypi.python.org/pypi/stripe/
    # Install the PHP library via Composer composer require stripe/stripe-php
    # Or download the source directly: https://github.com/stripe/stripe-php/releases
    /* For Gradle, add the following dependency to your build.gradle and replace {VERSION} with the version number you want to use from - https://mvnrepository.com/artifact/com.stripe/stripe-java or - https://github.com/stripe/stripe-java/releases/latest */ implementation "com.stripe:stripe-java:{VERSION}"
    <!-- For Maven, add the following dependency to your POM and replace {VERSION} with the version number you want to use from - https://mvnrepository.com/artifact/com.stripe/stripe-java or - https://github.com/stripe/stripe-java/releases/latest --> <dependency> <groupId>com.stripe</groupId> <artifactId>stripe-java</artifactId> <version>{VERSION}</version> </dependency>
    # For other environments, manually install the following JARs: # - The Stripe JAR from https://github.com/stripe/stripe-java/releases/latest # - Google Gson from https://github.com/google/gson
    # Install via npm npm install --save stripe
    # Install via go go get github.com/stripe/stripe-go
    // Then import the package import ( "github.com/stripe/stripe-go" )
    # Install via dotnet dotnet add package Stripe.net dotnet restore
    # Or install via NuGet PM> Install-Package Stripe.net

    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:14.0.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 switch 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 switch 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 switch 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 switch 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 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'); // 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 switch 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 switch 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(); var 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?

    Feedback about this page?

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

    On this page