Codeigniter 4 Stripe Payment Gateway Integration Tutorial

In this guide, we will elaborate on how to implement a Stripe payment gateway in Codeigniter 4 application with the help of the Stripe PHP package and Stripe secret keys.

This Codeigniter 4 Stripe payment gateway example will show you how to make the perfect coherence between Stripe and Codeigniter systems.

Suppose you struggle to add Stripe in Codeigniter and don’t know a thing about both. Generally, a payment gateway feature is significantly essential for eCommerce sites.

A payment gateway allows users to purchase either service or products right at the website; after checking out, the user can make a payment. There are plenty of payment gateway options available, but we chose to implement a stripe payment gateway in Codeigniter.

How to Add Stripe Payment Gateway in Codeigniter App

  • Step 1: Install Codeigniter App
  • Step 2: Generate Stripe API Keys
  • Step 3: Set Up PHP Stripe Pacakage
  • Step 4: Create New Controller
  • Step 5: Register New Route
  • Step 6: Build Codeigniter View
  • Step 7: View App in Browser

Install Codeigniter App

A Composer command allow you to dynamically install the Codeigniter application on your development machine.

composer create-project codeigniter4/appstarter

You can head over to, official site and manually download the Codeigniter app’s latest version.

Thereafter, unzip the project folder, change the project name based on your choice.

Generate Stripe API Keys

Here is the eloquent instructions that will help you to generate the Stripe API Keys (Secret Key and Publishable Key):

STEP 1: Log in to your Stripe dashboard.

STEP 2: Click on Developers and API in the left menu.

STEP 3: You will find, secret and publishable keys on this page. Make sure to turn on the toggle button which says “Viewing test data”.

STEP 4: Eventually, click on Reveal live key token.

Set Up Stripe Pacakage in Codeigniter

Installing the Stripe PHP library through the Composer is subtle and straightforward; you can install the bindings via Composer. Here is the command that installs the package.

composer require stripe/stripe-php

To use the bindings, use Composer’s autoload:

require_once('vendor/autoload.php');

If you do not want to rely on Composer and wants to manually install the package, you can download the latest version.

Further, to use the bindings, include the init.php file.

require_once('/path/to/stripe-php/init.php');

Creating a New Controller

The controller is the basic building block of CI app development; after all, all the logic goes into it.

After that, you have to create a new controller file and paste the provided code into the app/Controllers/StripeController.php.

<?php

namespace App\Controllers;
use CodeIgniter\Controller;


class StripeController extends Controller
{

    public function index()
    {
        return view('payment');
    }
        
    public function stripePayment()
    {
      require_once('application/libraries/stripe-php/init.php');
      $stripeSecret = 'sk_test_51H7bbSxxxxxxxxxxxxx';
 
        \Stripe\Stripe::setApiKey($stripeSecret);
      
        $stripe = \Stripe\Charge::create ([
                "amount" => $this->request->getVar('amount'),
                "currency" => "usd",
                "source" => $this->request->getVar('pk_test_51H7bbSxxxxxxxxxxxxx'),
                "description" => "You have just made the test payments."
        ]);
             
        $paymentData = array('success' => true, 'data'=> $stripe);
        
        echo '<pre>' , var_dump($paymentData) , '</pre>';

    }   

}

Register New Routes

Routes communicates with a controller, basically the code which handles the logic integrated into it.

Go ahead and insert the suggested code into app/Config/Routes.php file.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/

$routes->setDefaultController('StripeController');
$routes->get('/payment-stripe', 'StripeController::index');

Build Codeigniter View

Theoretically, the primary task has been done. In this section, you have to create the view file and create simple buttons for handling the payment. We will tie these buttons with the function, which will invoke when clicked on it.

Add the provided code into the app/Views/payment.php.

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Integrate Stripe Payment Gateway in Codeigniter 4</title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
  <div class="container">

    <pre id="getTokenRes"></pre>

    <div class="d-grid mb-3">
      <button class="btn btn-dark" onclick="handlePayment(50)">Pay $50</button>
    </div>
    <div class="d-grid mb-3">
      <button class="btn btn-danger" onclick="handlePayment(100)">Pay $100</button>
    </div>
    <div class="d-grid">
      <button class="btn btn-warning" onclick="handlePayment(200)">Pay $200</button>
    </div>
    
  </div>

  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script src="https://checkout.stripe.com/checkout.js"></script>
  <script type="text/javascript">
    function handlePayment(amount) {
      var handler = StripeCheckout.configure({
        key: 'pk_test_51H7bbSxxxxxxxxxxxxx',
        locale: 'auto',
        token: function (token) {
          console.log('Token Generated' + token);
          $('#getTokenRes').html(JSON.stringify(token));
          $.ajax({
            url: "<?php echo base_url(); ?>StripeController/stripePayment",
            method: 'post',
            data: {
              tokenId: token.id,
              amount: amount
            },
            dataType: "json",
            success: function (response) {
              console.log(response.data);
              $('#getTokenRes').append('<br />' + JSON.stringify(response
                .data));
            }
          })
        }
      });
      handler.open({
        name: 'RS Shopping Commerce',
        description: '2 Widgets',
        amount: amount * 50
      });
    }
  </script>
</body>

</html>

View App in Browser

Next, you are absolutely ready to test the app, why don’t you run the given command and start the CI server.

php spark serve

Now, Just paste the given url on the browser to view the app.

http://localhost:8080/payment-stripe

For making test payments, you can use the fake Credit Card details.

Name:     Test
Number:   4242 4242 4242 4242
Cvc:      456
Expiry:   12/25

Codeigniter 4 Stripe Payment Gateway Integration Tutorial

Summary

Using this step-by-step guide, anyone can effectively integrate a stripe payment gateway in Codeigniter. We highlighted all the essentials which help you swiftly integrate stripe in the Codeigniter app, and this comprehensive guide might solve a bit transactional problem of the web store.