Sample PHP code for Paypal RefundTransaction using Paypal NVP API

Depending on different conditions, sometimes we might need to refund the amount paid by users. We can refund the user by directly logging into the Paypal or use their API so, that everything can be handle from our own site with just one click. On this post, we will learn, how we can use Paypal NVP(Name Value Pair) API to refund users.

Paypal consists of RefundTransaction Method for these purposes. RefundTransaction API operation can be used to issue a full or partial refund for any transaction within a default period of 60 days from when the payment is received. Below, we use CURL to request the Paypal API, but you can use fsock as well.

Before, diving into the code, lets grab necessary API credentials from Paypal, which is required to authenticate the call to Paypal API’s. Below are the steps you need to follow to get your API credentials:

  • Login to your Paypal Business Account
  • Navigate to “My Selling Tools” under Profile menu. Refer to screenshot below:my-selling-tools-paypal
  • Under Selling online category, locate “API access” and click on “Update” button showing next to it. Refer to screenshot below:paypal-api-access
  • You will be presented with the Paypal API access page, click on Request API signature under Option 2
  • On Request API Credentials page, select Request API access and click Agree and Submit as shown in screenshot below.
  • Once submit, you will be taken to the page with your api credentials, as shown in screenshot below:paypal-api-credentials

API Username, API Password and Signature is what required for requesting Paypal API. Once you get these details, you can use the following code to refund the transaction.

Sample code in PHP to refund transaction using Paypal API NVP

 * 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_, $env) {

 // Set up your API credentials, PayPal end point, and API version.
 $API_UserName = urlencode('Your API username');
 $API_Password = urlencode('Your API password');
 $API_Signature = urlencode('Your API signature');
 if("sandbox" === $env)
 	$API_Endpoint = "https://api-3t.$";
 	$API_Endpoint = "";
 $version = urlencode('119');

 // 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_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;

// Set request-specific fields.
$transactionID = urlencode('example_transaction_id');
$refundType = urlencode('Full');  // or 'Partial'
$amount;                          // required if Partial.
$memo;                            // required if Partial.
$currencyID = urlencode('USD');   // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')

// Add request-specific fields to the request string.
$nvpStr = "&TRANSACTIONID=$transactionID&REFUNDTYPE=$refundType&CURRENCYCODE=$currencyID";

if(isset($memo)) {
	$nvpStr .= "&NOTE=$memo";

if(strcasecmp($refundType, 'Partial') == 0) {
	if(!isset($amount)) {
		exit('Partial Refund Amount is not specified.');
	} else {
		$nvpStr = $nvpStr."&AMT=$amount";
	if(!isset($memo)) {
		exit('Partial Refund Memo is not specified.');

// Execute the API operation; see the PPHttpPost function above.

$env = 'sandbox';
$httpParsedResponseAr = PPHttpPost('RefundTransaction', $nvpStr);

if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
	exit('Refund Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else  {
	exit('RefundTransaction failed: ' . print_r($httpParsedResponseAr, true));

Leave a Reply

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