# Card Element quickstart
# Card Element quickstart
> The Card Element is a legacy integration with significantly less functionality than the Payment Element. Stripe strongly recommends using the Payment Element to accept payments of all kinds, including card payments.
This quickstart describes how to use the legacy Card Element to collect card payments on Stripe.
To accept other payment methods and future-proof your integration, use the [Payment Element](https://docs.stripe.com/payments/payment-element.md). Learn more about [migrating to the Payment Element](https://docs.stripe.com/payments/payment-element/migration.md).
### Install the Stripe Node library
Install the package and import it in your code. Alternatively, if you’re starting from scratch and need a package.json file, download the project files using the Download link in the code editor.
#### npm
Install the library:
```bash
npm install --save stripe
```
#### GitHub
Or download the stripe-node library source code directly [from GitHub](https://github.com/stripe/stripe-node).
### Install the Stripe Ruby library
Install the Stripe ruby gem and require it in your code. Alternatively, if you’re starting from scratch and need a Gemfile, download the project files using the link in the code editor.
#### Terminal
Install the gem:
```bash
gem install stripe
```
#### Bundler
Add this line to your Gemfile:
```bash
gem 'stripe'
```
#### GitHub
Or download the stripe-ruby gem source code directly [from GitHub](https://github.com/stripe/stripe-ruby).
### Install the Stripe Java library
Add the dependency to your build and import the library. Alternatively, if you’re starting from scratch and need a sample pom.xml file (for Maven), download the project files using the link in the code editor.
#### Maven
Add the following dependency to your POM and replace {VERSION} with the version number you want to use.
```bash
\ncom.stripe\nstripe-java\n{VERSION}\n
```
#### Gradle
Add the dependency to your build.gradle file and replace {VERSION} with the version number you want to use.
```bash
implementation "com.stripe:stripe-java:{VERSION}"
```
#### GitHub
Download the JAR directly [from GitHub](https://github.com/stripe/stripe-java/releases/latest).
### Install the Stripe Python package
Install the Stripe package and import it in your code. Alternatively, if you’re starting from scratch and need a requirements.txt file, download the project files using the link in the code editor.
#### pip
Install the package through pip:
```bash
pip3 install stripe
```
#### GitHub
Download the stripe-python library source code directly [from GitHub](https://github.com/stripe/stripe-python).
### Install the Stripe PHP library
Install the library with composer and initialize with your secret API key. Alternatively, if you’re starting from scratch and need a composer.json file, download the files using the link in the code editor.
#### Composer
Install the library:
```bash
composer require stripe/stripe-php
```
#### GitHub
Or download the stripe-php library source code directly [from GitHub](https://github.com/stripe/stripe-php).
### Set up your server
Add the dependency to your build and import the library. Alternatively, if you’re starting from scratch and need a go.mod file, download the project files using the link in the code editor.
#### Go
Make sure to initialize with Go Modules:
```bash
go get -u github.com/stripe/stripe-go/v84
```
#### GitHub
Or download the stripe-go module source code directly [from GitHub](https://github.com/stripe/stripe-go).
### Install the Stripe.net library
Install the package with .NET or NuGet. Alternatively, if you’re starting from scratch, download the files which contains a configured .csproj file.
#### dotnet
Install the library:
```bash
dotnet add package Stripe.net
```
#### NuGet
Install the library:
```bash
Install-Package Stripe.net
```
#### GitHub
Or download the Stripe.net library source code directly [from GitHub](https://github.com/stripe/stripe-dotnet).
### Install the Stripe libraries
Install the packages and import them in your code. Alternatively, if you’re starting from scratch and need a `package.json` file, download the project files using the link in the code editor.
Install the libraries:
```bash
npm install --save stripe @stripe/stripe-js next
```
### Create a PaymentIntent
Add an endpoint on your server that creates a [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). A PaymentIntent tracks the customer’s payment lifecycle, keeping track of any failed payment attempts and ensuring the customer is only charged once. Return the PaymentIntent’s client secret in the response to finish the payment on the client.
### Add Stripe to your React app
Use the Stripe.js and the Stripe Elements UI library to stay PCI compliant by ensuring that card details go directly to Stripe and never reach your server.
```bash
npm install --save @stripe/react-stripe-js @stripe/stripe-js
```
### Load Stripe.js
Call `loadStripe()` with your Stripe publishable API key to configure the Stripe library.
### Initialize Stripe Elements
Pass the resulting promise from `loadStripe` to the Elements provider. This allows the child components to access the Stripe service through the Elements consumer.
If you’re a Connect user and you specified the [on_behalf_of](https://docs.stripe.com/connect/charges.md#on_behalf_of) property when creating your Payment or Setup intent, you must pass the same value to the Elements group using the [onBehalfOf](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-onBehalfOf) option.
### Set up the state
Initialize some state to keep track of the payment, show errors, and manage the user interface.
### Store a reference to Stripe
Access the Stripe library in your CheckoutForm component by using the `useStripe()` and `useElements()` hooks. If you need to access Elements through a class component, use the [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer) instead.
### Fetch a PaymentIntent
Immediately make a request to the endpoint on your server to create a new PaymentIntent as soon as your checkout page loads. The `clientSecret` returned by your endpoint is used to complete the payment.
### Add a CardElement
Add a CardElement to your payment form, which embeds an iframe with the necessary input fields to collect the card data. This creates a single input that collects the card number, expiry date, CVC, and postal code. Stripe Elements displays localized placeholder text of the postal code field based on your customer’s [browser locale](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-locale) (for example, showing “ZIP” for US cardholders, “Postcode” for U.K. cardholders).
### Listen for load errors
Listen to [load errors](https://docs.stripe.com/js/element/events/on_loaderror) that trigger if the `Element` fails to load.
### Optional: Style the card input
Stripe embeds an iframe to securely collect card details. Customize the iframe by passing a [style](https://docs.stripe.com/js/appendix/style) object. Use your company’s color scheme and font to make it match the rest of your checkout page. Use custom fonts (for example, from Google Fonts) by initializing Elements with a [font set](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-fonts).
### Optional: expose card errors
Define a function to listen for changes to the card input. Immediately expose card errors (for example, the expiry date is in the past) and disable the button if the input is empty.
### Optional: Style the card input
Stripe embeds an iframe to securely collect card details. Customize the iframe by passing a [style](https://docs.stripe.com/js/appendix/style) object. Use your company’s color scheme and font to make it match the rest of your checkout page. Use custom fonts (for example, from Google Fonts) by initializing Elements with a [font set](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts).
### Optional: expose card errors
Define a function to listen for changes to the card input. Immediately expose card errors (for example, the expiry date is in the past) and disable the button if the input is empty.
### Load Stripe.js
Use Stripe.js to remain PCI compliant by ensuring that card details are sent directly to Stripe without hitting your server. Always load Stripe.js from js.stripe.com to remain compliant. Don’t include the script in a bundle or host it yourself.
### Define the payment form
Add an empty placeholder `div` to your checkout form. Stripe inserts an iframe into this `div` that securely collects card information.
### Initialize Stripe.js
Initialize Stripe.js with your publishable API keys. You’ll use Stripe.js to create the card input field and complete the payment on the client.
### Fetch a PaymentIntent
Immediately make a request to the endpoint on your server to create a new PaymentIntent as soon as the page loads.
### Initialize Stripe Elements
Initialize the [Stripe Elements UI library](https://docs.stripe.com/js/elements_object/create_without_intent). Elements manages the UI components you need to collect card details.
If you’re a Connect user and you specified the [on_behalf_of](https://docs.stripe.com/connect/charges.md#on_behalf_of) property when creating your Payment or Setup intent, you must pass the same value to the Elements group using the [onBehalfOf](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-onBehalfOf) option.
### Create the Card Element
Create a Card Element and mount it to the placeholder `'
` in your payment form. This creates a single input that collects the card number, expiry date, CVC, and postal code. Stripe Elements displays localized placeholder text of the postal code field based on your customer’s [browser locale](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-locale) (for example, showing “ZIP” for US cardholders, “Postcode” for U.K. cardholders).
### Listen for load errors
Listen to [load errors](https://docs.stripe.com/js/element/events/on_loaderror) that trigger if the `Element` fails to load.
### Optional: Style the card input
Stripe embeds an iframe to securely collect card details. Customize the iframe by passing a [style](https://docs.stripe.com/js/appendix/style) object. Use your company’s color scheme and font to make it match the rest of your checkout page. Use custom fonts (for example, from Google Fonts) by initializing Elements with a [font set](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-fonts).
### Initialize Stripe Elements
Initialize the [Stripe Elements UI library](https://docs.stripe.com/js/elements_object/create). Elements manages the UI components you need to collect card details.
### Create the Card Element
Create a Card Element and mount it to the placeholder `'
` in your payment form. This creates a single input that collects the card number, expiry date, CVC, and postal code. Stripe Elements displays localized placeholder text of the postal code field based on your customer’s [browser locale](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-locale) (for example, showing “ZIP” for US cardholders, “Postcode” for U.K. cardholders).
### Optional: Style the card input
Stripe embeds an iframe to securely collect card details. Customize the iframe by passing a [style](https://docs.stripe.com/js/appendix/style) object. Use your company’s color scheme and font to make it match the rest of your checkout page. Use custom fonts (for example, from Google Fonts) by initializing Elements with a [font set](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts).
### Optional: Expose card errors
Listen to changes on the Card Element to immediately expose card errors (for example, the expiry date is in the past) and disable the button if the Element is empty.
### Handle the submit event
Listen to the form’s submit event to know when to confirm the payment through the Stripe API.
### Complete the payment
Call `confirmCardPayment()` with the client secret and Card Element to complete the payment. Stripe automatically displays a modal if the card requires authentication, such as 3D Secure, where the customer must enter a passcode or identifying information to finalize the purchase.
### Complete the payment
When your customer clicks the pay button, call `confirmCardPayment()` with the PaymentIntent client secret and Card Element. Stripe automatically displays a modal if the card requires authentication, such as 3D Secure, where the customer must enter a passcode or identifying information to finalize the purchase.
### Handle the API response
If no error occurred, tell your customer the payment was successful! For any important post-payment actions (such as shipping packages or sending email receipts) we recommend [setting up a webhook](https://docs.stripe.com/webhooks/handling-payment-events.md). If your customer’s card is declined, Stripe.js returns an error. Show that error message to your customer so they can try again with a different card.
### Run the application
Run the server and go to the checkout page.
### Make a test payment
Use a test card number to try your integration. These card numbers work in a testing environment with any CVC, postal code, and future expiration date. Stripe also has a set of [international test cards](https://docs.stripe.com/testing.md#international-cards) to test specific postal code formats (for example, only allow numerical values for US postal codes).
| Scenario | Card Number |
| ----------------------------------- | ---------------- |
| Payment succeeds | 4242424242424242 |
| Payment requires 3DS authentication | 4000002500003155 |
| Payment is declined | 4000000000009995 |
## Congratulations!
You’re ready to accept payments with Stripe. Continue with the steps below to add more features.
### Send an email receipt
Stripe can send an email receipt to your customer using your brand logo and color theme, configurable in [the Dashboard](https://dashboard.stripe.com/settings/branding).
### Collect the customer’s email address
Add an input field to your payment form to collect an email address.
### Provide the email address to Stripe
Pass the provided email address as the receipt_email value when completing the payment with `confirmCardPayment()`. Stripe sends an email receipt when the payment succeeds in live mode (but won’t send one in a testing environment).
### Save card after payment
SaaS or e-commerce businesses often save card details for recurring customers.
### Create a customer
Stripe stores the card on a [Customer](https://docs.stripe.com/api/customers.md) object. Create a new Customer before creating a PaymentIntent. You can also store name, email, shipping address, and other details on the Customer.
### Add the customer to the PaymentIntent
Pass the Customer ID to the PaymentIntent and set `setup_future_usage` to `off_session`. `setup_future_usage` tells Stripe how you plan to use the card—certain regions, such as Europe and India, have requirements around reusing card details. [Read more](https://docs.stripe.com/payments/save-and-reuse-cards-only.md#web-create-payment-intent-off-session) about optimizing `setup_future_usage`, otherwise simply set it to `off_session`. After the PaymentIntent succeeds, Stripe automatically [attaches](https://docs.stripe.com/api/payment_methods/attach.md) the card details (in a [PaymentMethod](https://docs.stripe.com/api/payment_methods.md) object) to your Customer.
### Charge the card
When you’re ready to charge the card again, create a new PaymentIntent with the Customer ID, the PaymentMethod ID of the card you want to charge, and set the `off_session` and `confirm` flags to true.
### Install the Stripe Node library
Install the package and import it in your code. Alternatively, if you’re starting from scratch and need a package.json file, download the project files using the Download link in the code editor.
#### npm
Install the library:
```bash
npm install --save stripe
```
#### GitHub
Or download the stripe-node library source code directly [from GitHub](https://github.com/stripe/stripe-node).
### Install the Stripe Ruby library
Install the Stripe ruby gem and require it in your code. Alternatively, if you’re starting from scratch and need a Gemfile, download the project files using the link in the code editor.
#### Terminal
Install the gem:
```bash
gem install stripe
```
#### Bundler
Add this line to your Gemfile:
```bash
gem 'stripe'
```
#### GitHub
Or download the stripe-ruby gem source code directly [from GitHub](https://github.com/stripe/stripe-ruby).
### Install the Stripe Java library
Add the dependency to your build and import the library. Alternatively, if you’re starting from scratch and need a sample pom.xml file (for Maven), download the project files using the link in the code editor.
#### Maven
Add the following dependency to your POM and replace {VERSION} with the version number you want to use.
```bash
\ncom.stripe\nstripe-java\n{VERSION}\n
```
#### Gradle
Add the dependency to your build.gradle file and replace {VERSION} with the version number you want to use.
```bash
implementation "com.stripe:stripe-java:{VERSION}"
```
#### GitHub
Download the JAR directly [from GitHub](https://github.com/stripe/stripe-java/releases/latest).
### Install the Stripe Python package
Install the Stripe package and import it in your code. Alternatively, if you’re starting from scratch and need a requirements.txt file, download the project files using the link in the code editor.
#### pip
Install the package through pip:
```bash
pip3 install stripe
```
#### GitHub
Download the stripe-python library source code directly [from GitHub](https://github.com/stripe/stripe-python).
### Install the Stripe PHP library
Install the library with composer and initialize with your secret API key. Alternatively, if you’re starting from scratch and need a composer.json file, download the files using the link in the code editor.
#### Composer
Install the library:
```bash
composer require stripe/stripe-php
```
#### GitHub
Or download the stripe-php library source code directly [from GitHub](https://github.com/stripe/stripe-php).
### Set up your server
Add the dependency to your build and import the library. Alternatively, if you’re starting from scratch and need a go.mod file, download the project files using the link in the code editor.
#### Go
Make sure to initialize with Go Modules:
```bash
go get -u github.com/stripe/stripe-go/v84
```
#### GitHub
Or download the stripe-go module source code directly [from GitHub](https://github.com/stripe/stripe-go).
### Install the Stripe.net library
Install the package with .NET or NuGet. Alternatively, if you’re starting from scratch, download the files which contains a configured .csproj file.
#### dotnet
Install the library:
```bash
dotnet add package Stripe.net
```
#### NuGet
Install the library:
```bash
Install-Package Stripe.net
```
#### GitHub
Or download the Stripe.net library source code directly [from GitHub](https://github.com/stripe/stripe-dotnet).
### Install the Stripe libraries
Install the packages and import them in your code. Alternatively, if you’re starting from scratch and need a `package.json` file, download the project files using the link in the code editor.
Install the libraries:
```bash
npm install --save stripe @stripe/stripe-js next
```
### Create a PaymentIntent
Add an endpoint on your server that creates a [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). A PaymentIntent tracks the customer’s payment lifecycle, keeping track of any failed payment attempts and ensuring the customer is only charged once. Return the PaymentIntent’s client secret in the response to finish the payment on the client.
### Install the SDK
The iOS SDK is [open source](http://github.com/stripe/stripe-ios), fully documented, and compatible with apps supporting iOS 13 or above. Import Stripe in your project after installing.
#### Swift Package Manager
In Xcode, select **File** > **Add Package Dependencies…** and enter `https://github.com/stripe/stripe-ios-spm` as the repository URL. Select the latest version number from our [releases page](https://github.com/stripe/stripe-ios/releases), and add the `StripePaymentsUI` module to your app’s target.
#### CocoaPods
Add this line to your Podfile, and use the .xcworkspace file to open your project in Xcode, instead of the .xcodeproj file, from here on out.
```bash
pod 'StripePaymentsUI'
```
#### Carthage
Add this line to your Cartfile.
```bash
github "stripe/stripe-ios"
```
#### Dynamic framework
To include Stripe in your project, download and unzip Stripe.xcframework.zip from a release on GitHub. Drag the required xcframework files to the “Embedded Binaries” settings in your Xcode project. Make sure to select “Copy items if needed”. See the GitHub README for the list of required xcframeworks.
### Set up the SDK
Configure the Stripe SDK with your Stripe publishable API key.
### Define your payment form
Use Stripe’s `STPPaymentCardTextField` class to display a text field to securely collect card details. By using `STPPaymentCardTextField`, you guarantee that sensitive card details never touch your server.
### Fetch a PaymentIntent
Make a request to your server for a PaymentIntent as soon as the view loads. Store a reference to the PaymentIntent’s client secret returned by the server.
### Collect payment details
When the customer clicks the pay button, create an [STPPaymentIntentParams](https://stripe.dev/stripe-ios/stripe-payments/Classes/STPPaymentIntentParams.html) object with the card details and client secret from the PaymentIntent you created on the server.
### Finish the payment
Send the payment details to Stripe by calling `confirmPayment()`.
### Complete the payment
Send the payment details to Stripe by calling `confirmPayment()` with the STPPaymentIntentParams.
### Handle the response from Stripe
If your customer’s card is declined, the completion block is called with an error. Show that error to your customer so they can try again with a different card. If no error occurred, tell your customer the payment was successful!
### Make a test payment
Use a test card number to try your integration. These card numbers work in a testing environment with any CVC, postal code, and future expiration date. Stripe also has a set of [international test cards](https://docs.stripe.com/testing.md#international-cards) to test specific postal code formats (for example, only allow numerical values for US postal codes).
| Scenario | Card Number |
| ----------------------------------- | ---------------- |
| Payment succeeds | 4242424242424242 |
| Payment requires 3DS authentication | 4000002500003155 |
| Payment is declined | 4000000000009995 |
// This is a public sample test API key.
// Don’t submit any personally identifiable information in requests made with this key.
// Sign in to see your own test API key embedded in code samples.
const stripe = require("stripe")("<>");
const chargeCustomer = async (customerId) => {
// Lookup the payment methods available for the customer
const paymentMethods = await stripe.paymentMethods.list({
customer: customerId,
type: "card"
});
// Charge the customer and payment method immediately
const paymentIntent = await stripe.paymentIntents.create({
amount: 1099,
currency: "usd",
customer: customerId,
payment_method: paymentMethods.data[0].id,
off_session: true,
confirm: true
});
if (paymentIntent.status === "succeeded") {
console.log("✅ Successfully charged card off session");
}
}
// Alternatively, set up a webhook to listen for the payment_intent.succeeded event
// and attach the PaymentMethod to a new Customer
const customer = await stripe.customers.create();
// Create a PaymentIntent with the order amount and currency
const paymentIntent = await stripe.paymentIntents.create({
customer: customer.id,
setup_future_usage: 'off_session',
amount: calculateOrderAmount(items),
currency: "usd"
});
res.send({
clientSecret: paymentIntent.client_secret
});
{
"name": "stripe-sample",
"version": "1.0.0",
"description": "A sample Stripe implementation",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"author": "stripe-samples",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"stripe": "^20.4.0"
}
}
{
"name": "stripe-sample",
"version": "0.1.0",
"dependencies": {
"@stripe/react-stripe-js": "^3.7.0",
"@stripe/stripe-js": "^7.3.0",
"express": "^4.17.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "^3.4.0",
"stripe": "20.4.0"
},
"devDependencies": {
"concurrently": "4.1.2"
},
"homepage": "http://localhost:3000/checkout",
"proxy": "http://localhost:4242",
"scripts": {
"start-client": "react-scripts start",
"start-server": "node server.js",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"start": "concurrently \"yarn start-client\" \"yarn start-server\""
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
require 'stripe'
\# This is a public sample test API key.
# Don’t submit any personally identifiable information in requests made with this key.
# Sign in to see your own test API key embedded in code samples.
Stripe.api_key = '<>'
def charge_customer(customerId)
\# Lookup all payment methods for customer
payment_methods = Stripe::PaymentMethod.list(
customer: customerId,
type: 'card'
)
# Charge the customer and payment method immediately
payment_intent = Stripe::PaymentIntent.create(
amount: 1099,
currency: 'usd',
customer: customerId,
payment_method: payment_methods.data[0]['id'],
off_session: true,
confirm: true
)
if payment_intent['status'] == 'succeeded'
puts '✅ Successfully charged card off session'
end
end
\# Alternatively, set up a webhook to listen for the payment_intent.succeeded event
# and attach the PaymentMethod to a new Customer
customer = Stripe::Customer.create
\# Create a PaymentIntent with amount and currency
payment_intent = Stripe::PaymentIntent.create(
customer: customer['id'],
setup_future_usage: 'off_session',
amount: calculate_order_amount(data['items']),
currency: 'usd'
)
{
clientSecret: payment_intent['client_secret'],
}.to_json
import stripe
\# This is a public sample test API key.
# Don’t submit any personally identifiable information in requests made with this key.
# Sign in to see your own test API key embedded in code samples.
stripe.api_key = "<>"
def charge_customer(customerId):
\# Lookup the saved card (you can store multiple PaymentMethods on a Customer)
payment_methods = stripe.PaymentMethod.list(
customer=customerId,
type='card'
)
# Charge the customer and payment method immediately
payment_intent = stripe.PaymentIntent.create(
amount=2000,
currency='usd',
customer=customerId,
payment_method=payment_methods.data[0].id,
off_session=True,
confirm=True
)
if payment_intent.status == 'succeeded':
print('Successfully charged card off session')
\# Alternatively, set up a webhook to listen for the payment_intent.succeeded event
# and attach the PaymentMethod to a new Customer
customer = stripe.Customer.create()
try:
data = json.loads(request.data)
intent = stripe.PaymentIntent.create(
customer=customer['id'],
setup_future_usage='off_session',
amount=calculate_order_amount(data['items']),
currency='usd'
)
return jsonify({
'clientSecret': intent['client_secret']
})
except Exception as e:
return jsonify(error=str(e)), 403
certifi==2026.1.4
chardet==5.2.0
click==8.3.1
Flask==3.1.2
idna==3.11
itsdangerous==2.2.0
Jinja2==3.1.6
MarkupSafe==3.0.3
requests==2.32.5
stripe==14.4.0
toml==0.10.2
Werkzeug==3.1.5
\Stripe\Stripe::setApiKey($stripeSecretKey);
// Alternatively, set up a webhook to listen for the payment_intent.succeeded event
// and attach the PaymentMethod to a new Customer
$customer = \Stripe\Customer::create();
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => calculateOrderAmount($json_obj->items),
'currency' => 'usd',
'customer' => $customer->id,
'setup_future_usage' => 'off_session',
]);
$output = [
'clientSecret' => $paymentIntent->client_secret,
];
$stripeSecretKey = '<>';
$payment_methods = \Stripe\PaymentMethod::all([
'customer' => $json_obj->customer,
'type' => 'card'
]);
// Charge the customer and card immediately
$payment_intent = \Stripe\PaymentIntent::create([
'amount' => 1099,
'currency' => 'usd',
'customer' => $json_obj->customer,
'payment_method' => $payment_methods->data[0]->id,
'off_session' => true,
'confirm' => true
]);
// This is a public sample test API key.
// Don’t submit any personally identifiable information in requests made with this key.
// Sign in to see your own test API key embedded in code samples.
services.AddSingleton(new StripeClient("<>"));
// Alternatively, set up a webhook to listen for the payment_intent.succeeded event
// and attach the PaymentMethod to a new Customer
var customer = _client.V1.Customers.Create(new CustomerCreateOptions());
var paymentIntent = _client.V1.PaymentIntents.Create(new PaymentIntentCreateOptions
{
Customer = customer.Id,
SetupFutureUsage = "off_session",
Amount = CalculateOrderAmount(request.Items),
Currency = "usd",
});
return Json(new { clientSecret = paymentIntent.ClientSecret });
public void ChargeCustomer(string customerId)
{
// Lookup the payment methods available for the customer
var availableMethods = _client.V1.PaymentMethods.List(new PaymentMethodListOptions
{
Customer = customerId,
Type = "card",
});
// Charge the customer and payment method immediately
var paymentIntent = _client.V1.PaymentIntents.Create(new PaymentIntentCreateOptions
{
Amount = 1099,
Currency = "usd",
Customer = customerId,
PaymentMethod = availableMethods.Data[0].Id,
OffSession = true,
Confirm = true
});
if (paymentIntent.Status == "succeeded")
Console.WriteLine("✅ Successfully charged card off session");
}
"github.com/stripe/stripe-go/v84"
"github.com/stripe/stripe-go/v84/paymentintent"
"github.com/stripe/stripe-go/v84/customer"
"github.com/stripe/stripe-go/v84/paymentmethod"
// This is a public sample test API key.
// Don’t submit any personally identifiable information in requests made with this key.
// Sign in to see your own test API key embedded in code samples.
stripe.Key = "<>"
func chargeCustomer(CustomerID string) {
params := &stripe.PaymentMethodListParams{
Customer: stripe.String(CustomerID),
Type: stripe.String(string(stripe.PaymentMethodTypeCard)),
}
i := paymentmethod.List(params)
for i.Next() {
pm := i.PaymentMethod()
piparams := &stripe.PaymentIntentParams{
Amount: stripe.Int64(1099),
Currency: stripe.String(string(stripe.CurrencyUSD)),
Customer: stripe.String(CustomerID),
PaymentMethod: stripe.String(pm.ID),
Confirm: stripe.Bool(true),
OffSession: stripe.Bool(true),
}
pi, _ := paymentintent.New(piparams)
log.Printf("pi.Status: %v", pi.Status)
}
}
// Alternatively, set up a webhook to listen for the payment_intent.succeeded event
// and attach the PaymentMethod to a new Customer
cparams := &stripe.CustomerParams{}
c, _ := customer.New(cparams)
params := &stripe.PaymentIntentParams{
Amount: stripe.Int64(calculateOrderAmount(req.Items)),
Currency: stripe.String(string(stripe.CurrencyUSD)),
Customer: stripe.String(c.ID),
SetupFutureUsage: stripe.String("off_session"),
}
pi, err := paymentintent.New(params)
log.Printf("pi.New: %v", pi.ClientSecret)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Printf("pi.New: %v", err)
return
}
writeJSON(w, struct {
ClientSecret string `json:"clientSecret"`
}{
ClientSecret: pi.ClientSecret,
})
require github.com/stripe/stripe-go/v84 v84.4.0
import com.stripe.model.PaymentMethod;
import com.stripe.model.Customer;
import com.stripe.model.PaymentMethodCollection;
import com.stripe.param.CustomerCreateParams;
import com.stripe.param.PaymentMethodListParams;
import com.stripe.exception.StripeException;
// Call this function with the ID of the Customer you want to charge
static void chargeCustomer(String customerId) {
try {
// List the customer's payment methods to find one to charge
PaymentMethodListParams listParams = new PaymentMethodListParams.Builder().setCustomer(customerId)
.setType(PaymentMethodListParams.Type.CARD).build();
PaymentMethodCollection paymentMethods = PaymentMethod.list(listParams);
PaymentIntentCreateParams createParams = new PaymentIntentCreateParams.Builder().setCurrency("usd")
.setAmount(new Long(1099))
.setPaymentMethod(paymentMethods.getData().get(0).getId())
.setCustomer(customerId)
.setConfirm(true)
.setOffSession(PaymentIntentCreateParams.OffSession.ONE_OFF).build();
PaymentIntent paymentIntent = PaymentIntent.create(createParams);
if (paymentIntent.getStatus().equals("succeeded")) {
System.out.println("Payment suceeded");
}
} catch (StripeException e) {
System.out.println("Error from Stripe: " + e.getMessage());
}
}
// This is a public sample test API key.
// Don’t submit any personally identifiable information in requests made with this key.
// Sign in to see your own test API key embedded in code samples.
Stripe.apiKey = "<>";
// Alternatively, set up a webhook to listen for the payment_intent.succeeded event
// and attach the PaymentMethod to a new Customer
CustomerCreateParams customerParams = new CustomerCreateParams.Builder().build();
Customer customer = Customer.create(customerParams);
CreatePayment postBody = gson.fromJson(request.body(), CreatePayment.class);
PaymentIntentCreateParams createParams = new PaymentIntentCreateParams.Builder()
.setCurrency("usd")
.setAmount(new Long(calculateOrderAmount(postBody.getItems())))
.setCustomer(customer.getId())
.setSetupFutureUsage(PaymentIntentCreateParams.SetupFutureUsage.OFF_SESSION)
.build();
// Create a PaymentIntent with the order amount and currency
PaymentIntent intent = PaymentIntent.create(createParams);
CreatePaymentResponse paymentResponse = new CreatePaymentResponse(intent.getClientSecret());
return gson.toJson(paymentResponse);
@import StripeCore;
@import StripePayments;
@import StripePaymentsUI;
[StripeAPI setDefaultPublishableKey:@"<>"];
// Set up the Stripe card text field
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.safeAreaLayoutGuide.topAnchor multiplier:2],
]];
// Create a PaymentIntent by calling your server's endpoint.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@create-payment-intent", BackendUrl]];
NSDictionary *json = @{
@"items": @[
@{@"id": @"xl_tshirt"}
]
};
NSData *body = [NSJSONSerialization dataWithJSONObject:json options:0 error:nil];
NSMutableURLRequest *request = [[NSURLRequest requestWithURL:url] mutableCopy];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:body];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *requestError) {
NSError *error = requestError;
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (error != nil || httpResponse.statusCode != 200) {
[self displayAlertWithTitle:@"Error loading page" message:error.localizedDescription ?: @""];
}
else {
NSLog(@"Created PaymentIntent");
self.paymentIntentClientSecret = json[@"clientSecret"];
}
}];
// Collect card details
STPPaymentIntentParams *paymentIntentParams = [[STPPaymentIntentParams alloc] initWithClientSecret:self.paymentIntentClientSecret];
paymentIntentParams.paymentMethodParams = self.cardTextField.paymentMethodParams;
// Submit the payment
STPPaymentHandler *paymentHandler = [STPPaymentHandler sharedHandler];
[paymentHandler confirmPayment:paymentIntentParams withAuthenticationContext:self completion:^(STPPaymentHandlerActionStatus status, STPPaymentIntent *paymentIntent, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
switch (status) {
case STPPaymentHandlerActionStatusFailed: {
[self displayAlertWithTitle:@"Payment failed" message:error.localizedDescription ?: @""];
break;
}
case STPPaymentHandlerActionStatusCanceled: {
[self displayAlertWithTitle:@"Payment canceled" message:error.localizedDescription ?: @""];
break;
}
case STPPaymentHandlerActionStatusSucceeded: {
[self displayAlertWithTitle:@"Payment succeeded" message:paymentIntent.description ?: @""];
break;
}
default:
break;
}
import StripePaymentsUI
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 now", for: .normal)
button.addTarget(self, action: #selector(pay), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
StripeAPI.defaultPublishableKey = "<>"
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.safeAreaLayoutGuide.topAnchor, multiplier: 2),
])
startCheckout()
}
func startCheckout() {
// Create a PaymentIntent as soon as the view loads
let url = URL(string: backendUrl + "create.php")!
let json: [String: Any] = [
"items": [
["id": "xl-shirt"]
]
]
// Create a PaymentIntent as soon as the view loads
let url = URL(string: backendUrl + "create-payment-intent")!
let json: [String: Any] = [
"items": [
["id": "xl-shirt"]
]
]
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: json)
let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in
guard let response = response as? HTTPURLResponse,
response.statusCode == 200,
let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
let clientSecret = json["clientSecret"] as? String else {
let message = error?.localizedDescription ?? "Failed to decode response from server."
self?.displayAlert(title: "Error loading page", message: message)
return
}
print("Created PaymentIntent")
self?.paymentIntentClientSecret = clientSecret
})
task.resume()
}
// Collect card details
let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret)
paymentIntentParams.paymentMethodParams = cardTextField.paymentMethodParams
// Submit the payment
let paymentHandler = STPPaymentHandler.shared()
paymentHandler.confirmPayment(paymentIntentParams, with: 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 ?? "")
break
@unknown default:
fatalError()
break
}
### Install the Stripe Node library
Install the package and import it in your code. Alternatively, if you’re starting from scratch and need a package.json file, download the project files using the Download link in the code editor.
#### npm
Install the library:
```bash
npm install --save stripe
```
#### GitHub
Or download the stripe-node library source code directly [from GitHub](https://github.com/stripe/stripe-node).
### Install the Stripe Ruby library
Install the Stripe ruby gem and require it in your code. Alternatively, if you’re starting from scratch and need a Gemfile, download the project files using the link in the code editor.
#### Terminal
Install the gem:
```bash
gem install stripe
```
#### Bundler
Add this line to your Gemfile:
```bash
gem 'stripe'
```
#### GitHub
Or download the stripe-ruby gem source code directly [from GitHub](https://github.com/stripe/stripe-ruby).
### Install the Stripe Java library
Add the dependency to your build and import the library. Alternatively, if you’re starting from scratch and need a sample pom.xml file (for Maven), download the project files using the link in the code editor.
#### Maven
Add the following dependency to your POM and replace {VERSION} with the version number you want to use.
```bash
\ncom.stripe\nstripe-java\n{VERSION}\n
```
#### Gradle
Add the dependency to your build.gradle file and replace {VERSION} with the version number you want to use.
```bash
implementation "com.stripe:stripe-java:{VERSION}"
```
#### GitHub
Download the JAR directly [from GitHub](https://github.com/stripe/stripe-java/releases/latest).
### Install the Stripe Python package
Install the Stripe package and import it in your code. Alternatively, if you’re starting from scratch and need a requirements.txt file, download the project files using the link in the code editor.
#### pip
Install the package through pip:
```bash
pip3 install stripe
```
#### GitHub
Download the stripe-python library source code directly [from GitHub](https://github.com/stripe/stripe-python).
### Install the Stripe PHP library
Install the library with composer and initialize with your secret API key. Alternatively, if you’re starting from scratch and need a composer.json file, download the files using the link in the code editor.
#### Composer
Install the library:
```bash
composer require stripe/stripe-php
```
#### GitHub
Or download the stripe-php library source code directly [from GitHub](https://github.com/stripe/stripe-php).
### Set up your server
Add the dependency to your build and import the library. Alternatively, if you’re starting from scratch and need a go.mod file, download the project files using the link in the code editor.
#### Go
Make sure to initialize with Go Modules:
```bash
go get -u github.com/stripe/stripe-go/v84
```
#### GitHub
Or download the stripe-go module source code directly [from GitHub](https://github.com/stripe/stripe-go).
### Install the Stripe.net library
Install the package with .NET or NuGet. Alternatively, if you’re starting from scratch, download the files which contains a configured .csproj file.
#### dotnet
Install the library:
```bash
dotnet add package Stripe.net
```
#### NuGet
Install the library:
```bash
Install-Package Stripe.net
```
#### GitHub
Or download the Stripe.net library source code directly [from GitHub](https://github.com/stripe/stripe-dotnet).
### Install the Stripe libraries
Install the packages and import them in your code. Alternatively, if you’re starting from scratch and need a `package.json` file, download the project files using the link in the code editor.
Install the libraries:
```bash
npm install --save stripe @stripe/stripe-js next
```
### Create a PaymentIntent
Add an endpoint on your server that creates a [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). A PaymentIntent tracks the customer’s payment lifecycle, keeping track of any failed payment attempts and ensuring the customer is only charged once. Return the PaymentIntent’s client secret in the response to finish the payment on the client.
### Add Stripe to your React app
Use the Stripe.js and the Stripe Elements UI library to stay PCI compliant by ensuring that card details go directly to Stripe and never reach your server.
```bash
npm install --save @stripe/react-stripe-js @stripe/stripe-js
```
### Load Stripe.js
Call `loadStripe()` with your Stripe publishable API key to configure the Stripe library.
### Initialize Stripe Elements
Pass the resulting promise from `loadStripe` to the Elements provider. This allows the child components to access the Stripe service through the Elements consumer.
If you’re a Connect user and you specified the [on_behalf_of](https://docs.stripe.com/connect/charges.md#on_behalf_of) property when creating your Payment or Setup intent, you must pass the same value to the Elements group using the [onBehalfOf](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-onBehalfOf) option.
### Set up the state
Initialize some state to keep track of the payment, show errors, and manage the user interface.
### Store a reference to Stripe
Access the Stripe library in your CheckoutForm component by using the `useStripe()` and `useElements()` hooks. If you need to access Elements through a class component, use the [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer) instead.
### Fetch a PaymentIntent
Immediately make a request to the endpoint on your server to create a new PaymentIntent as soon as your checkout page loads. The `clientSecret` returned by your endpoint is used to complete the payment.
### Add a CardElement
Add a CardElement to your payment form, which embeds an iframe with the necessary input fields to collect the card data. This creates a single input that collects the card number, expiry date, CVC, and postal code. Stripe Elements displays localized placeholder text of the postal code field based on your customer’s [browser locale](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-locale) (for example, showing “ZIP” for US cardholders, “Postcode” for U.K. cardholders).
### Listen for load errors
Listen to [load errors](https://docs.stripe.com/js/element/events/on_loaderror) that trigger if the `Element` fails to load.
### Optional: Style the card input
Stripe embeds an iframe to securely collect card details. Customize the iframe by passing a [style](https://docs.stripe.com/js/appendix/style) object. Use your company’s color scheme and font to make it match the rest of your checkout page. Use custom fonts (for example, from Google Fonts) by initializing Elements with a [font set](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-fonts).
### Optional: expose card errors
Define a function to listen for changes to the card input. Immediately expose card errors (for example, the expiry date is in the past) and disable the button if the input is empty.
### Optional: Style the card input
Stripe embeds an iframe to securely collect card details. Customize the iframe by passing a [style](https://docs.stripe.com/js/appendix/style) object. Use your company’s color scheme and font to make it match the rest of your checkout page. Use custom fonts (for example, from Google Fonts) by initializing Elements with a [font set](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts).
### Optional: expose card errors
Define a function to listen for changes to the card input. Immediately expose card errors (for example, the expiry date is in the past) and disable the button if the input is empty.
### Load Stripe.js
Use Stripe.js to remain PCI compliant by ensuring that card details are sent directly to Stripe without hitting your server. Always load Stripe.js from js.stripe.com to remain compliant. Don’t include the script in a bundle or host it yourself.
### Define the payment form
Add an empty placeholder `div` to your checkout form. Stripe inserts an iframe into this `div` that securely collects card information.
### Initialize Stripe.js
Initialize Stripe.js with your publishable API keys. You’ll use Stripe.js to create the card input field and complete the payment on the client.
### Fetch a PaymentIntent
Immediately make a request to the endpoint on your server to create a new PaymentIntent as soon as the page loads.
### Initialize Stripe Elements
Initialize the [Stripe Elements UI library](https://docs.stripe.com/js/elements_object/create_without_intent). Elements manages the UI components you need to collect card details.
If you’re a Connect user and you specified the [on_behalf_of](https://docs.stripe.com/connect/charges.md#on_behalf_of) property when creating your Payment or Setup intent, you must pass the same value to the Elements group using the [onBehalfOf](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-onBehalfOf) option.
### Create the Card Element
Create a Card Element and mount it to the placeholder `'
` in your payment form. This creates a single input that collects the card number, expiry date, CVC, and postal code. Stripe Elements displays localized placeholder text of the postal code field based on your customer’s [browser locale](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-locale) (for example, showing “ZIP” for US cardholders, “Postcode” for U.K. cardholders).
### Listen for load errors
Listen to [load errors](https://docs.stripe.com/js/element/events/on_loaderror) that trigger if the `Element` fails to load.
### Optional: Style the card input
Stripe embeds an iframe to securely collect card details. Customize the iframe by passing a [style](https://docs.stripe.com/js/appendix/style) object. Use your company’s color scheme and font to make it match the rest of your checkout page. Use custom fonts (for example, from Google Fonts) by initializing Elements with a [font set](https://docs.stripe.com/js/elements_object/create_without_intent#stripe_elements_no_intent-options-fonts).
### Initialize Stripe Elements
Initialize the [Stripe Elements UI library](https://docs.stripe.com/js/elements_object/create). Elements manages the UI components you need to collect card details.
### Create the Card Element
Create a Card Element and mount it to the placeholder `'
` in your payment form. This creates a single input that collects the card number, expiry date, CVC, and postal code. Stripe Elements displays localized placeholder text of the postal code field based on your customer’s [browser locale](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-locale) (for example, showing “ZIP” for US cardholders, “Postcode” for U.K. cardholders).
### Optional: Style the card input
Stripe embeds an iframe to securely collect card details. Customize the iframe by passing a [style](https://docs.stripe.com/js/appendix/style) object. Use your company’s color scheme and font to make it match the rest of your checkout page. Use custom fonts (for example, from Google Fonts) by initializing Elements with a [font set](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts).
### Optional: Expose card errors
Listen to changes on the Card Element to immediately expose card errors (for example, the expiry date is in the past) and disable the button if the Element is empty.
### Handle the submit event
Listen to the form’s submit event to know when to confirm the payment through the Stripe API.
### Complete the payment
Call `confirmCardPayment()` with the client secret and Card Element to complete the payment. Stripe automatically displays a modal if the card requires authentication, such as 3D Secure, where the customer must enter a passcode or identifying information to finalize the purchase.
### Complete the payment
When your customer clicks the pay button, call `confirmCardPayment()` with the PaymentIntent client secret and Card Element. Stripe automatically displays a modal if the card requires authentication, such as 3D Secure, where the customer must enter a passcode or identifying information to finalize the purchase.
### Handle the API response
If no error occurred, tell your customer the payment was successful! For any important post-payment actions (such as shipping packages or sending email receipts) we recommend [setting up a webhook](https://docs.stripe.com/webhooks/handling-payment-events.md). If your customer’s card is declined, Stripe.js returns an error. Show that error message to your customer so they can try again with a different card.
### Run the application
Run the server and go to the checkout page.
### Make a test payment
Use a test card number to try your integration. These card numbers work in a testing environment with any CVC, postal code, and future expiration date. Stripe also has a set of [international test cards](https://docs.stripe.com/testing.md#international-cards) to test specific postal code formats (for example, only allow numerical values for US postal codes).
| Scenario | Card Number |
| ----------------------------------- | ---------------- |
| Payment succeeds | 4242424242424242 |
| Payment requires 3DS authentication | 4000002500003155 |
| Payment is declined | 4000000000009995 |
## Congratulations!
You’re ready to accept payments with Stripe. Continue with the steps below to add more features.
### Send an email receipt
Stripe can send an email receipt to your customer using your brand logo and color theme, configurable in [the Dashboard](https://dashboard.stripe.com/settings/branding).
### Collect the customer’s email address
Add an input field to your payment form to collect an email address.
### Provide the email address to Stripe
Pass the provided email address as the receipt_email value when completing the payment with `confirmCardPayment()`. Stripe sends an email receipt when the payment succeeds in live mode (but won’t send one in a testing environment).
### Save card after payment
SaaS or e-commerce businesses often save card details for recurring customers.
### Create a customer
Stripe stores the card on a [Customer](https://docs.stripe.com/api/customers.md) object. Create a new Customer before creating a PaymentIntent. You can also store name, email, shipping address, and other details on the Customer.
### Add the customer to the PaymentIntent
Pass the Customer ID to the PaymentIntent and set `setup_future_usage` to `off_session`. `setup_future_usage` tells Stripe how you plan to use the card—certain regions, such as Europe and India, have requirements around reusing card details. [Read more](https://docs.stripe.com/payments/save-and-reuse-cards-only.md#web-create-payment-intent-off-session) about optimizing `setup_future_usage`, otherwise simply set it to `off_session`. After the PaymentIntent succeeds, Stripe automatically [attaches](https://docs.stripe.com/api/payment_methods/attach.md) the card details (in a [PaymentMethod](https://docs.stripe.com/api/payment_methods.md) object) to your Customer.
### Charge the card
When you’re ready to charge the card again, create a new PaymentIntent with the Customer ID, the PaymentMethod ID of the card you want to charge, and set the `off_session` and `confirm` flags to true.
var stripe = Stripe("<>");
fetch("/create-payment-intent", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(purchase)
})
fetch("/create.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(purchase)
})
var elements = stripe.elements();
var style = {
base: {
color: "#32325d",
fontFamily: 'Arial, sans-serif',
fontSmoothing: "antialiased",
fontSize: "16px",
"::placeholder": {
color: "#32325d"
}
},
invalid: {
fontFamily: 'Arial, sans-serif',
color: "#fa755a",
iconColor: "#fa755a"
}
};
var card = elements.create("card", { style: style });
// Stripe injects an iframe into the DOM
card.mount("#card-element");
card.on("loaderror", function (event) {
// Listen for load errors, handling any errors using your own observability tooling.
});
card.on("change", function (event) {
// Disable the Pay button if there are no card details in the Element
document.querySelector("button").disabled = event.empty;
document.querySelector("#card-error").textContent = event.error ? event.error.message : "";
});
var form = document.getElementById("payment-form");
form.addEventListener("submit", function(event) {
event.preventDefault();
// Complete payment when the submit button is clicked
payWithCard(stripe, card, data.clientSecret);
});
stripe
.confirmCardPayment(clientSecret, {
receipt_email: document.getElementById('email').value,
payment_method: {
card: card
}
})
.then(function(result) {
if (result.error) {
// Show error to your customer
showError(result.error.message);
} else {
// The payment succeeded!
orderComplete(result.paymentIntent.id);
}
});
/* Buttons and links */
button {
background: undefined;
font-family: undefined;
color: undefined;
border-radius: 0 0 4px 4px;
border: 0;
padding: 12px 16px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
display: block;
transition: all 0.2s ease;
box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07);
width: 100%;
}
const [succeeded, setSucceeded] = useState(false);
const [error, setError] = useState(null);
const [processing, setProcessing] = useState('');
const [disabled, setDisabled] = useState(true);
const [clientSecret, setClientSecret] = useState('');
const [email, setEmail] = useState('');
const stripe = useStripe();
const elements = useElements();
useEffect(() => {
// Create PaymentIntent as soon as the page loads
window
.fetch("/create-payment-intent", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({items: [{ id: "xl-tshirt" }]})
})
.then(res => {
return res.json();
})
.then(data => {
setClientSecret(data.clientSecret);
});
}, []);
useEffect(() => {
// Create PaymentIntent as soon as the page loads
window
.fetch("/create.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({items: [{ id: "xl-tshirt" }]})
})
.then(res => {
return res.json();
})
.then(data => {
setClientSecret(data.clientSecret);
});
}, []);
const cardStyle = {
style: {
base: {
color: "#32325d",
fontFamily: 'Arial, sans-serif',
fontSmoothing: "antialiased",
fontSize: "16px",
"::placeholder": {
color: "#32325d"
}
},
invalid: {
fontFamily: 'Arial, sans-serif',
color: "#fa755a",
iconColor: "#fa755a"
}
}
};
const handleChange = async (event) => {
// Listen for changes in the CardElement
// and display any errors as the customer types their card details
setDisabled(event.empty);
setError(event.error ? event.error.message : "");
};
const handleLoadError = async (event) => {
// Listen for load errors, handling any errors using your own observability tooling.
};
const payload = await stripe.confirmCardPayment(clientSecret, {
receipt_email: email,
payment_method: {
card: elements.getElement(CardElement)
}
});
setEmail(e.target.value)}
placeholder="Enter email address"
/>
{/* Show any error that happens when processing the payment */}
{error && (
import React from "react";
import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-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.
// A reference to Stripe.js initialized with a fake API key.
// Sign in to see examples prefilled with your key.
const promise = loadStripe("<>");
### Install the Stripe Node library
Install the package and import it in your code. Alternatively, if you’re starting from scratch and need a package.json file, download the project files using the Download link in the code editor.
#### npm
Install the library:
```bash
npm install --save stripe
```
#### GitHub
Or download the stripe-node library source code directly [from GitHub](https://github.com/stripe/stripe-node).
### Install the Stripe Ruby library
Install the Stripe ruby gem and require it in your code. Alternatively, if you’re starting from scratch and need a Gemfile, download the project files using the link in the code editor.
#### Terminal
Install the gem:
```bash
gem install stripe
```
#### Bundler
Add this line to your Gemfile:
```bash
gem 'stripe'
```
#### GitHub
Or download the stripe-ruby gem source code directly [from GitHub](https://github.com/stripe/stripe-ruby).
### Install the Stripe Java library
Add the dependency to your build and import the library. Alternatively, if you’re starting from scratch and need a sample pom.xml file (for Maven), download the project files using the link in the code editor.
#### Maven
Add the following dependency to your POM and replace {VERSION} with the version number you want to use.
```bash
\ncom.stripe\nstripe-java\n{VERSION}\n
```
#### Gradle
Add the dependency to your build.gradle file and replace {VERSION} with the version number you want to use.
```bash
implementation "com.stripe:stripe-java:{VERSION}"
```
#### GitHub
Download the JAR directly [from GitHub](https://github.com/stripe/stripe-java/releases/latest).
### Install the Stripe Python package
Install the Stripe package and import it in your code. Alternatively, if you’re starting from scratch and need a requirements.txt file, download the project files using the link in the code editor.
#### pip
Install the package through pip:
```bash
pip3 install stripe
```
#### GitHub
Download the stripe-python library source code directly [from GitHub](https://github.com/stripe/stripe-python).
### Install the Stripe PHP library
Install the library with composer and initialize with your secret API key. Alternatively, if you’re starting from scratch and need a composer.json file, download the files using the link in the code editor.
#### Composer
Install the library:
```bash
composer require stripe/stripe-php
```
#### GitHub
Or download the stripe-php library source code directly [from GitHub](https://github.com/stripe/stripe-php).
### Set up your server
Add the dependency to your build and import the library. Alternatively, if you’re starting from scratch and need a go.mod file, download the project files using the link in the code editor.
#### Go
Make sure to initialize with Go Modules:
```bash
go get -u github.com/stripe/stripe-go/v84
```
#### GitHub
Or download the stripe-go module source code directly [from GitHub](https://github.com/stripe/stripe-go).
### Install the Stripe.net library
Install the package with .NET or NuGet. Alternatively, if you’re starting from scratch, download the files which contains a configured .csproj file.
#### dotnet
Install the library:
```bash
dotnet add package Stripe.net
```
#### NuGet
Install the library:
```bash
Install-Package Stripe.net
```
#### GitHub
Or download the Stripe.net library source code directly [from GitHub](https://github.com/stripe/stripe-dotnet).
### Install the Stripe libraries
Install the packages and import them in your code. Alternatively, if you’re starting from scratch and need a `package.json` file, download the project files using the link in the code editor.
Install the libraries:
```bash
npm install --save stripe @stripe/stripe-js next
```
### Create a PaymentIntent
Add an endpoint on your server that creates a [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). A PaymentIntent tracks the customer’s payment lifecycle, keeping track of any failed payment attempts and ensuring the customer is only charged once. Return the PaymentIntent’s client secret in the response to finish the payment on the client.
### Install the SDK
To install the SDK, add stripe-android as a dependency. This sample uses OkHttp and GSON to make requests to the server, also include those as dependencies if needed.
#### Gradle
Add the dependencies to your build.gradle file:
#### Groovy
```groovy
dependencies {
// ...
implementation 'com.stripe:stripe-android:15.1.0'
implementation 'com.squareup.okhttp3:okhttp:4.4.0'
implementation 'com.google.code.gson:gson:2.8.6'
}
```
#### GitHub
The Stripe Android SDK is open-sourced. View on GitHub.
### Define your payment form
Add an instance of Stripe’s CardInputWidget to your checkout form. This is used to collect card details and ensures that the sensitive details never touch your server.
### Fetch a PaymentIntent
Make a request to your server for a PaymentIntent as soon as the view loads. Store a reference to the client secret.
### Collect payment details
When the customer clicks the pay button, create an [ConfirmPaymentIntentParams](https://stripe.dev/stripe-android/payments-core/com.stripe.android.model/-confirm-payment-intent-params/index.html) object with the card details and client secret from the PaymentIntent you created on the server.
### Finish the payment
Send the payment details to Stripe by calling `confirmPayment()`.
### Finish the payment
Send the payment details to Stripe with by calling `paymentLauncher.confirm()`.
### Handle the response from Stripe
If your customer’s card is declined, the completion block is called with an error. Show that error to your customer so they can try again with a different card. If no error occurred, tell your customer the payment was successful!
### Make a test payment
Use a test card number to try your integration. These card numbers work in a testing environment with any CVC, postal code, and future expiration date. Stripe also has a set of [international test cards](https://docs.stripe.com/testing.md#international-cards) to test specific postal code formats (for example, only allow numerical values for US postal codes).
| Scenario | Card Number |
| ----------------------------------- | ---------------- |
| Payment succeeds | 4242424242424242 |
| Payment requires 3DS authentication | 4000002500003155 |
| Payment is declined | 4000000000009995 |
### Make a test payment
Use a test card number to try your integration. These card numbers work in a testing environment with any CVC, postal code, and future expiration date. Stripe also has a set of [international test cards](https://docs.stripe.com/testing.md#international-cards) to test specific postal code formats (for example, only allow numerical values for US postal codes).
| Scenario | Card Number |
| ----------------------------------- | ---------------- |
| Payment succeeds | 4242424242424242 |
| Payment requires 3DS authentication | 4000002500003155 |
| Payment is declined | 4000000000009995 |
final PaymentConfiguration paymentConfiguration
= PaymentConfiguration.getInstance(getApplicationContext());
paymentLauncher = PaymentLauncher.Companion.create(
this,
paymentConfiguration.getPublishableKey(),
paymentConfiguration.getStripeAccountId(),
this::onPaymentResult
);
// Create a PaymentIntent by calling the server's endpoint.
MediaType mediaType = MediaType.get("application/json; charset=utf-8");
String json = "{"
+ ""currency":"usd","
+ ""items":["
+ "{"id":"photo_subscription"}"
+ "]"
+ "}";
RequestBody body = RequestBody.create(json, mediaType);
Request request = new Request.Builder()
.url(BACKEND_URL + "create-payment-intent")
.post(body)
.build();
httpClient.newCall(request)
.enqueue(new PayCallback(this));
// Hook up the pay button to the card widget and stripe instance
Button payButton = findViewById(R.id.payButton);
payButton.setOnClickListener((View view) -> {
CardInputWidget cardInputWidget = findViewById(R.id.cardInputWidget);
PaymentMethodCreateParams params = cardInputWidget.getPaymentMethodCreateParams();
if (params != null) {
ConfirmPaymentIntentParams confirmParams = ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(params, paymentIntentClientSecret);
paymentLauncher.confirm(confirmParams);
}
});
private void onPaymentResult(PaymentResult paymentResult) {
String message = "";
if (paymentResult instanceof PaymentResult.Completed) {
message = "Completed!";
} else if (paymentResult instanceof PaymentResult.Canceled) {
message = "Canceled!";
} else if (paymentResult instanceof PaymentResult.Failed) {
// This string comes from the PaymentIntent's error message.
// See here: https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error-message
message = "Failed: "
+ ((PaymentResult.Failed) paymentResult).getThrowable().getMessage();
}
displayAlert("PaymentResult: ", message, true);
}
// Configure the SDK with your Stripe publishable key so it can make requests to Stripe
val paymentConfiguration = PaymentConfiguration.getInstance(applicationContext)
paymentLauncher = PaymentLauncher.Companion.create(
this,
paymentConfiguration.publishableKey,
paymentConfiguration.stripeAccountId,
::onPaymentResult
)
val weakActivity = WeakReference(this)
// Create a PaymentIntent by calling your server's endpoint.
val mediaType = "application/json; charset=utf-8".toMediaType()
val requestJson = """
{
"currency":"usd",
"items": [
{"id":"xl-tshirt"}
]
}
"""
val body = requestJson.toRequestBody(mediaType)
val request = Request.Builder()
.url(backendUrl + "create.php")
.post(body)
.build()
val request = Request.Builder()
.url(backendUrl + "create-payment-intent")
.post(body)
.build()
// Hook up the pay button to the card widget and stripe instance
val payButton: Button = findViewById(R.id.payButton)
payButton.setOnClickListener {
val cardInputWidget =
findViewById(R.id.cardInputWidget)
cardInputWidget.paymentMethodCreateParams?.let { params ->
val confirmParams = ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(params, paymentIntentClientSecret)
paymentLauncher.confirm(confirmParams)
}
}
private fun onPaymentResult(paymentResult: PaymentResult) {
var title = ""
var message = ""
var restartDemo = false
when (paymentResult) {
is PaymentResult.Completed -> {
title = "Setup Completed"
restartDemo = true
}
is PaymentResult.Canceled -> {
title = "Setup Canceled"
}
is PaymentResult.Failed -> {
title = "Setup Failed"
message = paymentResult.throwable.message!!
}
}
displayAlert(title, message, restartDemo)
}
1. Build the server
~~~
pip3 install -r requirements.txt
~~~
1. Build the server
~~~
bundle install
~~~
1. Build the server
~~~
composer install
~~~
1. Build the server
~~~
dotnet restore
~~~
1. Build the server
~~~
mvn package
~~~
2. Run the server
~~~
export FLASK_APP=server.py
python3 -m flask run --port=4242
~~~
2. Run the server
~~~
ruby server.rb -o 0.0.0.0
~~~
2. Run the server
~~~
php -S 127.0.0.1:4242 --docroot=public
~~~
2. Run the server
~~~
dotnet run
~~~
2. Run the server
~~~
java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server
~~~
3. Build the client app
~~~
npm install
~~~
4. Run the client app
~~~
npm start
~~~
5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout)
3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html)
3. Build the client app
~~~
npm install
~~~
4. Run the client app
~~~
npm start
~~~
5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout)
3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html)
3. Build the client app
~~~
npm install
~~~
4. Run the client app
~~~
npm start
~~~
5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout)
3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html)
3. Build the client app
~~~
npm install
~~~
4. Run the client app
~~~
npm start
~~~
5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout)
3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html)
3. Build the client app
~~~
npm install
~~~
4. Run the client app
~~~
npm start
~~~
5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout)
3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html)
1. Run the server
~~~
go run server.go
~~~
2. Build the client app
~~~
npm install
~~~
3. Run the client app
~~~
npm start
~~~
4. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout)
1. Run the server
~~~
go run server.go
~~~
2. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html)
1. Build the application
~~~
npm install
~~~
2. Run the application
~~~
npm start
~~~
3. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout)
1. Build the server
~~~
npm install
~~~
2. Run the server
~~~
npm start
~~~
3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html)
### Install the Stripe Node library
Install the package and import it in your code. Alternatively, if you’re starting from scratch and need a package.json file, download the project files using the Download link in the code editor.
#### npm
Install the library:
```bash
npm install --save stripe
```
#### GitHub
Or download the stripe-node library source code directly [from GitHub](https://github.com/stripe/stripe-node).
### Install the Stripe Ruby library
Install the Stripe ruby gem and require it in your code. Alternatively, if you’re starting from scratch and need a Gemfile, download the project files using the link in the code editor.
#### Terminal
Install the gem:
```bash
gem install stripe
```
#### Bundler
Add this line to your Gemfile:
```bash
gem 'stripe'
```
#### GitHub
Or download the stripe-ruby gem source code directly [from GitHub](https://github.com/stripe/stripe-ruby).
### Install the Stripe Java library
Add the dependency to your build and import the library. Alternatively, if you’re starting from scratch and need a sample pom.xml file (for Maven), download the project files using the link in the code editor.
#### Maven
Add the following dependency to your POM and replace {VERSION} with the version number you want to use.
```bash
\ncom.stripe\nstripe-java\n{VERSION}\n
```
#### Gradle
Add the dependency to your build.gradle file and replace {VERSION} with the version number you want to use.
```bash
implementation "com.stripe:stripe-java:{VERSION}"
```
#### GitHub
Download the JAR directly [from GitHub](https://github.com/stripe/stripe-java/releases/latest).
### Install the Stripe Python package
Install the Stripe package and import it in your code. Alternatively, if you’re starting from scratch and need a requirements.txt file, download the project files using the link in the code editor.
#### pip
Install the package through pip:
```bash
pip3 install stripe
```
#### GitHub
Download the stripe-python library source code directly [from GitHub](https://github.com/stripe/stripe-python).
### Install the Stripe PHP library
Install the library with composer and initialize with your secret API key. Alternatively, if you’re starting from scratch and need a composer.json file, download the files using the link in the code editor.
#### Composer
Install the library:
```bash
composer require stripe/stripe-php
```
#### GitHub
Or download the stripe-php library source code directly [from GitHub](https://github.com/stripe/stripe-php).
### Set up your server
Add the dependency to your build and import the library. Alternatively, if you’re starting from scratch and need a go.mod file, download the project files using the link in the code editor.
#### Go
Make sure to initialize with Go Modules:
```bash
go get -u github.com/stripe/stripe-go/v84
```
#### GitHub
Or download the stripe-go module source code directly [from GitHub](https://github.com/stripe/stripe-go).
### Install the Stripe.net library
Install the package with .NET or NuGet. Alternatively, if you’re starting from scratch, download the files which contains a configured .csproj file.
#### dotnet
Install the library:
```bash
dotnet add package Stripe.net
```
#### NuGet
Install the library:
```bash
Install-Package Stripe.net
```
#### GitHub
Or download the Stripe.net library source code directly [from GitHub](https://github.com/stripe/stripe-dotnet).
### Install the Stripe libraries
Install the packages and import them in your code. Alternatively, if you’re starting from scratch and need a `package.json` file, download the project files using the link in the code editor.
Install the libraries:
```bash
npm install --save stripe @stripe/stripe-js next
```
### Create a PaymentIntent
Add an endpoint on your server that creates a [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). A PaymentIntent tracks the customer’s payment lifecycle, keeping track of any failed payment attempts and ensuring the customer is only charged once. Return the PaymentIntent’s client secret in the response to finish the payment on the client.
### Install the SDK
The [React Native SDK](https://github.com/stripe/stripe-react-native) is open source and fully documented. Internally, it uses the native [iOS](https://github.com/stripe/stripe-ios) and [Android](https://github.com/stripe/stripe-android) SDKs. To install Stripe’s React Native SDK, run one of the following commands in your project’s directory (depending on which package manager you use):
#### yarn
```bash
yarn add @stripe/stripe-react-native
```
#### npm
```bash
npm install @stripe/stripe-react-native
```
Next, install some other necessary dependencies:
- For iOS, go to the **ios** directory and run `pod install` to make sure that you also install the required native dependencies.
- For Android, you don’t need to install any more dependencies.
### Set up the SDK
Configure the Stripe SDK with your Stripe publishable API key.
### Define your payment form
Use Stripe’s `CardField` component to display a text field to securely collect card details. By using `CardField`, you guarantee that sensitive card details never touch your server.
### Fetch a PaymentIntent
When the customer clicks the Pay button, make a request to your server for a PaymentIntent.
### Confirm the payment
Pass the PaymentIntent’s `clientSecret` to `confirmPayment()` function. Stripe SDK automatically collects the card details from `CardField` component and send them to Stripe API. You can also optionally specify customer’s `billingDetails` through `paymentMethodData` parameter.
### Handle the response from Stripe
If your customer’s card is declined, the promise returned from `confirmPayment()` function will contain an error field. Show that error to your customer so they can try again with a different card. If no error occurred, tell your customer the payment was successful!
### Make a test payment
Use a test card number to try your integration. These card numbers work in a testing environment with any CVC, postal code, and future expiration date. Stripe also has a set of [international test cards](https://docs.stripe.com/testing.md#international-cards) to test specific postal code formats (for example, only allow numerical values for US postal codes).
| Scenario | Card Number |
| ----------------------------------- | ---------------- |
| Payment succeeds | 4242424242424242 |
| Payment requires 3DS authentication | 4000002500003155 |
| Payment is declined | 4000000000009995 |
import {StripeProvider} from '@stripe/stripe-react-native';
const fetchPaymentIntentClientSecret = async () => {
const apiEndpoint =
Platform.OS === 'ios' ? 'http://localhost:4242' : 'http://10.0.2.2:4567';
const response = await fetch(`${apiEndpoint}/create-payment-intent`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const {clientSecret} = await response.json();
return clientSecret;
};
// Confirm the payment with the card details
const {paymentIntent, error} = await confirmPayment(clientSecret, {
paymentMethodType: 'Card',
paymentMethodData: {
billingDetails,
},
});
if (error) {
console.log('Payment confirmation error', error);
{
console.log('cardDetails', cardDetails);
}}
onFocus={focusedField => {
console.log('focusField', focusedField);
}}
/>
## See also
#### [Payouts](https://docs.stripe.com/payouts.md)
Learn how to move funds out of your Stripe account into your bank account.
#### [Refunds](https://docs.stripe.com/refunds.md)
Handle requests for refunds by using the Stripe API or Dashboard.
#### [Fulfillment](https://docs.stripe.com/webhooks/quickstart.md)
Set up a webhook to fulfill orders after a payment succeeds. Webhooks are the most reliable way to handle business-critical events.