Skip to content

All topics  /  CodeIgniter

Codeigniter 4 Integrate Stripe Payment Gateway Tutorial

CodeIgniter ·

Teams applying “Codeigniter 4 Integrate Stripe Payment Gateway Tutorial” in a production project can use the complete guide to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.

Before copying the example into a live application, confirm version-specific behaviour with CodeIgniter and test it against the project’s actual database and runtime.

Hi Dev,

Today, I will let you know example of how to integrate stripe payment gateway in codeigniter 4 tutorial example. This article will give you simple example of stripe payment gateway in codeigniter 4. I would like to show you integrate stripe payment gateway in codeigniter 4. I would like to show you how to integrate stripe payment gateway.

Codeigniter 4 Stripe payment gateway integration tutorial; In this comprehensive example, you will learn how to implement Stripe Payment Gateway in Codeigniter using the Stripe PHP library and Stripe API key, secret.

Stripe is a notable payment processing for online business; It offers an outstanding infrastructure for payment APIs, which amplifies the transaction of payments for every business type regardless of the company’s size.

So let's start to the example.

Step 1: Install Codeigniter 4


This is optional; however, if you have not created the codeigniter app, then you may go ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news

After Download successfully, extract clean new Codeigniter 4 application.

Step 2 : Basic Configurations

So, we will now set basic configuration on the app/config/app.php file, so let’s implement to application/config/config.php and open this file on text editor.

app/config/app.php

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/example/';

Step 3 : Database Configurations

application/config/database.php

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
];

Step 4 : Install stripe package Via Composer

composer require stripe/stripe-php

To use the bindings, use the Composer’s autoload

require_once('vendor/autoload.php');

Step 5 : Set Up Controller

Further, you need to generate a new controller that manages the online stripe transaction, hence create a StripePayment file and append the example code in..

app/Controllers/StripePaymentController.php

 
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;

 
class StripePaymentController extends Controller
{

 
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view('home');
    }

        
    /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function payment()
    {
        require_once('application/libraries/stripe-php/init.php');

     
        $stripeSecret = 'sk_test_j5k0976GOLSOtiRzbDLpKqat00og5iM3cY';

 
        \Stripe\Stripe::setApiKey($stripeSecret);

      
        $stripe = \Stripe\Charge::create ([
                "amount" => $this->request->getVar('amount'),
                "currency" => "usd",
                "source" => $this->request->getVar('tokenId'),
                "description" => "Test payment from Nicesnippets.com."
        ]);

             
        $data = array('success' => true, 'data'=> $stripe);

 
        echo json_encode($data);
    }

 
}

Step 5 : Add Routes

app/Config/Routes.php

$routes->get('/', 'Stripe::index');

Step 6 : Set Up View

Head over to application/views/ folder, create a new home file. Likewise, open and add the suggested code example in application/views/home.php file:

application/views/home.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Codeigniter 4 Stripe Payment Gateway Integration - Nicesnippets.com</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
        <style>
            .container{
                padding: 0.5%;
            } 
        </style>
    </head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-12"><pre id="token_response"></pre></div>
    </div>
    <div class="row">
        <div class="col-md-4">
            <button class="btn btn-primary btn-block" onclick="pay(100)">Pay $100</button>
        </div>
        <div class="col-md-4">
            <button class="btn btn-success btn-block" onclick="pay(500)">Pay $500</button>
        </div>
        <div class="col-md-4">
            <button class="btn btn-info btn-block" onclick="pay(1000)">Pay $10000</button>
        </div>
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script type="text/javascript">
/*------------------------------------------
--------------------------------------------
Pay 
--------------------------------------------
--------------------------------------------*/
function pay(amount) {
    var handler = StripeCheckout.configure({
        key: 'pk_test_5f6jfFP2ZV5U9TXQYG0vtqFJ00eFVWNoRX',
        locale: 'auto',
        token: function (token) {
            console.log('Token Created!!');
            console.log(token)
            $('#token_response').html(JSON.stringify(token));
            $.ajax({
                url:"<?php echo base_url(); ?>stripe/payment",
                method: 'post',
                data: { tokenId: token.id, amount: amount },
                dataType: "json",
                success: function( response ) {
                    console.log(response.data);
                    $('#token_response').append( '<br />' + JSON.stringify(response.data));
                }
            })
        }
    });
    handler.open({
        name: 'Demo Site',
        description: '2 widgets',
        amount: amount * 100
    });
}
</script>
</body>
</html>

Step :7 Run Codeigniter App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:

php spark serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8080/