Paypal Refund a Transaction API and Sample PHP Code - Kvcodes
X

Congrats, You are Subscribed to Receive Updates.

Paypal Refund a Transaction API and Sample PHP Code


Paypal Refund a Transaction API and Sample PHP Code. Let’s create a class with PayPal Username, Password, Signature ,API end point and Version.

  private $API_Username, $API_Password, $Signature, $API_Endpoint, $version;

And with in the class it will be like this.

paypal-refund-kvcodes

  class KvPayPalRefund   {
        private $API_Username, $API_Password, $Signature, $API_Endpoint, $version;
      }

Here we have sandbox Credentials and Live Credentials. So let’s create a constructor to make it choice.

 
function __construct($mode = "sandbox")      {
            if($mode == "live")    {
                $this->API_Username = "xxxxxxx_xxxx.xxxxxx.com";
                $this->API_Password = "XXXXXXXXXXXXXXXX";
                $this->Signature = "XXXXXXXXXXXXXXXXXXXXXXXXX.XXXXXXXXXXXXXXX-XXXXXXXXXXXXXX";
                $this->API_Endpoint = "https://api-3t.paypal.com/nvp";
            }   else     {
                $this->API_Username = "XXXXXXX_XXXX.XXXXXXX.XXX";
                $this->API_Password = "XXXXXXXXXXXXXXXX";                
                $this->Signature    = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XX-XXXXXXXXXXXX.XXXXXXXX";
                $this->API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
            }
            $this->version = "94.0";
        }

Here with XXX, you have to replace with your API Credentials. you can get it by logging into your paypal account.

Profile->My selling preferences-> API Access ¬†Here. Click “Update”, you have to create API key and signature here with it.

And Now, let write the rest of the function to handle the inputs and validations.

function KvRefundAmount($DataInArray)   {
       if(trim(@$DataInArray['currencyCode'])=="")
            return array("ERROR_MESSAGE"=>"Currency Code is Missing");
       if(trim(@$DataInArray['refundType'])=="")
            return array("ERROR_MESSAGE"=>"Refund Type is Missing");
       if(trim(@$DataInArray['transactionID'])=="")
            return array("ERROR_MESSAGE"=>"Transaction ID is Missing");
}

Let’s Create the API Request with it.

  $Api_request = "&TRANSACTIONID={$DataInArray['transactionID']}&REFUNDTYPE={$DataInArray['refundType']}&CURRENCYCODE={$DataInArray['currencyCode']}";

The Refund may be a full or partial Refund. So, we have an option for it.

  if(strcasecmp($DataInArray['refundType'], 'Partial') == 0)    {
                if(!isset($DataInArray['amount']))   {
                    return array("ERROR_MESSAGE"=>"For Partial Refund - It is essential to mention Amount");
                }    else     {
                    $Api_request = $Api_request."&AMT={$DataInArray['amount']}";
                }

                if(!isset($DataInArray['memo']))   {
                    return array("ERROR_MESSAGE"=>"For Partial Refund - It is essential to enter text for Memo");
                }
            }

Let’s make a curl request to process the code to get response from PayPal Server.

 
 $curl_var = curl_init();
            curl_setopt($curl_var, CURLOPT_URL, $this->API_Endpoint);
            curl_setopt($curl_var, CURLOPT_VERBOSE, 1);

            curl_setopt($curl_var, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl_var, CURLOPT_SSL_VERIFYHOST, FALSE);

            curl_setopt($curl_var, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl_var, CURLOPT_POST, 1);

            $Api_request_final = "METHOD=RefundTransaction&VERSION={$this->version}&PWD={$this->API_Password}&USER={$this->API_UserName}&SIGNATURE={$this->API_Signature}$Api_request";

            curl_setopt($curl_var, CURLOPT_POSTFIELDS, $Api_request_final);

            // Get response from the server.
            $curlResponse = curl_exec($curl_var);

Suppose, if cURL returns any error. It will be cached here.

  if(!$curlResponse)
                return array("ERROR_MESSAGE"=>"Refund Transaction failed".curl_error($curl_var)."(".curl_errno($curl_var).")");

If it returns, success results, than parse the array string and make it usable.

 
 $httpResponseAr = explode("&", $curlResponse);

            $aryResponse = array();
            foreach ($httpResponseAr as $i => $value)     {
                $tmpAr = explode("=", $value);
                if(sizeof($tmpAr) > 1)   {
                    $aryResponse[$tmpAr[0]] = urldecode($tmpAr[1]);
                }
            }

Suppose the refund failed, than we can get it with the following check.

 if((0 == sizeof($aryResponse)) || !array_key_exists('ACK', $aryResponse))
                return array("ERROR_MESSAGE"=>"Invalid HTTP Response for POST request ($reqStr) to {$this->API_Endpoint}");

And Now, Let’s create an object for our class and make use of it.

 
 $DataInArray['transactionID'] =  "XXXXXXXXXXXXXXXXXXXXX";
 $DataInArray['refundType'] = "Full"; //Partial or Full
 $DataInArray['currencyCode'] = "GBP";
 $DataInArray['amount'] = 10;
 $DataInArray['memo'] = "There Memo Detail entered for Full Refund";
 $DataInArray['invoiceID'] = "";
              
 $ref = new KvPayPalRefund();
 $aryRes = $ref->refundAmount($DataInArray);
 if($aryRes['ACK'] == "Success"){                    
      $response = "Success";
 }else {
      $response = "Failure";
 } 

