Skip to Content
PHPCODE
Stripe payment gateway integration in codeigniter
codeigniter code / September 21, 2021

Stripe payment gateway is one of the most simple and powerful solutions for receiving payments online. The Stripe payment gateway API is the most convenient way to add a credit card payment option to your website. You can allow users to pay online with their credit or debit card using the Stripe API. Using the Stripe payment gateway, the credit card checkout system may be easily established on the online application.

The Stripe PHP library aids in the integration of the Stripe payment gateway into PHP. The Stripe API library must be included into your CodeIgniter application if it was built with the CodeIgniter framework. In this article, we’ll teach you how to integrate the Stripe payment gateway into CodeIgniter and use the Stripe API to accept credit card payments on your website.

The following functionality will be created in this example script to demonstrate the Stripe payment gateway integration in a CodeIgniter application.

Retrieve products from the database and display them on the website.
A Buy Now button will be available on each product, which will take the consumer to the payment page.
A form for entering credit card information will be available on the payment page.
The credit card information is validated and charged to the card after the payment form is submitted.
The transaction and order details are saved in the database, and the user is informed of the payment status.

Stripe API Keys for Testing

Before going live with the Stripe payment gateway, make sure the checkout procedure is working smoothly. To test the credit card payment procedure, you must utilise 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. Click the Reveal test key token button to reveal the Secret key.

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

Take a look at the file structure before getting started with the Stripe payment gateway API in the CodeIgniter framework.

codeigniter_stripe_integration/
├── application/
│   ├── config/
│   │   └── stripe.php
│   ├── controllers/
│   │   └── Products.php
│   ├── libraries/
│   │   └── Stripe_lib.php
│   ├── models/
│   │   └── Product.php
│   ├── third_party/
│   │   └── stripe-php/
│   ├── views/
│   │   └── products/
│   │       ├── index.php
│   │       ├── details.php
│   │       └── payment-status.php
└── assets/
    └── css/
        └── style.css

Tables in a Database

Two tables in the database are required to store product and payment information.

In the MySQL database, the following SQL creates a products table with some basic fields.

CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`price` float(10,2) NOT NULL,
`currency` char(10) COLLATE utf8_unicode_ci NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The following is a list of resources. To store transaction data, SQL creates an orders table in the MySQL database.

CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` int(11) NOT NULL,
`buyer_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`buyer_email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`paid_amount` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`paid_amount_currency` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`txn_id` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`payment_status` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Config 

stripe.php
This file contains the Stripe library’s configuration variables. Stripe API Secret key (stripe api key), API Publishable key (stripe publishable key), and currency code (stripe currency) must all be included.

<?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 
| 
| 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';

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

To make a charge with Stripe API, a third-party stripe-php/ Stripe PHP bindings library is used. The Stripe PHP library must be put in your CodeIgniter application’s third party/ directory.

It’s worth noting that the Stripe PHP library is included in the source code, so you won’t need to download it individually.

Library

Stripe lib.php
The Stripe CodeIgniter Library allows you to incorporate the Stripe payment gateway into your CodeIgniter 3 programme. A configuration file (application/config/stripe.php) and the Stripe PHP bindings library (application/third party/stripe-php) are required for this library to work.

__construct() – Initialize the Stripe class and set the API key.
addCustomer() — Adds a customer to a Stripe account using their email address and a unique token.
Charge a credit or debit card with createCharge().

<?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($email, $token){ 
try { 
// Add customer to stripe 
$customer = \Stripe\Customer::create(array( 
'email' => $email, 
'source' => $token 
)); 
return $customer; 
}catch(Exception $e) { 
$this->api_error = $e->getMessage(); 
return false; 
} 
} 
function createCharge($customerId, $itemName, $itemPrice){ 
// Convert price to cents 
$itemPriceCents = ($itemPrice*100); 
$currency = $this->CI->config->item('stripe_currency'); 
try { 
// Charge a credit or a debit card 
$charge = \Stripe\Charge::create(array( 
'customer' => $customerId, 
'amount' => $itemPriceCents, 
'currency' => $currency, 
'description' => $itemName 
)); 

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

the Controller (Products.php)
The Stripe library is used by the Products controller to handle product listing, checkout, and payment.

__construct() – This method loads the Stripe library as well as the product model.

index() – Retrieves product information from the database and passes it to view for display.

purchase() is a function that allows you to buy something.

Using the Product model’s getRows() method, retrieve specific product data from the database.

Pass data to view so that product details can be displayed.

If a payment form is completed and submitted,

Check to see if the stripe token is valid.

From the submitted form data, get the stripe token, card number, and user name.

To make a payment, use the payment() function and give the posted form data.

The payment status is passed to the view.
payment() — The Products controller uses this function internally.
Using the Stripe library’s addCustomer() method, you may add a customer by providing an email address and a token.
Using the Stripe library’s createCharge() method, generate a charge to a credit or debit card.
The insertOrder() method of the Product model is used to store the charge and order details in the database.
The order ID is returned if the transaction was successful.
payment status() – Using the Product model’s getOrder() method, retrieve order details from the database.
Pass order data to the view so that the payment status can be displayed.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
class Products extends CI_Controller { 
function __construct() { 
parent::__construct(); 
// Load Stripe library 
$this->load->library('stripe_lib'); 
// Load product model 
$this->load->model('product'); 
} 
public function index(){ 
$data = array(); 
// Get products from the database 
$data['products'] = $this->product->getRows(); 
// Pass products data to the list view 
$this->load->view('products/index', $data); 
} 
function purchase($id){ 
$data = array(); 
// Get product data from the database 
$product = $this->product->getRows($id); 
// 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(); 
$postData['product'] = $product; 
// Make payment 
$paymentID = $this->payment($postData); 
// If payment successful 
if($paymentID){ 
redirect('products/payment_status/'.$paymentID); 
}else{ 
$apiError = !empty($this->stripe_lib->api_error)?' ('.$this->stripe_lib->api_error.')':''; 
$data['error_msg'] = 'Transaction has been failed!'.$apiError; 
} 
} 
// Pass product data to the details view 
$data['product'] = $product; 
$this->load->view('products/details', $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']; 
// Add customer to stripe 
$customer = $this->stripe_lib->addCustomer($email, $token); 
if($customer){ 
// Charge a credit or a debit card 
$charge = $this->stripe_lib->createCharge($customer->id, $postData['product']['name'], $postData['product']['price']); 
if($charge){ 
// Check whether the charge is successful 
if($charge['amount_refunded'] == 0 && empty($charge['failure_code']) && $charge['paid'] == 1 && $charge['captured'] == 1){ 
// Transaction details 
$transactionID = $charge['balance_transaction']; 
$paidAmount = $charge['amount']; 
$paidAmount = ($paidAmount/100); 
$paidCurrency = $charge['currency']; 
$payment_status = $charge['status']; 
// Insert tansaction data into the database 
$orderData = array( 
'product_id' => $postData['product']['id'], 
'buyer_name' => $name, 
'buyer_email' => $email, 
'paid_amount' => $paidAmount, 
'paid_amount_currency' => $paidCurrency, 
'txn_id' => $transactionID, 
'payment_status' => $payment_status 
); 
$orderID = $this->product->insertOrder($orderData); 
// If the order is successful 
if($payment_status == 'succeeded'){ 
return $orderID; 
} 
} 
} 
} 
} 
return false; 
} 
function payment_status($id){ 
$data = array(); 
// Get order data from the database 
$order = $this->product->getOrder($id); 
// Pass order data to the view 
$data['order'] = $order; 
$this->load->view('products/payment-status', $data); 
} 
}

Model (Product.php)
The Product model is responsible for database operations (fetch and insert).

__construct() – Defines the database tables’ names.
getRows() – Returns an array containing the records from the products table.
getOrder() – Returns an array containing the record from the orders table.
Insert transaction data into the orders table with insertOrder().

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
class Product extends CI_Model{ 
function __construct() { 
$this->proTable = 'products'; 
$this->ordTable = 'orders'; 
} 
/* 
* Fetch products data from the database 
* @param id returns a single record if specified, otherwise all records 
*/ 
public function getRows($id = ''){ 
$this->db->select('*'); 
$this->db->from($this->proTable); 
$this->db->where('status', '1'); 
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('name', 'asc'); 
$query = $this->db->get(); 
$result = ($query->num_rows() > 0)?$query->result_array():array(); 
} 
// return fetched data 
return !empty($result)?$result:false; 
} 
/* 
* Fetch order data from the database 
* @param id returns a single record 
*/ 
public function getOrder($id){ 
$this->db->select('r.*, p.name as product_name, p.price as product_price, p.currency as product_price_currency'); 
$this->db->from($this->ordTable.' as r'); 
$this->db->join($this->proTable.' as p', 'p.id = r.product_id', 'left'); 
$this->db->where('r.id', $id); 
$query = $this->db->get(); 
return ($query->num_rows() > 0)?$query->row_array():false; 
} 
/* 
* Insert transaction data in the database 
* @param data array 
*/ 
public function insertOrder($data){ 
$insert = $this->db->insert($this->ordTable,$data); 
return $insert?$this->db->insert_id():false; 
} 
}

View
products/index.php
The Buy button is displayed alongside all of the products that have been retrieved from the database.

<!-- List all products -->
<?php if(!empty($products)){ foreach($products as $row){ 
<div class="pro-box">
<div class="info">
<h4><?php echo $row['name']; ?></h4>
<h5>Price: <?php echo '$'.$row['price'].' '.$row['currency']; ?></h5>
</div>
<div class="action">
<a href="<?php echo base_url('products/purchase/'.$row['id']); ?>">Purchase</a>
</div>
</div>
<?php } }else{ ?> 
<p>Product(s) not found...</p>
<?php } ?>

products/details.php
With the payment form, selected product information are presented.

Information about the product and a payment form can be found here.

At the top of the form, the product name and price are displayed.
The HTML form takes user information (name and email address) as well as card information (Card Number, Expiration Date, and CVC No.).

<div class="panel">
<div class="panel-heading">
<h3 class="panel-title">Charge <?php echo '$'.$product['price']; ?> with Stripe</h3>
<!-- Product Info -->
<p><b>Item Name:</b> <?php echo $product['name']; ?></p>
<p><b>Price:</b> <?php echo '$'.$product['price'].' '.$product['currency']; ?></p>
</div>
<div class="panel-body">
<!-- Display errors returned by createToken -->
<div class="card-errors"></div>
<!-- Payment form -->
<form action="" method="POST" id="paymentFrm">
<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>
</form>
</div>
</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.

<!-- Stripe JavaScript library -->
<script src="https://js.stripe.com/v3/"></script>

To generate a token with the Stripe JS v3 library, use the JavaScript code below.

Set your publishable API key that identifies your website and create an instance of the Stripe object.
To alter the UI components in the payment form, use Stripe Elements to link the card 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 the Stripe token to a hidden input element on the payment form.
If the token is successfully produced, the form is sent to the server, which creates a charge against the specified card. 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>

products/payment-status.php
With the transaction details, the payment status is displayed.

<?php if(!empty($order)){ ?>
<!-- Display transaction status -->
<?php if($order['payment_status'] == 'succeeded'){ ?>
<h1 class="success">Your Payment has been Successful!</h1>
<?php }else{ ?>
<h1 class="error">The transaction was successful! But your payment has been failed!</h1>
<?php } ?>
<h4>Payment Information</h4>
<p><b>Reference Number:</b> <?php echo $order['id']; ?></p>
<p><b>Transaction ID:</b> <?php echo $order['txn_id']; ?></p>
<p><b>Paid Amount:</b> <?php echo $order['paid_amount'].' '.$order['paid_amount_currency']; ?></p>
<p><b>Payment Status:</b> <?php echo $order['payment_status']; ?></p>
<h4>Product Information</h4>
<p><b>Name:</b> <?php echo $order['product_name']; ?></p>
<p><b>Price:</b> <?php echo $order['product_price'].' '.$order['product_price_currency']; ?></p>
<?php }else{ ?>
<h1 class="error">The transaction has 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 :

The payment gateway is an important component of every eCommerce site. The Stripe payment gateway aids in the user-friendliness of the online payment procedure. You may take credit card payments on your CodeIgniter website using the Stripe API. In CodeIgniter, our sample code makes it simple to charge a credit card using the Stripe payment gateway.

PHPCODE © 2024