Skip to Content
stripe payment subscription integration with php
php code / September 16, 2021

The Stripe Subscription API makes it simple to add recurring payments to your website. Subscription payment is necessary for recurring billing if you wish to build a membership subscription system on your web application. The Stripe payment gateway enables recurring payments to be integrated with the Plans and Subscription API. Stripe subscription is a simple and efficient way for your website’s visitors to buy a membership using their credit card online.

Stripe subscription payments bill the buyer on a recurring basis depending on a predetermined frequency. Your website’s members can subscribe to a plan and pay with their credit/debit card without ever leaving the site. This article will show you how to use PHP to incorporate Stripe subscription payment.

The following functionality will be implemented in the sample script to receive money for a subscription using Stripe Payment Gateway in PHP.

To choose a subscription plan and give credit card information, create an HTML form.
To securely transfer card information, create a Stripe token.
Fill out the form with your plan and credit card information.
Using the Stripe API, verify the card and create a subscription plan.
In the database, store transaction data together with subscription plan information.
Take a look at the file structure before getting started with the Stripe Subscription payment API in PHP.

├── config.php
├── dbConnect.php
├── index.php
├── payment.php
├── stripe-php/
└── css/
    └── style.css

Stripe API Keys for Testing
Before going live with the Stripe subscription payment gateway, make sure the subscription procedure is working smoothly. To check the subscription payment procedure, you’ll need the test API keys data.

Go to the Developers » API keys page after logging into your Stripe account.
The API keys (Publishable key and Secret key) are listed under the Standard keys section in the TEST DATA block. Click the Reveal test key token button to reveal the Secret key.

serp-api-access-key php

To utilise later in the script, collect the Publishable key and Secret key.

Tables in a Database
Two tables in the database are required to store member and subscription information.

1. Please read the following: SQL generates a users table in the MySQL database to store the member’s information.

