When it comes to accepting payment online, Stripe payment gateway is one of the easiest and powerful solution. The Stripe payment gateway API provides the quickest way to integrate the credit card payment option on the website. With stripe API you can allow the user to make the payment online by their credit or debit card. The credit card checkout system can be easily implemented on the web application using the Stripe payment gateway.
Stripe PHP library helps to integrate stripe payment gateway in PHP. If your web application built with the CodeIgniter framework, the Stripe API library needs to integrate into the CodeIgniter application. In this tutorial, we will show you how to integrate stripe payment gateway in CodeIgniter and accept credit card payment on the website with Stripe API.
In this example script, the following functionality will be implemented to demonstrate the Stripe payment gateway integration in CodeIgniter application.
Before making the Stripe payment gateway live, it needs to be checked whether the checkout process is working properly. You need to use the test API keys data to check the credit card payment process.
Collect the Publishable key and Secret key to later use in the script.
Before getting started to integrate Stripe payment gateway API in CodeIgniter framework, take a look at the files structure.
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
To store product and payment information two tables are needed in the database.
The following SQL creates a products
table with some basic fields in the MySQL database.
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 SQL creates a orders
table in the MySQL database to store the transaction information.
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;
stripe.php
The configuration variables of the Stripe library are defined in this file. Specify the Stripe API Secret key (stripe_api_key), API Publishable key (stripe_publishable_key), and 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
|
| 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: Stripe API Secret key and Publishable key will be found in the API Keys Data section of your Stripe account.
stripe-php/
Stripe PHP bindings library is used to create a charge with Stripe API. The Stripe PHP library needs to be placed in the third_party/
directory of your CodeIgniter application.
Note that: You don’t need to download the Stripe PHP library separately, all the required files are included in the source code.
Stripe_lib.php
The Stripe CodeIgniter Library helps to integrate Stripe payment gateway in CodeIgniter 3 application. This library has the dependency of a configuration file (application/config/stripe.php
) and Stripe PHP bindings library (application/third_party/stripe-php
).
<?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 Products controller handles the product listing, checkout and payment process with Stripe library.
getRows()
method of the Product model.payment()
function and pass posted form data to make the payment.addCustomer()
method of Stripe library.createCharge()
method of Stripe library.insertOrder()
method of the Product model.getOrder()
method of Product model.<?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);
}
}
The Product model handles database related (fetch and insert) operations.
<?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;
}
}
products/index.php
All the products are fetched from the database and listed with the Buy button.
<!-- 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
Selected product details are displayed with the payment form.
Product Info and Payment Form:
<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 that helps securely sending the sensitive information to Stripe directly from the browser.
<!-- Stripe JavaScript library -->
<script src="https://js.stripe.com/v3/"></script>
The following JavaScript code is used to generate token with Stripe JS v3 library.
stripe.createToken()
method and card elements.<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
The payment status is shown with the transaction details.
<?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 } ?>
Once the Stripe checkout process is working properly, follow the below steps to make Stripe payment gateway live.
application/config/stripe.php
file, replace the Test API keys (Publishable key and Secret key) by the Live API keys (Publishable key and Secret key).PayPal Pro Payment Gateway Integration in CodeIgniter
The payment gateway is an essential part of the eCommerce website. The Stripe payment gateway helps to make the online payment process user-friendly. With Stripe API you can accept the credit card payment on your CodeIgniter website. Our example code makes it easy to charge a credit card with the Stripe payment gateway in CodeIgniter.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
this is available in ci4?