Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

CodeIgniter 4 Stripe Payment Gateway Integration Tutorial

Last Updated on August 25, 2024 by

Stripe provides PHP libraries that allow developers to easily integrate the Stripe payment gateway into PHP frameworks such as CodeIgniter or Laravel.

Let’s start integrating the Stripe payment gateway into the application:

Step 1: Install Stripe PHP Library

Run the following command to install PHP stripe library using composer command:

composer require stripe/stripe-php

Step 2: Set Up Stripe API Keys

Edit the .env file located at the root of your project, and set up stripe api keys:

# Stripe API Keys
STRIPE_PUBLISHABLE_KEY=your_publishable_key_here
STRIPE_SECRET_KEY=your_secret_key_here

Step 3: Create a Stripe Controller

Go to app/Controllers directory and create a file named StripeController.php, and implement payment collection method in it:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use Stripe\Stripe;
use Stripe\Checkout\Session;

class StripeController extends Controller
{
    public function __construct()
    {
        // Load the Stripe API keys from the environment file
        Stripe::setApiKey(env('STRIPE_SECRET_KEY'));
    }

    public function index()
    {
        return view('stripe_payment');
    }

    public function createCheckoutSession()
    {
        header('Content-Type: application/json');

        $YOUR_DOMAIN = base_url();

        try {
            $checkout_session = Session::create([
                'payment_method_types' => ['card'],
                'line_items' => [[
                    'price_data' => [
                        'currency' => 'usd',
                        'product_data' => [
                            'name' => 'T-shirt',
                        ],
                        'unit_amount' => 2000, // Amount in cents
                    ],
                    'quantity' => 1,
                ]],
                'mode' => 'payment',
                'success_url' => $YOUR_DOMAIN . '/success',
                'cancel_url' => $YOUR_DOMAIN . '/cancel',
            ]);

            echo json_encode(['id' => $checkout_session->id]);
        } catch (\Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => $e->getMessage()]);
        }
    }
}

Step 4: Create a View for Stripe Payment

Go to app/Views directory and create a file named stripe_payment.php, and add html and stripe script in it:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stripe Payment Gateway in CodeIgniter 4 - itcodstuff.com</title>
    <script src="https://js.stripe.com/v3/"></script>
</head>
<body>
    <h1>Stripe Payment</h1>
    <button id="checkout-button">Checkout</button>

    <script type="text/javascript">
        var stripe = Stripe("<?= env('STRIPE_PUBLISHABLE_KEY') ?>");

        var checkoutButton = document.getElementById('checkout-button');

        checkoutButton.addEventListener('click', function () {
            fetch('/stripe/createCheckoutSession', {
                method: 'POST',
            })
            .then(function (response) {
                return response.json();
            })
            .then(function (sessionId) {
                return stripe.redirectToCheckout({ sessionId: sessionId.id });
            })
            .then(function (result) {
                if (result.error) {
                    alert(result.error.message);
                }
            })
            .catch(function (error) {
                console.error('Error:', error);
            });
        });
    </script>
</body>
</html>

Step 5: Define Routes

Edit app/Config/Routes.php file, and define routes for the Stripe payment:

$routes->get('stripe', 'StripeController::index');
$routes->post('stripe/createCheckoutSession', 'StripeController::createCheckoutSession');
$routes->get('success', function() {
    return view('payment_success');
});
$routes->get('cancel', function() {
    return view('payment_cancel');
});

Step 6: Create Success and Cancel Views

In the app/Views directory, create two files: payment_success.php and payment_cancel.php.

payment_success.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Success using stripe in ci4 - itcodstuff.com</title>
</head>
<body>
    <h1>Payment Successful</h1>
    <p>Your payment was processed successfully.</p>
</body>
</html>

payment_cancel.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Cancelled - itcodstuff.com</title>
</head>
<body>
    <h1>Payment Cancelled</h1>
    <p>Your payment was cancelled. Please try again.</p>
</body>
</html>

Step 7: Test the Integration

Type url http://localhost:8080/stripe on your browser and you will see the Stripe checkout button. When you click the button, it will redirect you to the Stripe payment page where you can complete the payment.

Leave a Comment