PayPal Payment Gateway Integration in CodeIgniter


PayPal is one of the world’s most popular internet payment solution. Many projects need a payment gateway for accepting payment. PayPal is the best choice for integrating payment gateway on your web project. After publishing PayPal standard payment gateway integration in PHP, many visitors sent us the request for PayPal standard payment gateway integration in CodeIgniter.

paypal-payment-gateway-integration-in-codeigniter-by-codexworld

In this tutorial, we’ll give you the step by step guide on PayPal standard payment gateway integration for CodeIgniter. We’ll provide the full source code and using it you can easily integrate PayPal payment gateway in CodeIgniter.

In this CodeIgniter application, we’ll display some products from the database along with the Buy button. Clicking on Buy button, the buyer would be redirected to the PayPal site. After completion of payment, the buyer will come back to the website. Using PayPal IPN (Instant Payment Notification) service, we will check the payment status and store the transaction details in the database.

Before starting to integrate PayPal payment gateway in CodeIgniter, create a Sandbox test account for testing PayPal transaction. You can get the Business account and Personal account from your Sandbox account.

Database Tables Creation

We’ll create two tables called products and payments.

products
This table is used to store the products data with some basic information. products table SQL would like the below.

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
This table is used to store the transaction data. payments table SQL would like the below.

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;

Controller Creation

We’ll create two controllers Products and Paypal. The functionalities of this two controllers are given below.

Products:
This controller has two methods, index(), and buy(). index() method would display the products using the product model along with the Buy button. buy() method helps to generate the PayPal form and redirect buyer to the PayPal site once the Buy button is clicked.

<?php defined('BASEPATH') OR exit('No direct script access allowed');
class 
Products extends CI_Controller
{
    function  
__construct() {
        
parent::__construct();
        
$this->load->library('paypal_lib');
        
$this->load->model('product');
    }
    
    function 
index(){
        
$data = array();
        
//get products data from database
        
$data['products'] = $this->product->getRows();
        
//pass the products data to view
        
$this->load->view('products/index'$data);
    }
    
    function 
buy($id){
        
//Set variables for paypal form
        
$returnURL base_url().'paypal/success'//payment success url
        
$cancelURL base_url().'paypal/cancel'//payment cancel url
        
$notifyURL base_url().'paypal/ipn'//ipn url
        //get particular product data
        
$product $this->product->getRows($id);
        
$userID 1//current user id
        
$logo base_url().'assets/images/codexworld-logo.png';
        

        
$this->paypal_lib->add_field('return'$returnURL);
        
$this->paypal_lib->add_field('cancel_return'$cancelURL);
        
$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();
    }
}

Paypal:
This controller has three methods, success(), cancel(), and ipn(). success() method responsible for displaying the transaction data on payment success. cancel() method is requested on payment cancel by the buyer. ipn() method gets the transaction data by PayPal IPN and insert the transaction data into the database.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class 
Paypal extends CI_Controller 
{
     function  
__construct(){
        
parent::__construct();
        
$this->load->library('paypal_lib');
        
$this->load->model('product');
     }
     
     function 
success(){
        
//get the transaction data
        
$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"];
        
        
//pass the transaction data to view
        
$this->load->view('paypal/success'$data);
     }
     
     function 
cancel(){
        
$this->load->view('paypal/cancel');
     }
     
     function 
ipn(){
        
//paypal return transaction details array
        
$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["payment_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);
        
        
//check whether the payment is verified
        
if(preg_match("/VERIFIED/i",$result)){
            
//insert the transaction data into the database
            
$this->product->insertTransaction($data);
        }
    }
}

Model (Product) Creation

Product model has two methods, getRows() and insertTransaction(). getRows() method is used to fetch the product data from the products table of the database. insertTransaction() method is used to insert the transaction data in into the payments table of the database.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class 
Product extends CI_Model{
    
//get and return product rows
    
public function getRows($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
    
public function insertTransaction($data = array()){
        
$insert $this->db->insert('payments',$data);
        return 
$insert?true:false;
    }
}

View Creation

Into the views directory, we’ll create two folders called products and paypal. products/ holds the view file of the Products controller and paypal/ holds the view files of Paypal controller.

products:
This directory has only one view file (index.php). This file holds the HTML for all the products listing.

<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']; ?> USD</h4>
            <h4><a href="javascript:void(0);"><?php echo $product['name']; ?></a></h4>
        </div>
        <a href="<?php echo base_url().'products/buy/'.$product['id']; ?>"><img src="<?php echo base_url(); ?>assets/images/x-click-but01.gif" style="width: 70px;"></a>
    </div>
    <?php endforeach; endif; ?>
</div>

paypal:
This directory has two view file, success.php and cancel.php.

  • success.php – This file holds the HTML for displaying the transaction success notification.
    <div>
        <h2>Dear Member</h2>
        <span>Your payment was successful, 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>
  • cancel.php – This file holds the HTML for displaying the transaction cancel notification.
    <div>
        <h3>Dear Member</h3>
        <p>We are sorry! Your last transaction was cancelled.</p>
    </div>

Library Creation

We’ll use the paypal_lib library for generating the PayPal form and submit the form to PayPal. This library has a dependency of a config file called paypallib_config.php. paypal_lib.php file will be placed in the application/libraries/ directory and paypallib_config.php file will be placed in the application/config/ directory.

Don’t forget to insert your PayPal business email in the paypal_config.php file.

Load Database

Don’t forget to load database library to using the database connectivity. With two ways you can load the database library.

  • You can load it manually by this line of code – $this->load->database();
  • Or

  • You can load it automatically in the application/config/autoload.php file by adding this line of code – $autoload['libraries'] = array('database');

Test PayPal Transaction

 Open the Products controller (http://localhost/codeigniter/products) at the browser.
 You’ll see the products are listed with the Buy button.
 Click on the Buy button and you would be redirected to the PayPal site for payment.
 Log into the PayPal with your Sandbox personal account and click on Pay.
 On payment success, you would be redirected to the website’s success page and you’ll see the payment details.

Make PayPal Payment Gateway Live

Once your test transaction is worked properly with the PayPal sandbox account, now it time to link your live PayPal account. You only need to make two changes for that. Open the application/config/paypallib_config.php and change the following two configuration value.

  • Change the SANDBOX environment to FALSE for make PayPal payment gateway live.
    $config['sandbox'] = FALSE;
  • Change the BUSINESS EMAIL with your live PayPal business email.
    $config['business'] = 'live_business@email.com';

55 Comments

  1. JJ Said...
  2. Majed Said...
    • CodexWorld Said...
  3. Kevin Flores Said...
  4. JP Said...
  5. Kivimango Said...
    • CodexWorld Said...
  6. Kivimango Said...
    • CodexWorld Said...
  7. Sachin Jaiswal Said...
  8. Mkay Said...
    • CodexWorld Said...
  9. Chad Said...
  10. Tito Said...
  11. NoMatch Said...
  12. Tarek Showkot Said...
  13. Muhammad Waqas Said...
  14. Pinak A Maheta Said...
  15. Ali Said...
    • CodexWorld Said...
  16. Romi Said...

Leave a reply

Connect With CodexWorld