Learn how to integrate Stripe payment gateway in CodeIgniter 4

             A payment gateway is a crucial component of any e-commerce site or application that requires payment processing. The CodeIgniter 4 Stripe payment gateway integration is one of the simplest and most powerful solutions available. The Stripe payment gateway API offers a streamlined way to integrate a credit card payment option on a website. With the Stripe API, users can make online payments using their credit or debit cards. A credit card checkout system can easily be implemented on a web application using the Stripe payment gateway in CodeIgniter 4.

Codeigniter 4 Stripe Payment Gateway: Fast & Secure Payment Integration

Table Of Content

1 Prerequisites

1.) PHP version of 8.2
2.) Composer
3.) Mysql
4.) Stripe Business Account

2 Introduction

In this tutorial, we show you how to integrate the Stripe payment gateway in CodeIgniter 4 and accept credit card payments on a website with the Stripe API.

3 Create / Install a Codeigniter 4 Project

3.1 Install Codeigniter 4 Project

First, make sure your computer has a composer.
Use the following command to install new Codeigniter Project.

composer create-project codeigniter4/appstarter ci-4-stripe-app

Then, navigate to your project directory:

cd ci-4-stripe-app

3.2 Configure Environment and MySql Database

Rename the env file to .env and set the development mode in the .env file also configure mysql:

# CI_ENVIRONMENT = production
CI_ENVIRONMENT = development


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ci4_stripe
DB_USERNAME=root
DB_PASSWORD=

4 Install the Stripe Library

To install the Stripe library in CodeIgniter 4, run:

composer require stripe/stripe-php

5 Configure Stripe Keys

Add your Stripe API keys in the .env file, which you can find on your Stripe account dashboard under Developers > API Keys.

    # STRIPE
    stripe.key = 'pk_test_XXXXXX'
    stripe.secret = 'sk_test_XXXXXX'
    

6 Create A Model and Migration

Set up a migration for the payments table and a model to manage the data.

php spark make:model PaymentModel

Edit app/Models/PaymentModel.php to configure fields for managing payment data.

<?php
namespace App\Models;

use CodeIgniter\Model;

class PaymentModel extends Model
{
    protected $table = 'payments';
    protected $primaryKey = 'id';
    protected $allowedFields = ['charge_id','transaction_id','amount','card_id','card_last_four','card_exp_month','card_exp_year','postal_code','created_at'];
}

Create a migration file for the payments table:

php spark make:migration AddPayment

Edit the migration file to define the table structure:

<?php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddPayment extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type' => 'BIGINT',
                'constraint' => 255,
                'unsigned' => true,
                'auto_increment' => true
            ],
            'charge_id' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
           'transaction_id' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'amount' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'card_id' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'card_last_four' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'card_exp_month' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'card_exp_year' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'postal_code' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'created_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
            'updated_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
        ]);
        $this->forge->addPrimaryKey('id');
        $this->forge->createTable('payments');
    }

    public function down()
    {
        $this->forge->dropTable('payments');
    }
}


Run the migration:

php spark migrate

7 Create New Controller (StripeController)

Generate a StripeController to handle payment logic:

php spark make:controller StripeController

Add index and createCharge methods to manage payment processes.

<?php
namespace App\Controllers;
 
use App\Controllers\BaseController;
use Stripe;
use App\Models\PaymentModel;

 
class StripeController extends BaseController
{
    public function index()
    {
        return view('index');
    }
 
    public function createCharge()
    {
        Stripe\Stripe::setApiKey(getenv('stripe.secret'));
      $charge=  Stripe\Charge::create ([
                "amount" => 10 * 100,
                "currency" => "cad",
                "source" => $this->request->getVar('stripeToken'),
                "description" => "Get Sample Code - Stripe Test  Card Payment"
        ]);
       
        $model = new PaymentModel();
        $data = [
            'charge_id'    => $charge->id,
            'transaction_id' => $charge->balance_transaction,
            'amount' => number_format(($charge->amount)/100,2),
            'card_id' => $charge->source->id,
            'card_last_four' => $charge->source->last4,
            'card_exp_month' => $charge->source->exp_month,
            'card_exp_year' => $charge->source->exp_year,
            'postal_code' => $charge->source->address_zip,
            'created_at' => date('Y-m-d H:i:s'),
        ];
        $model->save($data);


        return redirect()->back()->with('success', 'Card Payment Successful!');
  
    }
     
}
?>

8 Create Index View File

Create an index.php file in app/Views to display the payment form.


   <!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-4">
                <div class="card">
                    <div class="card-body">
                        <?php if (session()->getFlashdata('success')) { ?>
                            <div 
                                style="color: green;
                                    border: 2px green solid;
                                    text-align: center;
                                    padding: 5px;margin-bottom: 10px;">
                                <?php echo session()->getFlashdata('success');?>
                            </div>
                        <?php } ?>
                        <form id='checkout-form' method='post' action="<?php echo base_url('/stripe/create-charge'); ?>">             
                            <input type='hidden' name='stripeToken' id='stripe-token-id'>                              
                            <label for="card-element" class="mb-5">Checkout Forms</label>
                            <br>
                            <div id="card-element" class="form-control" ></div>
                            <button 
                                id='pay-btn'
                                class="btn btn-success mt-3"
                                type="button"
                                style="margin-top: 20px; width: 100%;padding: 7px;"
                                onclick="createToken()">PAY $10
                            </button>
                        <form>
                    </div>
                </div>
            </div>
        </div>
    </div>
  
    <script src="https://js.stripe.com/v3/" ></script>
    <script>
        var stripe = Stripe("<?php echo getenv('stripe.key') ?>");
        var elements = stripe.elements();
        var cardElement = elements.create('card');
        cardElement.mount('#card-element');
   
        function createToken() {
            document.getElementById("pay-btn").disabled = true;
            stripe.createToken(cardElement).then(function(result) {
   
                   
                if(typeof result.error != 'undefined') {
                    document.getElementById("pay-btn").disabled = false;
                    alert(result.error.message);
                }
   
                // creating token success
                if(typeof result.token != 'undefined') {
                    document.getElementById("stripe-token-id").value = result.token.id;
                    document.getElementById('checkout-form').submit();
                }
            });
        }
    </script>
</body>
</html>

9 Define a Route

Define the routes for StripeController in app/Config/Routes.php to map URL paths to the payment processing methods.


use CodeIgniter\Router\RouteCollection;
$routes->get('/', 'Home::index');
$routes->get('/stripe', 'StripeController::index');
$routes->post('/stripe/create-charge', 'StripeController::createCharge');

10 Folder Structure

11 Run Web Server to Test the App

Use this command to start the server and test the application:

php spark serve

Visit the URL http://localhost:8080/index.php/stripe

12 Conclusion

This example code makes it straightforward to integrate the CodeIgniter 4 Stripe payment gateway, enabling easy credit card processing on your site.

Reference URL

Tags