/stripe-guides

How to enable test mode in Stripe?

Learn how to enable test mode in Stripe, access test API keys, use test cards, and simulate payments for safe development and testing—step-by-step tutorial.

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 enable test mode in Stripe?

How to Enable Test Mode in Stripe: A Comprehensive Tutorial

 

Introduction

 

Stripe provides a test mode that allows developers to simulate transactions without processing actual payments. This tutorial will guide you through enabling and using Stripe's test mode for your development and testing needs.

 

Step 1: Create a Stripe Account

 

If you don't already have a Stripe account, you'll need to create one:

  1. Visit the Stripe website at https://stripe.com
  2. Click "Start now" or "Create account"
  3. Fill in your email address, full name, and create a password
  4. Complete the registration process by providing the required information

 

Step 2: Understanding Stripe's Test Mode

 

Stripe automatically provides two sets of API keys:

  • Live keys (for processing real payments)
  • Test keys (for simulating transactions)

Test mode is indicated by the "Test Mode" label in the dashboard. When you're in test mode, you'll see a prominent purple banner across your dashboard.

 

Step 3: Accessing Your Test API Keys

 

  1. Log in to your Stripe Dashboard at https://dashboard.stripe.com
  2. In the left sidebar, click on "Developers"
  3. Select "API keys" from the submenu
  4. You'll see your test API keys displayed. If you don't see test keys, make sure you've toggled to test mode by clicking "View test data" in the dashboard

 

Step 4: Toggle Between Live and Test Mode

 

To switch between live and test mode:

  1. Look for the toggle switch in the left sidebar of your Stripe Dashboard
  2. Click on "View test data" to switch to test mode
  3. Click on "View live data" to switch back to live mode

 

Step 5: Implementing Test Mode in Your Code

 

To use test mode in your application, you need to use your test API keys. Here's how to implement test mode with different Stripe SDKs:

Using Stripe.js (Frontend JavaScript)


// Initialize Stripe.js with your test publishable key
const stripe = Stripe('pk_test_your_test_publishable\_key');

// Create a payment method
stripe.createPaymentMethod({
  type: 'card',
  card: elements.getElement('card'),
}).then(function(result) {
  // Handle result
});

Using Node.js


// Install the Stripe package: npm install stripe

const stripe = require('stripe')('sk_test_your_test_secret\_key');

async function createPaymentIntent() {
  const paymentIntent = await stripe.paymentIntents.create({
    amount: 1000, // Amount in cents
    currency: 'usd',
  });
  
  return paymentIntent;
}

Using Python


# Install the Stripe package: pip install stripe

import stripe

# Set your test secret key
stripe.api_key = 'sk_test_your_test_secret_key'

# Create a PaymentIntent
payment\_intent = stripe.PaymentIntent.create(
  amount=1000,  # Amount in cents
  currency='usd',
)

Using PHP


// Install the Stripe package: composer require stripe/stripe-php

require\_once 'vendor/autoload.php';

// Set your test secret key
\Stripe\Stripe::setApiKey('sk_test_your_test_secret\_key');

// Create a PaymentIntent
$payment\_intent = \Stripe\PaymentIntent::create([
  'amount' => 1000, // Amount in cents
  'currency' => 'usd',
]);

 

Step 6: Using Test Card Numbers

 

Stripe provides test card numbers for simulating different scenarios:

  • Successful payment: 4242 4242 4242 4242
  • Failed payment: 4000 0000 0000 0002
  • Requires authentication: 4000 0025 0000 3155

For these test cards, you can use:

  • Any future expiration date
  • Any 3-digit CVC code
  • Any postal code

Example implementation:


// Client-side code for collecting card details
const cardElement = elements.create('card');
cardElement.mount('#card-element');

// When the form is submitted
form.addEventListener('submit', async (event) => {
  event.preventDefault();
  
  const {paymentMethod, error} = await stripe.createPaymentMethod({
    type: 'card',
    card: cardElement,
  });
  
  // Handle the result
  if (error) {
    console.error(error);
  } else {
    // Send paymentMethod.id to your server
    console.log(paymentMethod);
  }
});

 

Step 7: Testing Webhooks Locally

 

To test webhooks in your local development environment:

  1. Install the Stripe CLI from https://stripe.com/docs/stripe-cli
  2. Log in to your Stripe account through the CLI:

stripe login
  1. Forward webhook events to your local server:

stripe listen --forward-to http://localhost:4242/webhook
  1. In your application code, handle the webhook events:

// Node.js example
const express = require('express');
const app = express();

// Use the webhook signing secret from the CLI output
const endpointSecret = 'whsec\_...';

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

  let event;

  try {
    event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
  } catch (err) {
    response.status(400).send(`Webhook Error: ${err.message}`);
    return;
  }

  // Handle the event
  switch (event.type) {
    case 'payment\_intent.succeeded':
      const paymentIntent = event.data.object;
      console.log('PaymentIntent was successful!');
      break;
    // ... handle other event types
    default:
      console.log(`Unhandled event type ${event.type}`);
  }

  // Return a 200 response to acknowledge receipt of the event
  response.send();
});

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

 

Step 8: Testing Specific Scenarios

 

Use these special test parameters to simulate different payment scenarios:

Testing 3D Secure Authentication


// Using the test card number for 3D Secure
const paymentMethod = await stripe.paymentMethods.create({
  type: 'card',
  card: {
    number: '4000 0025 0000 3155',
    exp\_month: 12,
    exp\_year: 2030,
    cvc: '123',
  },
});

const paymentIntent = await stripe.paymentIntents.create({
  payment\_method: paymentMethod.id,
  amount: 1999,
  currency: 'usd',
  confirm: true,
  return\_url: 'https://your-website.com/return',
});

Testing Declined Payments


// Using the test card number for declined payments
const paymentMethod = await stripe.paymentMethods.create({
  type: 'card',
  card: {
    number: '4000 0000 0000 0002',
    exp\_month: 12,
    exp\_year: 2030,
    cvc: '123',
  },
});

const paymentIntent = await stripe.paymentIntents.create({
  payment\_method: paymentMethod.id,
  amount: 1999,
  currency: 'usd',
  confirm: true,
});

 

Step 9: Testing the Stripe Checkout Integration

 

If you're using Stripe Checkout, you can test it with test mode as well:


// Server-side code (Node.js)
const session = await stripe.checkout.sessions.create({
  payment_method_types: ['card'],
  line\_items: [
    {
      price\_data: {
        currency: 'usd',
        product\_data: {
          name: 'Test Product',
        },
        unit\_amount: 2000,
      },
      quantity: 1,
    },
  ],
  mode: 'payment',
  success\_url: 'https://your-website.com/success',
  cancel\_url: 'https://your-website.com/cancel',
});

// Client-side code
const stripe = Stripe('pk_test_your_test_publishable\_key');
stripe.redirectToCheckout({
  sessionId: '{{session.id}}'
});

 

Step 10: Verifying Test Transactions

 

After running test transactions, you can verify them in your Stripe Dashboard:

  1. Log in to your Stripe Dashboard (ensure you're in test mode)
  2. Go to "Payments" in the left sidebar
  3. You'll see all your test payments listed
  4. Click on any payment to see its details

You can also use the Stripe API to verify test transactions programmatically:


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

async function getPayment(paymentIntentId) {
  const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId);
  console.log(paymentIntent.status);
  return paymentIntent;
}

 

Conclusion

 

Stripe's test mode is an essential tool for developing and testing payment integrations without processing real transactions. By following this tutorial, you should now have a comprehensive understanding of how to enable and use test mode in Stripe for your development needs.

Remember to always switch to live mode and use your live API keys when you're ready to accept real payments from customers.

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