YouTube Icon

Code Playground.

How to Implement Stripe Payment Gateway in CodeIgniter


How to Implement Stripe Payment Gateway in CodeIgniter

With regards to stripe installment on the web, Strip installment door is one of the most straightforward and ground-breaking arrangement. The Stripe installment entryway API gives the speediest method to incorporate Mastercard installment alternative on the site. With stripe API you can permit the client to make the installment online by their credit or plastic. The charge card checkout framework can be effectively executed on the web application utilizing the Stripe installment passage. 

Stripe PHP library assists with incorporating stripe installment door in PHP. In the event that your web application worked with CodeIgniter structure, Stripe API library needs to coordinate into the CodeIgniter application. Right now, will tell you the best way to coordinate stripe installment passage in CodeIgniter and acknowledge Mastercard installment on the site with Stripe API.

Also Read:-How to Upload Image and Create Thumbnail in CodeIgniter

In this example script, the following functionality will be implemented to demonstrate the Stripe payment gateway integration in CodeIgniter application.

  • Fetch products from the database and list them on the web page.
  • Each product will have a Buy Now button which redirects the user to the payment page.
  • In the payment page, a form will be provided to enter the credit card information.
  • After the payment form submission, the credit card information is validated and charged to the card.
  • The transaction and order details are stored in the database, and payment status is shown to the user.

Stripe Test API Keys

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.

  • Login to your Stripe account and navigate to the Developers » API keys page.
  • In the TEST DATA, you’ll see the API keys (Publishable key and Secret key) are listed under the Standard keys section. To show the Secret key, click on Reveal test key token button.

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.

Create Database Tables

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` (
 `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',
) 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` (
 `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,
 `card_number` bigint(20) NOT NULL,
 `card_exp_month` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
 `card_exp_year` varchar(5) 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,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;



The setup factors of the Stripe library are characterized right now. Indicate the Stripe API Secret key (stripe_api_key), API Publishable key (stripe_publishable_key), and money code (stripe_currency).

defined('BASEPATH') OR exit('No direct script access allowed'); 

$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.

Third Party


Stripe PHP ties library is utilized to make an accuse of Stripe API. The Stripe PHP library should be set in the third_party/index of your CodeIgniter application. 

Note that: You don't have to download the Stripe PHP library independently, all the necessary records are remembered for the source code.



The Stripe CodeIgniter Library helps to incorporate Stripe installment portal in CodeIgniter 3 application. This library has the reliance of a setup document (application/config/stripe.php) and Stripe PHP ties library (application/third_party/stripe-php).

  • __construct() – Set API key and initiate the Stripe class.
  • addCustomer() – Add customer to Stripe account by email and token.
  • createCharge() – Charge a credit or a debit card.