CREATE TABLE `users` (
`subscription_id` int(11) NOT NULL DEFAULT '0',
`first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`gender` enum('Male','Female') COLLATE utf8_unicode_ci NOT NULL,
`phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The following SQL creates a user subscriptions table in the MySQL database to store subscription information.

CREATE TABLE `user_subscriptions` (
`user_id` int(11) NOT NULL DEFAULT '0',
`payment_method` enum('stripe') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'stripe',
`stripe_subscription_id` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`stripe_customer_id` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`stripe_plan_id` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`plan_amount` float(10,2) NOT NULL,
`plan_amount_currency` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`plan_interval` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`plan_interval_count` tinyint(2) NOT NULL,
`payer_email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`plan_period_start` datetime NOT NULL,
`plan_period_end` datetime NOT NULL,
`status` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration, Stripe API, and Plans (config.php)
Constant variables for the Stripe API, plans, and database settings are defined in the config.php file.

Data on the Plans:

$plans — An array that contains all of the available plan information.
Currency code is $currency.
Constants in the Stripe API:

STRIPE API KEY – The API Secret key must be specified.
STRIPE PUBLISHABLE KEY – The API Publishable key must be specified.
Constants in the Database:

DB HOST — This parameter specifies the database host.
DB USERNAME – This is the username for the database.
DB PASSWORD – This field is used to specify the database password.
DB NAME – Name of the database.

// Subscription plans 
// Minimum amount is $0.50 US 
// Interval day, week, month or year 
$plans = array( 
'1' => array( 
'name' => 'Weekly Subscription', 
'price' => 25, 
'interval' => 'week' 
'2' => array( 
'name' => 'Monthly Subscription', 
'price' => 85, 
'interval' => 'month' 
'3' => array( 
'name' => 'Yearly Subscription', 
'price' => 950, 
'interval' => 'year' 
$currency = "USD"; 
/* Stripe API configuration 
* Remember to switch to your live publishable and secret key in production! 
* See your keys here: 
define('STRIPE_API_KEY', 'Your_API_Secret_key'); 
define('STRIPE_PUBLISHABLE_KEY', 'Your_API_Publishable_key'); 
// Database configuration 
define('DB_HOST', 'MySQL_Database_Host'); 
define('DB_USERNAME', 'MySQL_Database_Username'); 
define('DB_PASSWORD', 'MySQL_Database_Password'); 
define('DB_NAME', 'MySQL_Database_Name');

The Stripe API Secret key and Publishable key can be located in your Stripe account’s API Keys Data section.

Connection to the database (dbConnect.php)
The dbConnect.php file is used to connect PHP and MySQL to the database.

// Connect with the database 
// Display error if failed to connect 
if ($db->connect_errno) { 
printf("Connect failed: %s\n", $db->connect_error); 

Subscription Form for Stripe (index.php)
Include the configuration file first.

// Include configuration file 
require_once 'config.php'; 

HTML Subscription Form: The HTML form below allows users to choose a subscription plan and give buyer information (name and email) as well as credit card information (Card Number, Expiration Date, and CVC No.). For subscription payment processing, the form data is sent to the server-side script (payment.php).

<div class="panel">
<form action="payment.php" method="POST" id="paymentFrm">
<div class="panel-heading">
<h3 class="panel-title">Plan Subscription with Stripe</h3>

<!-- Plan Info -->
<b>Select Plan:</b>
<select name="subscr_plan" id="subscr_plan">
<?php foreach($plans as $id=>$plan){ ?>
<option value="<?php echo $id; ?>"><?php echo $plan['name'].' [$'.$plan['price'].'/'.$plan['interval'].']'; ?></option>
<?php } ?>
<div class="panel-body">
<!-- Display errors returned by createToken -->
<div id="paymentResponse"></div>
<!-- Payment form -->
<div class="form-group">
<input type="text" name="name" id="name" class="field" placeholder="Enter name" required="" autofocus="">
<div class="form-group">
<input type="email" name="email" id="email" class="field" placeholder="Enter email" required="">
<div class="form-group">
<label>CARD NUMBER</label>
<div id="card_number" class="field"></div>
<div class="row">
<div class="left">
<div class="form-group">
<label>EXPIRY DATE</label>
<div id="card_expiry" class="field"></div>
<div class="right">
<div class="form-group">
<label>CVC CODE</label>
<div id="card_cvc" class="field"></div>
<button type="submit" class="btn btn-success" id="payBtn">Submit Payment</button>

Include the Stripe.js v3 package, which allows you to securely transfer sensitive information (credit card) to Stripe directly from the browser.

<script src=""></script>

The Stripe.js v3 package is used to generate a token using the JavaScript code below.

Set your Stripe publishable API key, which identifies your website.
Customize the UI components in the payment form with Stripe Elements.
Using the stripe.elements() method, create an instance of Elements.
Using elements, create an instance of a certain Element.
create() is a method for creating anything new.
Using the element.mount() method, you can attach your Element to the DOM.
The createToken() function uses stripe to generate a single-use token.
card components and the createToken() method

The stripeTokenHandler() function adds a Stripe token to a hidden input and adds it to the payment form.
The card details are transmitted to the server-side if the transaction is successful. The error notice is displayed if this is not the case.

// Create an instance of the Stripe object
// Set your publishable API key
var stripe = Stripe('<?php echo STRIPE_PUBLISHABLE_KEY; ?>');
// Create an instance of elements
var elements = stripe.elements();
var style = {
base: {
fontWeight: 400,
fontFamily: 'Roboto, Open Sans, Segoe UI, sans-serif',
fontSize: '16px',
lineHeight: '1.4',
color: '#555',
backgroundColor: '#fff',
'::placeholder': {
color: '#888',
invalid: {
color: '#eb1c26',
var cardElement = elements.create('cardNumber', {
style: style
var exp = elements.create('cardExpiry', {
'style': style
var cvc = elements.create('cardCvc', {
'style': style
// Validate input of the card elements
var resultContainer = document.getElementById('paymentResponse');
cardElement.addEventListener('change', function(event) {
if (event.error) {
resultContainer.innerHTML = '<p>'+event.error.message+'</p>';
} else {
resultContainer.innerHTML = '';
// Get payment form element
var form = document.getElementById('paymentFrm');
// Create a token when the form is submitted.
form.addEventListener('submit', function(e) {
// Create single-use token to charge the user
function createToken() {
stripe.createToken(cardElement).then(function(result) {
if (result.error) {
// Inform the user if there was an error
resultContainer.innerHTML = '<p>'+result.error.message+'</p>';
} else {
// Send the token to your server
// Callback to handle the response from stripe
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
// Submit the form

PHP Stripe Library
To use the Stripe API in PHP, you’ll need to use the Stripe PHP library. With the Stipre API, you may create customers, plans, and subscriptions. You don’t need to download any of the essential library files because they’re all included in our source code.

Process Payment for Subscriptions (payment.php)
The submitted card data are confirmed in this file, and the subscription plan is enabled using the Stripe API and PHP.

Process Payment for Subscriptions (payment.php)
The submitted card data are confirmed in this file, and the subscription plan is enabled using the Stripe API and PHP.

From the SESSION, get the logged-in user ID.

Using the PHP $_POST method, get the token, selected plan, card details, and buyer information from the form fields.

Get the plan data from the $plans array (name, price, and term).

Add the Stripe PHP library to your project.

Set the API Secret key with the Stripe class’s setApiKey() method.

The Stripe Customer API’s create() method is used to add the customer.

Buyer’s email address

Stripe token as a source

Create a plan via the Stripe Plan API’s create() method.
product – The product whose pricing will be represented by the created plan. – The name of the plan.

amount – A positive number in cents (or 0 for a free plan) for which a recurring charge will be made.

currency — Lowercase three-letter ISO currency code.

interval – Define how often you want to be billed (day, week, month or year).

The number of intervals between subscription billings is specified by interval count. Interval=month and interval count=2 invoices every two months, for example. Intervals of up to one year (1 year, 12 months, or 52 weeks) are permitted.

Create a subscription via the Stripe Subscription API’s create() method.

customer – The identifier for the subscribed consumer.
items – The subscription plans are listed below.
plan – Include the plan ID.
Retrieve transaction data if the plan and subscription creation went OK. Insert the subscription information into the database after it has been successfully activated.
The subscription reference ID should be attached to the appropriate member.
The payment status of a subscription should be displayed on the webpage.

// Include configuration file 
require_once 'config.php'; 
// Get user ID from current SESSION 
$userID = isset($_SESSION['loggedInUserID'])?$_SESSION['loggedInUserID']:1; 
$payment_id = $statusMsg = $api_error = ''; 
$ordStatus = 'error'; 
// Check whether stripe token is not empty 
if(!empty($_POST['subscr_plan']) && !empty($_POST['stripeToken'])){ 
// Retrieve stripe token and user info from the submitted form data 
$token = $_POST['stripeToken']; 
$name = $_POST['name']; 
$email = $_POST['email']; 
// Plan info 
$planID = $_POST['subscr_plan']; 
$planInfo = $plans[$planID]; 
$planName = $planInfo['name']; 
$planPrice = $planInfo['price']; 
$planInterval = $planInfo['interval']; 
// Include Stripe PHP library 
require_once 'stripe-php/init.php'; 
// Set API key 
// Add customer to stripe 
try { 
$customer = \Stripe\Customer::create(array( 
'email' => $email, 
'source' => $token 
}catch(Exception $e) { 
$api_error = $e->getMessage(); 
if(empty($api_error) && $customer){ 

// Convert price to cents 
$priceCents = round($planPrice*100); 
// Create a plan 
try { 
$plan = \Stripe\Plan::create(array( 
"product" => [ 
"name" => $planName 
"amount" => $priceCents, 
"currency" => $currency, 
"interval" => $planInterval, 
"interval_count" => 1 
}catch(Exception $e) { 
$api_error = $e->getMessage(); 
if(empty($api_error) && $plan){ 
// Creates a new subscription 
try { 
$subscription = \Stripe\Subscription::create(array( 
"customer" => $customer->id, 
"items" => array( 
"plan" => $plan->id, 
}catch(Exception $e) { 
$api_error = $e->getMessage(); 
if(empty($api_error) && $subscription){ 
// Retrieve subscription data 
$subsData = $subscription->jsonSerialize(); 
// Check whether the subscription activation is successful 
if($subsData['status'] == 'active'){ 
// Subscription info 
$subscrID = $subsData['id']; 
$custID = $subsData['customer']; 
$planID = $subsData['plan']['id']; 
$planAmount = ($subsData['plan']['amount']/100); 
$planCurrency = $subsData['plan']['currency']; 
$planinterval = $subsData['plan']['interval']; 
$planIntervalCount = $subsData['plan']['interval_count']; 
$created = date("Y-m-d H:i:s", $subsData['created']); 
$current_period_start = date("Y-m-d H:i:s", $subsData['current_period_start']); 
$current_period_end = date("Y-m-d H:i:s", $subsData['current_period_end']); 
$status = $subsData['status']; 
// Include database connection file 
include_once 'dbConnect.php'; 
// Insert transaction data into the database 
$sql = "INSERT INTO user_subscriptions(user_id,stripe_subscription_id,stripe_customer_id,stripe_plan_id,plan_amount,plan_amount_currency,plan_interval,plan_interval_count,payer_email,created,plan_period_start,plan_period_end,status) VALUES('".$userID."','".$subscrID."','".$custID."','".$planID."','".$planAmount."','".$planCurrency."','".$planinterval."','".$planIntervalCount."','".$email."','".$created."','".$current_period_start."','".$current_period_end."','".$status."')"; 
$insert = $db->query($sql); 
// Update subscription id in the users table 
if($insert && !empty($userID)){ 
$subscription_id = $db->insert_id; 
$update = $db->query("UPDATE users SET subscription_id = {$subscription_id} WHERE id = {$userID}"); 
$ordStatus = 'success'; 
$statusMsg = 'Your Subscription Payment has been Successful!'; 
$statusMsg = "Subscription activation failed!"; 
$statusMsg = "Subscription creation failed! ".$api_error; 
$statusMsg = "Plan creation failed! ".$api_error; 
$statusMsg = "Invalid card details! $api_error"; 
$statusMsg = "Error on form submission, please try again."; 
<div class="container">
<div class="status">
<h1 class="<?php echo $ordStatus; ?>"><?php echo $statusMsg; ?></h1>
<?php if(!empty($subscrID)){ ?>
<h4>Payment Information</h4>
<p><b>Reference Number:</b> <?php echo $subscription_id; ?></p>
<p><b>Transaction ID:</b> <?php echo $subscrID; ?></p>
<p><b>Amount:</b> <?php echo $planAmount.' '.$planCurrency; ?></p>

<h4>Subscription Information</h4>
<p><b>Plan Name:</b> <?php echo $planName; ?></p>
<p><b>Amount:</b> <?php echo $planPrice.' '.$currency; ?></p>
<p><b>Plan Interval:</b> <?php echo $planInterval; ?></p>
<p><b>Period Start:</b> <?php echo $current_period_start; ?></p>
<p><b>Period End:</b> <?php echo $current_period_end; ?></p>
<p><b>Status:</b> <?php echo $status; ?></p>
<?php } ?>
<a href="index.php" class="btn-link">Back to Subscription Page</a>

Details on the Test Card
Use the following test card numbers, a legitimate future expiration date, and any random CVC number to test the Stripe subscription payment API integration.


Visa – 4000056655665556 (debit)

Mastercard 5555555555554444

Mastercard – 5200828282828210 (debit)

American Express – 378282246310005

6011111111111117 – Find out more

Activate the Stripe Payment Gateway

Follow the steps below to activate the Stripe payment gateway once the subscription API integration is complete and the payment process is running successfully.

Go to the Developers » API keys page after logging into your Stripe account.

In the LIVE DATA area, collect the API keys (Publishable key and Secret key).
Replace the Test API keys (Publishable key and Secret key) with the Live API keys in the config.php file (Publishable key and Secret key).


Stripe subscription payment API is the simplest way to accept credit card payments for subscriptions online. Using the Stripe API and PHP, you may integrate recurring billing into your online application. Our sample script demonstrates how to charge a user via Stripe on a regular basis at a predetermined frequency. This Stripe subscription payment script’s functionality can be customised to meet your specific requirements.


PHPCODE © 2024