/stripe-guides

How to add a new customer in Stripe?

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.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free consultation

How to add a new customer in Stripe?

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:

  • A Stripe account (create one at https://stripe.com if needed)
  • Appropriate access credentials
  • Your Stripe API keys (for API methods)

 

Step 2: Adding a Customer via Stripe Dashboard

 

2.1 Log into Stripe Dashboard

  • Navigate to https://dashboard.stripe.com and log in with your credentials
  • This will take you to your Stripe Dashboard homepage

2.2 Access Customers Section

  • In the left sidebar menu, find and click on "Customers"
  • This will display your existing customers list

2.3 Create a New Customer

  • Click the "+ Add" or "Create customer" button (usually in the top right corner)
  • A new customer form will appear

2.4 Fill in Customer Details

  • Enter the customer's email address (required)
  • Add name, phone number, and description (optional)
  • Set a default payment method if available
  • Add custom metadata if needed for your business
  • Add shipping/billing address information if applicable

2.5 Save the Customer

  • Click "Create customer" button at the bottom of the form
  • The new customer will be added to your customer list

 

Step 3: Adding a Customer via Stripe API (Server-side)

 

3.1 Set Up Your Environment

  • Install the Stripe library/SDK for your programming language
  • Have your Stripe API keys ready (find them in the Stripe Dashboard under Developers → API keys)

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

  • Follow instructions at https://stripe.com/docs/stripe-cli to install the CLI
  • Authenticate with: 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

  • Ensure you're using the correct API key (test vs live)
  • Check that the API key is correctly formatted
  • Verify the API key has the necessary permissions

8.2 Invalid Parameters

  • Ensure all required fields are provided (like email)
  • Check that data formats are correct (e.g., email format, phone number format)
  • Verify that metadata values are strings or numbers only

8.3 Rate Limiting

  • If you're creating many customers rapidly, you might hit rate limits
  • Implement exponential backoff for retries
  • Consider batch processing for bulk customer creation

 

Step 9: Best Practices

 

9.1 Security Best Practices

  • Never expose your Stripe secret key in client-side code
  • Use HTTPS for all API requests
  • Implement proper authentication for your API endpoints
  • Consider using Stripe's test mode during development

9.2 Data Management Best Practices

  • Use descriptive customer descriptions to easily identify them later
  • Utilize metadata fields for internal references and categorization
  • Implement error handling and logging for all Stripe operations
  • Consider implementing idempotency keys for important operations

 

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.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022