How to Integration PayPal Payment Gateway in Codeigniter 4?

Apr 26, 2022 . Admin



Hi Dev,

I will explain a step-by-step tutorial on PayPal payment gateway integration in Codeigniter 4 example. I’m going to show you the PayPal payment gateway in Codeigniter 4. I’m going to show you about PayPal payment gateway integration in Codeigniter 4 source code. I would like to show you PayPal integration in the Codeigniter 4 demo. You just need to do some steps to do PayPal payment integration in Codeigniter 4.

In this example, I will show you an easy and simple way to integrate the PayPal payment gateway on Codeigniter 4 framework. I will learn you step by step to integrate the PayPal payment gateway in Codeigniter 4 as follow bellow step.

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
Step 2 : Download Paypal Payment Gateway Library

In this step First of all we need to download paypal payment gateway library for codeigniter.

You can download the PayPal payment gateway library website link is here Paypal Payment Gateway library for Codeigniter 4.

In this library holds two files named paypal_lib, paypallib_config, you can put the file according to the below steps:

paypal_lib.php file => will be placed in the application/libraries/ directory paypallib_config.php file => will be placed in the application/config/ directory. Step 3 : Create Database Tables

In this step, You will need to create two table like products and payment table. Product table in basic product information and payment table in payment data with basic information like user_id, payment_id, product_id, txt_id or currency code, etc.

