Skip to main content

Paypal payment gateway integration in codeigniter.

paypal payment gateway integration in codeigniter.

the last week was a tough week, I was interested to integrate my PayPal module to the new e-commerce project but when I started many problems hitting my face, which makes me think to read PayPal API documentation again, once I did this, I understood what’s happening exactly.


PayPal Payment Getaways Types :
It’s about two years ago I haven’t updated PayPal module, but on the other side PayPal made many changes with payment gateways which by logic reflect API SDK, so I specified some hours to figure out what going on, because my client asked me to select the appropriate payment getaway, after couple of hours I figured that PayPal now has three payment getaways:
1- PayPal Express Checkout
Which give a merchants the ability to sell for all buyers who have PayPal account, so if your customer hasn’t PayPal account he should create one ،otherwise he couldn’t complete the purchasing process.
2- PayPal Payment Standard
While , this gateway allow buyers to choose between two payment methods (PayPal) or (credit card), this seems very helpful for non-PayPal users, and very effective for increasing payments number, because many clients was lazy, they always have no time to fill a  registration form with Their details.
The second interested property for the credit card payment, that PayPal offers that payment on Their site not yours, so when the user hits the buy button it will redirect to PayPal paying page which appears two choices (use PayPal account-user credit card), this would be a good choice for anyone prefer to jumps over potential security issues and let take care of that, to just focus on his product.
Another interesting benefits I figured, it’s a free getaway, there’s no monthly or annually fees, also it is no restrictions or limits for using in any country because it’s available for every country PayPal available in.
3- PayPal Payment Pro.
This gateway like what named for, it’s for professional usage, your clients could pay with PayPal account or credit card but this time the whole process will be on your site which called (direct payment),but unfortunately this option only allowed for limited counties, also you should pay about $30 as a monthly fee.
This is the short story, and I liked to keep it simple for anyone who wants to know about the three payment getaways quickly but if you want to read more I suggest to read a PayPal documentation.
Now let’s give a full example for how to integrate PayPal SDK with Codeigniter ?
The example will cover the whole process from clicking the buy button to insert the response into payments tables, and it will only focus for the PayPal payment standard because I have not seen any updated tutorial that cover this getaway until now with the Payments REST API, let’s do it dude
PayPal Integration Steps :
1-Create sandbox account, then create a new app to get api paypal credential from your sandbox to test,you can follow steps in this Guide and get paypal credential
2-Create Paypal.php file, place it into application/config directory, you can replace client_id
And secret with your paypal credential or copy paste this code as it is (but remember to change it when your project go to the production phase also change the mode)
<?php
/** set your paypal credential **/

$config['client_id'] = '';
$config['secret'] = '';

/**
 * SDK configuration
 */
/**
 * Available option 'sandbox' or 'live'
 */
$config['settings'] = array(

    'mode' => 'sandbox',
    /**
     * Specify the max request time in seconds
     */
    'http.ConnectionTimeOut' => 1000,
    /**
     * Whether want to log to a file
     */
    'log.LogEnabled' => true,
    /**
     * Specify the file that want to write on
     */
    'log.FileName' => 'application/logs/paypal.log',
    /**
     * Available option 'FINE', 'INFO', 'WARN' or 'ERROR'
     *
     * Logging is most verbose in the 'FINE' level and decreases as you
     * proceed towards ERROR
     */
    'log.LogLevel' => 'FINE'
);
3-Download paypal sdk zip file from here, extract and place rest-api-sdk-php directory into application/libraries
4-Create PayPal.php controller and copy paste this code
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once(APPPATH . 'libraries/paypal-php-sdk/paypal/rest-api-sdk-php/sample/bootstrap.php'); // require paypal files

use PayPal\Api\ItemList;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\PaymentExecution;

class Paypal extends CI_Controller
{
    public $_api_context;

