PHP `use` import namespace causes page to crash - php

PHPMailer is working fine in a test script on it's own bare bones. However, it is crashing and not reporting an any errors on another page. I have isolated the problem to the following lines of code:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
When I leave these lines out I get the PHP error:
Fatal error: Uncaught Error: Class 'PHPMailer' not found in /path/to/file.php:166 Stack trace: #0 {main} thrown in /path/to/file.php on line 166
When I include these lines (which I believe I need to in order to use the namespace of the imported classes) I simply get a blank white screen. Error reporting is turned on at the top of the page as follows:
error_reporting(E_ALL);
ini_set('display_errors', 1);
However, no error reports on the page.
The rest of the class files are imported as below and the path is correct as they report no errors unless I change the path.
require '../../../wp-content/plugins/PHPMailer/Exception.php';
require '../../../wp-content/plugins/PHPMailer/PHPMailer.php';
require '../../../wp-content/plugins/PHPMailer/SMTP.php';
I looked for information about use on the PHP website, however there was nothing listed when I searched (http://ca3.php.net/manual-lookup.php?pattern=use&scope=quickref).
Here is the full code in the file.php. I know there are other issues such as data input sanitization, etc, but I am refactoring someone else's code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
var_dump($_POST);
// PayPal Config Constants
require "../../../mail-config.php";
require "../../../keys-config.php";
/** Send HTTP POST Request for PayPal Payment */
function PPHttpPost($methodName_, $nvpStr_) {
// Get the environment set in the keys-config.php file
$environment = PAYPAL_ENVIRONMENT;
// Use the keys and endpoint for the environment
if("sandbox" === $environment || "beta-sandbox" === $environment) {
// Set the API URL
$API_Endpoint = PAYPAL_API_ENDPOINT_SANDBOX;
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode(PAYPAL_API_USERNAME_SANDBOX);
$API_Password = urlencode(PAYPAL_API_PASSWORD_SANDBOX);
$API_Signature = urlencode(PAYPAL_API_SIGNATURE_SANDBOX);
} else {
// Set the API URL
$API_Endpoint = PAYPAL_API_ENDPOINT;
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode(PAYPAL_API_USERNAME);
$API_Password = urlencode(PAYPAL_API_PASSWORD);
$API_Signature = urlencode(PAYPAL_API_SIGNATURE);
}
// Set the version
$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 the method failed
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 data in response is invalid
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
// Return the http response
return $httpParsedResponseAr;
}
// Prepare PayPal Payment Request
// Set request-specific fields.
// 'Authorization' or 'Sale'
$paymentType = urlencode('Sale');
// Name Details
$firstName = urlencode($_POST['firstname']);
$lastName = urlencode($_POST['lastname']);
// Credit Card details
$creditCardType = urlencode($_POST['customer_credit_card_type']);
$creditCardNumber = urlencode($_POST['cardnum']);
$expDateMonth = $_POST['cc_expiration_month'];
// Month must be padded with leading zero
$padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));
$expDateYear = urlencode($_POST['cc_expiration_year']);
$cv = urlencode($_POST['cv']);
// Address Details
$address1 = urlencode($_POST['streetaddy']);
$city = urlencode($_POST['city']);
$state = urlencode($_POST['province']);
$postal_code = urlencode($_POST['postalcode']);
// US or other valid country code
$country = urlencode($_POST['country']);
$price = urlencode($_POST['price']);
// or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
$currencyID = urlencode('CAD');
// Add request-specific fields to the request string.
$nvpStr = "&PAYMENTACTION=$paymentType&AMT=$price&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
"&EXPDATE=$padDateMonth$expDateYear&CVV2=$cv&FIRSTNAME=$firstName&LASTNAME=$lastName".
"&STREET=$address1&CITY=$city&STATE=$state&ZIP=$postal_code&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"])) {
//Below line is response code from original
//exit('Direct Payment Completed Successfully: '.print_r($httpParsedResponseAr, true));
// Require the PHPMailer classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../../../wp-content/plugins/PHPMailer/Exception.php';
require '../../../wp-content/plugins/PHPMailer/PHPMailer.php';
require '../../../wp-content/plugins/PHPMailer/SMTP.php';
//FIELDS
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email_from = $_POST['email'];
$phone = $_POST['phone'];
$ad = $_POST['ad'];
$price = $_POST['price'];
$edition = $_POST['edition'];
$issues = $_POST['issues'];
$category = $_POST['category'];
$order_id = $_POST['order_id'];
$email_message = "A Classified Ad has been purchased from the Speaker website. Details of the ad are below.\n\n";
// Filter the string
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
$string = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
}
// Build the Email message body contents
$email_message .= "<b>Order ID:</b> ".clean_string($order_id)."<br>";
$email_message .= "<b>First Name:</b> ".clean_string($first_name)."<br>";
$email_message .= "<b>Last Name:</b> ".clean_string($last_name)."<br>";
$email_message .= "<b>Email:</b> ".clean_string($email_from)."<br>";
$email_message .= "<b>Telephone:</b> ".clean_string($phone)."<br>";
$email_message .= "<b>Category:</b> ".clean_string($category)."<br>";
$email_message .= "<b>Ad Text:</b> ".clean_string($ad)."<br>";
$email_message .= "<b>Edition:</b> ".clean_string($edition)."<br>";
$email_message .= "<b>Number of Issues:</b> ".clean_string($issues)."<br>";
$email_message .= "<b>Price:</b> ".clean_string($price)."<br>";
// Set up the email to be sent
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = SITE_EMAIL_SMTP_USERNAME;
$mail->Password = SITE_EMAIL_SMTP_PASSWORD;
$mail->SetFrom(SITE_EMAIL_FROM_ADRESS_LIST);
$mail->Subject = "Classified Ad Submission From The ".NEWSPAPER_NAME." Website";
$mail->Body = $email_message;
// Add all the company email addresses to the send list
foreach(PAYWALL_NOTIFICATION_EMAIL_ADDRESSES_ARRAY as $email_address){
$mail->AddAddress($email_address);
}
// Add the purchaser's email address to the send list
$mail->AddAddress($email_from);
// If mail fails to send
if(!$mail->Send()) {
//REDIRECT TO FAILED PAGE
header( 'Location: /order-not-completed' );
} else {
//REDIRECT TO SUCCESS PAGE
header( 'Location: /success' );
}
} else {
//Below line is response code for testing
exit('DoDirectPayment failed: ' . print_r($httpParsedResponseAr, true));
//REDIRECT TO FAILED PAGE
header( 'Location: /order-not-completed' );
}
?>

