How to Integrate PayPal Payment Gateway in CodeIgniter

Step 1 : First of all you can simple Download Paypal Payment Gateway Library Paypal Payment Gateway library for Codeigniter.

paypallib_config.php file => will be placed in the application/config/ directory.
paypal_lib.php file => will be placed in the application/libraries/ directory

Single Payment With Codeigniter

Step 2 : Create Backend database tables to fetch and store responses

CREATE TABLE `items` (
`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;

CREATE TABLE `payments` (
`payment_id` int(11) NOT NULL AUTO_INCREMENT,
`visitor_id` int(11) NOT NULL,
`item_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 3 : Create New Controller to call paypal api

application/controllers/Products.php

<?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('item');
$this->load->database();
}

function index(){
$response = array();
$response['items'] = $this->item->getProducts();
$this->load->view('items/index', $response);
}

function buyProduct($id){

$returnURL = base_url().'paypal/success'; //payment success url
$failURL = base_url().'paypal/fail'; //payment fail url
$notifyURL = base_url().'paypal/ipn'; //ipn url

$item = $this->item->getProducts($id);
$visitorID = 1; //current visitor 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', $item['name']);
$this->paypal_lib->add_field('custom', $visitorID);
$this->paypal_lib->add_field('item_number', $item['id']);
$this->paypal_lib->add_field('amount', $item['price']);
$this->paypal_lib->image($logo);

$this->paypal_lib->paypal_auto_form();
}

function paymentSuccess(){
$paymentData = $this->input->get();

$response['item_number'] = $paymentData['item_number'];
$response['txn_id'] = $paymentData["tx"];
$response['payment_amt'] = $paymentData["amt"];
$response['currency_code'] = $paymentData["cc"];
$response['status'] = $paymentData["st"];

$this->load->view('paypal/paymentSuccess', $response);
}

function paymentFail(){
$this->load->view('paypal/paymentFail');
}

function ipn(){
//paypal return transaction details array
$paymentData = $this->input->post();

$response['visitor_id'] = $paymentData['custom'];
$response['item_id'] = $paymentData["item_number"];
$response['txn_id'] = $paymentData["txn_id"];
$response['payment_gross'] = $paymentData["mc_gross"];
$response['currency_code'] = $paymentData["mc_currency"];
$response['payer_email'] = $paymentData["payer_email"];
$response['payment_status'] = $paymentData["payment_status"];

$paypalURL = $this->paypal_lib->paypal_url;
$solution = $this->paypal_lib->curlPost($paypalURL,$paymentData);

if(preg_match("/VERIFIED/i",$solution)){
$this->item->storeTransaction($response);
}
}
}

Step 4 : Create Paypal Model to interact with database

application/models/Paypal_model.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Product extends CI_Model{
public function __construct()
{
$this->load->database();
}

public function getProducts($id = ''){
$this->db->select('id,name,image,price');
$this->db->from('items');
if($id){
$this->db->where('id',$id);
$query = $this->db->get();
$solution = $query->row_array();
}else{
$this->db->order_by('name','asc');
$query = $this->db->get();
$solution = $query->result_array();
}
return !empty($solution)?$solution:false;
}

public function storeTransaction($response = array()){
$insert = $this->db->insert('payments',$response);
return $insert?true:false;
}
}

Step 5 : Create View File

application/views/items/index.php

<!DOCTYPE html>
<html>
<head>
<title>Codeigniter Paypal Integration Example - www.pakainfo.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($items)): foreach($items as $item): ?>
<div class="thumbnail">
<img src="<?php echo base_url().'assets/images/'.$item['image']; ?>" alt="">
<div class="caption">
<h4 class="pull-right">$<?php echo $item['price']; ?></h4>
<h4><a href="javascript:void(0);"><?php echo $item['name']; ?></a></h4>
</div>
<a href="<?php echo base_url().'items/buyProduct/'.$item['id']; ?>"><img src="<?php echo base_url(); ?>assets/images/buy-button" style="width: 70px;"></a>
</div>
<?php endforeach; endif; ?>
</div>
</div>
</body>
</html>

Step 6 :create a new file for payment success response paymentSuccess.php

application/views/paypal/paymentSuccess.php

<!DOCTYPE html>
<html>
<head>
<title>Transaction Successfull - Codeigniter Paypal Integration Example - www.pakainfo.com</title>
<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>

Step 7:create a file for payment failure

application/views/paypal/paymentFail.php

<html>
<head>
<title>Transaction Fail - Codeigniter Paypal Integration Example - www.pakainfo.com</title>
<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>

From sandbox to live integration, just change two places in config file application/config/paypallib_config.php

$config['sandbox'] = FALSE;
$config['business'] = 'business@email.com';

