Tutorials

Article Content:paypal payment gateway integration in codeigniter

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'] = 'AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS';
$config['secret'] = 'EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL';

/**
 * 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.

 

Download Full Code



  • Muhammad Imran
    Fatal error: Call to a member function getMessage() on a non-object in /var/www/staging/application/libraries/paypal-php-sdk/paypal/rest-api-sdk-php/sample/common.php on line 119 Can you please review what is the error
    May 4, 2017
    Reply
  • Pathik Vejani
    it is giving me City select validation error at the time of doing payment via Credit card.
    June 12, 2017
    Reply
  • Marcos
    how to change the price? Example default $14.00 to $5.00 or $23 or $100
    July 28, 2017
    Reply
    • admin
      info@webeasystep.com
      Hi Macros, you can change price like this $item1["price"] = 6;
      July 29, 2017
      Reply
  • neeraj kumar
    hello guys, Is this working fine?
    July 31, 2017
    Reply
    • admin
      info@webeasystep.com
      hello neeraj , of course works fine
      July 31, 2017
      Reply
      • neeraj kumar
        neerajrajput05@yahoo.com
        hi, i am new in paypal integarting can someone please suggest me,
        August 1, 2017
        Reply
  • Ronak Parmar
    Hi there, I have followed your steps but each and every step I have errors. I have to manually solve these errors, I am new to codeigniter and each time I have to search on google to fix the error. Few errors are as follow: - model name (typo mistake) - view files are not in content folder and in code you have used content folder path - need to write routes for each urls in route.php file.
    August 3, 2017
    Reply
    • admin
      info@webeasystep.com
      this because you tried to include in your project ,of course you should changing paths and naming
      August 6, 2017
      Reply
  • shaf
    An uncaught Exception was encountered Type: PayPal\Exception\PayPalConnectionException Message: Got Http response code 401 when accessing https://api.sandbox.paypal.com/v1/payments/payment/PAY-8W9188225L049732LLGKZ7QI.
    August 17, 2017
    Reply
    • admin
      info@webeasystep.com
      insure for not missing any property or making a wrong calculation in any of properties like (total-subtotal-tax-prices ... etc ) , or you will ran into problems
      August 21, 2017
      Reply
  • sagar
    This will working properly ?
    August 21, 2017
    Reply
    • admin
      info@webeasystep.com
      yes it is , but insure to do all steps and calculation properties well
      August 21, 2017
      Reply
  • Anuj
    Message: ReturnUrl is not a fully qualified URL
    August 31, 2017
    Reply
  • Akhil K R
    Hi, Not showing debit or credit card option for payment.Is there any settings needed to be enabled?
    September 7, 2017
    Reply
  • Mohammed Bhoraniya
    Message: Class 'PayPal\Rest\ApiContext' not found
    September 12, 2017
    Reply
  • Hussain
    Pay by Credit Card or credit card not working in Live
    September 18, 2017
    Reply
    • admin
      info@webeasystep.com
      Paypal has a list about countries that accept credit card payments,so may be your country has not been in this list
      September 24, 2017
      Reply
  • Anandan K
    Message: require_once(C:\xampp\htdocs\PHP\logocreator\1.0\application\libraries/paypal-php-sdk/paypal/rest-api-sdk-php/sample/bootstrap.php): failed to open stream: No such file or directory
    September 19, 2017
    Reply
  • Joe
    Good day, I am new to PayPal integration, am having issues running the code and is database related issues, please i need your assistance with the full demo database so as to understand the concept fully. Thanks.
    September 24, 2017
    Reply
  • Anandan
    I m gettting "Things don't appear to be working at the moment. Please try again later." this message if i put my sandbox crendentials in config/paypal.php. kindly help
    October 4, 2017
    Reply
  • chandra
    hi there, i can login to paypal sandbox i was create sandbox account but it's still not work for me can you hel me ?
    October 29, 2017
    Reply
  • noreen
    Recurring in this library is possible ?.
    November 14, 2017
    Reply
  • Madhu Kant Tiwari
    Could you please help me out with this error:- Call to a member function getMessage() on null in C:\xampp\htdocs\CodeIgniter\application\libraries\paypal-php-sdk\paypal\rest-api-sdk-php\sample\common.php on line 119
    November 15, 2017
    Reply
    • admin
      info@webeasystep.com
      in most cases it is probably about wrong calculations, you should insure for the total is right and sub total number is right, as example if the price is 2 dollars and the item number is 3 items ,the total should be 6 ,etc
      November 15, 2017
      Reply
      • Madhu Kant Tiwari
        redface.madhukant@gmail.com
        Thanks Admin, It's Done actually The parameter issues are there
        November 15, 2017
        Reply
  • Dev
    Your tutorial is awesome!. :) .Really. Could you please provide information about the below tables as well and the structure of these tables..along with any guide for how to pull data to these tables .. ci_providers ci_services ci_users services_requests Thank you so much.!
    November 18, 2017
    Reply
  • admin
    Hi DEV, thank you for your words , about your question , No these tables not related to this tutorial. you are welcome :)
    November 18, 2017
    Reply

Leave a Reply

Your email address will not be published.


Notify me of followup comments via e-mail.
You can also Subscribe without commenting.