Thursday 13 October 2011

recurring payment code for paypal using php with NVP

This is a quick code for creating recurring profile on paypal using PHP with NVP

<?php

$environment = 'sandbox'; // or 'beta-sandbox' or 'live'

/**
 * 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_) {
 global $environment;

 $API_UserName = urlencode('API Username');
 $API_Password = urlencode('API Password');
 $API_Signature = urlencode('API Signature');
 $API_Endpoint = "https://api-3t.paypal.com/nvp";
 
 if("sandbox" === $environment || "beta-sandbox" === $environment) {
  $API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
 }
 $version = urlencode('51.0');

 // setting the curl parameters.
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
 curl_setopt($ch, CURLOPT_VERBOSE, 1);

 // turning 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);

 // NVPRequest for submitting to server
 $nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";

 // setting the nvpreq as POST FIELD to curl
 curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

 // getting response from server
 $httpResponse = curl_exec($ch);

 if(!$httpResponse) {
  exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
 }

 // Extract the RefundTransaction 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;
}

/*--------------------*/
// Collect the payment info

// Set request-specific fields.
$firstName = urlencode('sajin');
$lastName = urlencode('tm');
$creditCardType = urlencode('Visa');
$creditCardNumber = urlencode('4824255179800020');
$expDateMonth = '10';
// Month must be padded with leading zero
$padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));

$expDateYear = urlencode('2016');
$cvv2Number = urlencode('');
$address1 = urlencode('address 1');
$address2 = urlencode('address 2');
$city = urlencode('United States ');
$state = urlencode('New York');
$zip = urlencode('13355');
$country = urlencode('US');    // US or other valid country code
$amount = urlencode('12');
$currencyID = urlencode('USD');       // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
/*--------------------*/


$token = urlencode("");
$paymentAmount = urlencode("12");
$currencyID = urlencode("USD");      // or other currency code ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
$startDate = urlencode("2011-12-12T0:0:0");
$billingPeriod = urlencode("Month");    // or "Day", "Week", "SemiMonth", "Year"
$billingFreq = urlencode("1");      // combination of this and billingPeriod must be at most a year
$desc = urlencode('desc sample');
$nvpStr="&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber&EXPDATE=$padDateMonth$expDateYear&FIRSTNAME=$firstName&LASTNAME=$lastName&AMT=$paymentAmount&CURRENCYCODE=$currencyID&PROFILESTARTDATE=$startDate";
$nvpStr .= "&BILLINGPERIOD=$billingPeriod&BILLINGFREQUENCY=$billingFreq&DESC=$desc";

$httpParsedResponseAr = PPHttpPost('CreateRecurringPaymentsProfile', $nvpStr);
echo "
";
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
exit('CreateRecurringPaymentsProfile Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else  {
exit('CreateRecurringPaymentsProfile failed: ' . print_r($httpParsedResponseAr, true));
}
echo "
"; ?>

The output in normal case will be

CreateRecurringPaymentsProfile Completed Successfully: Array
(
    [PROFILEID] => I%2dK1EXE5JU3JCC
    [TIMESTAMP] => 2011%2d10%2d23T13%3a30%3a55Z
    [CORRELATIONID] => a2133526075
    [ACK] => Success
    [VERSION] => 51%2e0
    [BUILD] => 2183220
)

2 comments:

  1. CreateRecurringPaymentsProfile failed: Array
    (
    [TIMESTAMP] => 2015%2d02%2d18T11%3a01%3a31Z
    [CORRELATIONID] => 235106507502
    [ACK] => Failure
    [VERSION] => 58%2e0
    [BUILD] => 15295733
    [L_ERRORCODE0] => 11586
    [L_SHORTMESSAGE0] => DPRP%20is%20disabled%2e
    [L_LONGMESSAGE0] => DPRP%20is%20disabled%20for%20this%20merchant%2e
    [L_SEVERITYCODE0] => Error
    )

    I am facing a problem white creating a recurring profile. Please help.
    Thanks in advance

    ReplyDelete
  2. Very nice tutorial thanks man

    ReplyDelete

Please share your thought about this