    function  __construct()
    {
        parent::__construct();
        $this->load->model('paypal_model', 'paypal');
        // paypal credentials
        $this->config->load('paypal');

        $this->_api_context = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential(
                $this->config->item('client_id'), $this->config->item('secret')
            )
        );
    }

    function index(){
        $this->load->view('content/payment_credit_form');
    }


    function create_payment_with_paypal()
    {

        // setup PayPal api context
        $this->_api_context->setConfig($this->config->item('settings'));


// ### Payer
// A resource representing a Payer that funds a payment
// For direct credit card payments, set payment method
// to 'credit_card' and add an array of funding instruments.

        $payer['payment_method'] = 'paypal';

// ### Itemized information
// (Optional) Lets you specify item wise
// information
        $item1["name"] = $this->input->post('item_name');
        $item1["sku"] = $this->input->post('item_number');  // Similar to `item_number` in Classic API
        $item1["description"] = $this->input->post('item_description');
        $item1["currency"] ="USD";
        $item1["quantity"] =1;
        $item1["price"] = $this->input->post('item_price');

        $itemList = new ItemList();
        $itemList->setItems(array($item1));

// ### Additional payment details
// Use this optional field to set additional
// payment information such as tax, shipping
// charges etc.
        $details['tax'] = $this->input->post('details_tax');
        $details['subtotal'] = $this->input->post('details_subtotal');
// ### Amount
// Lets you specify a payment amount.
// You can also specify additional details
// such as shipping, tax.
        $amount['currency'] = "USD";
        $amount['total'] = $details['tax'] + $details['subtotal'];
        $amount['details'] = $details;
// ### Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it.
        $transaction['description'] ='Payment description';
        $transaction['amount'] = $amount;
        $transaction['invoice_number'] = uniqid();
        $transaction['item_list'] = $itemList;

        // ### Redirect urls
// Set the urls that the buyer must be redirected to after
// payment approval/ cancellation.
        $baseUrl = base_url();
        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl($baseUrl."paypal/getPaymentStatus")
            ->setCancelUrl($baseUrl."paypal/getPaymentStatus");

// ### Payment
// A Payment Resource; create one using
// the above types and intent set to sale 'sale'
        $payment = new Payment();
        $payment->setIntent("sale")
            ->setPayer($payer)
            ->setRedirectUrls($redirectUrls)
            ->setTransactions(array($transaction));

        try {
            $payment->create($this->_api_context);
        } catch (Exception $ex) {
            // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
            ResultPrinter::printError("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", null, $ex);
            exit(1);
        }
        foreach($payment->getLinks() as $link) {
            if($link->getRel() == 'approval_url') {
                $redirect_url = $link->getHref();
                break;
            }
        }

        if(isset($redirect_url)) {
            /** redirect to paypal **/
            redirect($redirect_url);
        }

        $this->session->set_flashdata('success_msg','Unknown error occurred');
        redirect('paypal/index');

    }


    public function getPaymentStatus()
    {

        // paypal credentials

        /** Get the payment ID before session clear **/
        $payment_id = $this->input->get("paymentId") ;
        $PayerID = $this->input->get("PayerID") ;
        $token = $this->input->get("token") ;
        /** clear the session payment ID **/

        if (empty($PayerID) || empty($token)) {
            $this->session->set_flashdata('success_msg','Payment failed');
            redirect('paypal/index');
        }

        $payment = Payment::get($payment_id,$this->_api_context);


        /** PaymentExecution object includes information necessary **/
        /** to execute a PayPal account payment. **/
        /** The payer_id is added to the request query parameters **/
        /** when the user is redirected from paypal back to your site **/
        $execution = new PaymentExecution();
        $execution->setPayerId($this->input->get('PayerID'));

        /**Execute the payment **/
        $result = $payment->execute($execution,$this->_api_context);



        //  DEBUG RESULT, remove it later **/
        if ($result->getState() == 'approved') {
            $trans = $result->getTransactions();

            // item info
            $Subtotal = $trans[0]->getAmount()->getDetails()->getSubtotal();
            $Tax = $trans[0]->getAmount()->getDetails()->getTax();

            $payer = $result->getPayer();
            // payer info //
            $PaymentMethod =$payer->getPaymentMethod();
            $PayerStatus =$payer->getStatus();
            $PayerMail =$payer->getPayerInfo()->getEmail();

            $relatedResources = $trans[0]->getRelatedResources();
            $sale = $relatedResources[0]->getSale();
            // sale info //
            $saleId = $sale->getId();
            $CreateTime = $sale->getCreateTime();
            $UpdateTime = $sale->getUpdateTime();
            $State = $sale->getState();
            $Total = $sale->getAmount()->getTotal();
            /** it's all right **/
            /** Here Write your database logic like that insert record or value in database if you want **/
            $this->paypal->create($Total,$Subtotal,$Tax,$PaymentMethod,$PayerStatus,$PayerMail,$saleId,$CreateTime,$UpdateTime,$State);
            $this->session->set_flashdata('success_msg','Payment success');
            redirect('paypal/success');
        }
        $this->session->set_flashdata('success_msg','Payment failed');
        redirect('paypal/cancel');
    }
    function success(){
        $this->load->view("content/success");
    }
    function cancel(){
        $this->paypal->create_payment();
        $this->load->view("content/cancel");
    }
}
5-Create paypel_model.php and copy paste this code
<?php