It will mean that your PHP version is too old. Namespaces and the use syntax were introduced in PHP 5.3, and that is already many years out of date.
PHPMailer 6.0.x requires at least PHP 5.5, so update your PHP, ideally to the latest version (currently 7.3).

Here is the page describing the use of PHP's use function to import namespaces: http://php.net/manual/en/language.namespaces.importing.php
Scoping rules for importing
The use keyword must be declared in the outermost scope of a file (the
global scope) or inside namespace declarations. This is because the
importing is done at compile time and not runtime, so it cannot be
block scoped. The following example will show an illegal use of the
use keyword:
namespace Languages;
function toGreenlandic() {
use Languages\Danish;
// ... }
Although the above code is not using the use statement in side a function, it is not at the top of the file and other functions were declared before the use statements. I tested the above code with after moving the use statements to the top of the file directly under the
In short: always put your use statements at the top of your PHP file and outside of the functions or classes.

Related

How to send message to viber without input event?

I have a little problem, I have a php script for sending messages to viber. The problem is that bot sends message when I send some message with my profile, but I want only to run php script and send message to chat.
Check the script:
<?php
use Alserom\Viber\Request\Type\SendMessage;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$access_token = "TOKEN HERE";
$request = file_get_contents("php://input");
$input = json_decode($request, true);
if ($input['event'] == 'webhook') {
$webhook_response['status'] = 0;
$webhook_response['status_message'] = "ok";
$webhook_response['event_tyes'] = "delivered";
echo json_encode($webhook_response);
die;
} else if ($input['event'] == 'message') {
$text_received = $input['message']['text'];
$sender_id = $input['sender']['id'];
$sender_name = $input['sender']['name'];
$message_to_replay = "hello";
$data['auth_token'] = $access_token;
$data['receiver'] = $sender_id;
$data['type'] = "text";
$data['text'] = $message_to_replay;
sendMessage($data);
} else {
$message_to_replay = "Messageeeeeee";
$data['auth_token'] = $access_token;
/* $data['receiver'] = $sender_id; */
$data['type'] = "text";
$data['text'] = $message_to_replay;
sendMessage($data);
}
function sendMessage($data) {
$url = "https://chatapi.viber.com/pa/send_message";
$jsonData = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
return $result;
}
?>
When I run script through browser, it goes to ELSE and it should send message immediately... but I get this error:
{
"status": 999,
"status_message": "Bad receiver ID",
"message_token": 5485177081717755848,
"chat_hostname": "SN-CHAT-20_"
}
Should I put some static receiver ID? And how to get ID of some user?
*** UPDATE *****
I have added static ID of subscribed user in ELSE statement... now it sends immediately when I run script, but now it sends 100 same messages. How to limit sending only one message?
else {
$message_to_replay = "Messageeeeeee";
$data['auth_token'] = $access_token;
$data['receiver'] = "staticID";
$data['type'] = "text";
$data['text'] = $message_to_replay;
sendMessage($data);
}
According to the Viber documentation, you can only send messages to accounts subscribing to your bot:
The send_message API allows accounts to send messages to Viber users who subscribe to the account.
A requirement for the user id is, that it has to be a user id of a user who subscribed to the bot, so this should be your first step to check.
Edit: I would recommend saving the user ids of those who subscribed by sending an initial message or something to your bot and then you can send messages to them by taking the previously saved user ids.
If your script didn't responded in 5 seconds or responded with HTML status code not equal 200 - then Viber servers will try to resend this webhook every minute.

PayPal sandbox DoExpressCheckout API always returns 10422 or 10486 when only paying by a credit card

I'm a EC manager. PayPal payment in production works without problems, but there is a problem in development (sandbox environment).
As mentioned in the title, DoExpressCheckout API via PHP always returns 10422 or 10486 error codes when only paying by a credit card. This means it works correctly when sandbox account's PayPal balance is enough to pay for an item.
I suspect there are problems in my sandbox account setting or my php code.
Is there anyone have clues to a solution to this problem?
My PHP code here.
<?php
/** DoExpressCheckoutPayment NVP example; last modified 08MAY23.
*
* Complete an Express Checkout transaction.
*/
require_once('paypal_configure.php'); // API settings
// Set request-specific fields.
$environment = ENVIRONMENT; // sandbox
$paymentType = urlencode("Authorization"); // or 'Sale' or 'Order'
$currencyID = urlencode(CURRENCY);
// Set parameter
$token = urlencode($argv[1]);
$payerID = urlencode($argv[2]);
$paymentAmount = urlencode($argv[3]);
$invNum = urlencode($argv[4]);
/**
* 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(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);
// Set the curl parameters.
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;
}
/**
* This example assumes that a token was obtained from the SetExpressCheckout API call.
* This example also assumes that a payerID was obtained from the SetExpressCheckout API call
* or from the GetExpressCheckoutDetails API call.
*/
// Add request-specific fields to the request string.
$nvpStr = "&TOKEN=$token&PAYERID=$payerID&PAYMENTACTION=$paymentType&AMT=$paymentAmount&CURRENCYCODE=$currencyID";
$nvpStr .= "&INVNUM=$invNum";
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('DoExpressCheckoutPayment', $nvpStr);
// result
$resAck = strtoupper($httpParsedResponseAr["ACK"]);
$resTime = urldecode($httpParsedResponseAr["TIMESTAMP"]);
if( $resAck == "SUCCESS" || $resAck == "SUCCESSWITHWARNING" ) {
// get result
$resCode = "10000";
$resMsg = "_";
$resTranid = urldecode($httpParsedResponseAr["TRANSACTIONID"]);
$resAmount = urldecode($httpParsedResponseAr["AMT"]);
}
else {
// get result
$resCode = $httpParsedResponseAr["L_ERRORCODE0"];
$resMsg = mb_ereg_replace(" ","###SPACE###",urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]));
$resTranid = "_";
$resAmount = "_";
}
// return text
$rtnText = "";
$rtnText = $resAck;
$rtnText .= " ".$resCode;
$rtnText .= " ".$resMsg;
$rtnText .= " ".$resTranid;
$rtnText .= " ".$resAmount;
$rtnText .= " ".$token;
$rtnText .= " ".$payerID;
$rtnText .= " ".$invNum;
$rtnText .= " ".$resTime;
$rtnText .= "\n";
echo $rtnText;
exit(0);
?>
Sometimes sandbox accounts get screwed up. Try creating a fresh sandbox buyer account and make sure to add a credit card to it during that process.

