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.

UPDATE 09/10/2018

Jay Patel
Hey guys, this is a very good starting point for a paypal integration. However, I found some tiny issues with the code.

1. You should NOT use `sample/bootstrap.php` file. It is as the name suggest, for Sample use only. You can however, use the instructions mentioned here to initialize. https://github.com/paypal/PayPal-PHP-SDK/wiki/Making-First-Call

2. You could use `$payment->getApprovalLink()` on payment create success instead of iterating through it. Not a big deal however using either way.

3. When `execute` call is made you forgot to catch that exception. You should have a similar try catch block as you had for create, and make sure you return false, if for any reason your execute call fails. Note: I am one of the contributor to that library, but consider this comment as a person opinion and not from PayPal. I want to make sure people realize the difference here. I am just trying to help fellow developers get access to better knowledge. Also, checkout the shiny new 2.0-beta version of the SDK. It has solved a lot of problem for you. Made it extremely easy to use, and is almost ready for production release.

 

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



  • Marcos
    how to change the price? Example default $14.00 to $5.00 or $23 or $100
    July 29, 2017
    Reply
    • admin
      info@webeasystep.com
      Hi Macros, you can change price like this $item1["price"] = 6;
      July 29, 2017
      Reply
    • rajnikant
      rajni@gmail.com
      doller ma reva de ne
      June 12, 2018
      Reply
    • Muhammad Wasim Akram
      mwasimakram0@gmail.com
      Message: Call to a member function getMessage() on null Sir im facing this error when i tried to change values in input hiddent or in controller and want to own values. Kindly help
      February 10, 2019
      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
  • 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
    • Jay Patel
      jaypatel512@gmail.com
      To get more details of that particular problem, you can always catch the `PayPalConnectionException` and look at the data. It is explained very easily here: https://github.com/paypal/PayPal-PHP-SDK/wiki/exception-%27PayPal%5CException%5CPayPalConnectionException%27-with-message-%27Got-Http-response-code-400-when-accessing
      May 16, 2018
      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
    • Jay Patel
      jaypatel512@gmail.com
      What is your `$baseUrl` value ? Probably if you are running locally, it would not work.
      May 16, 2018
      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
    • BuddyBoy
      buddysuri@yahoo.com
      I'm also facing this, when i running it from my website hosting. What's the cause of this, are we missing anything here? -Thanks
      June 1, 2018
      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 30, 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
  • albert
    hello sir thanks for your good work.But please assist me here .A getting the below error when i click pay now button..what might be the problem ( ! ) Fatal error: Call to a member function getMessage() on a non-object in C:\wamp\www\codeigniter_paypal\application\libraries\PayPal-PHP-SDK\paypal\rest-api-sdk-php\sample\common.php on line 119 Call Stack # Time Memory Function Location 1 0.0017 163024 {main}( ) ..\index.php:0 2 0.0059 208288 require_once( 'C:\wamp\www\codeigniter_paypal\system\core\CodeIgniter.php' ) ..\index.php:293 3 0.1387 2273112 call_user_func_array ( ) ..\CodeIgniter.php:514 4 0.1388 2273240 Paypal->create_payment_with_paypal( ) ..\CodeIgniter.php:514 5 0.9961 2621248 ResultPrinter::printError( ) ..\Paypal.php:107 A PHP Error was encountered Severity: Error Message: Call to a member function getMessage() on a non-object Filename: sample/common.php Line Number: 119 Backtrace:
    November 23, 2017
    Reply
    • admin
      info@webeasystep.com
      try the demo code and showing the paypal tutorial step by step
      November 26, 2017
      Reply
  • Yogesh khasturi
    Hey its working nice , but when user login its showing 'return to merchant ' and redirecting to cancel page , can u suggest something ?
    December 2, 2017
    Reply
  • hardik kumbhani
    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
    January 17, 2018
    Reply
  • Jafar Ansari
    Hello Friends, I have setup on my local machine and first page working fine and while clicking on pay now button it give following error. The requested URL /codeigniter_paypal/paypal/create_payment_with_paypal was not found on this server. anybody can suggest thanks jafar
    February 11, 2018
    Reply
  • Muhammad Imran
    Is Recurring possible with this library. Please answer
    March 6, 2018
    Reply
  • Pavan Dubey
    A PHP Error was encountered Severity: Warning Message: require_once(/opt/lampp/htdocs/employee/application/libraries/paypal-php-sdk/paypal/rest-api-sdk-php/sample/bootstrap.php): failed to open stream: No such file or directory Filename: controllers/PayPal.php Line Number: 3 Backtrace: File: /opt/lampp/htdocs/employee/application/controllers/PayPal.php Line: 3 Function: _error_handler File: /opt/lampp/htdocs/employee/application/controllers/PayPal.php Line: 3 Function: require_once File: /opt/lampp/htdocs/employee/index.php Line: 315 Function: require_once Fatal error: require_once(): Failed opening required '/opt/lampp/htdocs/employee/application/libraries/paypal-php-sdk/paypal/rest-api-sdk-php/sample/bootstrap.php' (include_path='.:/opt/lampp/lib/php') in /opt/lampp/htdocs/employee/application/controllers/PayPal.php on line 3 A PHP Error was encountered Severity: Compile Error Message: require_once(): Failed opening required '/opt/lampp/htdocs/employee/application/libraries/paypal-php-sdk/paypal/rest-api-sdk-php/sample/bootstrap.php' (include_path='.:/opt/lampp/lib/php') Filename: controllers/PayPal.php Line Number: 3 Backtrace:
    April 16, 2018
    Reply
  • SD
    yo! after a go through of many tutorials, your tutorial was well paid my attention. thanks for this tutorial.. ERROR: I got an error __________ Response Object error:141640B5:SSL routines:tls_construct_client_hello:no ciphers available No Data ________________ here's the screenshot of web page https://drive.google.com/file/d/16L3Fs4xk5C-fEU6zUAgzogsil5XFz6Q5/view?usp=drivesdk .. please tell me where is the error .. I copied your full source code into mine server file .. I changed the client ID and secret code only .. everything else is same as intact.
    April 18, 2018
    Reply
  • SD
    here's the screenshot https://drive.google.com/file/d/0Byw-53o6N8q8aXUxOEYyTXFNSFE/view?usp=drivesdk i got the error while trying sdk files.. ________ Response Object error:141640B5:SSL routines:tls_construct_client_hello:no ciphers available No Data _________ PS: your tutorial was the one which paid off my searches on web ..
    April 18, 2018
    Reply
  • Jay Patel
    Hey guys, this is a very good starting point for a paypal integration. However, I found some tiny issues with the code. 1. You should NOT use `sample/bootstrap.php` file. It is as the name suggest, for Sample use only. You can however, use the instructions mentioned here to initialize. https://github.com/paypal/PayPal-PHP-SDK/wiki/Making-First-Call 2. You could use `$payment->getApprovalLink()` on payment create success instead of iterating through it. Not a big deal however using either way. 3. When `execute` call is made you forgot to catch that exception. You should have a similar try catch block as you had for create, and make sure you return false, if for any reason your execute call fails. Note: I am one of the contributor to that library, but consider this comment as a person opinion and not from PayPal. I want to make sure people realize the difference here. I am just trying to help fellow developers get access to better knowledge. Also, checkout the shiny new 2.0-beta version of the SDK. It has solved a lot of problem for you. Made it extremely easy to use, and is almost ready for production release.
    May 16, 2018
    Reply
    • admin
      info@webeasystep.com
      thank you very much Jay Patel for this clear information , i will add a new tutorial about this version and i will use the latest featues thank you
      October 9, 2018
      Reply
  • Iktou Sama
    I can't find the main file, index.php... where is it?
    May 30, 2018
    Reply
  • TSB
    Hi, when I tested in local it's working really good but when I try this in live like under cpanel and aws hosting, its ending up with the errors. Severity: Warning Message: require_once(/var/www/html/application/libraries/paypal-php-sdk/paypal/rest-api-sdk-php/sample/bootstrap.php): failed to open stream: No such file or directory Filename: controllers/Paypal.php Line Number: 3 & Message: require_once(): Failed opening required '/var/www/html/application/libraries/paypal-php-sdk/paypal/rest-api-sdk-php/sample/bootstrap.php' (include_path='.:/usr/share/php') Filename: controllers/Paypal.php Line Number: 3 Please let me know what I was missing here.
    June 7, 2018
    Reply
  • Yogendrasinh
    Message: require_once(/home/tandaa5/public_html/application/libraries/paypal-php-sdk/paypal/rest-api-sdk-php/sample/bootstrap.php): failed to open stream: No such file or directory Can you please hep me to solve this issue?
    June 11, 2018
    Reply
  • Adel ELECHI
    Hello, Thanks for your good work the "Payment_state" of table "payments" is always inserted with "pending" what can i do to make it work ?
    September 10, 2018
    Reply
  • jj
    An uncaught Exception was encountered Type: Error Message: Call to a member function getMessage() on null Filename: E:\XAMP\htdocs\Ordering\application\libraries\Paypal-php-sdk\paypal\rest-api-sdk-php\sample\common.php Line Number: 119 Backtrace: File: E:\XAMP\htdocs\Ordering\application\controllers\Paypal.php Line: 149 Function: printError File: E:\XAMP\htdocs\Ordering\index.php Line: 315 Function: require_once
    October 7, 2018
    Reply
  • Tahseen Ullah
    found this error: Message: session_start(): Failed to decode session object. Session has been destroyed Filename: Session/Session.php Line Number: 140 Backtrace: File: C:\xampp\htdocs\paypal\application\controllers\Paypal.php Line: 16 Function: __construct
    October 14, 2018
    Reply
  • shoaib hassan
    When i gave $item1["price"] = 13, or $item1["price"] = $this->input->post('item_price'); // price is 13 then it gave me Type: Error Message: Call to a member function getMessage() on null Filename: /var/www/html/carandzer/application/libraries/paypal-php-sdk/paypal/rest-api-sdk-php/sample/common.php Line Number: 119 Backtrace: File: /var/www/html/carandzer/application/controllers/Shared_Ride.php Line: 580 Function: printError File: /var/www/html/carandzer/index.php Line: 315 Function: require_once
    December 26, 2018
    Reply
  • jlanjlan
    Hi, i have been downloaded your code. And I compare the library to the github download. And it is totally different. Is this tutorial still valid for the paypal integration?
    February 2, 2019
    Reply
  • Arjun
    Hi, I am getting this error: Message: Class 'ResultPrinter' not found
    April 16, 2019
    Reply
  • Maaz Khan
    I used your code and its work fine but when i changed total value to $this->cart->total(); it is not forwarding total to paypal not showing total on paypal site can u help me with it its urgent
    June 28, 2019
    Reply
  • Amit sharma
    Hi, I have downloaded paypal integration code and its working fine on sandbox mode but when i changed from sandbox to live with live credentials then showing this error. please help me out. Type: PayPal\Exception\PayPalConnectionException Message: Got Http response code 401 when accessing https://api.sandbox.paypal.com/v1/payments/payment/PAYID-LVPW4IA18C76049MX6049828. Filename: /home/getwhoisdb/public_html/application/third_party/paypal-php-sdk/paypal/rest-api-sdk-php/lib/PayPal/Core/PayPalHttpConnection.php
    August 23, 2019
    Reply
  • snehal
    How can I change paypal Currency USD to INR in coding??
    November 26, 2019
    Reply
  • Hamza
    Fatal error: require_once(): Failed opening required '/home/abprngudtrxv/public_html/pws/application/libraries/paypal-php-sdk/paypal/rest-api-sdk-php/sample/bootstrap.php' Getting this error on hosting, kindly help to sort out
    December 2, 2019
    Reply
  • Mazaman
    Dear I have followed your tutorial and found some problems in SDK version and thats why it didnot work. I replaced that with newer version then it worked perfectly. Could you please make a tutorial for SDK v2. I will really appreciate your effort. thanks in advance.
    May 16, 2020
    Reply
  • Shahzad Tanveer
    how can we use PayPal Payment Standard method?
    May 26, 2020
    Reply
  • nikhil thakare
    how to add indian currency INR
    December 19, 2020
    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.