Paypal IPN keeps retrying and then it fails - php

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'>

Related

PayPal IPN Sent with 200 response but my database is not updating

I am trying to implement the PayPal IPN solution. I am checking the IPN History page of my saccount and all messages are being sent with a 200 response. The problem is that nothing in my DB is being updated or inserted.
My environment is:
PHP 7.4
Apache
CentOS 8
I also tried to log something to a file but I am failing to do so. This is the first time I try to implement the PayPal IPN and I am very confused.
This is my current code:
<?php
class PaypalIPN
{
/** #var bool Indicates if the sandbox endpoint is used. */
private $use_sandbox = false;
/** #var bool Indicates if the local certificates are used. */
private $use_local_certs = true;
/** Production Postback URL */
const VERIFY_URI = 'https://ipnpb.paypal.com/cgi-bin/webscr';
/** Sandbox Postback URL */
const SANDBOX_VERIFY_URI = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
/** Response from PayPal indicating validation was successful */
const VALID = 'VERIFIED';
/** Response from PayPal indicating validation failed */
const INVALID = 'INVALID';
const DEBUG = true;
/**
* 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;
}
/**
* Sets curl to use php curl's built in certs (may be required in some
* environments).
* #return void
*/
public function usePHPCerts()
{
$this->use_local_certs = false;
}
/**
* 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 = array();
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';
foreach ($myPost as $key => $value) {
$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, array(
'User-Agent: PHP-IPN-Verification-Script',
'Connection: Close',
));
$res = curl_exec($ch);
if ( ! ($res)) {
$errno = curl_errno($ch);
$errstr = curl_error($ch);
curl_close($ch);
throw new Exception("cURL error: [$errno] $errstr");
}
$info = curl_getinfo($ch);
$http_code = $info['http_code'];
if ($http_code != 200) {
throw new Exception("PayPal responded with http code $http_code");
}
curl_close($ch);
// Check if PayPal verifies the IPN data, and if so, return true.
if ($res == self::VALID) {
// crea el LOG
if($this->DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "IPN Verification: $req ". PHP_EOL, 3, 'ipn.log');
}
return true;
} else {
// crea el LOG
if($this->DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "IPN Verification: $req ". PHP_EOL, 3, 'ipn.log');
}
return false;
}
}
}
$ipn = new PaypalIPN();
// Use the sandbox endpoint during testing.
$ipn->useSandbox();
$verified = $ipn->verifyIPN();
if ($verified) {
/*
* Process IPN
* A list of variables is available here:
* https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNandPDTVariables/
*/
$payment_amount = $_POST['mc_gross'];
$payment_status = $_POST['payment_status'];
$custom = $_POST['custom'];
$payer_email = $_POST['payer_email'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$item_name = $_POST['item_name'];
$payment_currency = $_POST['mc_currency'];
$item_number = $_POST['item_number'];
if($payment_amount >= '20') {
// Donation is $20 or higher, so let's add 20% to the coins.
$coins = $payment_amount*10*1.2;
}
else {
// Donation is less than $20, no bonus.
$coins = $payment_amount*10;
}
// Add E. Coins
$acc = new PDO("sqlsrv:Server=myhost;Database=mydb", "myusr", "mypass");
$add = $acc->prepare("UPDATE CashAccount SET Cash = Cash + :coins WHERE ID = :account");
$add->bindParam(':coins', $coins, PDO::PARAM_INT);
$add->bindParam(':account', $custom, PDO::PARAM_STR);
$add->execute();
// Log the donation
$db = new PDO("sqlsrv:Server=myhost;Database=mydb", "myusr", "mypass");
$method = 'PayPal';
$query = $db->prepare("INSERT INTO logs (Account, Amount, Coins, Method, Date, Email) VALUES (:account, :amount, :coins, :method, GETDATE(), :email)");
$query->bindParam(':account', $custom, PDO::PARAM_STR);
$query->bindParam(':amount', $payment_amount, PDO::PARAM_INT);
$query->bindParam(':coins', $coins, PDO::PARAM_INT);
$query->bindParam(':method', $method, PDO::PARAM_STR);
$query->bindParam(':email', $payer_email, PDO::PARAM_STR);
$query->execute();
}
// Reply with an empty 200 response to indicate to paypal the IPN was received correctly.
header("HTTP/1.1 200 OK");
I also enbled IPN Notifications in my Business/Sandbox accounts and updated the URL to http://example.com/paypal_ipn.php
Here is my IPN History from the PayPal sandbox.
Maybe someone here can point me to the right direction.
Where have you looked for your ipn.log file?
PHP may not have write permissions to the current directory.
What happens if you turn on errors/warnings and access your IPN listener from a browser? Does it print errors to the screen, about not being able to open ipn.log for writing?
You may need to use an absolute path to a directory PHP does have permissions to write to, for example:
error_log("This is a message!", 3, "/tmp/ipn.log");

I need to set up paypal ipn to add tokens to accounts & transfer there steam id; stuck on error

The user enters there steamid into paypal somewhere and the paypal ipn listener(in the index.php) needs to get that steam id from paypal to add to there account. The part im stuck on is setting up the ipn verification since iv never done php or anything like that. Right now it gets this error
Fatal error: Uncaught Exception: Missing POST Data in /home/vol12_1/epizy.com/epiz_23648301/htdocs/PaypalIPN.php:57 Stack trace: #0 /home/vol12_1/epizy.com/epiz_23648301/htdocs/index.php(7): PaypalIPN->verifyIPN() #1 {main} thrown in /home/vol12_1/epizy.com/epiz_23648301/htdocs/PaypalIPN.php on line 57
Heres the code.
index.php
<?php namespace Listener;
require('PaypalIPN.php');
use PaypalIPN;
$ipn = new PaypalIPN();
// Use the sandbox endpoint during testing.
$ipn->useSandbox();
$verified = $ipn->verifyIPN();
if ($verified) {
/*
* Process IPN
* A list of variables is available here:
* https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNandPDTVariables/
*/
echo "verifyed";
}
else{
echo "not verifyed";
}
// Reply with an empty 200 response to indicate to paypal the IPN was received correctly.
header("HTTP/1.1 200 OK");
?>
<html>
<head>
<title> Riegn Of Darkness </title>
</head>
<body>
<form action="search.php" method="post">
Search: <input type="text" name="search" placeholder=" Find account "/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
PayPalIPN.php
I got this from here https://github.com/paypal/ipn-code-samples
<?php
class PaypalIPN
{
/** #var bool Indicates if the sandbox endpoint is used. */
private $use_sandbox = false;
/** #var bool Indicates if the local certificates are used. */
private $use_local_certs = true;
/** Production Postback URL */
const VERIFY_URI = 'https://ipnpb.paypal.com/cgi-bin/webscr';
/** Sandbox Postback URL */
const SANDBOX_VERIFY_URI = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
/** Response from PayPal indicating validation was successful */
const VALID = 'VERIFIED';
/** Response from PayPal indicating validation failed */
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;
}
/**
* Sets curl to use php curl's built in certs (may be required in some
* environments).
* #return void
*/
public function usePHPCerts()
{
$this->use_local_certs = false;
}
/**
* 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 = array();
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, array(
'User-Agent: PHP-IPN-Verification-Script',
'Connection: Close',
));
$res = curl_exec($ch);
if ( ! ($res)) {
$errno = curl_errno($ch);
$errstr = curl_error($ch);
curl_close($ch);
throw new Exception("cURL error: [$errno] $errstr");
}
$info = curl_getinfo($ch);
$http_code = $info['http_code'];
if ($http_code != 200) {
throw new Exception("PayPal responded with http code $http_code");
}
curl_close($ch);
// Check if PayPal verifies the IPN data, and if so, return true.
if ($res == self::VALID) {
return true;
} else {
return false;
}
}
}

Paypal ipn not works?

I'm using PayPal ipn and always had problems with that.
I've downloaded the sample ipn usage from GitHub (official PayPal git)
PayPalIPN.php :
<?php
class PaypalIPN
{
/**
* #var bool $use_sandbox Indicates if the sandbox endpoint is used.
*/
private $use_sandbox = false;
/**
* #var bool $use_local_certs Indicates if the local certificates are used.
*/
private $use_local_certs = true;
/** Production Postback URL */
const VERIFY_URI = 'https://ipnpb.paypal.com/cgi-bin/webscr';
/** Sandbox Postback URL */
const SANDBOX_VERIFY_URI = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
/** Response from PayPal indicating validation was successful */
const VALID = 'VERIFIED';
/** Response from PayPal indicating validation failed */
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;
}
/**
* Sets curl to use php curl's built in certs (may be required in some
* environments).
* #return void
*/
public function usePHPCerts()
{
$this->use_local_certs = false;
}
/**
* 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 = array();
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, array('Connection: Close'));
$res = curl_exec($ch);
if ( ! ($res)) {
$errno = curl_errno($ch);
$errstr = curl_error($ch);
curl_close($ch);
throw new Exception("cURL error: [$errno] $errstr");
}
$info = curl_getinfo($ch);
$http_code = $info['http_code'];
if ($http_code != 200) {
throw new Exception("PayPal responded with http code $http_code");
}
curl_close($ch);
// Check if PayPal verifies the IPN data, and if so, return true.
if ($res == self::VALID) {
return true;
} else {
return false;
}
}
}
And my ipn usage is :
<?php namespace Listener;
error_reporting(E_ALL);
require('PaypalIPN.php');
use PaypalIPN;
$ipn = new PaypalIPN();
// Use the sandbox endpoint during testing.
$ipn->useSandbox();
$verified = $ipn->verifyIPN();
if ($verified)
{
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "TEST TEXT";
fwrite($myfile, $txt);
fclose($myfile);
}
// Reply with an empty 200 response to indicate to paypal the IPN was received correctly.
header("HTTP/1.1 200 OK");
I've created an example file just to check if everything works and its looks like everything gets stuck on the verified check when I check things out of it, they were working fine.

Paypal Masspay API Masspay input parse error

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.

How to manage PayPal subscriptions using the API?

Does anyone know how to manage PayPal subscriptions using their API? I've read that I can use ManageRecurringPaymentsProfileStatus to cancel, suspend and reactivate subscriptions, but I haven't been able to find a method to get the IDs so I'm unable to use it.
This page says to use the method CreateRecurringPaymentsProfile's response which contains the ID, although I'm not creating the subscriptions using the API so I wouldn't be able to do this.
Is there a API method to only get the IDs? Thanks.
Paypal direct payment..please change credential as your sand box provided...
<?php
/** DoDirectPayment NVP example; last modified 08MAY23.
*
* Process a credit card payment.
*/
$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('debash_1332929919_biz_api1.gmail.com');
$API_Password = urlencode('1332929952');
$API_Signature = urlencode('AIiPJKMw38NGZuaiDaeLWrH9x.WBAK4WXf1vh9.Y.YxEM-4DlbDLMEVe');
$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.
$paymentType = urlencode('Sale'); // or 'Sale'
$firstName = urlencode('Debashis');
$lastName = urlencode('Banerjee');
$creditCardType = urlencode('visa');
$creditCardNumber = urlencode('4860795409505688');
$expDateMonth = '3';
// Month must be padded with leading zero
$padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));
$expDateYear = urlencode('2017');
$cvv2Number = urlencode('111');
$address1 = urlencode('Kaikala');
$address2 = urlencode('Hooghly');
$city = urlencode('Kaikala');
$state = urlencode('WB');
$zip = urlencode('712405');
$country = urlencode('IN'); // US or other valid country code
$amount = urlencode('71');
$currencyID = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
// Add request-specific fields to the request string.
$nvpStr = "&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
"&EXPDATE=$padDateMonth$expDateYear&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName".
"&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=$currencyID";
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('DoDirectPayment', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
exit('Direct Payment Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else {
exit('DoDirectPayment failed: ' . print_r($httpParsedResponseAr, true));
}
?>
please visit https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_code
Thanks

Categories