Skip to Content
PHPCODE
stripe payment gateway integration in codeigniter
codeigniter code / September 10, 2021

On the web application, the Stripe payment gateway makes it simple to take subscription fees. The Stripe API can be used to construct a membership subscription system with recurring billing. The Stripe Plans & Subscription API enables you to quickly and easily incorporate recurring payment features. Stripe Subscription is a sophisticated tool that allows members of your website to buy/subscribe to memberships online using their credit cards.

Stripe PHP library makes it possible to use the Stripe Subscription API in PHP. The Stripe PHP library and API must be included into the CodeIgniter application if your website is built with the CodeIgniter framework. The subscriber is charged recurringly depending on a specific interval in the Stripe subscription payment system. The subscriber can use their credit/debit card to purchase a subscription package on your website without leaving the web application. In this tutorial, we’ll teach you how to use CodeIgniter to incorporate Stripe subscription payment capabilities.

To integrate Stripe Subscription API in PHP, you’ll need to use a Stripe PHP library. Using the CodeIgniter framework, you’ll need to integrate the Stripe PHP library and API. For example, if you use Stripe’s subscription payment system, you’ll be charged on a regular basis according to the interval. Using their credit/debit card, the subscriber can purchase a membership package on your website without ever leaving the online application. Using CodeIgniter, we’ll teach you how to connect Stripe’s subscription-based payment system.

Test API Keys for Stripe
Stripe payment gateway needs to be tested to ensure that the checkout process works properly before it can go live. Testing credit card payments requires that you utilise test API keys.

Visit the Developers » API keys section of your Stripe account.
There are two API keys listed under Standard keys in the TEST DATA. Cliquer sur “Reveal test key token” to reveal the Secret Key.

 

codeigniter_stripe_subscription_payment_integration/
├── application/
│   ├── config/
│   │   └── stripe.php
│   ├── controllers/
│   │   └── Subscription.php
│   ├── libraries/
│   │   └── Stripe_lib.php
│   ├── models/
│   │   └── User.php
│   ├── third_party/
│   │   └── stripe-php/
│   ├── views/
│   │   └── subscription/
│   │       ├── index.php
│   │       └── payment-status.php
└── assets/
    └── css/
        └── style.css


DATABASE

In order to store the plan, member, and subscription information in the database, three tables are required.

As an example, To store subscription plan information in MySQL, SQL constructs a plans table.

CREATE TABLE `plans` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`price` float(10,2) NOT NULL,
`currency` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'USD',
`interval` enum('week','month','year') COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;/* Your code... */

Here’s what’s next Users is a table that SQL creates in the MySQL database to keep track of the website’s members’ 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;

What’s next? To store the subscription and payment information in the MySQL database, SQL creates a user subscriptions table in the database using a SQL statement.