defined('BASEPATH') OR exit('No direct script access allowed'); 
class Stripe_lib{ 
    var $CI; 
    var $api_error; 
    function __construct(){ 
        $this->api_error = ''; 
        $this->CI =& get_instance(); 
        // Include the Stripe PHP bindings library 
        require APPPATH .'third_party/stripe-php/init.php'; 
        // Set 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, $orderID){ 
        // 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, 
                'metadata' => array( 
                    'order_id' => $orderID 
            // Retrieve charge details 
            $chargeJson = $charge->jsonSerialize(); 
            return $chargeJson; 
        }catch(Exception $e) { 
            $this->api_error = $e->getMessage(); 
            return false; 

Controller (Products.php)

The Products controller handles the product listing, checkout and payment process with Stripe library.

  • __construct() –Loads the Stripe library and item model. 
  • index() –Fetch the items information from the database and go to see for items posting. 
  • purchase() – 
  • Get a particular item information from the database using getRows() method of the Product model. 
  • Pass information to see for show the item subtleties. 
  • On the off chance that installment structure is submitted, 
  • Check whether it has a substantial stripe token. 
  • Recover stripe token, card and client information from the submitted structure information. 
  • Call the payment() function and pass presented structure information on make the installment. 
  • Pass the installment status to the view. 
  • payment() –This capacity is for inside use by Products controller. 
  • Include client by submitted email address and token using addCustomer() method of Stripe library. 
  • Make a charge to the Mastercard or check card using createCharge() method of Stripe library. 
  • Supplement the charge and request subtleties in the database using insertOrder() method of the Product model. 
  • On the off chance that the exchange is fruitful, the request ID is returned. 
  • payment_status() – 
  • Get the request subtleties from the database using getOrder() method of Product model. 
  • Pass request information to the view for indicating the installment status.


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
class Products extends CI_Controller { 
    function __construct() { 
        // Load Stripe library & product model 
    public function index(){ 
        $data = array(); 
        // Get products data 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 
            // Retrieve stripe token, card and user info from the submitted form data 
            $postData = $this->input->post(); 
            $postData['product'] = $product; 
            // Make payment 
            $paymentID = $this->payment($postData); 
            // If payment successful 
                $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 
            // Retrieve stripe token, card and user info from the submitted form data 
            $token  = $postData['stripeToken']; 
            $name = $postData['name']; 
            $email = $postData['email']; 
            $card_number = $postData['card_number']; 
            $card_number = preg_replace('/\s+/', '', $card_number); 
            $card_exp_month = $postData['card_exp_month']; 
            $card_exp_year = $postData['card_exp_year']; 
            $card_cvc = $postData['card_cvc']; 
            // Unique order ID 
            $orderID = strtoupper(str_replace('.','',uniqid('', true))); 
            // Add customer to stripe 
            $customer = $this->stripe_lib->addCustomer($email, $token); 
                // Charge a credit or a debit card 
                $charge = $this->stripe_lib->createCharge($customer->id, $postData['product']['name'], $postData['product']['price'], $orderID); 
                    // 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, 
                            'card_number' => $card_number, 
                            'card_exp_month' => $card_exp_month, 
                            'card_exp_year' => $card_exp_year, 
                            '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 contains 4 functions, __construct()getRows()getOrder() and insertOrder().

  • __construct() – Defines the name of the database tables.
  • getRows() – Fetch the records from the products table and returns as an array.
  • getOrder() – Fetch the record from the orders table and returns as an array.
  • insertOrder() – Insert the transaction data in the orders table.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
class Product extends CI_Model{ 
    function __construct() { 
        $this->proTable   = 'products'; 
        $this->ordTable = 'orders'; 
    public function getRows($id = ''){ 
        $this->db->where('status', '1'); 
            $this->db->where('id', $id); 
            $query  = $this->db->get(); 
            $result = ($query->num_rows() > 0)?$query->row_array():array(); 
            $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; 
    public function getOrder($id){ 
        $this->db->select('r.*, 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', ' = r.product_id', 'left'); 
        $this->db->where('', $id); 
        $query  = $this->db->get(); 
        return ($query->num_rows() > 0)?$query->row_array():false; 
    public function insertOrder($data){ 
        $insert = $this->db->insert($this->ordTable,$data); 
        return $insert?$this->db->insert_id():false; 


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 class="action">
        <a href="<?php echo base_url('products/purchase/'.$row['id']); ?>">Purchase</a>
<?php } }else{ ?> 

    <p>Product(s) not found...</p>
<?php } ?>

Selected product details are displayed with the payment form.

Product Info and Payment Form:

  • The product name and price are displayed at the top of the form.
  • The HTML form collects the user information (name and email) and card details (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 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">
                <input type="text" name="name" id="name" placeholder="Enter name" required="" autofocus="">
            <div class="form-group">
                <input type="email" name="email" id="email" placeholder="Enter email" required="">
            <div class="form-group">
                <label>CARD NUMBER</label>
                <input type="text" name="card_number" id="card_number" placeholder="1234 1234 1234 1234" autocomplete="off" required="">
            <div class="row">
                <div class="left">
                    <div class="form-group">
                        <label>EXPIRY DATE</label>
                        <div class="col-1">
                            <input type="text" name="card_exp_month" id="card_exp_month" placeholder="MM" required="">
                        <div class="col-2">
                            <input type="text" name="card_exp_year" id="card_exp_year" placeholder="YYYY" required="">
                <div class="right">
                    <div class="form-group">
                        <label>CVC CODE</label>
                        <input type="text" name="card_cvc" id="card_cvc" placeholder="CVC" autocomplete="off" required="">
            <button type="submit" class="btn btn-success" id="payBtn">Submit Payment</button>

Validate Card with Stripe.js:

Include the Stripe.js library that helps securely sending the sensitive information to Stripe directly from the browser.

<!-- Stripe JavaScript library -->
<script src=""></script>

Include the jQuery library that helps to control the form submission process.

<!-- jQuery is used only for this example; it isn't required to use Stripe -->
<script src=""></script>

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

  • Use setPublishableKey() function to set your publishable API key that identifies your website to Stripe.
  • The stripeResponseHandler() function creates a single-use token and inserts a token field in the payment form HTML.
// Set your publishable key
Stripe.setPublishableKey('<?php echo $this->config->item('stripe_publishable_key'); ?>');

// Callback to handle the response from stripe
function stripeResponseHandler(status, response) {
    if (response.error) {
        // Enable the submit button
        // Display the errors on the form
    } else {
        var form$ = $("#paymentFrm");
        // Get token id
        var token =;
        // Insert the token into the form
        form$.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
        // Submit form to the server

$(document).ready(function() {
    // On form submit
    $("#paymentFrm").submit(function() {
        // Disable the submit button to prevent repeated clicks
        $('#payBtn').attr("disabled", "disabled");
        // Create single-use token to charge the user
            number: $('#card_number').val(),
            exp_month: $('#card_exp_month').val(),
            exp_year: $('#card_exp_year').val(),
            cvc: $('#card_cvc').val()
        }, stripeResponseHandler);
        // Submit from callback
        return false;

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 } ?>

Make Stripe Payment Gateway Live

Once the Stripe checkout process is working properly, follow the below steps to make Stripe payment gateway live.

  • Login to your Stripe account and navigate to the Developers » API keys page.
  • Collect the API keys (Publishable key and Secret key) from Live Data.
  • In the 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).


The payment portal is a basic piece of the eCommerce site. The Stripe payment entryway assists with making the online payment process easy to use. With Stripe API you can acknowledge the charge card payment on your CodeIgniter site. Our model code makes it simple to accuse a charge card of the Stripe payment passage in CodeIgniter.