/stripe-guides

How to fix “no such customer” error in Stripe?

Learn how to fix the "No such customer" error in Stripe by verifying customer IDs, checking environments, handling deletions, and updating your database. Step-by-step guide.

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 fix “no such customer” error in Stripe?

How to Fix "No Such Customer" Error in Stripe

 

The "No such customer" error in Stripe occurs when you're trying to access a customer that doesn't exist in your Stripe account. This can happen for several reasons including incorrect customer IDs, deleted customers, or when trying to access customers across different Stripe accounts or environments. Let's go through a comprehensive tutorial on how to fix this issue.

 

Step 1: Understand the Error

 

When you encounter the "No such customer" error, Stripe typically returns an error message like this:


{
  "error": {
    "code": "resource\_missing",
    "doc\_url": "https://stripe.com/docs/error-codes/resource-missing",
    "message": "No such customer: 'cus\_12345678'",
    "param": "id",
    "type": "invalid_request_error"
  }
}

This error indicates that Stripe couldn't find a customer with the ID you provided.

 

Step 2: Verify the Customer ID

 

First, make sure you're using the correct customer ID:


// Node.js example with Stripe
const stripe = require('stripe')('your_stripe_secret\_key');

try {
  // Verify if customer exists by attempting to retrieve it
  const customer = await stripe.customers.retrieve('cus\_12345678');
  console.log('Customer exists:', customer.id);
} catch (error) {
  console.error('Error:', error.message);
  // Handle the "No such customer" error
}

 

Step 3: Check the Stripe Dashboard

 

Navigate to your Stripe Dashboard to verify if the customer exists:

  1. Log in to your Stripe Dashboard at https://dashboard.stripe.com/
  2. Go to Customers section
  3. Use the search functionality to look for the customer by ID, email, or name
  4. If the customer doesn't appear, it confirms they don't exist in your account

 

Step 4: Check if You're Using the Correct Stripe Environment

 

Stripe has separate test and live environments, and customers created in one environment aren't accessible in the other.


// Make sure you're using the correct API key for your environment
// Test environment
const stripeTest = require('stripe')('sk_test_your_test_key');

// Live environment
const stripeLive = require('stripe')('sk_live_your_live_key');

// Depending on which environment your customer exists in, use the appropriate client

 

Step 5: Recreate the Customer if Needed

 

If you can't find the customer or if they were deleted, you may need to create a new one:


// Node.js example
const stripe = require('stripe')('your_stripe_secret\_key');

async function createNewCustomer() {
  try {
    const customer = await stripe.customers.create({
      email: '[email protected]',
      name: 'John Doe',
      phone: '+1234567890',
      description: 'Customer recreated after not found error'
    });
    console.log('New customer created:', customer.id);
    return customer;
  } catch (error) {
    console.error('Error creating customer:', error.message);
    throw error;
  }
}

 

Step 6: Update Your Database References

 

If you're storing customer IDs in your database, make sure to update them:


// Pseudocode for database update
async function updateCustomerIdInDatabase(userId, newStripeCustomerId) {
  try {
    // Example using a fictional database client
    await database.users.update({
      where: { id: userId },
      data: { stripeCustomerId: newStripeCustomerId }
    });
    console.log(`Updated Stripe customer ID for user ${userId}`);
  } catch (error) {
    console.error('Database update error:', error.message);
    throw error;
  }
}

 

Step 7: Implement Error Handling for Customer Lookup

 

Add robust error handling in your code to gracefully handle missing customers:


async function handleCustomerOperation(customerId) {
  try {
    // Attempt to retrieve the customer
    const customer = await stripe.customers.retrieve(customerId);
    return customer;
  } catch (error) {
    if (error.type === 'invalid_request_error' && error.message.includes('No such customer')) {
      console.log('Customer not found, creating a new one...');
      // Get user details from your database
      const userDetails = await getUserDetailsFromDatabase();
      // Create new customer
      const newCustomer = await stripe.customers.create({
        email: userDetails.email,
        name: userDetails.name
      });
      // Update database with new customer ID
      await updateCustomerIdInDatabase(userDetails.id, newCustomer.id);
      return newCustomer;
    } else {
      // Handle other types of errors
      console.error('Unexpected error:', error.message);
      throw error;
    }
  }
}

 