products table
CREATE TABLE `products` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `price` float(10,2) NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
payments table
CREATE TABLE `payments` (
 `payment_id` int(11) NOT NULL AUTO_INCREMENT,
 `user_id` int(11) NOT NULL,
 `product_id` int(11) NOT NULL,
 `txn_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `payment_gross` float(10,2) NOT NULL,
 `currency_code` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
 `payer_email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `payment_status` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`payment_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Step 4 : Create New Controller

First of all you will create controller. In paypal controller, we need to create five methods, index(), buyProduct(), success(), cancel(), and ipn().

application/controller/paypalController.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    function  __construct() {
        parent::__construct();
        $this->load->library('paypal_lib');
        $this->load->model('product');
        $this->load->database();
    }
     
    /**
     * Write code on Method
     *
     * @return response()
     */
    function index(){
        $data = array();
        $data['products'] = $this->product->getProducts();
        $this->load->view('products/index', $data);
    }
     
    /**
     * Set variables for paypal form
     *
     * @return response()
     */ 
    function buyProduct($id){
        $returnURL = base_url().'paypal/success'; 
        $failURL = base_url().'paypal/fail'; 
        $notifyURL = base_url().'paypal/ipn';
        $product = $this->product->getProducts($id);
        $userID = 1; //current user id
        $logo = base_url().'Your_logo_url';
         
        $this->paypal_lib->add_field('return', $returnURL);
        $this->paypal_lib->add_field('fail_return', $failURL);
        $this->paypal_lib->add_field('notify_url', $notifyURL);
        $this->paypal_lib->add_field('item_name', $product['name']);
        $this->paypal_lib->add_field('custom', $userID);
        $this->paypal_lib->add_field('item_number',  $product['id']);
        $this->paypal_lib->add_field('amount',  $product['price']);        
        $this->paypal_lib->image($logo);
         
        $this->paypal_lib->paypal_auto_form();
    }

    /**
     * get the transaction data
     *
     * @return response()
     */ 
    function paymentSuccess(){
        $paypalInfo = $this->input->get();
           
        $data['item_number'] = $paypalInfo['item_number']; 
        $data['txn_id'] = $paypalInfo["tx"];
        $data['payment_amt'] = $paypalInfo["amt"];
        $data['currency_code'] = $paypalInfo["cc"];
        $data['status'] = $paypalInfo["st"];
        $this->load->view('paypal/paymentSuccess', $data);
    }
     
    /**
     * if transaction cancelled
     *
     * @return response()
     */  
    function paymentFail(){
        $this->load->view('paypal/paymentFail');
     }
     
    /**
     * paypal return transaction details array
     *
     * @return response()
     */  
    function ipn(){
        $paypalInfo = $this->input->post();
 
        $data['user_id'] = $paypalInfo['custom'];
        $data['product_id']    = $paypalInfo["item_number"];
        $data['txn_id']    = $paypalInfo["txn_id"];
        $data['payment_gross'] = $paypalInfo["mc_gross"];
        $data['currency_code'] = $paypalInfo["mc_currency"];
        $data['payer_email'] = $paypalInfo["payer_email"];
        $data['payment_status']    = $paypalInfo["payment_status"];
 
        $paypalURL = $this->paypal_lib->paypal_url;        
        $result    = $this->paypal_lib->curlPost($paypalURL,$paypalInfo);
         
        if(preg_match("/VERIFIED/i",$result)){
            $this->product->storeTransaction($data);
        }
    }
}
Step 5 : Create Paypal Model

After then, we need to create paypal model. In PayPal model, we need to create two methods, getProducts(), StoreTransaction().

application/models/Paypal.php

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Product extends CI_Model{

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function __construct()
    {
        $this->load->database();
    }

    /**
     * get and return product rows
     *
     * @return response()
     */
    public function getProducts($id = ''){
        $this->db->select('id,name,image,price');
        $this->db->from('products');
        if($id){
            $this->db->where('id',$id);
            $query = $this->db->get();
            $result = $query->row_array();
        }else{
            $this->db->order_by('name','asc');
            $query = $this->db->get();
            $result = $query->result_array();
        }
        return !empty($result)?$result:false;
    }
 
    /**
     * insert transaction data
     *
     * @return response()
     */
    public function storeTransaction($data = array()){
        $insert = $this->db->insert('payments',$data);
        return $insert?true:false;
    }
}
Step 6 : Create View

In this step, You will create two folder named products and paypal. you will create views files where we will show the product listing and payment-related information like payment success or fail details.

application/views/products/index.php
<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter Paypal Integration Example - Mywebtuts.com</title>
  <!-- Latest CSS -->
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
</head>
<body>
  <div class="container">
    <h2 class="mt-3 mb-3">Products</h2>
    <div class="row">
        <?php if(!empty($products)): foreach($products as $product): ?>
        <div class="thumbnail">
            <img src="<?php echo base_url().'assets/images/'.$product['image']; ?>" alt="">
            <div class="caption">
                <h4 class="pull-right">$<?php echo $product['price']; ?></h4>
                <h4><a href="javascript:void(0);"><?php echo $product['name']; ?></a></h4>
            </div>
            <a href="<?php echo base_url().'products/buyProduct/'.$product['id']; ?>"><img src="<?php echo base_url(); ?>assets/images/buy-button" style="width: 70px;"></a>
        </div>
        <?php endforeach; endif; ?>
    </div>
  </div>
</body>
</html>

You can go to application/views/paypal folder,

now you will create a new file paymentSuccess.php and put the below code into your file:

application/views/paypal/paymentSuccess.php
<!DOCTYPE html>
<html>
<head>
  <title>Transaction Successfull - Codeigniter Paypal Integration Example - Mywebtuts.com</title>
  <!-- Latest CSS -->
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
</head>
<body>
  <div class="container">
    <h2 class="mt-3 mb-3">Transaction Detalis</h2>
    <div class="row">
          <span>Your payment was successful done, thank you for purchase.</span><br/>
          <span>Item Number : 
              <strong><?php echo $item_number; ?></strong>
          </span><br/>
          <span>TXN ID : 
              <strong><?php echo $txn_id; ?></strong>
          </span><br/>
          <span>Amount Paid : 
              <strong>$<?php echo $payment_amt.' '.$currency_code; ?></strong>
          </span><br/>
          <span>Payment Status : 
              <strong><?php echo $status; ?></strong>
        </span><br/>
    </div>
  </div>
</body>
</html>

You can go to application/views/paypal folder,

You will create a new file paymentFail.php.php and put the below code into your file:

application/views/paypal/paymentFail.php
<!DOCTYPE html>
<html>
<head>
  <title>Transaction Fail - Codeigniter Paypal Integration Example - Mywebtuts.com</title>
  <!-- Latest CSS -->
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
</head>
<body>
  <div class="container">
    <h2 class="mt-3 mb-3">Transaction Detalis</h2>
    <div class="row">
       <p>Sorry! Your last transaction was cancelled.</p>
    </div>
  </div>
</body>
</html>
Note:- Paypal Payment Gateway Live

If your test PayPal transaction is worked properly using the PayPal sandbox account. You want to make it live your PayPal payment gateway.

So Open the application/config/paypallib_config.php and change the following two configuration values

1. Change the SANDBOX environment to FALSE to make the PayPal payment gateway live.

$config['sandbox'] = FALSE;

2.Change the BUSINESS EMAIL with your live PayPal business email.

$config['business'] = 'business@email.com';
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/

It will help you...

#Codeigniter 4