Table of Contents
As we all know in most web application either in CodeIgniter 4 or any of the PHP Framework, we sometimes need to integrate payment gateway. Inside this article, we will see Stripe payment Integration in codeIgniter 4. Stripe payment system settings in CodeIgniter 4. Easy and in complete detailed concept.
Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started – Stripe payment gateway in CodeIgniter 4
Download & Install CodeIgniter 4 Setup
We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –
- Manual Download
- Composer Installation
- Clone Github repository of CodeIgniter 4
Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.
Here is the command to install via composer –
$ composer create-project codeigniter4/appstarter codeigniter-4
Assuming you have successfully installed application into your local system.
Settings Environment Variables
When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env
Open project in terminal
$ cp env .env
Above command will create a copy of env file to .env file. Now we are ready to use environment variables.
CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.
# CI_ENVIRONMENT = production // Do it to CI_ENVIRONMENT = development
Now application is in development mode.
Stripe PHP Package Installation
We will install stripe package via composer into CodeIgniter 4 setup. Open CodeIgniter 4 project in terminal and hit this composer command.
$ composer require stripe/stripe-php

Autoload Stripe Library
Open Autoload.php from /app/Config. Find $psr4 and add stripe library.
# Add Library public $psr4 = [ APP_NAMESPACE => APPPATH, // For custom app namespace 'Config' => APPPATH . 'Config', 'Stripe' => ROOTPATH . 'vendor/stripe/stripe-php/init.php' // added here ];
Set Stripe API Key and SECRET
Open up /app/Config/Constants.php file of CodeIgniter 4 application. Into the file, set stripe api key and secret.
defined("STRIPE_KEY") || define('STRIPE_KEY', "pk_test_MaQhP2b8XqG9R7PTL6VUmipt"); defined("STRIPE_SECRET") || define('STRIPE_SECRET', "sk_test_MtVxg0tJfCGJXQY8xZlu69Ie");
This is our stripe sandbox detail, you can replace it with your own. If you are wondering to find stripe test account keys. Follow these steps –
- Login to https://dashboard.stripe.com/

