Paypal Masspay API Masspay input parse error - php

I am using Paypal MassPay API in php.
My code was working fine but now I am getting this error.
MassPay failed:
Array ( [TIMESTAMP] => 2014/07/06T17%3a27%3a04Z
[CORRELATIONID] => 5d6bf81231859
[ACK] => Failure
[VERSION] => 51%2e0
[BUILD] => 11753088
[L_ERRORCODE0] => 10314
[L_SHORTMESSAGE0] => Masspay input parse error
[L_LONGMESSAGE0] =>The input to the masspay server is incorrect e Please make sure that you are using a correctly formatted input e
[L_SEVERITYCODE0] => Error
Anyone has idea why I am getting this error now? I can provide code if required.
This is the main class:
Paypal_class.php
<?php
class Paypal {
public function __construct($username, $password, $signature) {
$this->username = urlencode($username);
$this->password = urlencode($password);
$this->signature = urlencode($signature);
$this->version = urlencode("51.0");
$this->api = "https://api-3t.paypal.com/nvp";
//The functions can be modified but need to be urlencoded
$this->type = urlencode("EmailAddress");
$this->currency = urlencode("USD");
$this->subject = urlencode("Instant Paypal Payment");
}
public function pay($email, $amount, $note="Instant Payment") {
$string = "&EMAILSUBJECT=".$this->subject."&RECEIVERTYPE=".$this->type."&CURRENCYCODE=".$this->currency;
$string .= "&L_EMAIL0=".urlencode($email)."&L_Amt0=".urlencode($amount)."&L_NOTE0=".urlencode($note);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->api);
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);
$request = "METHOD=MassPay&VERSION=".$this->version."&PWD=".$this->password."&USER=".$this->username."&SIGNATURE=".$this->signature."$string";
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit("MassPay failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
$httpResponseArray = explode("&", $httpResponse);
$httpParsedResponse = array();
foreach ($httpResponseArray as $i => $value) {
$tempArray = explode("=", $value);
if(sizeof($tempArray) > 1) {
$httpParsedResponse[$tempArray[0]] = $tempArray[1];
}
}
if((0 == sizeof($httpParsedResponse)) || !array_key_exists('ACK', $httpParsedResponse)) {
exit("Invalid HTTP Response for POST request($request) to ".$this->api);
}
return $httpParsedResponse;
}
}
?>
Calling this class with example.php file:
<?php
require "paypal_class.php";
$paypal = new Paypal("example.com", "xyz, "abc");
$send_payment = $paypal->pay("abc#gmail.com", ".001", "Thanks for an amazing service");
if("SUCCESS" == strtoupper($send_payment["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($send_payment["ACK"])) {
exit('MassPay Completed Successfully: '.print_r($send_payment, true));
} else {
exit('MassPay failed: ' . print_r($send_payment, true));
}
?>
Thanks

I was able to solve my problem. I changed the amount to be sent from "0.001" to "0.01", this code worked.
May be Paypal MassPay API doesn't deal with amount having more than two digits after decimal.

Related

Paypal IPN keeps retrying and then it fails

I've tested on IPN simulator and it seems fine, IPN is being sent and verified. Now I'm testing on sandbox, but in IPN History I can see that the delivery status keeps retrying and then it fails. It's never being sent. The HTTP response code field is empty. I'm working on localhost, but I'm using with ngrok where I receive the 200 OK HTTP response. I also want to insert data into mysql database, but I suppose it's also one of the reasons I can't. What am I doing wrong? I'm fairly new to PHP and I've gone through similar questions, but didn't seem to find a solution. I've been on this all day and it's driving me crazy. :) Any help or guideline would be much appreciated!
I'm using a script from github, here is the ipn.php:
<?php
include 'xxxxxxx.php';
require('PaypalIPN.php');
use PaypalIPN;
$ipn = new PayPalIPN();
// Use the sandbox endpoint during testing.
$ipn->useSandbox();
$verified = $ipn->verifyIPN();
if ($verified) {
$item_number = $_POST['item_number'];
$txn_id = $_POST['txn_id'];
$payment_gross = $_POST['mc_gross'];
$currency_code = $_POST['mc_currency'];
$payment_status = $_POST['payment_status'];
$insert =mysqli_query($conn, "INSERT INTO payments(item_number, txn_id,payment_gross,currency_code,payment_status) VALUES('".$item_number."','".$txn_id."','".$payment_gross."','".$currency_code."','".$payment_status."')");
}
?>
And here is my paypalIPN.php:
<?php
class PaypalIPN
{
private $use_sandbox = false;
private $use_local_certs = false;
/*
* PayPal IPN postback endpoints
*/
const VERIFY_URI = 'https://ipnpb.paypal.com/cgi-bin/webscr';
const SANDBOX_VERIFY_URI = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
/*
* Possible responses from PayPal after the request is issued.
*/
const VALID = 'VERIFIED';
const INVALID = 'INVALID';
/**
* Sets the IPN verification to sandbox mode (for use when testing,
* should not be enabled in production).
* #return void
*/
public function useSandbox()
{
$this->use_sandbox = true;
}
/**
* Determine endpoint to post the verification data to.
* #return string
*/
public function getPaypalUri()
{
if ($this->use_sandbox) {
return self::SANDBOX_VERIFY_URI;
} else {
return self::VERIFY_URI;
}
}
/**
* Verification Function
* Sends the incoming post data back to paypal using the cURL library.
*
* #return bool
* #throws Exception
*/
public function verifyIPN()
{
if ( ! count($_POST)) {
throw new Exception("Missing POST Data");
}
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = [];
foreach ($raw_post_array as $keyval) {
$keyval = explode('=', $keyval);
if (count($keyval) == 2) {
// Since we do not want the plus in the datetime string to be encoded to a space, we manually encode it.
if ($keyval[0] === 'payment_date') {
if (substr_count($keyval[1], '+') === 1) {
$keyval[1] = str_replace('+', '%2B', $keyval[1]);
}
}
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
}
// Build the body of the verification post request, adding the _notify-validate command.
$req = 'cmd=_notify-validate';
$get_magic_quotes_exists = false;
if (function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if ($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// Post the data back to paypal, using curl. Throw exceptions if errors occur.
$ch = curl_init($this->getPaypalUri());
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// This is often required if the server is missing a global cert bundle, or is using an outdated one.
if ($this->use_local_certs) {
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/cert/cacert.pem");
}
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Connection: Close']);
$res = curl_exec($ch);
$info = curl_getinfo($ch);
$http_code = $info['http_code'];
if ($http_code != 200) {
throw new Exception("PayPal responded with http code $http_code");
}
if ( ! ($res)) {
$errno = curl_errno($ch);
$errstr = curl_error($ch);
curl_close($ch);
throw new Exception("cURL error: [$errno] $errstr");
}
curl_close($ch);
// Check if paypal verfifes the IPN data, and if so, return true.
if ($res == self::VALID) {
return true;
} else {
return false;
}
}
}
I've also inserted the notify_url in my html form:
<input type='hidden' name='notify_url' value='http://xxxxxxx/xxxx/ipn.php'>

How to use curl with the MediaWiki API

I want to use mediawiki api to retrieve some informations with a symfony project, i want tu use curl to fo api calls,
I tried with
$ch=curl_init();
$postfield = "action=query&titles=Watch&prop=langlinks&lllimit=20";
$url = "https://en.wikipedia.org/w/api.php"; //url to wiki's api
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfield);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
var_dump($output);
curl_close($ch);
but it does not work, it gives me boolean false as result
Here's a good example of using the PHP API using cURL from WikiMedia itself.
First, logging in:
/**
* Configuration
* -------------------------------------------------
*/
// Start session
session_start();
// Login
$app['username'] = "Example";
$app['password'] = "mypassword";
// Version
$app["version"] = "0.0.1-dev";
// Last modified
date_default_timezone_set("UTC");
$app["lastmod"] = date("Y-m-d H:i", getlastmod()) . " UTC"; // Example: 2010-04-15 18:09 UTC
// User-Agent used for loading external resources
$app["useragent"] = "My First Tool " . $app["version"] . " (LastModified: " . $app["lastmod"] . ") Contact: myfirsttool (at) example (.) com";
// Cookie file for the session
$app["cookiefile"] = tempnam("/tmp", "CURLCOOKIE");
// cURL to avoid repeating ourselfs
$app["curloptions"] =
array(
CURLOPT_COOKIEFILE => $app["cookiefile"],
CURLOPT_COOKIEJAR => $app["cookiefile"],
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $app["useragent"],
CURLOPT_POST => true
);
$app["apiURL"] = "http://www.mediawiki.org/w/api.php";
Then to do the login using cookies:
/**
* Login
* -------------------------------------------------
*/
// Info: http://www.mediawiki.org/wiki/API:Login
$postdata = http_build_query([
"action" => "login",
"format" => "php",
"lgname" => $app["username"],
"lgpassword" => $app["password"],
]);
$ch = curl_init();
curl_setopt_array($ch, $app["curloptions"]);
curl_setopt($ch, CURLOPT_URL, $app["apiURL"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = unserialize(curl_exec($ch));
if(curl_errno($ch)){
$curl_error = "Error 003: " . curl_error($ch);
}
curl_close($ch);
//print_r($result);//die;//DEBUG
// Basic error check + Confirm token
if ($curl_error){
$domain_error = $curl_error;
} else if ($result["login"]["result"] == "NeedToken") {
if (!empty($result["login"]["token"])) {
$_SESSION["logintoken"] = $result["login"]["token"];
$postdata = http_build_query([
"action" => "login",
"format" => "php",
"lgname" => $app["username"],
"lgpassword" => $app["password"],
"lgtoken" => $_SESSION["logintoken"],
]);
$ch = curl_init();
curl_setopt_array($ch, $app["curloptions"]);
curl_setopt($ch, CURLOPT_URL, $app["apiURL"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = unserialize(curl_exec($ch));
if(curl_errno($ch)){
$curl_error = "Error 004: " . curl_error($ch);
}
curl_close($ch);
//print_r($result);//die;//DEBUG
} else {
$other_error = "Error 006: Token error.";
}
}
// Check for all documented errors
// Source: http://www.mediawiki.org/wiki/API:Login#Errors
// Date: 2010-04-17
if ($curl_error){
$domain_error = $curl_error;
} else if ($result["login"]["result"] == "Success") {
$_SESSION["login_result"] = $result["login"]["result"];
$_SESSION["login_lguserid"] = $result["login"]["lguserid"];
$_SESSION["login_lgusername"] = $result["login"]["lgusername"];
} else if ($result["login"]["result"] == "NeedToken") {
$other_error = "Error 005: Token error.";
} else if ($result["login"]["result"] == "NoName") {
$username_error = "The username can not be blank";
} else if ($result["login"]["result"] == "Illegal") {
$username_error = "You provided an illegal username";
} else if ($result["login"]["result"] == "NotExists") {
$username_error = "The username you provided doesn't exist";
} else if ($result["login"]["result"] == "EmptyPass") {
$password_error = "The password can not be blank";
} else if ($result["login"]["result"] == "WrongPass" || $result["login"]["result"] == "WrongPluginPass") {
$password_error = "The password you provided is incorrect";
} else if ($result["login"]["result"] == "CreateBlocked") {
$username_error = "Autocreation was blocked from this IP address";
} else if ($result["login"]["result"] == "Throttled") {
$other_error = "You've logged in too many times in a short time. Try again later.";
} else if ($result["login"]["result"] == "mustbeposted") {
$other_error = "Error 004: Logindata was not send correctly";
} else if ($result["login"]["result"] == "Blocked") {
$username_error = "This account is blocked.";
} else if ($result["login"]["result"]){
$other_error = "Error 001: An unknown event occurred.";
} else {
$other_error = "Error 002: An unknown event occurred.";
}
// The tool you use may log or display the variables:
// $other_error, $username_error and $password_error in the appropiate place
// Such as near a login form, or in a specific debug/logfile
// by default the errors are not outputted
if($_SESSION["login_result"] !== "Success"){
die("Login error. Have you defined app[username] and app[password] ?");
}
Example of building a query:
/**
* Get userinfo
* -------------------------------------------------
*/
$postdata = http_build_query([
"action" => "query",
"format" => "php",
"meta" => "userinfo",
"uiprop" => "rights|hasmsg",
]);
$ch = curl_init();
curl_setopt_array($ch, $app["curloptions"]);
curl_setopt($ch, CURLOPT_URL, $app["apiURL"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = unserialize(curl_exec($ch));
if(curl_errno($ch)){
Death("Error 003: " . curl_error($ch),"API connection failed.");
}
curl_close($ch);
//print_r($result);//die;//DEBUG
// Check for usermessages
if (isset($result['query']['userinfo']['messages'])) {
$api['hasmsg'] = true;
$api['hasmsghtml'] = '<div class="usermessage">You have new messages !</div>';
} else {
// User does not have new messages
}
And finally, how to clean up the session:
// Delete the cookie file
unlink($app["cookiefile"]);
// Destroy the session
session_destroy();
// End this file
die($output);
I tried that, and it works either
public function callWiki($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function getAllCategories()
{
$api = 'https://en.wikipedia.org/w/api.php? action=query&titles=watch&prop=categories&format=json';
//get query result
$api_response = $this->callWiki($api);
$results = json_decode($api_response, true);
}

Paypal PHP MassPay API got declined all the time

We are using Paypal MassPay API to pay for our clients online. Every time we try to send out Mass payment via the API (look at the code below), although it does NOT throw any error, and the money got sent out successfully (logs on Paypal), but then in less than 20 seconds we always receive another message on paypal saying that fund was declined/rejected right away (70% of the time).
So first like this:
Then for majority of the time it becomes to this:
It works perfectly fine when we upload our csv to paypal and do mass payment directly.
Any ideas?
=======
protected function PPHttpPost($methodName_, $nvpStr_){
$environment = 'live'; // or 'beta-sandbox' or 'live'.
// Set up your API credentials, PayPal end point, and API version.
// How to obtain API credentials:
// https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_NVPAPIBasics#id084E30I30RO
$API_UserName = urlencode('xxxx');
$API_Password = urlencode('xxxx');
$API_Signature = urlencode('xxxxxxxx');
$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('93');
// 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;
}
public function actionSend(){
$vEmailSubject = 'XXXX payment - Paypal';
$emailSubject = urlencode($vEmailSubject);
$receiverType = urlencode('EmailAddress');
$currency = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
// Receivers
// Use '0' for a single receiver. In order to add new ones: (0, 1, 2, 3...)
// Here you can modify to obtain array data from database.
$receivers = array(
0 => array(
'receiverEmail' => $model->paypal,
'amount' => $model->money,
'uniqueID' => time(), // 13 chars max
'note' => "XXXX payment",
),
);
$receiversLenght = count($receivers);
// Add request-specific fields to the request string.
$nvpStr="&&EMAILSUBJECT=$emailSubject&RECEIVERTYPE=$receiverType&CURRENCYCODE=$currency";
$receiversArray = array();
for($i = 0; $i < $receiversLenght; $i++)
{
$receiversArray[$i] = $receivers[$i];
}
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 = $this->PPHttpPost('MassPay', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
echo "success";
}else{
echo "something is wrong";
}
}
......

PayPal API refund giving transection id not valid

I am trying to refund with PayPal API.
But i am getting this below error.
public function paypal_refund() {
// Set request-specific fields.
$transactionID = urlencode('2MH09332752606614');
$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 = $this->PPHttpPost('RefundTransaction', $nvpStr);
pr($httpParsedResponseAr);
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));
}
}
/**
* 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
*/
public function PPHttpPost($methodName_, $nvpStr_) {
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode('myusername');
$API_Password = urlencode('mypassword');
$API_Signature = urlencode('mysignature');
$API_Endpoint = "https://api-3t.paypal.com/nvp";
$environment = 'sandbox';
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;
}
Error:
Array
(
[TIMESTAMP] => 2015%2d10%2d29T10%3a18%3a16Z
[CORRELATIONID] => e2b916cdb99d6
[ACK] => Failure
[VERSION] => 51%2e0
[BUILD] => 18308778
[L_ERRORCODE0] => 10004
[L_SHORTMESSAGE0] => Transaction%20refused%20because%20of%20an%20invalid%20argument%2e%20See%20additional%20error%20messages%20for%20details%2e
[L_LONGMESSAGE0] => The%20transaction%20id%20is%20not%20valid
[L_SEVERITYCODE0] => Error
)
RefundTransaction failed: Array ( [TIMESTAMP] => 2015%2d10%2d29T10%3a18%3a16Z [CORRELATIONID] => e2b916cdb99d6 [ACK] => Failure [VERSION] => 51%2e0 [BUILD] => 18308778 [L_ERRORCODE0] => 10004 [L_SHORTMESSAGE0] => Transaction%20refused%20because%20of%20an%20invalid%20argument%2e%20See%20additional%20error%20messages%20for%20details%2e [L_LONGMESSAGE0] => The%20transaction%20id%20is%20not%20valid [L_SEVERITYCODE0] => Error )
2MH09332752606614 is not a PayPal transaction id. refer to https://en.support.wordpress.com/paypal-transaction-id/, login sandbox.paypal.com, in account history page to get a valid transaction id.

PayPal Adaptive Payments Error: API credentials are incorrect. Error Code: 520003 [duplicate]

I have stored the customers paypal email address in database and I want to send them money using that email address. I am using PHP.
Anyone please suggest how to do that.
I was looking for the same issue, here's what is working for me.
Tested in 'sandbox' mode and using NVP (instead of SOAP).
Your server must support CURL, in order to verify it use:
<?php
echo 'curl extension/module loaded/installed: ';
echo ( !extension_loaded('curl')) ? 'no' : 'yes';
echo "<br />\n";
phpinfo(INFO_MODULES); // just to be sure
?>
If is not loaded or installed ask to your hostmaster or get it here, otherwise go ahead:
<?php
// code modified from source: https://cms.paypal.com/cms_content/US/en_US/files/developer/nvp_MassPay_php.txt
// documentation: https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_api_masspay
// sample code: https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_code
// eMail subject to receivers
$vEmailSubject = 'PayPal payment';
/** MassPay NVP example.
*
* Pay one or more recipients.
*/
// For testing environment: use 'sandbox' option. Otherwise, use 'live'.
// Go to www.x.com (PayPal Integration center) for more information.
$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.
// How to obtain API credentials:
// https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_NVPAPIBasics#id084E30I30RO
$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($vEmailSubject);
$receiverType = urlencode('EmailAddress');
$currency = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
// Receivers
// Use '0' for a single receiver. In order to add new ones: (0, 1, 2, 3...)
// Here you can modify to obtain array data from database.
$receivers = array(
0 => array(
'receiverEmail' => "user1#paypal.com",
'amount' => "20.00",
'uniqueID' => "id_001", // 13 chars max
'note' => " payment of commissions"), // I recommend use of space at beginning of string.
1 => array(
'receiverEmail' => "user2#paypal.com",
'amount' => "162.38",
'uniqueID' => "A47-92w", // 13 chars max, available in 'My Account/Overview/Transaction details' when the transaction is made
'note' => " payoff of what I owed you" // space again at beginning.
)
);
$receiversLenght = count($receivers);
// Add request-specific fields to the request string.
$nvpStr="&EMAILSUBJECT=$emailSubject&RECEIVERTYPE=$receiverType&CURRENCYCODE=$currency";
$receiversArray = array();
for($i = 0; $i < $receiversLenght; $i++)
{
$receiversArray[$i] = $receivers[$i];
}
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));
}
?>
Good luck!
What you're looking for is DoMassPay from the PayPal official code samples, not easy to guess that name :P
They have added sample code to their website:
https://cms.paypal.com/cms_content/US/en_US/files/developer/nvp_MassPay_php.txt

Categories