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.
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 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:
Step 2: Understanding Stripe's Test Mode
Stripe automatically provides two sets of API keys:
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
Step 4: Toggle Between Live and Test Mode
To switch between live and test 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:
For these test cards, you can use:
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:
stripe login
stripe listen --forward-to http://localhost:4242/webhook
// 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:
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.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.