Step 8: Check for Deleted Customers

 

If a customer was deleted, you can still retrieve them with the expand parameter to check their deleted status:


// Node.js example
const stripe = require('stripe')('your_stripe_secret\_key');

async function checkDeletedCustomer(customerId) {
  try {
    const customer = await stripe.customers.retrieve(customerId, {
      expand: ['deleted']
    });
    
    if (customer.deleted) {
      console.log('This customer has been deleted');
      // Handle accordingly - perhaps recreate
    }
    
    return customer;
  } catch (error) {
    console.error('Error:', error.message);
    // This will still throw "No such customer" if the ID is completely invalid
  }
}

 

Step 9: Implement a Webhook Listener for Customer Deletions

 

To stay in sync with customer deletions in Stripe, set up a webhook:


// Express.js webhook handler example
const express = require('express');
const app = express();
const stripe = require('stripe')('your_stripe_secret\_key');

app.post('/stripe-webhook', express.raw({type: 'application/json'}), async (req, res) => {
  const sig = req.headers['stripe-signature'];
  let event;

  try {
    event = stripe.webhooks.constructEvent(
      req.body,
      sig,
      'whsec_your_webhook_signing_secret'
    );
  } catch (err) {
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Handle customer.deleted event
  if (event.type === 'customer.deleted') {
    const customer = event.data.object;
    console.log(`Customer ${customer.id} has been deleted`);
    
    // Update your database to mark this customer as deleted
    await updateCustomerStatusInDatabase(customer.id, 'deleted');
  }

  res.json({received: true});
});

app.listen(3000, () => console.log('Running on port 3000'));

 

Step 10: Verify API Permissions

 

Ensure your API key has the necessary permissions to access customers:


// Check if your API key has the right permissions
// This is a simple test to see if you can list customers
async function testApiPermissions() {
  try {
    // Try to list just one customer to test permissions
    const customers = await stripe.customers.list({ limit: 1 });
    console.log('API key has customer read permissions');
    return true;
  } catch (error) {
    console.error('API permission error:', error.message);
    return false;
  }
}

 

Troubleshooting Common Scenarios

 

Scenario 1: Customer ID from a different Stripe account

If you're migrating between Stripe accounts or using multiple accounts, ensure you're using the correct account:


// Configure multiple Stripe clients
const stripeAccount1 = require('stripe')('sk_account1_key');
const stripeAccount2 = require('stripe')('sk_account2_key');

// Try finding the customer in both accounts
async function findCustomerAcrossAccounts(customerId) {
  try {
    return await stripeAccount1.customers.retrieve(customerId);
  } catch (error1) {
    console.log('Not found in account 1, trying account 2...');
    try {
      return await stripeAccount2.customers.retrieve(customerId);
    } catch (error2) {
      console.error('Customer not found in either account');
      throw new Error('Customer not found in any connected Stripe account');
    }
  }
}

 

Scenario 2: Customer exists but you're receiving "No such customer" in webhooks

This can happen due to webhook signature issues:


// Proper webhook handling with logging
app.post('/stripe-webhook', express.raw({type: 'application/json'}), async (req, res) => {
  const sig = req.headers['stripe-signature'];
  
  // Log the raw payload for debugging
  console.log('Received webhook payload:', req.body.toString());
  console.log('Signature:', sig);
  
  let event;
  try {
    event = stripe.webhooks.constructEvent(
      req.body,
      sig,
      'whsec_your_webhook_signing_secret'
    );
    
    // Process the event...
    
  } catch (err) {
    console.error('Webhook error:', err.message);
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }
  
  res.json({received: true});
});

 

By following these detailed steps, you should be able to diagnose and fix the "No such customer" error in your Stripe integration. Remember to always test your fixes in the Stripe test environment before deploying them to production.

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