loading

How to Stripe Subscription Payment Integration in PHP

How to Stripe Subscription Payment Integration in PHP

How to Stripe Subscription Payment Integration in PHP

0 Sales

Free

The Stripe Subscription API makes it simple to add recurring payments into your website. Subscription payment is essential for recurring billing if you wish to install the affiliation subscription system on the web application. Stripe payment gateway aids in the integration of recurring payments with the Plans and Subscription API. Stripe subscription is a quick and easy way for your website's members to pay a membership online with their credit card.

Stripe subscription payments bill the buyer on a recurring basis based on the specified frequency. A member of your website may subscribe to a plan and pay with a credit/debit card without leaving the site. In this article, we'll teach you how to use PHP to connect Stripe subscription payments.

In the demo script, we will develop the following functionality in PHP to take subscription payments over the Stripe Payment Gateway.

 - Make an HTML form for choosing a subscription plan and entering payment card details.

 - To securely transfer card information, create a Stripe token.

 - Fill up the form with your plan and credit card information and submit it.

 - Using the Stripe API, verify the card and establish a subscription plan.

 - In the database, save transaction data together with subscription plan information.

Take a look at the file structure before beginning to integrate the Stripe Subscription payment API in PHP.

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

Stripe Test API Keys

Before launching the Stripe subscription payment gateway, ensure that the subscription process is operational. To test the subscription payment procedure, you'll need the test API keys data.

1. Login to the Devs » API keys page after logging into your Stripe account.

2. The keys (Secret key and Publishable key) are given underneath the Standard keys area in the Testing Data block. Click the Display test key token icon to reveal the Secret key.

Create Database Tables

 

In order to keep member and subscription information in the database, two tables are necessary.

1. The following are examples: SQL generates a users table in the MySQL database to store the member's information.

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 are examples SQL creates a user subscriptions table in the MySQL database to store subscription information.

