I have successfully implement PayPal with laravel. I am able to make payment using PayPal APIs. Now I want to implement refund from PayPal using laravel. I don't want to make refund from PayPal dashboard but i want to make it done from our admin panel where admin user can see list of payments and link to refund that amount to customer. After successful payment I got Transaction id in response from PayPal. If i use that transaction id to refund then i am not able to do that successfully, and if i copy transaction id from paypal dashboard where all transactions are listed and get detail information of that transaction, then i am able to make refund success. Can anyone tell me how can i get that transaction id using which i can make refund using laravel.
I have to use below code to get actual sale id to refund amount using code not from paypal dashboard
$apiContext = new ApiContext(new OAuthTokenCredential(
"<CLIENT_ID>", "<CLIENT_SCRET_KEY>")
);
$payments = Payment::get($payment_id, $apiContext);
$payments->getTransactions();
$obj = $payments->toJSON();//I wanted to look into the object
$paypal_obj = json_decode($obj);//I wanted to look into the object
$transaction_id = $paypal_obj->transactions[0]->related_resources[0]->sale->id;
$this->getRefundPayment($transaction_id);
public function getRefundPayment($transaction_id){
$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);
$transactionid = $transaction_id;
$DataInArray['currencyCode'] = 'INR';
$DataInArray['refundType'] = 'Full';
$DataInArray['transactionID'] = $transactionid;
$DataInArray['invoiceID'] = '';
$DataInArray['memo'] = 'This is refund of transaction id ='.$transactionid;
$DataInArray['amount'] = '';
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;
}
Related
This is the API provided by https://www.cashmaal.com/api I deposited some cash in my cashmaal account and the transaction id I got whenever I try to verify the payment by transaction id it shows me an error
Error: Error! Transaction Id () is invalid.
$web_id=""; // Your Web ID here (you can found this on cashmaal account where you add site)
if(isset($_POST['CM_TID'])) {
$CM_TID=$_POST['CM_TID']; // getting TID with user redirection
$url="https://www.cashmaal.com/Pay/verify_v2.php?CM_TID=".urlencode($CM_TID)."&web_id=".urlencode($web_id);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result,true);
if($obj['status'] == 1)
{ // it means payment received....
//response format in JSON
//Example Response
/*
{"status":"1","receiver_account":"8","USD_amount":"1.670","fee_in_USD":"0.000","PKR_amount":"280","fee_in_PKR":"0","USD_amount_with_fee":"1.670","PKR_amount_with_fee":"280","trx_website":"website.com","transaction_id":"2JW9651118P","trx_date":"25-03-2020 9:13:48 PM","order_id":"12345678","addi_info":"Test Payment","sender_details":"Fund Received From 161919","trx_details":"$1.67 Receive against TID: '2JW9651118P'"}
*/
// Verify All things and Confirm user order here
if($obj['USD_amount'] == '2')
{
echo 'we received your payment';
}
else
{
echo "we didn't received the your mentioned payment ";
}
}
else
{
echo "Error:".$obj['error'];
}
}
Just found a solution of this that this cashmaal api verify the transaction id only if the transaction is done by other cashmaal account
I am using the PayPal IPN feature but I keep getting _POST[payment_status] = Pending when I make a test using the Sandbox. Because of that, I can't test the full purchase to make sure the whole process works properly.
Here is my code:
// Set the request paramaeter
$req = 'cmd=_notify-validate';
// Run through the posted array
foreach ($_POST as $key => $value)
{
// If magic quotes is enabled strip slashes
if (get_magic_quotes_gpc())
{
$_POST[$key] = stripslashes($value);
$value = stripslashes($value);
}
$value = urlencode($value);
// Add the value to the request parameter
$req .= "&$key=$value";
}
$ch = curl_init(); // Starts the curl handler
curl_setopt($ch, CURLOPT_URL,$paypal[$testing]); // Sets the paypal address for curl
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // Returns result to a variable instead of echoing
curl_setopt($ch, CURLOPT_TIMEOUT, 3); // Sets a time limit for curl in seconds (do not set too low)
curl_setopt($ch, CURLOPT_POST, 1); // Set curl to send data using post
curl_setopt($ch, CURLOPT_POSTFIELDS, $req); // Add the request parameters to the post
$result = curl_exec($ch); // run the curl process (and return the result to $result
curl_close($ch);
if (strcmp ($result, "VERIFIED") == 0) // It may seem strange but this function returns 0 if the result matches the string So you MUST check it is 0 and not just do strcmp ($result, "VERIFIED") (the if will fail as it will equate the result as false)
{
// It worked
// do my stuff
}else{
foreach($_POST as $key=>$value){
$post_str .="_POST[$key] = $value<br>";
}
$sub = "Paypal error";
$mes = "$post_str";
mailer($sub, $mes, $from, $to);
}
This is the error message I get in my email:
_POST[mc_gross] = 120.00
_POST[protection_eligibility] = Ineligible
_POST[address_status] = confirmed
_POST[payer_id] = QDZDYY4JWGFVG
_POST[tax] = 0.00
_POST[address_street] = 1 Maire-Victorin
_POST[payment_date] = 12:25:03 Apr 11, 2013 PDT
_POST[payment_status] = Pending
_POST[charset] = windows-1252
_POST[address_zip] = M5A 1E1
_POST[first_name] = gppl
_POST[address_country_code] = CA
_POST[address_name] = gppl Simard's Test Store
_POST[notify_version] = 3.7
_POST[custom] =
_POST[payer_status] = verified
_POST[address_country] = Canada
_POST[address_city] = Toronto
_POST[quantity] = 1
_POST[verify_sign] = An5ns1Kso7MWUdW4ErQKJJJ4qi4-AjAXF3KMNcb6G83Jslw18dw.Ti32
_POST[payer_email] = 78h23d8712h3d#x.com
_POST[txn_id] = 2KU491796R824634N
_POST[payment_type] = instant
_POST[payer_business_name] = gppl x's Test Store
_POST[last_name] = Simard
_POST[address_state] = Ontario
_POST[receiver_email] = x#x.x
_POST[pending_reason] = unilateral
_POST[txn_type] = web_accept
_POST[item_name] = 926537
_POST[mc_currency] = CAD
_POST[item_number] =
_POST[residence_country] = CA
_POST[test_ipn] = 1
_POST[handling_amount] = 0.00
_POST[transaction_subject] = 926537
_POST[payment_gross] =
_POST[shipping] = 0.00
_POST[ipn_track_id] = c7dcef0b1c333
This error is really driving me nuts.
Just so you guys know, I already have the Payment review set to off.
If you are useing sandbox, open developer.paypal.com->Dashboard->Accounts->facilitator#yourhost.com->Profile->Settings. Set 'Payment review' to 'Off'
Make sure your accounts have a confirmed email address. This typically happens when you send a payment to an account that doesn't have a confirmed email address. So check the seller account, and make sure the email address is confirmed that you sent the payment to.
I had this problem - I was sending PayPal my "live" payer_email, when I changed it to the business email in the sandbox it worked. same as my live email with ****-facilitator#yoursite.com
Login to your Sandbox account with the business, and see if you have any 'Unclaimed' payments. This could be because they are in a different currency than the one of your main account.
I know you may ask why I don't try to google the solution first, now I can say that I already googled for it, unfortunately it come out too many solutions and different ways to do that.
My situation is like this, I want to allow those clients to be able to subscribe my service annually.
From this link, they suggested too much solution, I don't know which 1 is fit to my situation. And of course, I want to use the free service (direct debit need monthly fee).
Which mean that, I want to store the transaction# into my db every year when the service subscribed by my client is expired, and it automatically send an acknowledgement email to clients and my company's email.
In summary,
Which way is suitable to my situation.
Is cron job need in this case? or just need to use recurring payment that provided by paypal?
Is there any link or example (i.e. coding implementation in sandbox)?
Thanks in advanced.
You could use PayPal Payments Pro with the Direct Payment API to process the initial credit card transactions. Then you can store the transaction in your system, and set your system to run a cron job and perform a reference transaction API call to charge the buyer again. This will give you the effects of setting up a recurring payment profile without actually having the service through PayPal.
However, if you prefer to do less coding and setting up your system to perform cron jobs and etc, then you could just sign up for PayPal's recurring payments/recurring billing services, which would allow you to just make an API call to PayPal to set up a profile. Then PayPal will take of billing your buyers when they should be billed.
HI I have made code for ZF
public function processPaymentAction()
{
$methodName = 'CreateRecurringPaymentsProfile';
// from nvpHeader function
$API_Endpoint = 'https://api-3t.sandbox.paypal.com/nvp';
$version = '65.2';
// But you can use here your own Sandbox API credentials of Business account
// and you can get through Payapl Sandbox API Credentials Link on Left.
$API_UserName = 'platfo_1255077030_biz_api1.gmail.com';
$API_Password = '1255077037';
$API_Signature = 'Abg0gYcQyxQvnf2HDJkKtA-p6pqhA1k-KTYE0Gcy1diujFio4io5Vqjf';
$subject = '';
global $nvp_Header, $AUTH_token, $AUTH_signature, $AUTH_timestamp;
$nvpHeaderStr = "";
//pr($this->data);die;
//$this->data['User']['paymentType']
$paymentType = urlencode('Sale');
$firstName = urlencode("Jaskaran");
$lastName = urlencode("Singh");
$creditCardType = urlencode("Visa");
$creditCardNumber = urlencode("4798720058660243");
$expDateMonth =urlencode(11);
// Month must be padded with leading zero
$padDateMonth = str_pad($expDateMonth, 2, '0', STR_PAD_LEFT);
$expDateYear = urlencode(2015);
$cvv2Number = urlencode(962);
$address1 = urlencode("1 Main St");
$address2 = urlencode("");
$city = urlencode("San Jose");
$state = urlencode("CA");
$zip = urlencode(95131);
$amount = urlencode(1.00);
// $init_amount = urlencode($this->data['User']['pack_price']);
$currencyCode="USD";
$profileDesc = urlencode("Welcome to the world of shopping where you get everything");
$billingPeriod = urlencode("Week");
$billingFrequency = urlencode(4);
$totalBillingCycles = urlencode(0);
################# Commented as we need to define through Admin ##############
$profileStartDateDay = 10;
// Day must be padded with leading zero
$padprofileStartDateDay = str_pad($profileStartDateDay, 2, '0', STR_PAD_LEFT);
$profileStartDateMonth = 02;
// Month must be padded with leading zero
$padprofileStartDateMonth = str_pad($profileStartDateMonth, 2, '0', STR_PAD_LEFT);
$profileStartDateYear = 2015;
$profileStartDate = urlencode($profileStartDateYear . '-' . $padprofileStartDateMonth . '-' . $padprofileStartDateDay . 'T00:00:00Z');
//string from nvpHeader
$nvpHeaderStr = "&PWD=".urlencode($API_Password)."&USER=".urlencode($API_UserName)."&SIGNATURE=".urlencode($API_Signature);
$nvpstr="&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber&EXPDATE=". $padDateMonth.$expDateYear."&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName&STREET=$address1&CITY=$city&STATE=$state".
"&ZIP=$zip&COUNTRYCODE=US&CURRENCYCODE=$currencyCode&PROFILESTARTDATE=$profileStartDate&DESC=$profileDesc&BILLINGPERIOD=$billingPeriod&BILLINGFREQUENCY=$billingFrequency&TOTALBILLINGCYCLES=$totalBillingCycles";
$nvpstr = $nvpHeaderStr.$nvpstr;
//check if version is included in $nvpStr else include the version.
if(strlen(str_replace('VERSION=','', strtoupper($nvpstr))) == strlen($nvpstr))
{
$nvpstr = "&VERSION=" . urlencode($version) . $nvpstr;
}
$nvpreq="METHOD=".urlencode($methodName).$nvpstr;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
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);
//$nvpreq=”METHOD=”.urlencode($methodName).$nvpStr;
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
//getting response from server
$response = curl_exec($ch);
//convrting NVPResponse to an Associative Array
$nvpResArray=$this->deformatNVP($response);
$nvpReqArray=$this->deformatNVP($nvpreq);
if (curl_errno($ch))
{
echo "cURL Error";
die;
// moving to display page to display curl errors
$_SESSION['curl_error_no']=curl_errno($ch) ;
$_SESSION['curl_error_msg']=curl_error($ch);
//$location = "APIError.php";
//header("Location: $location");
}
else
{
//closing the curl
curl_close($ch);
}
#### Checking error ###
if(!empty($nvpResArray))
{
if($nvpResArray['ACK'] == 'Failure')
{
echo "ERROR : ". $errmsg = $nvpResArray["L_LONGMESSAGE0"];
echo "<pre>";
print_r($nvpResArray);
die;
}
}
// Print this array you will get some necessary info
################ Starting data insert##################
if($nvpResArray['ACK'] == 'Success')
{
echo 'Success';
print_r($nvpResArray);
die;
// save data into tables for Recurring Profile
}
}
############### Function deformatNVP #########
/** This function will take NVPString and convert it to an Associative Array and it will decode the response.
* It is usefull to search for a particular key and displaying arrays.
* #nvpstr is NVPString.
* #nvpArray is Associative Array.
*/
function deformatNVP ($nvpstr)
{
$intial = 0;
$nvpArray = array();
while (strlen($nvpstr)) {
//postion of Key
$keypos = strpos($nvpstr, '=');
//position of value
$valuepos = strpos($nvpstr, '&') ? strpos($nvpstr, '&') : strlen(
$nvpstr);
/*getting the Key and Value values and storing in a Associative Array*/
$keyval = substr($nvpstr, $intial, $keypos);
$valval = substr($nvpstr, $keypos + 1, $valuepos - $keypos - 1);
//decoding the respose
$nvpArray[urldecode($keyval)] = urldecode($valval);
$nvpstr = substr($nvpstr, $valuepos + 1, strlen($nvpstr));
}
return $nvpArray;
}
function formAutorization ($auth_token, $auth_signature, $auth_timestamp)
{
$authString = "token=" . $auth_token . ",signature=" . $auth_signature .
",timestamp=" . $auth_timestamp;
return $authString;
}
I work with an e-commerce website that uses a PayPal checkout component written in PHP. For accounting purposes I want to retrieve some additional information using the PayPal PHP SOAP API.
I found out how to access the transaction using the transaction id and the GetTransactionDetails object:
// snip - include PayPal libraries and set up APIProfile object -
$trans_details =& PayPal::getType('GetTransactionDetailsRequestType');
$tran_id = $_GET['transactionID'];
$trans_details->setTransactionId($tran_id, 'iso-8859-1');
$caller =& PayPal::getCallerServices($profile);
$response = $caller->GetTransactionDetails($trans_details);
$paymentTransDetails = $response->getPaymentTransactionDetails();
// snip - work with transaction details -
However, I need to enhance this so that I can find out the 12-character string transaction id first by using the invoice id which I have available in a local MySQL database (which is also referenced in the transaction on the PayPal website).
I guess that I have to use Transaction Search for that but I don't know how to do this with the PHP SOAP API. How can I retrieve the transaction id for an invoice id?
I dived into the API documentation and managed to find it out.
// snip - include PayPal libraries and set up APIProfile object (variable: profile) -
$trans_search =& PayPal::getType('TransactionSearchRequestType');
// 01/12/201 as an example date, we always need a start date for the API
$start_date_str = '01/12/2011';
$start_time = strtotime($start_date_str);
$iso_start = date('Y-m-d\T00:00:00\Z', $start_time);
$trans_search->setStartDate($iso_start, 'iso-8859-1');
$invoice_ID = '10942456'; // here we insert the invoice ID we know
$trans_search->setInvoiceID($invoice_ID);
$caller =& PayPal::getCallerServices($profile);
$response = $caller->TransactionSearch($trans_search); // execute search
$ptsr = $response->getPaymentTransactions();
$nrecs = sizeof($ptsr);
$ack = $response->getAck();
if( ($ack != ACK_SUCCESS)
&& ($ack != ACK_SUCCESS_WITH_WARNING) )
exit; // jump out on error
if($nrecs == 1){ // check whether we found only one transaction (as expected)
$paymentTransaction = $ptsr[0];
// we found our transaction ID
$transID = $paymentTransaction->getTransactionID();
}else{
// invoice ID not unique?! :-(
exit('Found multiple transactions: '. print_r($ptsr, true)); // jump out
}
// snip - work with transaction ID -
It's easy enough to use the TransactionSearch API to find a transaction by invoice number. All you need to do is send the INVNUM parameter along in the API call to PayPal.
For example (based on PayPal's TransactionSearch PHP sample code):
<?php
/** TransactionSearch NVP example; last modified 08MAY23.
*
* Search your account history for transactions that meet the criteria you specify.
*/
$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;
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode('xxxxxxxxxxxx');
$API_Password = urlencode('yyyyyyyyy');
$API_Signature = urlencode('zzzzzzzzzzzzzzzzzzzzzzz');
$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('84.0');
// 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;
}
Up to here it's all as usual. The only changes to the sample are here:
// Set request-specific fields.
//$transactionID = urlencode('example_transaction_id');
$invoice = urlencode('1234');
// Add request-specific fields to the request string.
//$nvpStr = "&TRANSACTIONID=$transactionID";
$nvpStr = "&INVNUM=$invoice";
Here, by setting a proper STARTDATE:
// Set additional request-specific fields and add them to the request string.
$startDateStr = "01/01/2010"; // in 'mm/dd/ccyy' format
$endDateStr; // in 'mm/dd/ccyy' format
if(isset($startDateStr)) {
$start_time = strtotime($startDateStr);
$iso_start = date('Y-m-d\T00:00:00\Z', $start_time);
$nvpStr .= "&STARTDATE=$iso_start";
}
if(isset($endDateStr)&&$endDateStr!='') {
$end_time = strtotime($endDateStr);
$iso_end = date('Y-m-d\T24:00:00\Z', $end_time);
$nvpStr .= "&ENDDATE=$iso_end";
}
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('TransactionSearch', $nvpStr);
And here, by adding a simple if statement to trigger whether or not to return the full TransactionSearch API result, or only return the PayPal transaction ID (bla.php?view=minimal):
if($_GET['view'] != "minimal") {
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
echo('TransactionSearch Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else {
echo('TransactionSearch failed: ' . print_r($httpParsedResponseAr, true));
}
}
else {
// Output only the TransactionID
echo $httpParsedResponseAr['L_TRANSACTIONID0'];
}
?>
This is a question about Paypal Mass Pay IPN. My platform is PHP & mySQL.
All over the Paypal support website, I have found IPN for only payments made. I need an IPN on similar lines for Mass Pay but could not find it. Also tried experimenting with already existing Mass Pay NVP code, but that did not work either.
What I am trying to do is that for all the recipients to whom the payment has been successfully sent via Mass Pay, I want to record their email, amount and unique_id in my own database table. If possible, I want to capture the payment status as well, whether it has been a success of failure and based upon the same, I need to do some in house processing.
The existing code Mass pay code is below:
<?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;
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode('my_api_username');
$API_Password = urlencode('my_api_password');
$API_Signature = urlencode('my_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');
// 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;
}
// Set request-specific fields.
$emailSubject =urlencode('example_email_subject');
$receiverType = urlencode('EmailAddress');
$currency = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
// Add request-specific fields to the request string.
$nvpStr="&EMAILSUBJECT=$emailSubject&RECEIVERTYPE=$receiverType&CURRENCYCODE=$currency";
$receiversArray = array();
for($i = 0; $i < 3; $i++) {
$receiverData = array( 'receiverEmail' => "user$i#paypal.com",
'amount' => "example_amount",
'uniqueID' => "example_unique_id",
'note' => "example_note");
$receiversArray[$i] = $receiverData;
}
foreach($receiversArray as $i => $receiverData) {
$receiverEmail = urlencode($receiverData['receiverEmail']);
$amount = urlencode($receiverData['amount']);
$uniqueID = urlencode($receiverData['uniqueID']);
$note = urlencode($receiverData['note']);
$nvpStr .= "&L_EMAIL$i=$receiverEmail&L_Amt$i=$amount&L_UNIQUEID$i=$uniqueID&L_NOTE$i=$note";
}
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('MassPay', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
exit('MassPay Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else {
exit('MassPay failed: ' . print_r($httpParsedResponseAr, true));
}
?>
In the code above, how and where do I add code to capture the fields that I requested above? Any code indicating the solution is highly appreciated.
Thank you very much.
I am more familiar with Recurring Payments, but I think the IPN response will send back the values you are seeking. Just capture them out of the array sent back, place them in some variables, and save to the database.
$email = $httpParsedResponseAr["receiver_email"];
$amount = $httpParsedResponseAr["mc_currency_x"];
Here are the values for the Mass Pay Variables
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_IPNandPDTVariables
There are generally two ways to get this data, one is to look at the responses from the call you make to masspay directly, and the other is setting up IPN for your account.
You have to setup the global IPN, I cannot find a way to send in the IPN listen url as a variable on this call.
HTH
-FT