Don’t forget, those parameters are important before making API Request. Here is the Complete code.

<?php

    class KvPayPalRefund   {
        private $API_Username, $API_Password, $Signature, $API_Endpoint, $version;
        function __construct($mode = "sandbox")      {
            if($mode == "live")    {
                $this->API_Username = "xxxxxxx_xxxx.xxxxxx.com";
                $this->API_Password = "XXXXXXXXXXXXXXXX";
                $this->Signature = "XXXXXXXXXXXXXXXXXXXXXXXXX.XXXXXXXXXXXXXXX-XXXXXXXXXXXXXX";
                $this->API_Endpoint = "https://api-3t.paypal.com/nvp";
            }   else     {
                $this->API_Username = "XXXXXXX_XXXX.XXXXXXX.XXX";
                $this->API_Password = "XXXXXXXXXXXXXXXX";                
                $this->Signature    = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XX-XXXXXXXXXXXX.XXXXXXXX";
                $this->API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
            }
            $this->version = "94.0";
        }

        function refundAmount($DataInArray)   {
			$this->API_UserName  = urlencode($this->API_Username);
            $this->API_Password  = urlencode($this->API_Password);
            $this->API_Signature = urlencode($this->Signature);

            $this->version = urlencode($this->version);
			
            if(trim(@$DataInArray['currencyCode'])=="")
                return array("ERROR_MESSAGE"=>"Currency Code is Missing");
            if(trim(@$DataInArray['refundType'])=="")
                return array("ERROR_MESSAGE"=>"Refund Type is Missing");
            if(trim(@$DataInArray['transactionID'])=="")
                return array("ERROR_MESSAGE"=>"Transaction ID is Missing");

            $Api_request = "&TRANSACTIONID={$DataInArray['transactionID']}&REFUNDTYPE={$DataInArray['refundType']}&CURRENCYCODE={$DataInArray['currencyCode']}";

            if(trim(@$DataInArray['invoiceID'])!="")
                $Api_request = "&INVOICEID={$DataInArray['invoiceID']}";

            if(isset($DataInArray['memo']))
                $Api_request .= "&NOTE={$DataInArray['memo']}";

            if(strcasecmp($DataInArray['refundType'], 'Partial') == 0)    {
                if(!isset($DataInArray['amount']))   {
                    return array("ERROR_MESSAGE"=>"For Partial Refund - It is essential to mention Amount");
                }    else     {
                    $Api_request = $Api_request."&AMT={$DataInArray['amount']}";
                }

                if(!isset($DataInArray['memo']))   {
                    return array("ERROR_MESSAGE"=>"For Partial Refund - It is essential to enter text for Memo");
                }
            }			           

            $curl_var = curl_init();
            curl_setopt($curl_var, CURLOPT_URL, $this->API_Endpoint);
            curl_setopt($curl_var, CURLOPT_VERBOSE, 1);

            curl_setopt($curl_var, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl_var, CURLOPT_SSL_VERIFYHOST, FALSE);

            curl_setopt($curl_var, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl_var, CURLOPT_POST, 1);

            $Api_request_final = "METHOD=RefundTransaction&VERSION={$this->version}&PWD={$this->API_Password}&USER={$this->API_UserName}&SIGNATURE={$this->API_Signature}$Api_request";

            curl_setopt($curl_var, CURLOPT_POSTFIELDS, $Api_request_final);

            // Get response from the server.
            $curlResponse = curl_exec($curl_var);

            if(!$curlResponse)
                return array("ERROR_MESSAGE"=>"RefundTransaction failed".curl_error($curl_var)."(".curl_errno($curl_var).")");

            // Extract the response details.
            $httpResponseAr = explode("&", $curlResponse);

            $aryResponse = array();
            foreach ($httpResponseAr as $i => $value)     {
                $tmpAr = explode("=", $value);
                if(sizeof($tmpAr) > 1)   {
                    $aryResponse[$tmpAr[0]] = urldecode($tmpAr[1]);
                }
            }

            if((0 == sizeof($aryResponse)) || !array_key_exists('ACK', $aryResponse))
                return array("ERROR_MESSAGE"=>"Invalid HTTP Response for POST request ($reqStr) to {$this->API_Endpoint}");
           // var_dump($aryResponse);
            return $aryResponse;
           
        }
    }

	
	// execution code. 

     $DataInArray['transactionID'] =  "XXXXXXXXXXXXXXXXX";
     $DataInArray['refundType'] = "Full"; //Partial or Full
     $DataInArray['currencyCode'] = "GBP";
     $DataInArray['amount'] = 20;
     $DataInArray['memo'] = "There Memo Detail entered for Full Refund";
     $DataInArray['invoiceID'] = "";
    // print_r($DataInArray);
     $ref = new KvPayPalRefund();
     $aryRes = $ref->KvRefundAmount($DataInArray);
     
     if($aryRes['ACK'] == "Success"){         
        $response = "Success";
     }else {
         $response = "Failure";
     } 
	 echo $response; 
?>

 

commenter

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, OpenCart Theme Development, PHP, HTML, CSS, jQuery, Bootstrap development and content SEO.

One comment

  1. commenter

    Thank You for the given Information. It’s special to read about refunding a transaction of PayPal transfer.

Comment Below

Your email address will not be published. Required fields are marked *

*

Current ye@r *

Menu

Sidebar

Subscribe E-mail Updates

Congrats, You are Subscribed to Receive Updates.

Advertisement

Category Posts