CREATE TABLE `user_subscriptions` (
 `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;

Plans, Stripe API and Database Configuration (config.php)

Constant variables for the Stripe API, plans, and database settings are defined in the config.php file.

Plans Data:

 - $plans — An array containing all of the available plan information.

- $currency - Currency symbol.

Stripe API Constants:

 - STRIPE API KEY – Enter the API Secret key here.

 - STRIPE PUBLISHABLE KEY – The API Publishable key must be specified.

Database Constants:

 - DB HOST – The database hostname.

 - DB USERNAME – Enter the database username here.

 - DB PASSWORD – Enter the database password here.

 - DB NAME – Enter the name of the database.

 

<?php 
// 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: https://dashboard.stripe.com/account/apikeys 
 */ 
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');

 

Database Connection (dbConnect.php)

The dbConnect.php code is being used to connect PHP and MySQL to the database.

<?php  
// Connect with the database  
$db = new mysqli(DB_HOSTDB_USERNAMEDB_PASSWORDDB_NAME);  
  
// Display error if failed to connect  
if ($db->connect_errno) {  
    printf("Connect failed: %s\n"$db->connect_error);  
    exit();  
}

Stripe Subscription Form (index.php)

Also include configuration file first.

<?php 
// Include configuration file  
require_once 'config.php'; 
?>

HTML Subscription Form:

The HTML form below allows the user to choose a membership plan and give buyer information (name and email) as well as credit card information (Card Number, Expiration Date, and CVC No.). The form data is sent to the server-side script (payment.php) to be processed for subscription payments.

<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 -->
            <p>
                <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 ?>
                </select>
            </p>
        </div>
        <div class="panel-body">
            <!-- Display errors returned by createToken -->
            <div id="paymentResponse"></div>
			
            <!-- Payment form -->
            <div class="form-group">
                <label>NAME</label>
                <input type="text" name="name" id="name" class="field" placeholder="Enter name" required="" autofocus="">
            </div>
            <div class="form-group">
                <label>EMAIL</label>
                <input type="email" name="email" id="email" class="field" placeholder="Enter email" required="">
            </div>
            <div class="form-group">
                <label>CARD NUMBER</label>
                <div id="card_number" class="field"></div>
            </div>
            <div class="row">
                <div class="left">
                    <div class="form-group">
                        <label>EXPIRY DATE</label>
                        <div id="card_expiry" class="field"></div>
                    </div>
                </div>
                <div class="right">
                    <div class="form-group">
                        <label>CVC CODE</label>
                        <div id="card_cvc" class="field"></div>
                    </div>
                </div>
            </div>
            <button type="submit" class="btn btn-success" id="payBtn">Submit Payment</button>
        </div>
    </form>
</div>

Create Stripe Token and Validate Card with Stripe JS Library:

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

<script src="https://js.stripe.com/v3/"></script>

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

 - Specify your publishable API key, which will be used to identify your website to Stripe.

 - Stripe Elements may be used to alter UI components in the payment method.

      - Using the stripe.elements() function, create an instance of Elements.

      - Using elements, create an instance of a certain element.create() is a method.

      - Using the element.mount() function, you may attach your Element to the DOM.

 - The createToken() method uses stripe to generate a single-use token. card components and the createToken() function

 - The stripeTokenHandler() method adds a hidden input with the Stripe token to the payment form.

 - When the transaction is successful, the card information is sent to the server. Otherwise, the error notice appears.

<script>
// 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
});
cardElement.mount('#card_number');

var exp = elements.create('cardExpiry', {
    'style': style
});
exp.mount('#card_expiry');

var cvc = elements.create('cardCvc', {
    'style': style
});
cvc.mount('#card_cvc');

// 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) {
    e.preventDefault();
    createToken();
});

// 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
            stripeTokenHandler(result.token);
        }
    });
}

// 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');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);
	
    // Submit the form
    form.submit();
}
</script>

 

Stripe PHP Library

To access the Stripe API in PHP, utilise the Stripe PHP library. It aids in the creation of customers, plans, and subscriptions using the Stipre API. All of the necessary library files are included in our source code; you do not need to download them individually.

Process Subscription Payment (payment.php)

The provided card data are confirmed in this file, and the subscription plan is enabled with the Stripe API through PHP.

 - Get the SESSION's logged-in user ID.

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

 - Get the specifics of the plan (name, price, and term) from the $plans array.

 - Include the Stripe PHP library in your code.

 - Set the API Secret key with the Stripe class's setApiKey() function.

 - The Stripe Customer API's create() function is used to add the customer.

      - email – Buyer email

      - source – Stripe token

 - Create a plan via the Stripe Plan API's create() function.

      - product – The product whose pricing will be represented by the established plan.

           - product.name – Name of the plan.

      - amount – A positive integer in cents (or 0 for a free plan) for recurring charges.

      - currency — Lowercase three-letter ISO currency code.

      - interval – Define the charging frequency (day, week, month or year).

      - interval count – The number of billing intervals between subscriptions. For

      - instance, interval=month and interval count=2 generate bills every two months.

      - Intervals of up to one year (1 year, 12 months, or 52 weeks) are permitted.

 - Generate a subscription via the Stripe Subscription API's create() function.

      - customer – The subscriber's unique identification.

      - items – A list of subscription plans.

           - items.plan – Include the plan ID.

 - Retrieve transaction data if the plan and subscription activation were successful. Following successful activation,

      - Fill out the subscription form and save it to the database.

      - Assign the subscription reference ID to the appropriate member.

 - Display the payment status of a subscription on the webpage.

<?php 
// 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 
    \Stripe\Stripe::setApiKey(STRIPE_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( 
                        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!'; 
                }else{ 
                    $statusMsg "Subscription activation failed!"; 
                } 
            }else{ 
                $statusMsg "Subscription creation failed! ".$api_error; 
            } 
        }else{ 
            $statusMsg "Plan creation failed! ".$api_error; 
        } 
    }else{  
        $statusMsg "Invalid card details! $api_error";  
    } 
}else{ 
    $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 ?>
    </div>
    <a href="index.php" class="btn-link">Back to Subscription Page</a>
</div>

 

Make Stripe Payment Gateway Live

Once subscription Platform is complete and the payment process is operational, proceed with the steps below to activate the Stripe payment gateway.

 - Browse to the Devs » API keys page after logging into your Stripe account.

 - Take note of the keys (Secret key and Publishable key) under the LIVE DATA area.

 - Change the Experiment API keys (Publishable key and Secret key) in the config.php file with the Active API keys (Publishable key and Secret key).

Conclusion

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

 

 

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : Jan 24, 2022

Updated Date : Jan 24, 2022

Ratings

Comments : 0

Downloads : 0