Paypal Payment Gateway Integration In Codeigniter


In this tutorial, we will learn Paypal payment gateway integration in Codeigniter source code. and also We’ll provide the PayPal payment gateway integration in Codeigniter source code some people call billdesk payment gateway integration in PHP. PayPal payment gateway integrates very easily.

Very simple and easy way to integrate PayPal payment gateway in the Codeigniter framework. This time learn step by step how to integrate PayPal payment gateway in Codeigniter with example.

Follow a few steps to create payment gateway integration in Codeigniter.

Follow the below-given steps and easily integrate PayPal payment gateway in Codeigniter:

  • Download Paypal Payment Gateway Library
  • Create Database Tables
  • Build Paypal Controller
  • Build a Paypal Model
  • Create View
Paypal Payment Gateway Integration In Codeigniter With Source Code
1. Download Paypal Payment Gateway Library

We will create payment gateway integration in Codeigniter. We need to download the PayPal payment gateway library for Codeigniter. And place this library into your Codeigniter project. PayPal payment gateway library here => Paypal Payment Gateway library for Codeigniter.

This library holds two files name 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.
2. Create Database Tables

How to add payment gateway in codeigniter. We need to create two tables in the database for fetching the product information and stored payment information in it.

PayPal integration in PHP step by step creates the first table name is products and it stored the product data like product name, image, price or product status, etc. So you can use the below SQL query for creating a product table in your database:

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;

Next, how to make payment gateway in PHP then create Second table name is payments and it stored the payment data like user_id, payment_id, product_id, txt_id or currency code, etc. So you can use the below SQL query for creating a payments table in your database:

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;
3. Create New Controller

First of all, how to implement PayPal payment gateway so we need to create a new PayPal controller, So go to application/controller and create a new controller name paypal.php.

In paypal controller, we need to create five methods, index(), buyProduct(), success(), cancel(), and ipn().

Explanation of the following few methods:

  • index() this method would fetch and display the product information.
  • buyProudct() this method helps to generate the PayPal form and redirect buyer to the PayPal site once the Buy button is clicked.
  • success() this method will be used to display transaction data after successful payment.
  • cancel() this method is requested when the user cancels the payment.
  • ipn() this method receives transaction data by PayPal IPN and inserts the transaction data into the database.
<?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');
		$this->load->database();
	}
	function index(){
		$data = array();
		//get products inforamtion from database table
		$data['products'] = $this->product->getRows();
		//loav view and pass the products information to view
		$this->load->view('products/index', $data);
	}
	function buyProduct($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().'Your_logo_url';
		$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();
	}
	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(){
		//if transaction cancelled
		$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["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);
		//check whether the payment is verified
		if(preg_match("/VERIFIED/i",$result)){
			//insert the transaction data into the database
			$this->product->storeTransaction($data);
		}
	}
}
4. Create Paypal Model

How to integrate payment gateway in Codeigniter. we need to create a new PayPal model, So go application/models and create a new model name paypal.php.

In PayPal model, we need to create two methods, getRows(), StoreTransaction().

Explanation of the following few methods:

  • getRows() this method is used to fetch the product information data from the database table product.
  • storeTransaction() When the transaction is successful then we will use The storeTransaction() this method to insert transaction data into a payment table.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Product extends CI_Model{
	public function __construct()
	{
		$this->load->database();
	}
		//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 storeTransaction($data = array()){
		$insert = $this->db->insert('payments',$data);
		return $insert?true:false;
	}
}
5. Create View

In this step, we need to create two folders named products and PayPal. Write code payment gateway integration in codeigniter.

After that, we need to create views files that will show the product listing and payment-related information like payment success or cancel details. then how to make a payment gateway in PHP.

First of all, go to application/views/products and create a new file inside the products folder named index.php. Then update the HTML code below in your index.php file we create PayPal payment gateway integration in Codeigniter:

<!DOCTYPE html>
<html>
   <head>
      <title>paypal payment gateway integration in codeigniter source code - phpcodingstuff.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']; ?> USD</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>

After that, we need to create two more views files to display the transaction details as if the transaction was successful or canceled in paypal payment gateway.

So go to application/views/Paypal folder, Create a new file name success.php and update the below code into your file:

<!DOCTYPE html>
<html>
   <head>
      <title>Transaction Success - paypal payment gateway integration in codeigniter source code - phpcodingstuff.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>

Create a second new file name cancel.php and update the below code into your file:

<!DOCTYPE html>
<html>
   <head>
      <title>Transaction Fail - paypal payment gateway integration in codeigniter source code - phpcodingstuff.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 in payment gateway integration in Codeigniter. You want to make it live your PayPal payment gateway integration.

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'] = 'info@website.com';

I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close