Single payout with codeigniter

You have to just define client id , secret key and also log path if you need log.

private function curl_request($url, $method, $headers = [], $response = [], $curl_options = []){

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_TIMEOUT, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

//--- If any headers set add them to curl request
if(!empty($headers)){
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}

//--- Set the request type , GET, POST, PUT or DELETE
switch($method){
case "POST":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
break;
default:
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
break;
}

//--- If any response is supposed to be send along with request add it to curl request
if($response){
curl_setopt($curl, CURLOPT_POSTFIELDS, $response);
}
//--- Any extra curl options to add in curl object
if($curl_options){
foreach($curl_options as $option_key => $option_value){
curl_setopt($curl, $option_key, $option_value);
}
}

$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);

//--- If curl request returned any error return the error
if ($error) {
return "CURL Error: $error";
}
//--- Return response received from call
return $response;
}


public function get_access_token()
{

//--- Headers for our token request
$headers[] = "Accept: application/json";
$headers[] = "Content-Type: application/x-www-form-urlencoded";

//--- Data field for our token request
$response = "grant_type=client_credentials";

//--- Pass client id & client secrent for authorization
$curl_options[CURLOPT_USERPWD] = $this->CI->config->item('client_id') . ":" . $this->CI->config->item('client_secret');

$token_request = $this->curl_request($this->CI->config->item('PAYPAL_TOKEN_URL'), "POST", $headers, $response, $curl_options);
$token_request = json_decode($token_request);
if(isset($token_request->error)){

$solution['no_error'] = FALSE;

$solution['message_error'] = $token_request->error_description;



}else{

$solution['no_error'] = TRUE;

$solution['token_request'] = $token_request ;

}

return $solution;

}


function transfer_money_from_business_to_personal($email_receiver,$cifra)
{

if ($email_receiver=='') {

$this->log_ipn_test('Mail vuota impossibile pagare');
die();
}

//restituisce un array per poter inserire nel caso gli errori
$solution= $this->get_access_token();



if($solution['no_error']){


$token_request = $solution['token_request'];

$this->log_ipn_test('Token Ok');

$headers = $response = [];
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer $token_request->access_token";

$time = time();
$sender_batch_header["sender_batch_id"] = $time;
$sender_batch_header["email_subject"] = "Payout Received";
$sender_batch_header["email_message"] = "You have received a payout, Thank you for using our services";


$receiver["recipient_type"] = "EMAIL";
$receiver["note"] = "Thank you for your services";
$receiver["sender_item_id"] = $time++;
$receiver["receiver"] = $email_receiver;
$receiver["amount"]["value"] = $cifra;
$receiver["amount"]["currency"] = "EUR";
$outputs[] = $receiver;
/*
//--- Second receiver
$receiver["recipient_type"] = "EMAIL";
$receiver["note"] = "You received a payout for your services";
$receiver["sender_item_id"] = $time++;
$receiver["receiver"] = "buyer2@example.com";
$receiver["amount"]["value"] = 15.00;
$receiver["amount"]["currency"] = "USD";
$outputs[] = $receiver;
*/
$response["sender_batch_header"] = $sender_batch_header;
$response["outputs"] = $outputs;

//--- Send payout request
$payout = $this->curl_request($this->CI->config->item('PAYPAL_PAYOUTS_URL'), "POST", $headers, json_encode($response));

$payout = json_decode($payout);
//$this->log_ipn_test("|2|$payout[0]['batch_header']");
//$this->log_ipn_test("|2|$payout[0]['batch_header']['payout_batch_id']");



$headers2 = $response2 = [];
//--- Headers for payment description
$headers2[] = "Content-Type: application/json";
$headers2[] = "Authorization: Bearer $token_request->access_token";

$link = $payout->links[0]->href;

$this->log_ipn_test($link);

sleep(3); //sleep to prevent PENDING

$dati_pagamento = $this->curl_request($link, "GET", $headers2);

$this->log_ipn_test(json_encode($dati_pagamento));

var_dump($dati_pagamento);

if($payout){

return TRUE;

}else{

return FALSE;

}


}else{

$this->log_ipn_test($solution['message_error']);

return FALSE;


}

} //fine transfer_money_from_business_to_personal
public function log_ipn_test($response=''){

$payoutLogFile=PAYOUT_IPNLOG_PATH;
// Success or failure being logged?
if ($response) $text .= $response;
// Write to log
$fp=fopen($payoutLogFile,'a');
fwrite($fp, $text . "\n\n");
fclose($fp); // close file
}

I hope you get an idea about payfast payment gateway integration in codeigniter.


#codeigniter 

How to Integrate PayPal Payment Gateway in CodeIgniter
1.50 GEEK