Learn how to add a new customer in Stripe using the Dashboard, API, CLI, or frontend, with step-by-step instructions, code examples, and best practices.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
How to Add a New Customer in Stripe: A Comprehensive Tutorial
Introduction
Adding new customers in Stripe is a fundamental operation for businesses using this payment processing platform. This detailed tutorial will guide you through various methods to create a new customer in Stripe, including using the Dashboard UI, Stripe API with different programming languages, and Stripe CLI.
Step 1: Preparation
Before adding a customer to Stripe, ensure you have:
Step 2: Adding a Customer via Stripe Dashboard
2.1 Log into Stripe Dashboard
2.2 Access Customers Section
2.3 Create a New Customer
2.4 Fill in Customer Details
2.5 Save the Customer
Step 3: Adding a Customer via Stripe API (Server-side)
3.1 Set Up Your Environment
3.2 Using Node.js
First, install the Stripe package:
npm install stripe
Then, create a customer with this code:
const stripe = require('stripe')('sk_test_YOUR_SECRET_KEY');
async function createStripeCustomer() {
try {
const customer = await stripe.customers.create({
email: '[email protected]',
name: 'John Doe',
description: 'New customer from API',
phone: '+15551234567',
address: {
line1: '123 Main St',
city: 'San Francisco',
state: 'CA',
postal\_code: '94111',
country: 'US',
},
metadata: {
customerType: 'premium',
internalId: 'CUS12345'
}
});
console.log('Customer created successfully:');
console.log(customer);
return customer;
} catch (error) {
console.error('Error creating customer:', error);
throw error;
}
}
createStripeCustomer();
3.3 Using Python
First, install the Stripe package:
pip install stripe
Then, create a customer with this code:
import stripe
# Set your API key
stripe.api_key = "sk_test_YOUR_SECRET\_KEY"
try:
# Create a customer
customer = stripe.Customer.create(
email="[email protected]",
name="John Doe",
description="New customer from Python API",
phone="+15551234567",
address={
"line1": "123 Main St",
"city": "San Francisco",
"state": "CA",
"postal\_code": "94111",
"country": "US",
},
metadata={
"customerType": "premium",
"internalId": "CUS12345"
}
)
print("Customer created successfully:")
print(customer)
except stripe.error.StripeError as e:
print(f"Error creating customer: {e}")
3.4 Using PHP
First, install the Stripe package:
composer require stripe/stripe-php
Then, create a customer with this code:
'[email protected]',
'name' => 'John Doe',
'description' => 'New customer from PHP API',
'phone' => '+15551234567',
'address' => [
'line1' => '123 Main St',
'city' => 'San Francisco',
'state' => 'CA',
'postal\_code' => '94111',
'country' => 'US',
],
'metadata' => [
'customerType' => 'premium',
'internalId' => 'CUS12345'
]
]);
echo "Customer created successfully:\n";
print\_r($customer);
} catch (\Stripe\Exception\ApiErrorException $e) {
echo "Error creating customer: " . $e->getMessage();
}
3.5 Using Ruby
First, install the Stripe gem:
gem install stripe
Then, create a customer with this code:
require 'stripe'
# Set your API key
Stripe.api_key = 'sk_test_YOUR_SECRET\_KEY'
begin
# Create a customer
customer = Stripe::Customer.create({
email: '[email protected]',
name: 'John Doe',
description: 'New customer from Ruby API',
phone: '+15551234567',
address: {
line1: '123 Main St',
city: 'San Francisco',
state: 'CA',
postal\_code: '94111',
country: 'US',
},
metadata: {
customer\_type: 'premium',
internal\_id: 'CUS12345'
}
})
puts "Customer created successfully:"
puts customer
rescue Stripe::StripeError => e
puts "Error creating customer: #{e.message}"
end
Step 4: Adding a Customer with Payment Method via API
If you want to add a customer with a payment method in one process:
const stripe = require('stripe')('sk_test_YOUR_SECRET_KEY');
async function createCustomerWithPaymentMethod() {
try {
// 1. Create a Payment Method first
const paymentMethod = await stripe.paymentMethods.create({
type: 'card',
card: {
number: '4242424242424242',
exp\_month: 12,
exp\_year: 2025,
cvc: '123',
},
billing\_details: {
name: 'John Doe',
email: '[email protected]',
}
});
// 2. Create the Customer
const customer = await stripe.customers.create({
email: '[email protected]',
name: 'John Doe',
payment\_method: paymentMethod.id, // Attach the payment method
invoice\_settings: {
default_payment_method: paymentMethod.id // Set as default
}
});
console.log('Customer created with payment method:');
console.log(customer);
return customer;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
createCustomerWithPaymentMethod();
Step 5: Adding a Customer via Stripe CLI
5.1 Install Stripe CLI
stripe login
5.2 Create Customer with CLI
Basic customer creation:
stripe customers create --email="[email protected]" --name="John Doe"
Customer with more details:
stripe customers create \\
--email="[email protected]" \\
--name="John Doe" \\
--description="Customer from CLI" \\
--phone="+15551234567" \\
--metadata="customerType=premium" \\
--metadata="internalId=CUS12345"
Step 6: Adding a Customer from Frontend (Client-side)
For secure client-side customer creation, you typically collect basic information client-side and send it to your server to create the customer.
6.1 HTML Form
<form id="customer-form">
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" required>
</div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" required>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="tel" id="phone">
</div>
<button type="submit">Create Customer</button>
</form>
6.2 JavaScript
document.getElementById('customer-form').addEventListener('submit', async function(event) {
event.preventDefault();
const customerData = {
email: document.getElementById('email').value,
name: document.getElementById('name').value,
phone: document.getElementById('phone').value
};
try {
// Send to your backend endpoint
const response = await fetch('/api/create-customer', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(customerData),
});
const result = await response.json();
if (response.ok) {
alert('Customer created successfully!');
console.log(result);
} else {
throw new Error(result.error || 'Failed to create customer');
}
} catch (error) {
alert('Error: ' + error.message);
console.error('Error:', error);
}
});
6.3 Backend API Endpoint (Node.js/Express)
const express = require('express');
const stripe = require('stripe')('sk_test_YOUR_SECRET_KEY');
const app = express();
app.use(express.json());
app.post('/api/create-customer', async (req, res) => {
try {
const { email, name, phone } = req.body;
// Server-side validation
if (!email) {
return res.status(400).json({ error: 'Email is required' });
}
// Create customer in Stripe
const customer = await stripe.customers.create({
email,
name,
phone
});
// Return the new customer object (you may want to filter sensitive data)
res.status(201).json({
success: true,
customerId: customer.id,
customerEmail: customer.email
});
} catch (error) {
console.error('Error creating customer:', error);
res.status(500).json({
error: 'Failed to create customer',
message: error.message
});
}
});
app.listen(3000, () => console.log('Server running on port 3000'));
Step 7: Advanced Customer Creation Options
7.1 Creating a Customer with Subscription
const stripe = require('stripe')('sk_test_YOUR_SECRET_KEY');
async function createCustomerWithSubscription() {
try {
// 1. Create a customer
const customer = await stripe.customers.create({
email: '[email protected]',
name: 'John Doe',
payment_method: 'pm_card\_visa', // Test payment method
invoice\_settings: {
default_payment_method: 'pm_card_visa'
}
});
// 2. Create the subscription
const subscription = await stripe.subscriptions.create({
customer: customer.id,
items: [
{ price: 'price_YOUR_PRICE\_ID' }, // Replace with your price ID
],
expand: ['latest_invoice.payment_intent'],
});
console.log('Customer created with subscription:');
console.log(subscription);
return { customer, subscription };
} catch (error) {
console.error('Error:', error);
throw error;
}
}
createCustomerWithSubscription();
7.2 Creating a Customer with Tax IDs
const stripe = require('stripe')('sk_test_YOUR_SECRET_KEY');
async function createCustomerWithTaxId() {
try {
// 1. Create the customer
const customer = await stripe.customers.create({
email: '[email protected]',
name: 'ACME Corporation',
description: 'Business customer with Tax ID'
});
// 2. Add tax ID to the customer
const taxId = await stripe.customers.createTaxId(
customer.id,
{
type: 'eu_vat', // Options: eu_vat, au_abn, br_cnpj, br_cpf, ca_bn, ca_qst, ch_vat, etc.
value: 'DE123456789', // The tax ID value
}
);
console.log('Customer created with Tax ID:');
console.log({ customer, taxId });
return { customer, taxId };
} catch (error) {
console.error('Error:', error);
throw error;
}
}
createCustomerWithTaxId();
Step 8: Troubleshooting Common Issues
8.1 Invalid API Key
8.2 Invalid Parameters
8.3 Rate Limiting
Step 9: Best Practices
9.1 Security Best Practices
9.2 Data Management Best Practices
Conclusion
You now have a comprehensive understanding of how to add customers to Stripe using various methods. Whether you prefer the Dashboard UI, API, or CLI, you can create customers with different attributes, payment methods, and even subscriptions. Remember to follow security best practices and properly handle errors for a robust implementation.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.