Site icon Tutorials Website: Upgrade Your Web Development & Coding Skills

Integrate Recurring Stripe Subscription Payment with PHP

stripe-recurring-payment-in-php

The Stripe Subscription API is a simple way to integrate recurring website payments For recurring billing, subscription payment is required if you want to implement the membership subscription system on the web application. The Stripe payment gateway allows you to integrate recurring payment with the APIs. Stripe subscription is a fast and efficient way for you to buy membership online with a credit card.

In the Stripe subscription payment, the buyer is recurringly charged on the basis of a specific period of time. Your website members will agree to a plan and make the payment without leaving the website with their credit/debit card. We will show you how to integrate Stripe subscription payment with PHP in this tutorial.

Take a look at the directory layout before you begin implementing Stripe Subscription Payment API in PHP.

stripe_subscription_payment_php/
├── dbconfig.php
├── index.php
├── payment.php
├── stripe-php/

Generate Stripe Test API Keys

You need the test API keys data to check the subscription payment process.

Copay and Paste the Publishable key and Secret key in your Notepad to use later in the script.

Download Stripe PHP Library

The Stripe PHP library is used to access the PHP Stripe API. It helps create customer, plan, and subscription to Stipre API. The required library files should be included in our source code.

Create Plans, Stripe API and Database Configuration (dbconfig.php)

 array( 
        'name' => 'Weekly Subscription', 
        'price' => 25, 
        'interval' => 'week' 
    ), 
    '2' => array( 
        'name' => 'Monthly Subscription', 
        'price' => 80, 
        'interval' => 'month' 
    ), 
    '3' => array( 
        'name' => 'Yearly Subscription', 
        'price' => 850, 
        'interval' => 'year' 
    ) 
); 

//Currency code
$currency = "usd";  
 
// Stripe API configuration  
define('STRIPE_API_KEY', 'Your_API_Secret_key');  //STRIPE_API_KEY – Specify the API Secret key.
define('STRIPE_PUBLISHABLE_KEY', 'Your_API_Publishable_key'); //STRIPE_PUBLISHABLE_KEY – Specify the 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');

// Connect with the database  
$db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);  
  
// Display error if failed to connect  
if ($db->connect_errno) {  
    printf("Connect failed: %s\n", $db->connect_error);  
    exit();  
}

Note: Stripe API Secret key and Publishable key will be found in the API Keys Data section of your Stripe account.

Create Database Tables

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

1. The following SQL creates an users table to hold the member’s info in the MySQL database.

CREATE TABLE users (
 id int(11) NOT NULL AUTO_INCREMENT,
 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',
 PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

2. The following SQL creates a user_subscriptions_details table to hold the subscription info in the MySQL database.

CREATE TABLE user_subscriptions_details (
 id int(11) NOT NULL AUTO_INCREMENT,
 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,
 PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Create Stripe Subscription Form (index.php)




Plan Subscription with Stripe

Select Plan:

In the above code:

//Create Stripe Token and Validate Card with Stripe.js Library:

the Stripe.js library that helps securely sending sensitive information (credit card) to Stripe directly from the browser.

The following JavaScript code is used to generate a token with the Stripe.js library.


Process Subscription Payment (payment.php)

In this file, the submitted card details are validated and the subscription plan is activated with Stripe API using PHP.

 $email, 
        'source'  => $token 
    )); 
     
    // 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( 
                    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']; 
                     
                // Insert transaction data into the database 
                $sql = "INSERT INTO user_subscriptions_details (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!'; 
            }else{ 
                $statusMsg = "Subscription activation failed!"; 
            } 
        }else{ 
            $statusMsg = "Subscription creation failed! ".$api_error; 
        } 
    }else{ 
        $statusMsg = "Plan creation failed! ".$api_error; 
    } 
}else{ 
    $statusMsg = "Error on form submission, please try again."; 
} 
?>

Payment Information

Reference Number:

Transaction ID:

Amount:

Subscription Information

Plan Name:

Amount:

Plan Interval:

Period Start:

Period End:

Status:

Back to Subscription Page

Test Card Details

Expiration date : 10/2021

CVC number : 123 (Any random number)

Make Stripe Payment Gateway Live

Follow the steps below to make Stripe payment gateway live once the subscription API integration is complete and the payment process works properly.

SEE ALSO: How to Integrate 2Checkout Payment Gateway in PHP

SEE ALSO: How to Integrate Paypal Payment System with Paypal API in PHP and MySql

Conclusion

Stripe subscription payment API is the simplest way to accept online subscription credit payment. Using Stripe API and PHP, you can implement the recurring billing featured in the web application. Our example script allows you to periodically charge the user via Stripe at a specific interval. This Stripe payment script’s functionality can be enhanced as per your needs.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Exit mobile version