if (!defined('BASEPATH'))
 exit('No direct script access allowed');

class Paypal_model extends CI_Model {

 function __construct() {
  parent::__construct();
 }

 /* This function create new Service. */

 function create($Total,$SubTotal,$Tax,$PaymentMethod,$PayerStatus,$PayerMail,$saleId,$CreateTime,$UpdateTime,$State) {
        $this->db->set('txn_id',$saleId);
        $this->db->set('PaymentMethod',$PaymentMethod);
        $this->db->set('PayerStatus',$PayerStatus);
        $this->db->set('PayerMail',$PayerMail);
        $this->db->set('Total',$Total);
        $this->db->set('SubTotal',$SubTotal);
        $this->db->set('Tax',$Tax);
        $this->db->set('Payment_state',$State);
  $this->db->set('CreateTime',$CreateTime);
  $this->db->set('UpdateTime',$UpdateTime);
  $this->db->insert('payments');
  $id = $this->db->insert_id();
  return $id;
 }

}
6-Create buy_form.php, success.php, cancel.php and place them into application/views, copy paste this code.
/////////////////// the buy form file //////////////////  
      <div class="container">

            <div class="starter-template">
                <h1>PayPal Payment</h1>
                <p class="lead">Pay Now</p>
            </div>

            <div class="contact-form">

                <p class="notice error"><?= $this->session->flashdata('error_msg') ?></p><br/>
                <p class="notice error"><?= $this->session->flashdata('success_msg') ?></p><br/>

                <form method="post" class="form-horizontal" role="form" action="<?= base_url() ?>paypal/create_payment_with_paypal">
                    <fieldset>
                        <input title="item_name" name="item_name" type="hidden" value="ahmed fakhr">
                        <input title="item_number" name="item_number" type="hidden" value="12345">
                        <input title="item_description" name="item_description" type="hidden" value="to buy samsung smart tv">
                        <input title="item_tax" name="item_tax" type="hidden" value="1">
                        <input title="item_price" name="item_price" type="hidden" value="7">
                        <input title="details_tax" name="details_tax" type="hidden" value="7">
                        <input title="details_subtotal" name="details_subtotal" type="hidden" value="7">

                        <div class="form-group">
                            <div class="col-sm-offset-5">
                                <button  type="submit"  class="btn btn-success">Pay Now</button>
                            </div>
                        </div>
                    </fieldset>
                </form>
            </div>
        </div><!-- /.container -->


////////////////// the success view file /////////////////  

    <div class="starter-template">
        <h1>PayPal Payment</h1>
        <p class="lead">Success</p>
    </div>

    <div class="contact-form">
        <div>
            <h2 style="font-family: 'quicksandbold'; font-size:16px; color:#313131; padding-bottom:8px;">Dear Member</h2>
            <span style="color: #646464;">Your payment was successful, thank you for purchase.</span><br/>
        </div>
    </div>
</div><!-- /.container -->



//////////////// the cancel view file ///////////

<div class="container">

    <div class="starter-template">
        <h1>PayPal Payment</h1>
        <p class="lead">Canceld order</p>
    </div>

    <div class="contact-form">

        <div>
            <h3 style="font-family: 'quicksandbold'; font-size:16px; color:#313131; padding-bottom:8px;">Dear Member</h3>
            <span style="color:#D70000; font-size:16px; font-weight:bold;">We are sorry! Your last transaction was cancelled.</span>
        </div>
    </div>
