SnapShooter Backups Server, Database, Application and Laravel Backups - Get fully protected with SnapShooter

How to implement PayPal Express Checkout for Digital Good in CakePHP - Part 1

PayPal Digital Goods for Express Checkout Provides a very easy and user friendly way for users to make payment. All transactions happen in an overlayer modal box, users will not need to leave your site during the whole process unlike other methods, where users will be redirected to PayPal official site to make payment.

In this tutorial, we will show you how to implement PayPal Express Checkout for Digital Good in CakePHP. We have divided this tutorial into two parts, first part we will roughly discuss the process of PayPal Digital Goods for Express Checkout, and write a model class which acts as a wrapper for PayPal API functions.

Introduction

The flow of PayPal Digital Goods for Express Checkout is discussed very clearly on the official page, if you have never heard or used it before; we suggest you spend some time reading the documentation firstly. To implement PayPal Digital Goods for Express Checkout in CakePHP, the simplest way is to implement two main API calls which are SetExpressCheckout and DoExpressCheckoutPayment.

Some notes to take before we get started:

  1. Intermedia knowledge of CakePHP is required, we will not go though the process of installing CakePHP, so you will need to have some basic understanding of CakePHP.
  2. This tutorial is based on CakePHP 1.3, but adapting it to CakePHP 2.x should be easy.
  3. PayPal API version used in this tutorial is 65.1 .
  4. We are using Name/Value Pair (NVP) API in this tutorial.

PayPal Model Class

To communicate with PayPal, we use the concept of model class in CakePHP. This class will perform two main API calls to PayPal; it will return us needed information such as token and transaction id from PayPal upon on success, error message otherwise.

Copy the class below to your CakePHP directory app/models/paypal.php, and we will go through each function later.

<?php
class Paypal extends AppModel {
    var $name = 'Paypal';
    var $useTable = false;
     
    //configuration
    var $environment = 'sandbox';   // or 'beta-sandbox' or 'live'
    var $version = '65.1';
    //give correct info below
    var $API_UserName  = null;
    var $API_Password  = null;
    var $API_Signature = null;     
    //variables
    var $errors        = null;   
    var $token         = null;
    var $transId       = null;
        
     
    /**
     * Send HTTP POST Request
     *
     * @param   string  The API method name
     * @param   string  The POST Message fields in &name=value pair format
     * @return  array   Parsed HTTP Response body
     */
    function PPHttpPost($methodName, $nvpStr) {
        // Set up your API credentials, PayPal end point, and API version.
        $API_UserName = $this->API_UserName;
        $API_Password = $this->API_Password;
        $API_Signature = $this->API_Signature;
        $API_Endpoint = "https://api-3t.paypal.com/nvp";
        if("sandbox" === $this->environment || "beta-sandbox" === $this->environment) {
            $API_Endpoint = "https://api-3t.$this->environment.paypal.com/nvp";
        }
        $version = urlencode($this->version);
 
        // Set the curl parameters.
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
 
        // Turn off the server and peer verification (TrustManager Concept).
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
 
        // Set the API operation, version, and API signature in the request.
        $nvpreq = "METHOD=$methodName&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature&$nvpStr";
 
        // Set the request as a POST FIELD for curl.
        curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
 
        // Get response from the server.
        $httpResponse = curl_exec($ch);
 
        if(!$httpResponse) {
            exit("$methodName failed: ".curl_error($ch).'('.curl_errno($ch).')');
        }
 
        // Extract the response details.
        $httpResponseAr = explode("&", $httpResponse);
 
        $httpParsedResponseAr = array();
        foreach ($httpResponseAr as $i => $value) {
            $tmpAr = explode("=", $value);
            if(sizeof($tmpAr) > 1) {
                $httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
            }
        }
 
        if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
            exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
        }
 
        return $httpParsedResponseAr;
    }
     
    /*
     * get PayPal Url for redirecting page
     */
    function getPaypalUrl($token) {    
        $payPalURL = "https://www.paypal.com/incontext?token={$token}";
        if("sandbox" === $this->environment || "beta-sandbox" === $this->environment) {        
            $payPalURL = "https://www.sandbox.paypal.com/incontext?token={$token}";
        }
        return $payPalURL;
    }
 
         
    /*
     * call PayPal API: SetExpressCheckout
     */
    function setExpressCheckout($nvpStr) {
        // Execute the API operation; see the PPHttpPost function above.
        $httpParsedResponseAr = $this->PPHttpPost('SetExpressCheckout', $nvpStr);
        if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
            $this->token = urldecode($httpParsedResponseAr["TOKEN"]);          
            return true;
        } else  {
            $this->errors = $httpParsedResponseAr;
            return false;          
        }
    }
 
    /*
     * call PayPal API: DoExpressCheckoutPayment
     */
    function doExpressCheckoutPayment($nvpStr) {
        // Execute the API operation; see the PPHttpPost function above.
        $httpParsedResponseAr = $this->PPHttpPost('DoExpressCheckoutPayment', $nvpStr);
        if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
            $this->transId = urldecode($httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]);        
            return true;
        } else  {
            $this->errors = $httpParsedResponseAr;
            return false;
        }      
    }
}
  1. function PPHttpPost($methodName, $nvpStr): this function uses cURL to send post request to PayPal API server.
  2. function getPaypalUrl($token): this function returns correct PayPal Url based on application environment(sandbox or live).
  3. function setExpressCheckout($nvpStr): this function does API call(SetExpressCheckout),and it will set token if success, error messages if failed.
  4. function doExpressCheckoutPayment($nvpStr): this function does API call(DoExpressCheckoutPayment),and it will set transId if success, error messages if failed.

Now we have the core backend class to communicate with PayPal API server.

The End

In next tutorial, we will go through the front part of implementing PayPal Express Checkout for Digital Good in CakePHP. And the front script will utilize the PayPal model class to set and get information from PayPal. Stay tuned for next tutorial.

Hopefully this simple tutorial helped you with your development. If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.