Paypal - payment issue while trying to implement recurring payment

paypalrecurring.php
private $test = false;
private $liveServer = 'https://api-3t.paypal.com/nvp'; # https://api.paypal.com/nvp
private $testServer = 'https://api-3t.sandbox.paypal.com/nvp'; # https://api.sandbox.paypal.com/nvp
private $methodName = 'CreateRecurringPaymentsProfile';
public function sendRequest()
{
$nvpreq = '';
foreach ($this->request as $fldname => $val)
if($val != '') $nvpreq .= strtoupper($fldname) . "=" . urlencode($val) . "&";
$url = ($this->test) ? $this->testServer : $this->liveServer;
$post = "METHOD=" . $this->methodName . "&" . $nvpreq . "&VERSION=56.0";
$retstr = $this->sendAPIRequest($url . "?" . $post);
$retarrtmp = explode("&",$retstr);
$retarr = array();
for($i=0;$i<count($retarrtmp);$i++)
{
$sparr = explode("=",$retarrtmp[$i]);
$txt = urldecode($sparr[0]);
$val = urldecode($sparr[1]);
$retarr[$txt] = $val;
}
return $retarr;
}
/**
* True for test server. False for production.
* #param bool $isTest
*/
public function setIsTest($isTest)
{
$this->test = $isTest;
}
private function sendAPIRequest($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
if(curl_errno($ch))
$response = curl_error($ch);
curl_close($ch);
return $response;
}
}
Usageexample.php
<?php
require_once 'PaypalRecurring.php';
$pp = new PayPalRecurring();
$pp->setIsTest(true); // PayPal test sandbox or live server
// Your PayPal account credentials go here
$pp->request['user'] = 'xxx';
$pp->request['pwd'] = 'xxx';
$pp->request['signature'] = 'xxx';
// End PayPal account credentials
// User info
$pp->request['firstname'] = 'The users first name';
$pp->request['lastname'] = 'The users last name';
$pp->request['email'] = 'The users email address';
$pp->request['creditcardtype'] = 'Visa'; // Visa, Mastercard, Discover, Amex
$pp->request['acct'] = ''; // Credit card number
$pp->request['expdate'] = str_pad('8',2,'0', STR_PAD_LEFT) .'2020'; // Expiration month and full year. Pad the month with 0. Month should be 1-12. This example is 8/2020.
// End user info
// Product info
$pp->request['countrycode'] = 'US';
$pp->request['billingperiod'] = 'Month'; // Bill per month
$pp->request['billingfrequency'] = 1; // How many times to bill per billing period.. This example is once per month
$pp->request['currencycode'] = 'USD';
$pp->request['amt'] = 9.95; // Amount to bill every month
$pp->request['initamt'] = 0.00; // Setup fee.. One time on account creation
$pp->request['taxamt'] = $pp->request['amt'] * .07; // Replace .07 with your tax percentage. 0 for no tax.
$pp->request['desc'] = 'Super Deluxe Package'; // The description of your product for reporting in your account
$pp->request['profilestartdate'] = gmdate('Y-m-d\TH:i:s\Z');
$pp->request['totalbillingcycles'] = '3'; // How many billing cycles. 0 for no expiration. This example is for 3 total months of billing.
$pp->request['payerstatus'] = 'verified';
// End product info
$ppResponse = $pp->sendRequest();
if(isset($ppResponse['L_ERRORCODE0']))
echo "Error: {$ppResponse['L_LONGMESSAGE0']}";
else if(isset($ppResponse['ACK']) && $ppResponse['ACK'] == ('Success' || 'SuccessWithWarning'))
echo "Success: {$ppResponse['ACK']}";
else
print_r($ppResponse);
whenever i am trying to implement recurring payment in paypal always got error
security header is not valid
Above example is from github
i need to integrate recurring payment in ecommerce site
I have two files paypalrecurring.php & usageExample.php
When i executed usageExample.php i got error security header is not valid
can anybody help me
This is because your API credentials in below codes is not correct.
$pp->request['user'] = 'xxx';
$pp->request['pwd'] = 'xxx';
$pp->request['signature'] = 'xxx';
You can follow up the steps below to find your API credentials:
For sandbox account:
Access https://developer.paypal.com/ and login, then access below URL:
https://developer.paypal.com/developer/accounts
Click the business account being used for your test, then click the "Profile" link under the account.
Then click the "API Credentials" tab, you will find the API credentials.
For live account:
Login to www.paypal.com, go to Profile->Selling tools->API Access, click "Request API credentials" link,
then select "Request API signature" and click "Agree and Submit".
Then you can find your API username, API password and API signature in the final page.

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

How to send money to paypal using php

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