</div><!-- /.container -->

7-Create payments transactions table to save payment on this table
--
-- Database: `demo`
--

-- --------------------------------------------------------

--
-- Table structure for table `payments`
--

CREATE TABLE `payments` (
  `txn_id` int(11) NOT NULL,
  `PaymentMethod` varchar(50) NOT NULL,
  `PayerStatus` varchar(50) NOT NULL,
  `PayerMail` int(100) NOT NULL,
  `Total` decimal(19,2) NOT NULL,
  `SubTotal` decimal(19,2) NOT NULL,
  `Tax` decimal(19,2) NOT NULL,
  `Payment_state` varchar(50) NOT NULL,
  `CreateTime` varchar(50) NOT NULL,
  `UpdateTime` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
8-Go to this URL to start the demo http://localhost/project_name/paypal

What happen in the demo scenario ?
1-After going to paypal/index function the buy form will appear
2-When click pay now you will redirect to PayPal sandbox by using create_payment_with_paypal function and you will see payment page with two choices, if you have a paypal account then login, if not click (Pay with Debit or Credit Card) button.
3-After login with email and password for your PayPal account you will see payment details page, you have two choices, to click continue button and complete the order or click cancel button to cancel the order.
4-When you click continue you will redirect to getPaymentStatus function, this function will detect the current payment method state if it is approved then it will collect payment details and send it to create function to insert into payments tables, then redirect to success function to see success message, or to cancel function to see cancel message
Conclusion
I hope this help you to understand PayPal API and save your time as possible, and I will continue to update this tutorial to follow PayPal updates as possible.

Comments

Popular posts from this blog

What is the api of WhatsApp?

What is the api of WhatsApp? WhatsApp  has released a “Click to Chat” function  where  you  can create links where the person can start a conversation    with you without    it having the saved phone number.  With  this function you can even add standard texts for the person to send to you. How to Fix WhatsApp Api in Desktop Browsers What’s the problem? There are two bases for you to do this solution: api.whatsapp and web.whatsapp. Throughout the internet you will find people teaching with api., However in some tests I realized that it does not work in Firefox and Safari desktop browsers. These only work the web.whatsapp and the web does not work on mobiles. A Change where “YOURNUMBER” is by its number in the following format 15551234567, without the “+” and “()”.. Replace the text “YOURTEXT” with what you want the person to send by changing the space for “+”. Ex. “I+Want” Save the file named index.php and uplo...

Read Latest Litcoin news from News Portal

Today everybody needs to get current with the most up-to-date happenings of litcoin information round the South Africa. Else Coin Supply you with information regarding litcoin every single discipline which includes investment decision, cost, technology and much more. We are not only offer information litcoin but will also teach men and women in regards to the social & political construction. Individuals come to understand about the impending litcoin problems and learn how to overcome the situations. Else Coins delivers the litcoin latest news only one click on away. People today could possibly get a minute update across South Africa only by just one click. Individuals of South Africa has enough of the choices to choose from. Men and women can go through litcoin news as per their desire.  Our information portals is easily accessible. Bitcoin investments Uganda People could possibly get up-to-date with the latest litcoin updates everywhere they go. We are an internet base...

The best short term cryptocurrency 2019

In this article, we are discussing about the short-term and top cryptocurrencies of year 2019. Moreover we also discuss about the investment benefit in these cryptocurrencies: EOS-  EOS is the biggest Rival of Ethereum and we can see the bright future of this broken. As a price of EOS is increasing day by day and find so many positive response among the cryptocurrency enthusiasts . Ripple: With the starting of 2019 year, we can see also positive sign in ripple growth. From last six month, the experts find ripple growing day by day unexpected at the year of end you can make good money by the investment of ripple. TRON: TRON is rising as the biggest digital currency at the end of 2018. And it Kane certain growth in last 2 month of year 2019. So you have the best option to invest in cryptocurrency as a TRON. Litecoin- by the starting of year 2019, you can also see positive growth sign in litecoin. The cryptocurrency experts find positive growth in litecoin stock mar...