- You need to enable Viewing test data to use Test account details
- Go to Developer >> Click on API keys
Create Routes
Next, need to set few routes. To configure routes, open up /app/Config/Routes.php file.
//.. Other routes $routes->get("stripe", "StripeController::stripe"); $routes->post("payment", "StripeController::payment");
Create Controller File
Create application controller in setup.
$ php spark make:controller Stripe --suffix
It will create a controller file /app/Controllers/StripeController.php .
Open StripeController.php and paste the given code.
<?php namespace App\Controllers; use App\Controllers\BaseController; use Stripe; class StripeController extends BaseController { /** * Get All Data from this method. * * @return Response */ public function __construct() { helper(["url"]); } /** * Get All Data from this method. * * @return Response */ public function stripe() { return view("stripe"); } /** * Get All Data from this method. * * @return Response */ public function payment(){ Stripe\Stripe::setApiKey(STRIPE_SECRET); $stripe = Stripe\Charge::create ([ "amount" => 70 * 100, "currency" => "usd", "source" => $_REQUEST["stripeToken"], "description" => "Test payment via Stripe From onlinewebtutorblog.com" ]); // after successfull payment, you can store payment related information into your database //$data = array('success' => true, 'data' => $stripe); //echo json_encode($data); session()->setFlashdata("message", "Payment done successfully"); return redirect('stripe'); } }
Create Template File
Let’s create template file for setting the layout of payment details for user. Create a file stripe.php inside /app/Views. Open file and paste the given code
<!DOCTYPE html> <html> <head> <title>CodeIgniter 4 - Stripe Payment Gateway Integration - onlinewebtutorblog.com</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style type="text/css"> .panel-title { display: inline; font-weight: bold; } .display-table { display: table; } .display-tr { display: table-row; } .display-td { display: table-cell; vertical-align: middle; width: 61%; } </style> </head> <body> <div class="container"> <h3 style="text-align: center;">CodeIgniter 4 - Stripe Payment Gateway Integration - onlinewebtutorblog.com</h3><br /> <?php if (session()->get("message")) { ?> <div class="alert alert-success"> <?= session()->get("message") ?> </div> <?php } ?> <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="panel panel-default credit-card-box"> <div class="panel-body"> <form role="form" action="<?php echo base_url('payment') ?>" method="post" class="require-validation" data-cc-on-file="false" data-stripe-publishable-key="<?= STRIPE_KEY ?>" id="payment-form"> <div class='form-row row'> <div class='col-xs-12 form-group required'> <label class='control-label'>Name on Card</label> <input class='form-control' size='4' type='text'> </div> </div> <div class='form-row row'> <div class='col-xs-12 form-group card required'> <label class='control-label'>Card Number</label> <input autocomplete='off' class='form-control card-number' size='20' type='text'> </div> </div> <div class='form-row row'> <div class='col-xs-12 col-md-4 form-group cvc required'> <label class='control-label'>CVC</label> <input autocomplete='off' class='form-control card-cvc' placeholder='ex. 311' size='4' type='text'> </div> <div class='col-xs-12 col-md-4 form-group expiration required'> <label class='control-label'>Expiration Month</label> <input class='form-control card-expiry-month' placeholder='MM' size='2' type='text'> </div> <div class='col-xs-12 col-md-4 form-group expiration required'> <label class='control-label'>Expiration Year</label> <input class='form-control card-expiry-year' placeholder='YYYY' size='4' type='text'> </div> </div> <div class='form-row row'> <div class='col-md-12 error form-group hide'> <div class='alert-danger alert'>Please correct the errors and try again.</div> </div> </div> <div class="row"> <div class="col-xs-12"> <button class="btn btn-primary btn-lg btn-block" type="submit">Pay Now ($70)</button> </div> </div> </form> </div> </div> </div> </div> </div> </body> <script type="text/javascript" src="https://js.stripe.com/v2/"></script> <script type="text/javascript"> $(function() { var $form = $(".require-validation"); $('form.require-validation').bind('submit', function(e) { var $form = $(".require-validation"), inputSelector = ['input[type=text]'].join(', '), $inputs = $form.find('.required').find(inputSelector), $errorMessage = $form.find('div.error'), valid = true; $errorMessage.addClass('hide'); $('.has-error').removeClass('has-error'); $inputs.each(function(i, el) { var $input = $(el); if ($input.val() === '') { $input.parent().addClass('has-error'); $errorMessage.removeClass('hide'); e.preventDefault(); } }); if (!$form.data('cc-on-file')) { e.preventDefault(); Stripe.setPublishableKey($form.data('stripe-publishable-key')); Stripe.createToken({ number: $('.card-number').val(), cvc: $('.card-cvc').val(), exp_month: $('.card-expiry-month').val(), exp_year: $('.card-expiry-year').val() }, stripeResponseHandler); } }); function stripeResponseHandler(status, response) { if (response.error) { $('.error') .removeClass('hide') .find('.alert') .text(response.error.message); } else { /* token contains id, last4, and card type */ var token = response['id']; $form.find('input[type=text]').empty(); $form.append("<input type='hidden' name='stripeToken' value='" + token + "'/>"); $form.get(0).submit(); } } }); </script> </html>
Application Testing
Now, start development server.
$ php spark serve
here you can test with these given test card details.
URL: http://localhost:8080/stripe
Name: Sample Number: 4242 4242 4242 4242 CSV: 123 Expiration Month: 04 Expiration Year: 2024


We hope this article helped you to learn about Stripe Payment Gateway Integration in CodeIgniter 4 in a very detailed way.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.
Find More on CodeIgniter 4 here
- CodeIgniter 4 Cookie Helper Tutorial
- CodeIgniter 4 CRUD Application Tutorial
- CodeIgniter 4 CRUD REST APIs Tutorial
- CodeIgniter 4 CSRF Token in AJAX Request
- Database Query in CodeIgniter 4 Tutorial
- CodeIgniter 4 Ajax Form Data Submit
- CodeIgniter 4 Form Validation Tutorial
- CodeIgniter 4 Image Upload with Form Tutorial
- Multi language in CodeIgniter 4 Tutorial
- Stripe Payment Gateway Integration in CodeIgniter 4
- CodeIgniter 4 CSRF Token Tutorial
- CodeIgniter 4 Basics Tutorial
- CodeIgniter 4 Spark CLI Commands Tutorial
- Migration in CodeIgniter 4 Tutorial
- Seeders in CodeIgniter 4 Tutorial
Hi, I am Sanjay the founder of ONLINE WEB TUTOR. I welcome you all guys here to join us. Here you can find the web development blog articles. You can add more skills in web development courses here.
I am a Web Developer, Motivator, Author & Blogger. Total experience of 7+ years in web development. I also used to take online classes including tech seminars over web development courses. We also handle our premium clients and delivered up to 50+ projects.