My current project allows users to subscribe to a membership without registering for a paypal account.
The users' username and password is created and managed by my own application, not PayPal.
Can anyone tell me how to create an hTMl form that would cancel that subscription? Could I perhaps cancel a subscription by sending the txn_id??
I believe I can capture this info with the IPN.
I should also mention that I'm a DBA and not really a developer so bear with me if i'm a little newbish.
Thanks in advance.
Here's what I ended up doing.
<?php
require 'core/init.php';
require 'core/conn.php';
/*The paypal_transactions table is a table I'm using to store the IPN data. This is necessary to capture the Profile_ID/Subscr_ID. The Custom parameter is being used to pass the username.*/
$profileid_sql = "select subscr_id from paypal_transactions where custom ='". escape($user->data()->username)."'";
$result=mysql_query($profileid_sql);
while($row=mysql_fetch_array($result)){
$profileid = $row['subscr_id'];
}
include 'functions/change_subscription_status.php';
change_subscription_status( $profileid, 'Cancel' );
header('Location: Cancelled.php');
?>
The change_subscription_status function is here...
<?php
/**
* Performs an Express Checkout NVP API operation as passed in $action.
*
* Although the PayPal Standard API provides no facility for cancelling a subscription, the PayPal
* Express Checkout NVP API can be used.
*/
function change_subscription_status( $profile_id, $action ) {
$api_request = 'USER=' . urlencode( 'API_username' )
. '&PWD=' . urlencode( 'API_Password' )
. '&SIGNATURE=' . urlencode( 'API_Signature' )
. '&VERSION=76.0'
. '&METHOD=ManageRecurringPaymentsProfileStatus'
. '&PROFILEID=' . urlencode( $profile_id )
. '&ACTION=' . urlencode( $action )
. '&NOTE=' . urlencode( 'Profile cancelled at store' );
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, 'https://api-3t.sandbox.paypal.com/nvp' ); // For live transactions, change to 'https://api-3t.paypal.com/nvp'
curl_setopt( $ch, CURLOPT_VERBOSE, 1 );
// Uncomment these to turn off server and peer verification
// 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 parameters for this transaction
curl_setopt( $ch, CURLOPT_POSTFIELDS, $api_request );
// Request response from PayPal
$response = curl_exec( $ch );
// If no response was received from PayPal there is no point parsing the response
if( ! $response )
die( 'Calling PayPal to change_subscription_status failed: ' . curl_error( $ch ) . '(' . curl_errno( $ch ) . ')' );
curl_close( $ch );
// An associative array is more usable than a parameter string
parse_str( $response, $parsed_response );
return $parsed_response;
}
?>
Use paypal api method ManageRecurringPaymentsProfileStatus ( API Operation NVP ), using ACTION parameter you can:
Cancel – Only profiles in Active or Suspended state can be canceled.
Suspend – Only profiles in Active state can be suspended.
Reactivate – Only profiles in a suspended state can be reactivated.
Paypal Documentation - https://developer.paypal.com/docs/classic/api/merchant/ManageRecurringPaymentsProfileStatus_API_Operation_NVP/
To create a recurring profile follow this (PHP) example:
// Parameters for SetExpressCheckout, which will be sent to PayPal
$padata['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Product description';
$padata['L_BILLINGAGREEMENTDESCRIPTION0'] = $padata['L_BILLINGAGREEMENTDESCRIPTION0'] .
' $'.$product->price.'/month';
$padata['L_PAYMENTREQUEST_0_DESC0'] = $padata['L_BILLINGAGREEMENTDESCRIPTION0'] .
' $'.$product->price.'/month';$padata['PAYMENTREQUEST_0_NOTIFYURL'] = 'http://site_url/paypal/ipn';
$padata['PAYMENTREQUEST_0_DESC'] = $product->name;
$padata['RETURNURL'] = 'http://site_url/paypal/returnurl';
$padata['CANCELURL'] = 'http://site_url/paypal/cancelurl';
$padata['PAYMENTREQUEST_0_CURRENCYCODE'] = 'USD';
$padata['PAYMENTREQUEST_0_PAYMENTACTION'] = 'SALE';
$padata['PAYMENTREQUEST_0_ITEMAMT'] = $product->price;$padata['PAYMENTREQUEST_0_AMT'] = $product->price;$padata['L_BILLINGTYPE0'] = 'RecurringPayments';$padata['L_PAYMENTREQUEST_0_NAME0'] = $product->name;$padata['L_PAYMENTREQUEST_0_NUMBER0']= '322';$padata['L_PAYMENTREQUEST_0_QTY0'] = '1';$padata['L_PAYMENTREQUEST_0_AMT0'] = $product->price;
$paypal_data = http_build_query($padata);
$httpParsedResponseAr = $this->PPHttpPost('SetExpressCheckout', $paypal_data);
//Respond according to message we receive from Paypal
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])){
//Redirect user to PayPal store with Token received.
$paypalurl ='https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token='.$httpParsedResponseAr["TOKEN"].'';
header('Location: '.$paypalurl);
}else{
echo 'Error : '.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'';
}
Page returnurl:
$hosteddata['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Description';$hosteddata['L_BILLINGAGREEMENTDESCRIPTION0'] = $hosteddata['L_BILLINGAGREEMENTDESCRIPTION0'] . ' $'.$pr->price.'/month';$hosteddata['L_PAYMENTREQUEST_0_NAME0'] = $pr->name;$hosteddata['PROFILEREFERENCE'] = $GetExpressCheckoutDetails['L_PAYMENTREQUEST_0_NUMBER0'];$hosteddata['PROFILESTARTDATE'] = date('Y-m-d') . 'T' . date('H:i:s').'Z';$hosteddata['SUBSCRIBERNAME'] = $GetExpressCheckoutDetails['FIRSTNAME'] . ' ' . $GetExpressCheckoutDetails['LASTNAME'];$hosteddata['TOKEN'] = urlencode($_POST['token']);$hosteddata['DESC'] = $hosteddata['L_BILLINGAGREEMENTDESCRIPTION0'];$hosteddata['AMT'] = $pr->price;$hosteddata['BILLINGPERIOD'] = 'Month';$hosteddata['BILLINGFREQUENCY'] = '1';$hosteddata['TOTALBILLINGCYCLES'] = '12';$hosteddata['REGULARTOTALBILLINGCYCLES'] = '1';$hosteddata['VERSION'] = '74.0';$hosteddata['MAXFAILEDPAYMENTS'] = '1';$hosteddata['L_PAYMENTREQUEST_0_QTY0'] = '1';$hosteddata['L_BILLINGTYPE0'] = 'RecurringPayments';$hosteddata['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Digital';$hosteddata['L_PAYMENTREQUEST_0_AMT0'] = $pr->price;$hosteddata['INITAMT'] = $pr->price;$hosteddata['L_PAYMENTREQUEST_0_NUMBER0'] = $pr->id;$hosteddata['PAYMENTREQUEST_0_NOTIFYURL'] = 'http://site_url/paypal/ipn';
$paypal_data = http_build_query($hosteddata);
$hosted_saas_response = $this->PPHttpPost('CreateRecurringPaymentsProfile', $paypal_data);
I used a separate method to post parameters to paypal
private function PPHttpPost( $methodName_, $nvpStr_ ) {
$api_username = 'yourpaypal#email.com';
$api_password = 'QWEQWEWQEQWEQEQWE';$api_signature = 'WQEQWEQWEQWEWQEQWEQWEQWEQWEQWE.cT';$api_endpoint = "https://api-3t.paypal.com/nvp";$version = '124.0';
$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=$methodName_&VERSION=$version&PWD=$api_password&USER=$api_username&SIGNATURE=$api_signature&$nvpStr_";
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);$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;
}
The other way to cancel is inside the user account:
Log in to your PayPal account.
Click Profile near the top of the page.
Click My money.
Click Update in the My preapproved payments section.
Click Cancel, Cancel automatic billing, or Cancel subscription and follow the instructions.
Related
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.
I have made an web application for reservation system and used paypal as payment gateway. Using the paypal express checkout I can make a payment, but now I want to split payment between me as service provider and respected hotel in the ratio of 5% : 95%. How can I accomplish this using express checkout in php?
Paypal.config
$currency = '$'; //Currency sumbol or code APP-80W284485P519543T
//paypal settings sandbox
$PayPalMode = 'sandbox'; // sandbox or live
$PayPalApiUsername = 'email'; //PayPal API Username
$PayPalApiPassword = '1400209342'; //Paypal API password
$PayPalApiSignature = 'AFcWxV21C7fd0v3bYYYRCpSSRl31AIicHs2L8N-aSaeIWzH3DX-kQJPv'; //Paypal API Signature
$PayPalCurrencyCode = 'USD'; //Paypal Currency Code
$PayPalReturnURL = returnURL; //Point to process.php page
$PayPalCancelURL = cancelURL; //Cancel URL if user clicks cancel
paypal.class
class MyPayPal {
public function PPHttpPost($methodName_, $nvpStr_, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode) {
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode($PayPalApiUsername);
$API_Password = urlencode($PayPalApiPassword);
$API_Signature = urlencode($PayPalApiSignature);
$paypalmode = ($PayPalMode=='sandbox') ? '.sandbox' : '';
$API_Endpoint = "https://api-3t".$paypalmode.".paypal.com/nvp";
$version = urlencode('109.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;
}
}
and paypal payment method
$padata = '&METHOD=SetExpressCheckout' .
'&RETURNURL=' . urlencode($PayPalReturnURL) .
'&CANCELURL=' . urlencode($PayPalCancelURL) .
'&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") .
$paypal_data .
'&NOSHIPPING=1' . //set 1 to hide buyer's shipping address, in-case products that does not require shipping
'&PAYMENTREQUEST_0_ITEMAMT=' . urlencode($ItemTotalPrice) .
'&PAYMENTREQUEST_0_SHIPPINGAMT=' . urlencode($ShippinCost) .
'&PAYMENTREQUEST_0_SHIPDISCAMT=' . urlencode($discount) .
'&PAYMENTREQUEST_0_AMT=' . urlencode($GrandTotal) .
'&PAYMENTREQUEST_0_CURRENCYCODE=' . urlencode($PayPalCurrencyCode) .
'&LOCALECODE=GB' . //PayPal pages to match the language on your website.
'&LOGOIMG=http://salyani.org/booking/contents/images/BookingBeta100PX.png' . //site logo
'&CARTBORDERCOLOR=FFFFFF' . //border color of cart
'&ALLOWNOTE=1';
You can do Parallel Payment using Express Checkout by including both primary and secondary information for each of the two payments. More details here
But, you cannot do Chain Payments with express checkout.
You will need to look into adaptive payments .
You will just need to include the following sample request in your SEtexpress checkout request.
METHOD=SetExpressCheckout
RETURNURL=http://example.com/success.html
CANCELURL=http://example.com/canceled.html
VERSION=93
PAYMENTREQUEST_0_CURRENCYCODE=USD
PAYMENTREQUEST_0_AMT=250
PAYMENTREQUEST_0_ITEMAMT=225
PAYMENTREQUEST_0_TAXAMT=25
PAYMENTREQUEST_0_PAYMENTACTION=Order
PAYMENTREQUEST_0_DESC=Sunset Sail for Two
PAYMENTREQUEST_0_SELLERPAYPALACCOUNTID=XXX#gmail.com
PAYMENTREQUEST_0_PAYMENTREQUESTID=CART286-PAYMENT0
L_PAYMENTREQUEST_0_NAME0=Departs Santa Cruz Harbor
L_PAYMENTREQUEST_0_NUMBER0=Sunset Sail 22
L_PAYMENTREQUEST_0_QTY0=1
L_PAYMENTREQUEST_0_AMT0=225
L_PAYMENTREQUEST_0_TAXAMT0=25
PAYMENTREQUEST_1_AMT=250
PAYMENTREQUEST_1_ITEMAMT=225
PAYMENTREQUEST_1_TAXAMT=25
PAYMENTREQUEST_1_PAYMENTACTION=Order
PAYMENTREQUEST_1_DESC=Sunset Sail for Two
PAYMENTREQUEST_1_SELLERPAYPALACCOUNTID=YYY.com
PAYMENTREQUEST_1_PAYMENTREQUESTID=CART286-PAYMENT1
L_PAYMENTREQUEST_1_NAME0=Departs Santa Cruz Harbor
L_PAYMENTREQUEST_1_NUMBER0=Sunset Sail 22
L_PAYMENTREQUEST_1_QTY0=1
L_PAYMENTREQUEST_1_AMT0=225
L_PAYMENTREQUEST_1_TAXAMT0=25
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
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
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