Implement Stripe Payment Gateway in CodeIgniter

by Shailender K. 4 minute read 15 views

Stripe integration in CodeIgniter enables secure payments, trusted by most developers for modern digital solutions requiring reliable online transactions.

Key Points

  • Over 90% of developers prefer Stripe for simplified payment gateway integrations in new projects.
  • About 85% of tech teams integrate Stripe for faster checkouts and improved user payment experience.
  • Nearly 70% of businesses rely on Stripe to reduce fraud and ensure PCI-compliant transactions online.

Introduction

Integrating a secure payment gateway is crucial for any modern digital solution. Stripe stands out as one of the most reliable platforms for handling online payments globally, offering flexibility and developer-friendly APIs.

In this guide, you’ll learn how to implement Stripe Checkout in CodeIgniter 4 by building a simple donation system. We’ll walk through installing Stripe’s PHP SDK, configuring environment variables, creating routes, controllers, and designing a user-friendly frontend with Bootstrap 5.3 and jQuery 3.7.

This tutorial is perfect for businesses focused on web app development and those exploring advanced technical integrations.

Prerequisite: Create a Stripe Account

Before coding:

  1. Go to the Stripe Dashboard Signup and create or log in to your account.

  2. Navigate to Developers → API keys.

  3. Copy your:

  • Publishable key (starts with pk_test_...)
  • Secret key (starts with sk_test_...)

These keys are essential for secure integrations and are a routine part of many custom software development projects.

1. Install Stripe PHP SDK via Composer

Run this in your CodeIgniter 4 project root:

                                        composer require stripe/stripe-php
                                    

Why install the SDK?

Stripe’s official PHP SDK streamlines communication with their API and handles errors gracefully. Without it, developers would have to manually manage HTTP requests and JSON processing—a tedious process that’s best avoided if you plan to hire PHP developer talent to maintain robust integrations.

2. Configure Stripe API Keys

Instead of hardcoding your API keys, store them securely in the .env file:

                                        	STRIPE_SECRET_KEY=your_secret_key
	STRIPE_PUBLISHABLE_KEY=your_publishable_key
                                    

CodeIgniter’s .env file makes managing environment variables simple. It’s a helpful feature for any web app development company aiming for clean and maintainable codebases.

3. Create Routes

Open app/Config/Routes.php and add these routes:

                                        		use CodeIgniter\Router\RouteCollection;


$routes->get('donate', 'PaymentController::donate');
$routes->post('stripe/payment', 'PaymentController::payment');
$routes->get('stripe/payment-success/', 'PaymentController::payment_success');
$routes->get('stripe/payment-cancel', 'PaymentController::payment_cancel');
                                    

Defining precise routes ensures your payment flow remains organized and scalable, which is key in successful web app development projects.

4. Create the Payment Controller

Create the following file:

                                        namespace App\Controllers;
              
use App\Controllers\BaseController;
            use CodeIgniter\Database\BaseConnection;
class PaymentController extends BaseController {
    protected $session;
    
    public function __construct(){
        $this->session = \Config\Services::session();        
    }

    
	    // ---------------------------- Donation Page -------------------------------------
   	    public function donate(){
	        return view('index');
	    }
		    
	    // ---------------------------- Checkout Session ----------------------------------
	    public function payment() {
	        $secretKey = env('STRIPE_SECRET_KEY'); 
	        \Stripe\Stripe::setApiKey($secretKey);
	        $amount = $this->request->post('amount');
	        if ($amount < 1) {
		return $this->response->setStatusCode(400)->setJSON([
			 'error' => 'Invalid amount'
		 ]);
	        }
	        try {            
	            $session = \Stripe\Checkout\Session::create([
	                'payment_method_types' => ['card'],
	                'line_items' => [
	                    [
	                        'price_data' => [
	                            'currency' => 'usd',
	                            'product_data' => [
	                                'name' => 'Donation',
	                            ],
	                            'unit_amount' => $amount * 100, // Convert to cents
	                        ],
	                        'quantity' => 1,
	                    ]
	                ],
	                'mode' => 'payment',
	                'success_url' => base_url('stripe/payment-success'),
	                'cancel_url' => base_url('stripe/payment-cancel'),
	            ]);
	            return redirect()->to($session->url);
	        } catch (\Exception $e) {
            return $this->response->setStatusCode(500)->setJSON([
	                'error' => $e->getMessage()
	            ]);
	        }
	    }

	    // ---------------------------- Success Page --------------------------------------
	    public function payment_success() {
	        return view('payment_success');
	    }

	    // ---------------------------- Cancel Page ---------------------------------------
	    public function payment_cancel(){
	        return view('payment_cancle');
	    }
	}
                                    

This controller structure is commonly used in custom software development, ensuring business logic is separate from presentation layers for better maintainability.

5. Create the Donation Form View

                                        <!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Donate</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/css/bootstrap.min.css"
      rel="stylesheet">
  </head>
  <body>
    <div class="container mt-5">
      <h2 class="mb-4 text-center">Make a Donation</h2>
      <?php if (session()->getFlashdata('error')): ?>
      <div class="alert alert-danger">
        <?= session()->getFlashdata('error') ?>
      </div>
      <?php endif; ?>
      <form id="donation_form" method="POST" action="<?= base_url('stripe/payment'); ?>">
        <div class="mb-3">
          <label for="donation_amount" class="form-label">
          Donation Amount (USD)
          </label>
          <!-- step="1" use to prevent decimals value -->
          <input type="number" class="form-control" id="donation_amount"
            name="amount" min="1" step="1" required>
        </div>
        <button type="submit" id="submitDonation" class="btn btn-warning w-100 mb-3">
        Donate with <span id="button_name">Stripe</span>
        </button>
      </form>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/js/bootstrap.bundle.min.js"> </script>
  </body>
</html>
                                    

The frontend is built with Bootstrap, making it user-friendly and responsive—an essential consideration for any project delivered by a web app development company.

Create Success Views

Optionally, create:

                                        app/Views/payment_success.php

<h2>Payment Successful!</h2>
<p>Thank you for your donation.</p>
                                    

Create Cancel Views

                                        app/Views/payment_cancel.php

<h2>Payment Cancelled</h2>
<p>Your payment was cancelled.</p>
                                    

Testing Your Integration

Visit your site at:

http://yourdomain.test/donate

Steps to test:

  • Enter an amount

  • Click Donate with Stripe

  • You’ll be redirected to Stripe’s secure checkout page

  • Use this test card:

Card Number: 4242 4242 4242 4242

Expiry: any future date

CVC: any 3 digits

ZIP: any 5 digits

  • Complete payment

  • View your success or cancellation page

Final Words

Well done! You’ve successfully integrated Stripe Checkout in CodeIgniter 4. This is a valuable capability for anyone working in web app development or planning large-scale platforms requiring secure online payments.

Whether you want to hire PHP developer professionals for complex integrations or collaborate with a web app development company, this guide provides a solid foundation for building robust payment solutions.

Tech Stack & Version

Frontend

  • Bootstrap 5.3
  • jQuery 3.7
  • HTML5
  • CSS3

Backend

  • PHP 8
  • CodeIgniter 4.0
  • Stripe PHP SDK

Deployment

  • Apache
  • Ubuntu
  • HTTPS
  • MySQL
  • MariaDB
img

©2025Digittrix Infotech Private Limited , All rights reserved.