CREATE TABLE `user_subscriptions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL DEFAULT 0,
`plan_id` int(11) NOT NULL,
`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,
`plan_period_start` datetime NOT NULL,
`plan_period_end` datetime NOT NULL,
`payer_email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`status` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Config

sstripe.php
This file contains the configuration variables for the Stripe library.

You’ll need the Stripe API Secret key (stripe api key), the API Publishable key (stripe publishable key) and the currency code (stripe currency).

<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 
/* 
| ------------------------------------------------------------------- 
| Stripe API Configuration 
| ------------------------------------------------------------------- 
| 
| You will get the API keys from Developers panel of the Stripe account 
| Login to Stripe account (https://dashboard.stripe.com/) 
| and navigate to the Developers » API keys page 
| Remember to switch to your live publishable and secret key in production! 
| 
| stripe_api_key string Your Stripe API Secret key. 
| stripe_publishable_key string Your Stripe API Publishable key. 
| stripe_currency string Currency code. 
*/ 
$config['stripe_api_key'] = 'Your_API_Secret_key'; 
$config['stripe_publishable_key'] = 'Your_API_Publishable_key'; 
$config['stripe_currency'] = 'usd';

Note that the Stripe API Secret key and Publishable key may be located in the API Keys Data area of your Stripe account under the API Keys Data heading, respectively.

It is need to use a third-party library called stripe-php/ Stripe PHP bindings in order to create a customer, plan, and subscription using the Stripe API. The Stripe PHP library must be put in your CodeIgniter application’s third party/ directory.

Stripe’s PHP library is already included in the source code and does not need to be downloaded separately.

Library \sStripe lib.php
Using the Stripe CodeIgniter Library, CodeIgniter 3 applications can accept Stripe subscription payments. An application/config/stripe.php configuration file and a third-party Stripe PHP binding library (application/third party/stripe-php) are required.

__construct() – Initialize the Stripe class and set an API key.
useStripeCustomer API to add a customer to a Stripe account.
useStripePlan API to construct a plan with the createPlan() method.
useStripeSubscription API to create a subscription.

<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 
/** 
* Stripe Library for CodeIgniter 3.x 
* 
* Library for Stripe payment gateway. It helps to integrate Stripe payment gateway 
* in CodeIgniter application. 
* 
* This library requires the Stripe PHP bindings and it should be placed in the third_party folder. 
* It also requires Stripe API configuration file and it should be placed in the config directory. 
* 
* @package CodeIgniter 
* @category Libraries 
* @author CodexWorld 
* @license http://www.codexworld.com/license/ 
* @link http://www.codexworld.com 
* @version 3.0 
*/ 
class Stripe_lib{ 
var $CI; 
var $api_error; 

function __construct(){ 
$this->api_error = ''; 
$this->CI =& get_instance(); 
$this->CI->load->config('stripe'); 

// Include the Stripe PHP bindings library 
require APPPATH .'third_party/stripe-php/init.php'; 

// Set API key 
\Stripe\Stripe::setApiKey($this->CI->config->item('stripe_api_key')); 
} 
function addCustomer($name, $email, $token){ 
try { 
// Add customer to stripe 
$customer = \Stripe\Customer::create(array( 
'name' => $name, 
'email' => $email, 
'source' => $token 
)); 
return $customer; 
}catch(Exception $e) { 
$this->api_error = $e->getMessage(); 
return false; 
} 
} 
function createPlan($planName, $planPrice, $planInterval){ 
// Convert price to cents 
$priceCents = ($planPrice*100); 
$currency = $this->CI->config->item('stripe_currency'); 
try { 
// Create a plan 
$plan = \Stripe\Plan::create(array( 
"product" => [ 
"name" => $planName 
], 
"amount" => $priceCents, 
"currency" => $currency, 
"interval" => $planInterval, 
"interval_count" => 1 
)); 
return $plan; 
}catch(Exception $e) { 
$this->api_error = $e->getMessage(); 
return false; 
} 
} 
function createSubscription($customerID, $planID){ 
try { 
// Creates a new subscription 
$subscription = \Stripe\Subscription::create(array( 
"customer" => $customerID, 
"items" => array( 
array( 
"plan" => $planID 
), 
), 
)); 

// Retrieve charge details 
$subsData = $subscription->jsonSerialize(); 
return $subsData; 
}catch(Exception $e) { 
$this->api_error = $e->getMessage(); 
return false; 
} 
} 
}

As a result of this (Subscription.php)
Using the Stripe library as a backend, Subscription handles the subscription and payment process.

the function Object() { [native code] } __construct().

Stripe library and user model loaded.

Obtain the logged-in user’s ID from the SESSION object.

iterator == index() ==

Plan data should be fetched from the database and passed on to view for plan listing.

If you submit a payment form,

The Stripe token should be present.

Retrieve the subscriber, plan, and stripe token information from the form’s submitted data.

To make a payment, call the payment() function and pass the posted data to the function to initiate the transaction.
Redirect to the subscription status page if payment was successful.

Subscription controller uses payment() internally.
Take a look at the Stripe token and the user’s information.
A plan can be retrieved by a specific method in the User model: the getPlans() method.
Using the addCustomer() method of the Stripe library, you can add a customer by submitting their name, email, and token.
You can use the Stripe library’s createPlan() method in order to create an account based on selected plan information.
Subscriptions can be created by using the Stripe library’s subscribe() method.
Using the User model’s insertSubscription() method, insert transaction and subscription details into the database if subscription activation was successful.
Reply with the subscription identifier (ID).

User model’s getSubscription() method can be used to retrieve subscription details from the database.
Pass subscription data to the view so that it can show the status of the subscription.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
class Subscription extends CI_Controller { 
function __construct() { 
parent::__construct(); 
// Load Stripe library 
$this->load->library('stripe_lib'); 
// Load product model 
$this->load->model('user'); 
// Get user ID from current SESSION 
$this->userID = isset($_SESSION['loggedInUserID'])?$_SESSION['loggedInUserID']:1; 
} 
public function index(){ 
$data = array(); 
// If payment form is submitted with token 
if($this->input->post('stripeToken')){ 
// Retrieve stripe token and user info from the posted form data 
$postData = $this->input->post(); 
// Make payment 
$paymentID = $this->payment($postData); 
// If payment successful 
if($paymentID){ 
redirect('subscription/payment_status/'.$paymentID); 
}else{ 
$apiError = !empty($this->stripe_lib->api_error)?' ('.$this->stripe_lib->api_error.')':''; 
$data['error_msg'] = 'Transaction has been failed!'.$apiError; 
} 
} 
// Get plans from the database 
$data['plans'] = $this->user->getPlans(); 
// Pass plans data to the list view 
$this->load->view('subscription/index', $data); 
} 
function payment($postData){ 
// If post data is not empty 
if(!empty($postData)){ 
// Retrieve stripe token and user info from the submitted form data 
$token = $postData['stripeToken']; 
$name = $postData['name']; 
$email = $postData['email']; 
// Plan info 
$planID = $_POST['subscr_plan']; 
$planInfo = $this->user->getPlans($planID); 
$planName = $planInfo['name']; 
$planPrice = $planInfo['price']; 
$planInterval = $planInfo['interval']; 
// Add customer to stripe 
$customer = $this->stripe_lib->addCustomer($name, $email, $token); 
if($customer){ 
// Create a plan 
$plan = $this->stripe_lib->createPlan($planName, $planPrice, $planInterval); 
if($plan){ 
// Creates a new subscription 
$subscription = $this->stripe_lib->createSubscription($customer->id, $plan->id); 
if($subscription){ 
// Check whether the subscription activation is successful 
if($subscription['status'] == 'active'){ 
// Subscription info 
$subscrID = $subscription['id']; 
$custID = $subscription['customer']; 
$planID = $subscription['plan']['id']; 
$planAmount = ($subscription['plan']['amount']/100); 
$planCurrency = $subscription['plan']['currency']; 
$planInterval = $subscription['plan']['interval']; 
$planIntervalCount = $subscription['plan']['interval_count']; 
$created = date("Y-m-d H:i:s", $subscription['created']); 
$current_period_start = date("Y-m-d H:i:s", $subscription['current_period_start']); 
$current_period_end = date("Y-m-d H:i:s", $subscription['current_period_end']); 
$status = $subscription['status']; 
// Insert tansaction data into the database 
$subscripData = array( 
'user_id' => $this->userID, 
'plan_id' => $planInfo['id'], 
'stripe_subscription_id' => $subscrID, 
'stripe_customer_id' => $custID, 
'stripe_plan_id' => $planID, 
'plan_amount' => $planAmount, 
'plan_amount_currency' => $planCurrency, 
'plan_interval' => $planInterval, 
'plan_interval_count' => $planIntervalCount, 
'plan_period_start' => $current_period_start, 
'plan_period_end' => $current_period_end, 
'payer_email' => $email, 
'created' => $created, 
'status' => $status 
); 
$subscription_id = $this->user->insertSubscription($subscripData); 
// Update subscription id in the users table 
if($subscription_id && !empty($this->userID)){ 
$data = array('subscription_id' => $subscription_id); 
$update = $this->user->updateUser($data, $this->userID); 
} 
return $subscription_id; 
} 
} 
} 
} 
} 
return false; 
} 
function payment_status($id){ 
$data = array(); 

// Get subscription data from the database 
$subscription = $this->user->getSubscription($id); 

// Pass subscription data to the view 
$data['subscription'] = $subscription; 
$this->load->view('subscription/payment-status', $data); 
} 
}

When it comes to the model (User.php)
Fetch, insert and update operations are handled by the User model.

Database table names are defined by using __construct().
User data can be updated using the updateUser() function.
user subscriptions and plans table.
replace() – Replace a row in the user subscriptions table with a new one.
getPlans() – Returns an array of records from the plans table.

<?php 
if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
class User extends CI_Model { 
function __construct(){ 
$this->userTbl = 'users'; 
$this->planTbl = 'plans'; 
$this->subscripTbl = 'user_subscriptions'; 
} 
/* 
* Update user data to the database 
* @param data array 
* @param id specific user 
*/ 
public function updateUser($data, $id){ 
$update = $this->db->update($this->userTbl, $data, array('id' => $id)); 
return $update?true:false; 
} 
/* 
* Fetch order data from the database 
* @param id returns a single record 
*/ 
public function getSubscription($id){ 
$this->db->select('s.*, p.name as plan_name, p.price as plan_price, p.currency as plan_price_currency, p.interval'); 
$this->db->from($this->subscripTbl.' as s'); 
$this->db->join($this->planTbl.' as p', 'p.id = s.plan_id', 'left'); 
$this->db->where('s.id', $id); 
$query = $this->db->get(); 
return ($query->num_rows() > 0)?$query->row_array():false; 
} 
/* 
* Insert subscription data in the database 
* @param data array 
*/ 
public function insertSubscription($data){ 
$insert = $this->db->insert($this->subscripTbl,$data); 
return $insert?$this->db->insert_id():false; 
} 
/* 
* Fetch plans data from the database 
* @param id returns a single record if specified, otherwise all records 
*/ 
public function getPlans($id = ''){ 
$this->db->select('*'); 
$this->db->from($this->planTbl); 
if($id){ 
$this->db->where('id', $id); 
$query = $this->db->get(); 
$result = ($query->num_rows() > 0)?$query->row_array():array(); 
}else{ 
$this->db->order_by('id', 'asc'); 
$query = $this->db->get(); 
$result = ($query->num_rows() > 0)?$query->result_array():array(); 
} 
// return fetched data 
return !empty($result)?$result:false; 
} 
}

VIEW

subscription/index.php

There is a dropdown menu for selecting a plan, and a payment form is displayed on the page.

It collects the user’s information (name and email) as well as card information (Card Number, Expiration Date, and CVC No.).

Under a dropdown menu, you can choose from a variety of plans.

<div class="panel">
<form action="" 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 $plan){ ?>
<option value="<?php echo $plan['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>

Validate Card with Stripe JS Library: Include the Stripe.js v3 library, which allows you to securely communicate sensitive data to Stripe from your browser.

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

To create a token with the Stripe JS v3 library, use 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 appends the Stripe token to the payment form as a hidden entry.

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.

<script>
// Create an instance of the Stripe object
// Set your publishable API key
var stripe = Stripe('<?php echo $this->config->item('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>

subscription/payment-status.php

This page displays the subscription details as well as the payment status.

<?php if(!empty($subscription)){ ?><?php if($subscription['status'] == 'active'){ ?> <h1 class="success">Your Subscription Payment has been Successful!</h1> <?php }else{ ?> <h1 class="error">Subscription activation failed!</h1> <?php } ?> <h4>Payment Information</h4> <p><b>Reference Number:</b> <?php echo $subscription['id']; ?></p> <p><b>Transaction ID:</b> <?php echo $subscription['stripe_subscription_id']; ?></p> <p><b>Amount:</b> <?php echo $subscription['plan_amount'].' '.$subscription['plan_amount_currency']; ?></p> <h4>Subscription Information</h4> <p><b>Plan Name:</b> <?php echo $subscription['plan_name']; ?></p> <p><b>Amount:</b> <?php echo $subscription['plan_price'].' '.$subscription['plan_price_currency']; ?></p> <p><b>Plan Interval:</b> <?php echo $subscription['plan_interval']; ?></p> <p><b>Period Start:</b> <?php echo $subscription['plan_period_start']; ?></p> <p><b>Period End:</b> <?php echo $subscription['plan_period_end']; ?></p> <p><b>Status:</b> <?php echo $subscription['status']; ?></p> <?php }else{ ?> <h1 class="error">The transaction has been failed!</h1> <?php } ?>

Activate the Stripe Payment Gateway
Follow the steps below to make the Stripe payment gateway live once the Stripe checkout process is running properly.

Go to the Developers » API keys page after logging into your Stripe account.
Collect the API keys from Live Data (Publishable key and Secret key).
Replace the Test API keys (Publishable key and Secret key) with the Live API keys in the application/config/stripe.php file (Publishable key and Secret key).

Note

Stripe Subscription API comes in handy when you need to bill a customer on a weekly, monthly, or annual basis. This example script will help you integrate a payment system for membership subscriptions into your website. You can accept credit/debit card payments for subscriptions on your CodeIgniter website. The membership payment process is made simple with our sample code, and the checkout can be completed in a single page utilising the Stripe API.

PHPCODE © 2024