Codeigniter 4 Stripe Integration Example

Stripe payment gateway integration in codeigniter 4; In this tutorial, i will show you step by step guide on how to integrate stripe payment gateway in codeigniter 4 app

For codeigniter 4 stripe payment gateway integration example; I create a simple three buttons on form. And implement javascript api of stripe payment gateway in codeigniter 4 app.

How to Integrate Stripe Payment Gateway In Codegniter 4

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Install stripe package Via Composer
  • Connect App to Database
  • Create Stripe Controller Class
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

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

Step 3 – Install stripe package Via Composer

Install strip package vie composer; so open your terminal and execute the following command on it:

composer require stripe/stripe-php

To use the bindings, use the Composer’s autoload

require_once('vendor/autoload.php');

Step 4 – Connect App to Database

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

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

Step 5 – Create Stripe Controller Class

Create StripeController.php file. So, visit app/Controllers directory and create StripeController.php.Then add the following code into it:

<?php namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;

class StripeController extends Controller
{


    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 tutsmake.com." 
        ]);
            
       // after successfull payment, you can store payment related information into your database
             
        $data = array('success' => true, 'data'=> $stripe);

        echo json_encode($data);
    }

}
  • The index() function renders stripe payment template into the view.

Step 6 – Create Views

Create home.php view file, so visit app/views/ directory and create home.php file. Then add the following HTML into home.php file:

<!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 - laratutorials.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">
 
  function pay(amount) {
    var handler = StripeCheckout.configure({
      key: 'pk_test_5f6jfFP2ZV5U9TXQYG0vtqFJ00eFVWNoRX', // your publisher key id
      locale: 'auto',
      token: function (token) {
        // You can access the token ID with `token.id`.
        // Get the token ID to your server-side code for use.
        console.log('Token Created!!');
        console.log(token)
        $('#token_response').html(JSON.stringify(token));
 
        $.ajax({
          url:"<?php echo base_url(); ?>StripeController/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 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

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

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

Stripe payment gateway integration in codeigniter 4; In this tutorial, You have learned how to integrate stripe payment gateway in codeigniter 4 app

Recommended CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4
  3. Codeigniter 4 Form Validation Example Tutorial
  4. How to add jQuery Validation on Form in Codeigniter 4 Example
  5. Codeigniter 4 Ajax Form Submit Validation Example
  6. Codeigniter 4 File Upload Validation Example
  7. Image Upload with Validation in Codeigniter 4
  8. Codeigniter 4 Image Upload Preview Using jQuery Example
  9. Codeigniter 4 Ajax Image Upload Preview Example
  10. How to Upload Multiple Images in Codeigniter 4
  11. Codeigniter 4 Multiple Image Upload with Preview
  12. Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
  13. Simple Codeigniter 4 CRUD with Bootstrap and MySQL Example
  14. Codeigniter 4 CRUD with Datatables Example
  15. Codeigniter 4 Image Crop and Save using Croppie Example
  16. Dependent Dropdown using jQuery Ajax in Codeigniter 4
  17. CodeIgniter 4 Rest Api CRUD Example
  18. Codeigniter 4 Login Registration and Logout Example
  19. Get Address from Latitude and Longitude in Codeigniter 4
  20. Codeigniter 4 Google Column Charts Example
  21. Codeigniter 4 Google Place Autocomplete Address
  22. Export Data to Excel Example in Codeigniter 4
  23. Codeigniter 4 Google ReCaptcha V2 Example
  24. Google Pie Chart in Codeigniter 4

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *