magento - integrating paypal adaptive payments (chained payments) - php

I am currently working on integrating paypal's chained payment method into magento.
https://cms.paypal.com/ca/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_APIntro
The payment flow would be:
buyer pays seller's paypal account -> pp adaptive payment gateway -> 85% goes to seller's paypal, 15% goes to site's default paypal account (buyer not aware of this split).
I already have the api function take takes 2 paypal accounts (seller's & site's default), and payment amount, and am looking to integrate this.
Has anyone integrated adaptive payments before, or point me to where I should integrate this logic? Would I overwrite one of the functions in /app/code/core/Mage/paypal ?
I basically need to get the total cost in the current shopping cart, and the paypal email of the current store, and pass that over to my function.

First of all you need to create a seprate payment method for magento i would suggest to create a payment module for it after that you need to signup in to the paypal sandbox account . i am attaching sample code for adaptive payment integration also some useful links for the flow how it will work
ini_set("track_errors", true);
//set PayPal Endpoint to sandbox
$sandbox="";
$API_AppID = XXXXXXXXXXXXXXXXXXX;//your adaptive payment app Id
//value for check sandbox enable or disable
$sandboxstatus=1;
if($sandboxstatus==1){
$sandbox="sandbox.";
$API_AppID="APP-80W284485P519543T";
}
$url = trim("https://svcs.".$sandbox."paypal.com/AdaptivePayments/Pay");
//PayPal API Credentials
$API_UserName = XXXXXXXXXXXXXXXXXXX;//TODO
$API_Password = XXXXXXXXXXXXXXXXXXX;//TODO
$API_Signature = XXXXXXXXXXXXXXXXXXX;//TODO
//Default App ID for Sandbox
$API_RequestFormat = "NV";
$API_ResponseFormat = "NV";
$bodyparams = array (
"requestEnvelope.errorLanguage" => "en_US",
"actionType" => "PAY",
"currencyCode" => "USD",//currency Code
"cancelUrl" => "",// cancle url
"returnUrl" => "paymentsuccess",//return url
"ipnNotificationUrl" => "paymentnotify"//notification url that return all data related to payment
);
$finalcart=array(
array('paypalid'=>"partner1",'price'=>50),
array('paypalid'=>"partner2",'price'=>50),
array('paypalid'=>"partner3",'price'=>50),
array('paypalid'=>"partner4",'price'=>50),
array('paypalid'=>"partner5",'price'=>50)
);
$i=0;
foreach($finalcart as $partner){
$temp=array("receiverList.receiver($i).email"=>$partner['paypalid'],"receiverList.receiver($i).amount"=>$partner['price']);
$bodyparams+=$temp;
$i++;
}
// convert payload array into url encoded query string
$body_data = http_build_query($bodyparams, "", chr(38));
try{
//create request and add headers
$params = array("http" => array(
"method" => "POST",
"content" => $body_data,
"header" => "X-PAYPAL-SECURITY-USERID: " . $API_UserName . "\r\n" .
"X-PAYPAL-SECURITY-SIGNATURE: " . $API_Signature . "\r\n" .
"X-PAYPAL-SECURITY-PASSWORD: " . $API_Password . "\r\n" .
"X-PAYPAL-APPLICATION-ID: " . $API_AppID . "\r\n" .
"X-PAYPAL-REQUEST-DATA-FORMAT: " . $API_RequestFormat . "\r\n" .
"X-PAYPAL-RESPONSE-DATA-FORMAT: " . $API_ResponseFormat . "\r\n"
));
//create stream context
$ctx = stream_context_create($params);
//open the stream and send request
$fp = #fopen($url, "r", false, $ctx);
//get response
$response = stream_get_contents($fp);
//check to see if stream is open
if ($response === false) {
throw new Exception("php error message = " . "$php_errormsg");
}
//close the stream
fclose($fp);
//parse the ap key from the response
$keyArray = explode("&", $response);
foreach ($keyArray as $rVal){
list($qKey, $qVal) = explode ("=", $rVal);
$kArray[$qKey] = $qVal;
}
//set url to approve the transaction
$payPalURL = "https://www.".$sandbox."paypal.com/webscr?cmd=_ap-payment&paykey=" . $kArray["payKey"];
//print the url to screen for testing purposes
If ( $kArray["responseEnvelope.ack"] == "Success") {
echo '<p><a id="paypalredirect" href="' . $payPalURL . '"> Click here if you are not redirected within 10 seconds...</a> </p>';
echo '<script type="text/javascript">
function redirect(){
document.getElementById("paypalredirect").click();
}
setTimeout(redirect, 2000);
</script>';
}
else {
echo 'ERROR Code: ' . $kArray["error(0).errorId"] . " <br/>";
echo 'ERROR Message: ' . urldecode($kArray["error(0).message"]) . " <br/>";
}
}
catch(Exception $e) {
echo "Message: ||" .$e->getMessage()."||";
}
you may ignore the module flow but you can follow the steps for setting up the sandbox account for paypal payment hope it will help

You're probably going to need to write a completely new payment module for that. From what I've seen (and I'll admit it's been a little bit since I've looked at it in detail) the current PayPal integration in Magento does not support chained payments.
You could still extend the existing PayPal module(s) if you want, but you'll need to write the API requests to handle the adaptive payments calls accordingly. Again, there aren't any existing functions that you would simply override in your extended module. You'll just need to create your own from the start.
If the latest version of Magento added some adaptive payments then I could be wrong on that. If that's the case, you'd probably see something in the /paypal directory directly referring to it, and you can study the functions in there to see what you could override with your own. That said, if they've already adaptive payments included as a payment module then you really shouldn't need to customize it in code.

Related

Paypal Express Checkout Not Charging

So I used the PayPal integration wizard for the Express Checkout. The Express Checkout window pops up and authenticates properly, but payments transactions aren't charging the Buyer's account or even showing up in the transaction history and also aren't showing up as a transaction on the seller's account (Note this is all through the Sandbox).
The API credentials are good (I even completely changed the seller account once)
I've tried with multiple different buyer accounts, all the same result
After clicking "Pay Now" in the Express Checkout window it never gives any indication that it's completed, aside from going directly to my 'confirm' page. To my understanding, this is due to SetExpressCheckout not being called, but as far as I can tell, it appears to be set. I have searched PayPal's documentation for hours trying to find a code example of how to set it but couldn't find anything other than what the integration wizard provided.
Any help is greatly appreciated and I'd even accept someone pointing me in the direction of a solid tutorial on implementing Express Checkout, because PayPal's documentation is horrid.
Please let me know if you need anymore information :)
EDIT: The the confirmation page it sends me to does have both a payerID and a transcationID. Example: confirm.php?token=EC-0NX928722D104283H&PayerID=R4GZS3H3JHGRC
Anyways, here's the code:
paypalfunctions.php
<?php
/********************************************
PayPal API Module
Defines all the global variables and the wrapper functions
********************************************/
$PROXY_HOST = '127.0.0.1';
$PROXY_PORT = '808';
$SandboxFlag = true;
//' TODO:
//'------------------------------------
//' PayPal API Credentials
//' Replace <API_USERNAME> with your API Username
//' Replace <API_PASSWORD> with your API Password
//' Replace <API_SIGNATURE> with your Signature
//'------------------------------------
$API_UserName = "XXX";
$API_Password = "XXX";
$API_Signature = "XXX";
// BN Code is only applicable for partners
$sBNCode = "PP-ECWizard";
/*
' Define the PayPal Redirect URLs.
' This is the URL that the buyer is first sent to do authorize payment with their paypal account
' change the URL depending if you are testing on the sandbox or the live PayPal site
'
' For the sandbox, the URL is https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
' For the live site, the URL is https://www.paypal.com/webscr&cmd=_express-checkout&token=
*/
if ($SandboxFlag == true)
{
$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
$PAYPAL_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
$PAYPAL_DG_URL = "https://www.sandbox.paypal.com/incontext?token=";
}
else
{
$API_Endpoint = "https://api-3t.paypal.com/nvp";
$PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
$PAYPAL_DG_URL = "https://www.paypal.com/incontext?token=";
}
$USE_PROXY = false;
$version = "84";
/* An express checkout transaction starts with a token, that
identifies to PayPal your transaction
In this example, when the script sees a token, the script
knows that the buyer has already authorized payment through
paypal. If no token was found, the action is to send the buyer
to PayPal to first authorize payment
*/
/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the SetExpressCheckout API Call for a Digital Goods payment.
' Inputs:
' paymentAmount: Total value of the shopping cart
' currencyCodeType: Currency code value the PayPal API
' paymentType: paymentType has to be one of the following values: Sale or Order or Authorization
' returnURL: the page where buyers return to after they are done with the payment review on PayPal
' cancelURL: the page where buyers return to when they cancel the payment review on PayPal
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
function SetExpressCheckoutDG( $paymentAmount, $currencyCodeType, $paymentType, $returnURL,
$cancelURL, $items)
{
//------------------------------------------------------------------------------------------------------------------------------------
// Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
$nvpstr = "&PAYMENTREQUEST_0_AMT=". $paymentAmount;
$nvpstr .= "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
$nvpstr .= "&RETURNURL=" . $returnURL;
$nvpstr .= "&CANCELURL=" . $cancelURL;
$nvpstr .= "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
$nvpstr .= "&REQCONFIRMSHIPPING=0";
$nvpstr .= "&NOSHIPPING=1";
foreach($items as $index => $item) {
$nvpstr .= "&L_PAYMENTREQUEST_0_NAME" . $index . "=" . urlencode($item["name"]);
$nvpstr .= "&L_PAYMENTREQUEST_0_AMT" . $index . "=" . urlencode($item["amt"]);
$nvpstr .= "&L_PAYMENTREQUEST_0_QTY" . $index . "=" . urlencode($item["qty"]);
$nvpstr .= "&L_PAYMENTREQUEST_0_ITEMCATEGORY" . $index . "=Digital";
}
//'---------------------------------------------------------------------------------------------------------------
//' Make the API call to PayPal
//' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
//' If an error occured, show the resulting errors
//'---------------------------------------------------------------------------------------------------------------
$resArray = hash_call("SetExpressCheckout", $nvpstr);
$ack = strtoupper($resArray["ACK"]);
if($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING")
{
$token = urldecode($resArray["TOKEN"]);
$_SESSION['TOKEN'] = $token;
}
return $resArray;
}
/*
'-------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the GetExpressCheckoutDetails API Call.
'
' Inputs:
' None
' Returns:
' The NVP Collection object of the GetExpressCheckoutDetails Call Response.
'-------------------------------------------------------------------------------------------
*/
function GetExpressCheckoutDetails( $token )
{
//'--------------------------------------------------------------
//' At this point, the buyer has completed authorizing the payment
//' at PayPal. The function will call PayPal to obtain the details
//' of the authorization, incuding any shipping information of the
//' buyer. Remember, the authorization is not a completed transaction
//' at this state - the buyer still needs an additional step to finalize
//' the transaction
//'--------------------------------------------------------------
//'---------------------------------------------------------------------------
//' Build a second API request to PayPal, using the token as the
//' ID to get the details on the payment authorization
//'---------------------------------------------------------------------------
$nvpstr="&TOKEN=" . $token;
//'---------------------------------------------------------------------------
//' Make the API call and store the results in an array.
//' If the call was a success, show the authorization details, and provide
//' an action to complete the payment.
//' If failed, show the error
//'---------------------------------------------------------------------------
$resArray=hash_call("GetExpressCheckoutDetails",$nvpstr);
$ack = strtoupper($resArray["ACK"]);
if($ack == "SUCCESS" || $ack=="SUCCESSWITHWARNING")
{
return $resArray;
}
else return false;
}
/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the GetExpressCheckoutDetails API Call.
'
' Inputs:
' sBNCode: The BN code used by PayPal to track the transactions from a given shopping cart.
' Returns:
' The NVP Collection object of the GetExpressCheckoutDetails Call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
function ConfirmPayment( $token, $paymentType, $currencyCodeType, $payerID, $FinalPaymentAmt, $items )
{
/* Gather the information to make the final call to
finalize the PayPal payment. The variable nvpstr
holds the name value pairs
*/
$token = urlencode($token);
$paymentType = urlencode($paymentType);
$currencyCodeType = urlencode($currencyCodeType);
$payerID = urlencode($payerID);
$serverName = urlencode($_SERVER['SERVER_NAME']);
$nvpstr = '&TOKEN=' . $token . '&PAYERID=' . $payerID . '&PAYMENTREQUEST_0_PAYMENTACTION=' . $paymentType . '&PAYMENTREQUEST_0_AMT=' . $FinalPaymentAmt;
$nvpstr .= '&PAYMENTREQUEST_0_CURRENCYCODE=' . $currencyCodeType . '&IPADDRESS=' . $serverName;
foreach($items as $index => $item) {
$nvpstr .= "&L_PAYMENTREQUEST_0_NAME" . $index . "=" . urlencode($item["name"]);
$nvpstr .= "&L_PAYMENTREQUEST_0_AMT" . $index . "=" . urlencode($item["amt"]);
$nvpstr .= "&L_PAYMENTREQUEST_0_QTY" . $index . "=" . urlencode($item["qty"]);
$nvpstr .= "&L_PAYMENTREQUEST_0_ITEMCATEGORY" . $index . "=Digital";
}
/* Make the call to PayPal to finalize payment
If an error occured, show the resulting errors
*/
$resArray=hash_call("DoExpressCheckoutPayment",$nvpstr);
/* Display the API response back to the browser.
If the response from PayPal was a success, display the response parameters'
If the response was an error, display the errors received using APIError.php.
*/
$ack = strtoupper($resArray["ACK"]);
return $resArray;
}
/**
'-------------------------------------------------------------------------------------------------------------------------------------------
* hash_call: Function to perform the API call to PayPal using API signature
* #methodName is name of API method.
* #nvpStr is nvp string.
* returns an associtive array containing the response from the server.
'-------------------------------------------------------------------------------------------------------------------------------------------
*/
function hash_call($methodName,$nvpStr)
{
//declaring of global variables
global $API_Endpoint, $version, $API_UserName, $API_Password, $API_Signature;
global $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $gv_ApiErrorURL;
global $sBNCode;
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//turning 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);
//if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
//Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
if($USE_PROXY)
curl_setopt ($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT);
//NVPRequest for submitting to server
$nvpreq="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode($version) . "&PWD=" . urlencode($API_Password) . "&USER=" . urlencode($API_UserName) . "&SIGNATURE=" . urlencode($API_Signature) . $nvpStr . "&BUTTONSOURCE=" . urlencode($sBNCode);
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
//getting response from server
$response = curl_exec($ch);
//convrting NVPResponse to an Associative Array
$nvpResArray=deformatNVP($response);
$nvpReqArray=deformatNVP($nvpreq);
$_SESSION['nvpReqArray']=$nvpReqArray;
if (curl_errno($ch))
{
// moving to display page to display curl errors
$_SESSION['curl_error_no']=curl_errno($ch) ;
$_SESSION['curl_error_msg']=curl_error($ch);
//Execute the Error handling module to display errors.
}
else
{
//closing the curl
curl_close($ch);
}
return $nvpResArray;
}
/*'----------------------------------------------------------------------------------
Purpose: Redirects to PayPal.com site.
Inputs: NVP string.
Returns:
----------------------------------------------------------------------------------
*/
function RedirectToPayPal ( $token )
{
global $PAYPAL_URL;
// Redirect to paypal.com here
$payPalURL = $PAYPAL_URL . $token;
header("Location: ".$payPalURL);
exit;
}
function RedirectToPayPalDG ( $token )
{
global $PAYPAL_DG_URL;
// Redirect to paypal.com here
$payPalURL = $PAYPAL_DG_URL . $token;
header("Location: ".$payPalURL);
exit;
}
/*'----------------------------------------------------------------------------------
* This function will take NVPString and convert it to an Associative Array and it will decode the response.
* It is usefull to search for a particular key and displaying arrays.
* #nvpstr is NVPString.
* #nvpArray is Associative Array.
----------------------------------------------------------------------------------
*/
function deformatNVP($nvpstr)
{
$intial=0;
$nvpArray = array();
while(strlen($nvpstr))
{
//postion of Key
$keypos= strpos($nvpstr,'=');
//position of value
$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
/*getting the Key and Value values and storing in a Associative Array*/
$keyval=substr($nvpstr,$intial,$keypos);
$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
//decoding the respose
$nvpArray[urldecode($keyval)] =urldecode( $valval);
$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
}
return $nvpArray;
}
?>
checkout.php
<?php
require_once ("paypalfunctions.php");
$PaymentOption = "PayPal";
if ( $PaymentOption == "PayPal")
{
// ==================================
// PayPal Express Checkout Module
// ==================================
//'------------------------------------
//' The paymentAmount is the total value of
//' the purchase.
//'
//' TODO: Enter the total Payment Amount within the quotes.
//' example : $paymentAmount = "15.00";
//'------------------------------------
$fakeBook = "4.99";
//'------------------------------------
//' The currencyCodeType
//' is set to the selections made on the Integration Assistant
//'------------------------------------
$currencyCodeType = "USD";
$paymentType = "Sale";
//'------------------------------------
//' The returnURL is the location where buyers return to when a
//' payment has been succesfully authorized.
//'
//' This is set to the value entered on the Integration Assistant
//'------------------------------------
$returnURL = "http://example.com";
//'------------------------------------
//' The cancelURL is the location buyers are sent to when they hit the
//' cancel button during authorization of payment during the PayPal flow
//'
//' This is set to the value entered on the Integration Assistant
//'------------------------------------
$cancelURL = "http://example.com";
//'------------------------------------
//' Calls the SetExpressCheckout API call
//'
//' The CallSetExpressCheckout function is defined in the file PayPalFunctions.php,
//' it is included at the top of this file.
//'-------------------------------------------------
$items = array();
$items[] = array('name' => 'Fake Book', 'amt' => $fakeBook, 'qty' => 1);
//::ITEMS::
// to add anothe item, uncomment the lines below and comment the line above
// $items[] = array('name' => 'Item Name1', 'amt' => $itemAmount1, 'qty' => 1);
// $items[] = array('name' => 'Item Name2', 'amt' => $itemAmount2, 'qty' => 1);
// $paymentAmount = $itemAmount1 + $itemAmount2;
// assign corresponding item amounts to "$itemAmount1" and "$itemAmount2"
// NOTE : sum of all the item amounts should be equal to payment amount
$resArray = SetExpressCheckoutDG( $fakeBook, $currencyCodeType, $paymentType,
$returnURL, $cancelURL, $items );
$ack = strtoupper($resArray["ACK"]);
if($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING")
{
$token = urldecode($resArray["TOKEN"]);
RedirectToPayPalDG( $token );
}
else
{
//Display a user friendly Error on the page using any of the following error information returned by PayPal
$ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
$ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
$ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
$ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
echo "SetExpressCheckout API call failed. ";
echo "Detailed Error Message: " . $ErrorLongMsg;
echo "Short Error Message: " . $ErrorShortMsg;
echo "Error Code: " . $ErrorCode;
echo "Error Severity Code: " . $ErrorSeverityCode;
}
}
?>
orderconfirm.php
<?php
/* =====================================
* PayPal Express Checkout Call
* =====================================
*/
require_once ("paypalfunctions.php");
$PaymentOption = "PayPal";
if ( $PaymentOption == "PayPal" )
{
/*
'------------------------------------
' this step is required to get parameters to make DoExpressCheckout API call,
' this step is required only if you are not storing the SetExpressCheckout API call's request values in you database.
' ------------------------------------
*/
$res = GetExpressCheckoutDetails( $_REQUEST['token'] );
/*
'------------------------------------
' The paymentAmount is the total value of
' the purchase.
'------------------------------------
*/
$finalPaymentAmount = $res["PAYMENTREQUEST_0_AMT"];
/*
'------------------------------------
' Calls the DoExpressCheckoutPayment API call
'
' The ConfirmPayment function is defined in the file PayPalFunctions.php,
' that is included at the top of this file.
'-------------------------------------------------
*/
//Format the parameters that were stored or received from GetExperessCheckout call.
$token = $_REQUEST['token'];
$payerID = $_REQUEST['PayerID'];
$paymentType = 'Sale';
$currencyCodeType = $res['CURRENCYCODE'];
$items = array();
$i = 0;
// adding item details those set in setExpressCheckout
while(isset($res["L_PAYMENTREQUEST_0_NAME$i"]))
{
$items[] = array('name' => $res["L_PAYMENTREQUEST_0_NAME$i"], 'amt' => $res["L_PAYMENTREQUEST_0_AMT$i"], 'qty' => $res["L_PAYMENTREQUEST_0_QTY$i"]);
$i++;
}
$resArray = ConfirmPayment ( $token, $paymentType, $currencyCodeType, $payerID, $finalPaymentAmount, $items );
$ack = strtoupper($resArray["ACK"]);
if( $ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING" )
{
/*
* TODO: Proceed with desired action after the payment
* (ex: start download, start streaming, Add coins to the game.. etc)
'********************************************************************************************************************
'
' THE PARTNER SHOULD SAVE THE KEY TRANSACTION RELATED INFORMATION LIKE
' transactionId & orderTime
' IN THEIR OWN DATABASE
' AND THE REST OF THE INFORMATION CAN BE USED TO UNDERSTAND THE STATUS OF THE PAYMENT
'
'********************************************************************************************************************
*/
$transactionId = $resArray["PAYMENTINFO_0_TRANSACTIONID"]; // Unique transaction ID of the payment.
$transactionType = $resArray["PAYMENTINFO_0_TRANSACTIONTYPE"]; // The type of transaction Possible values: l cart l express-checkout
$paymentType = $resArray["PAYMENTINFO_0_PAYMENTTYPE"]; // Indicates whether the payment is instant or delayed. Possible values: l none l echeck l instant
$orderTime = $resArray["PAYMENTINFO_0_ORDERTIME"]; // Time/date stamp of payment
$amt = $resArray["PAYMENTINFO_0_AMT"]; // The final amount charged, including any taxes from your Merchant Profile.
$currencyCode = $resArray["PAYMENTINFO_0_CURRENCYCODE"]; // A three-character currency code for one of the currencies listed in PayPay-Supported Transactional Currencies. Default: USD.
$feeAmt = $resArray["PAYMENTINFO_0_FEEAMT"]; // PayPal fee amount charged for the transaction
// $settleAmt = $resArray["PAYMENTINFO_0_SETTLEAMT"]; // Amount deposited in your PayPal account after a currency conversion.
$taxAmt = $resArray["PAYMENTINFO_0_TAXAMT"]; // Tax charged on the transaction.
// $exchangeRate = $resArray["PAYMENTINFO_0_EXCHANGERATE"]; // Exchange rate if a currency conversion occurred. Relevant only if your are billing in their non-primary currency. If the customer chooses to pay with a currency other than the non-primary currency, the conversion occurs in the customer's account.
/*
' Status of the payment:
'Completed: The payment has been completed, and the funds have been added successfully to your account balance.
'Pending: The payment is pending. See the PendingReason element for more information.
*/
$paymentStatus = $resArray["PAYMENTINFO_0_PAYMENTSTATUS"];
/*
'The reason the payment is pending:
' none: No pending reason
' address: The payment is pending because your customer did not include a confirmed shipping address and your Payment Receiving Preferences is set such that you want to manually accept or deny each of these payments. To change your preference, go to the Preferences section of your Profile.
' echeck: The payment is pending because it was made by an eCheck that has not yet cleared.
' intl: The payment is pending because you hold a non-U.S. account and do not have a withdrawal mechanism. You must manually accept or deny this payment from your Account Overview.
' multi-currency: You do not have a balance in the currency sent, and you do not have your Payment Receiving Preferences set to automatically convert and accept this payment. You must manually accept or deny this payment.
' verify: The payment is pending because you are not yet verified. You must verify your account before you can accept this payment.
' other: The payment is pending for a reason other than those listed above. For more information, contact PayPal customer service.
*/
$pendingReason = $resArray["PAYMENTINFO_0_PENDINGREASON"];
/*
'The reason for a reversal if TransactionType is reversal:
' none: No reason code
' chargeback: A reversal has occurred on this transaction due to a chargeback by your customer.
' guarantee: A reversal has occurred on this transaction due to your customer triggering a money-back guarantee.
' buyer-complaint: A reversal has occurred on this transaction due to a complaint about the transaction from your customer.
' refund: A reversal has occurred on this transaction because you have given the customer a refund.
' other: A reversal has occurred on this transaction due to a reason not listed above.
*/
$reasonCode = $resArray["PAYMENTINFO_0_REASONCODE"];
// Add javascript to close Digital Goods frame. You may want to add more javascript code to
// display some info message indicating status of purchase in the parent window
?>
<html>
<script>
alert("Payment Successful");
// add relevant message above or remove the line if not required
window.onload = function(){
if(window.opener){
window.close();
}
else{
if(top.dg.isOpen() == true){
top.dg.closeFlow();
return true;
}
}
};
</script>
</html>
<?php
}
else
{
//Display a user friendly Error on the page using any of the following error information returned by PayPal
$ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
$ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
$ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
$ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
echo "DoExpressCheckoutDetails API call failed. ";
echo "Detailed Error Message: " . $ErrorLongMsg;
echo "Short Error Message: " . $ErrorShortMsg;
echo "Error Code: " . $ErrorCode;
echo "Error Severity Code: " . $ErrorSeverityCode;
?>
<html>
<script>
alert("Payment failed");
// add relevant message above or remove the line if not required
window.onload = function(){
if(window.opener){
window.close();
}
else{
if(top.dg.isOpen() == true){
top.dg.closeFlow();
return true;
}
}
};
</script>
</html>
<?php
}
}
?>
lightbox.php
<!DOCTYPE html>
<html>
<head>
<title>Digital Goods</title>
</head>
<body>
<form id="myContainer" method="post" action="paypal/checkout.php">
<img src="https://www.vanishingincmagic.co.uk/gallery/photos/the-modern-con-man.jpg">
<p>$4.99</p>
<p>Buy my totally not fake book!</p>
</form>
<script>window.paypalCheckoutReady=function(){paypal.checkout.setup('EMAIL-HERE',{environment:'sandbox',container:'myContainer'})};</script>
<script src="//www.paypalobjects.com/api/checkout.js" async></script>
</body>
</html>
Have you call DoExpressCheckout? From the code you attach I can see you are calling SetExpressCheckout but did not see the functions of DoExpressCheckout is invoke. Probably you wanted to try out the samples here?

call to DoReferenceTransaction method giving error

I am calling CreateBillingAgreement after SetExpressCheckout, both are successfull. BILLINGAGREEMENTID is returnd by CreateBillingAgreement.
This BILLINGAGREEMENTID is passed as REFERENCEID to DoReferenceTransaction.
NVP is constructed as :
$nvpstr = '&TOKEN=' . $token . '&REFERENCEID=' . $billing_agreement_id . '&PAYMENTACTION=' . $paymentType . '&AMT=' . $FinalPaymentAmt;
$nvpstr .= '&CURRENCYCODE=' . $currencyCodeType . '&IPADDRESS=' . $serverName .'&L_ITEMCATEGORY0=Digital'.'&DESC='.urlencode("Test Recurring Payment( $" . $_SESSION["Payment_Amount"] . " monthly)");
$nvpstr.="&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital";
$nvpstr.="&L_PAYMENTREQUEST_0_QTY0=Digital";
$nvpstr.="&L_PAYMENTREQUEST_0_NAME0=Test Name";
$nvpstr.="&L_PAYMENTREQUEST_0_AMT0=".$_SESSION["Payment_Amount"];
$nvpstr.="&L_NAME0=Test Name";
$nvpstr.="&L_DESC0=".urlencode("Test Recurring Payment( $" . $_SESSION["Payment_Amount"] . " monthly)");
$nvpstr.="&L_AMT0=".$_SESSION["Payment_Amount"];
$nvpstr.="&L_QTY0=1";
call to DoReferenceTransaction method giving error:
Array
(
[TIMESTAMP] => 2015-11-02T10:20:06Z
[CORRELATIONID] => 3e60a1baba3b3
[ACK] => Failure
[VERSION] => 64
[BUILD] => 000000
[L_ERRORCODE0] => 10209
[L_ERRORCODE1] => 10004
[L_SHORTMESSAGE0] => Disabled
[L_SHORTMESSAGE1] => Invalid Data
[L_LONGMESSAGE0] => Preapproved Payments not enabled.
[L_LONGMESSAGE1] => This transaction cannot be processed.
[L_SEVERITYCODE0] => Error
[L_SEVERITYCODE1] => Error
[TRANSACTIONTYPE] => None
[PAYMENTTYPE] => None
[ORDERTIME] => 1970-01-01T00:00:00Z
[PAYMENTSTATUS] => None
[PENDINGREASON] => None
[REASONCODE] => None
)
Note: Using Sandbox account for testing.
UPDATE:
function DoReferenceTransaction(){
//Format the other parameters that were stored in the session from the previous calls
$token = urlencode($_SESSION['TOKEN']);
$paymentType = urlencode($_SESSION['PaymentType']);
$currencyCodeType = urlencode($_SESSION['currencyCodeType']);
//$payerID = urlencode($_SESSION['payer_id']); $_SESSION['billing_agreement_id']
$billing_agreement_id = urlencode($_SESSION['billing_agreement_id']);
$FinalPaymentAmt = urlencode( $_SESSION["Payment_Amount"]);
$serverName = urlencode($_SERVER['SERVER_NAME']);
$nvpstr = '&TOKEN=' . $token . '&REFERENCEID=' . $billing_agreement_id . '&PAYMENTACTION=' . $paymentType . '&AMT=' . $FinalPaymentAmt;
$nvpstr .= '&CURRENCYCODE=' . $currencyCodeType . '&IPADDRESS=' . $serverName .'&L_ITEMCATEGORY0=Digital'.'&DESC='.urlencode("Test Recurring Payment( $" . $_SESSION["Payment_Amount"] . " monthly)");
$nvpstr.="&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital";
$nvpstr.="&L_PAYMENTREQUEST_0_QTY0=Digital";
$nvpstr.="&L_PAYMENTREQUEST_0_NAME0=Test Name";
$nvpstr.="&L_PAYMENTREQUEST_0_AMT0=".$_SESSION["Payment_Amount"];
$nvpstr.="&L_NAME0=Test Name";
$nvpstr.="&L_DESC0=".urlencode("Test Recurring Payment( $" . $_SESSION["Payment_Amount"] . " monthly)");
$nvpstr.="&L_AMT0=".$_SESSION["Payment_Amount"];
$nvpstr.="&L_QTY0=1";
/* Make the call to PayPal to finalize payment
If an error occured, show the resulting errors
*/
$resArray = hash_call("DoReferenceTransaction", $nvpstr);
echo "<pre>";
print_r($resArray); exit;
/* Display the API response back to the browser.
If the response from PayPal was a success, display the response parameters'
If the response was an error, display the errors received using APIError.php.
*/
$ack = strtoupper($resArray["ACK"]);
return $resArray;
}
NVP for DoReferenceTransaction:
&TOKEN=EC-30M31870BS241854X&REFERENCEID=B-81S156104Y376273D&PAYMENTACTION=Sale&AMT=3&CURRENCYCODE=USD&IPADDRESS=paypalrecurring.com&L_ITEMCATEGORY0=Digital&DESC=Test+Recurring+Payment%28+%243+monthly%29&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital&L_PAYMENTREQUEST_0_QTY0=Digital&L_PAYMENTREQUEST_0_NAME0=Test Name&L_PAYMENTREQUEST_0_AMT0=3&L_NAME0=Test Name&L_DESC0=Test+Recurring+Payment%28+%243+monthly%29&L_AMT0=3&L_QTY0=1
Is it a live or a sandbox API call?
You need to have Reference Transaction activated on your PayPal account to be able to call this API.
The Reference Transaction API is not available for everybody. I would advise to contact your PayPal representative to ask them to activate this on your PayPal account.
If you are doing this on the sandbox, you should simply upgrade your sandbox account to a Pro account. This should activate Reference Transaction on the sandbox account.
To be sure, you should ask PayPal if your sandbox account has Reference Transaction enabled.
Can you send the full API call in your question please?
Update
I see something strange in your code:
$nvpstr.="&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital";
$nvpstr.="&L_PAYMENTREQUEST_0_QTY0=Digital";
Change it by:
$nvpstr.="&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Physical";
$nvpstr.="&L_PAYMENTREQUEST_0_QTY0=1";
Update 2
I see few errors in the API call:
&TOKEN=EC-30M31870BS241854X&
REFERENCEID=B-81S156104Y376273D&
PAYMENTACTION=Sale&
AMT=3&
CURRENCYCODE=USD&
IPADDRESS=paypalrecurring.com&
L_ITEMCATEGORY0=Digital&
DESC=Test+Recurring+Payment%28+%243+monthly%29&
L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital&
L_PAYMENTREQUEST_0_QTY0=Digital&
L_PAYMENTREQUEST_0_NAME0=Test Name&
L_PAYMENTREQUEST_0_AMT0=3&
L_NAME0=Test Name&
L_DESC0=Test+Recurring+Payment%28+%243+monthly%29&
L_AMT0=3&
L_QTY0=1string(606)
Provide a valid IP address in the IP address variable.
Replace
L_PAYMENTREQUEST_0_QTY0=Digital&
by:
L_PAYMENTREQUEST_0_QTY0=1&
In the last parameter there is a wrong parameter replace:
L_QTY0=1string(606)
by:
L_QTY0=1
Eventually change the item category from Digital to Physical. I know you need special rights to do Digital Goods with PayPal.
L_ITEMCATEGORY0=Physical&
L_PAYMENTREQUEST_0_ITEMCATEGORY0=Physical&

Braintree push notification is not working

I have used the Sandbox account of Braintree for recurring subscriptions. The verification of the webhook end URL is succeeded.But I didn't get any push notifications to my server even after successful completion of the subscription. I am using PHP environment to fetch the POST details. Below is the code segment I have used.
<?php
require_once(app_classes.'DB.Class.php');
require_once(app_classes.'util.Class.php');
require_once app_classes.'braintree/lib/Braintree.php';
Braintree_Configuration::environment(bt_environment);
Braintree_Configuration::merchantId(bt_merchant_id);
Braintree_Configuration::publicKey(bt_public_key);
Braintree_Configuration::privateKey(bt_private_key);
if(
isset($_POST["bt_signature"]) &&
isset($_POST["bt_payload"])
) {
$webhookNotification = Braintree_WebhookNotification::parse(
$_POST["bt_signature"], $_POST["bt_payload"]
);
$message = "[Webhook Received " . $webhookNotification->timestamp->format('Y-m-d H:i:s') . "] "
. "Kind: " . $webhookNotification->kind . " | "
. "Subscription: " . $webhookNotification->subscription->id . "\n";
$subDetails = array( 'data' => $message );
DB::insert('subscription_notifications', $subDetails);
}
return 200;
?>
The server has SSL certificate. Please let me know if any thing I need to do to get it working.
Finally I got the solution. This was the issue related with SSL certificate. The connection get closed with an HTTP status of 599 for all the attempts to POST. This is happened because of the intermediate certificate was missing in the server. We added the certificate .Now I can access the push notifications from Braintree.

How to obtain Pay API key from PayPal for Adaptive Payments

I am at my wits end trying to get this work but cant understand it. I have to use Adaptive payments in a webapp which is created using cakephp framework. I have API credentials like API Username, Password and Signature. But the main problem i am facing is how to call the Pay API to get the API key which is the first thing required to make this work. I am new to this so i dont have much knowledge about this and after lot digging in google i am asking this question. Can someone please give steps for using Adaptive Payments..
Thanks in advance for your help!
You have to follow only three steps:
1- You send a PayRequest message to PayPal
{"returnUrl":"http://example.com/returnURL.htm", \ "requestEnvelope":{"errorLanguage":"en_US"},"currencyCode":"USD", \ "receiverList":{"receiver":[{"email":"david#example.com", \
"amount":"10.00",}]},"cancelUrl":"http://example.com/cancelURL.htm",\ "actionType":"PAY"}
2- You receive a response with a pay key.
{"responseEnvelope":\ {"timestamp":"2009-10-06T14:30:39.383-07:00","ack":"Success",\ "correlationId":"cfe8f8783f1d3","build":"DEV"},\ "payKey":"AP-17266198048308436","paymentExecStatus":"CREATED"}
3- You must redirect the sender’s browser to PayPal to approve the payment.
This would be an example code for step 1 (it works on my local server):
<?php
//turn php errors on
ini_set("track_errors", true);
//set PayPal Endpoint to sandbox
$url = trim("https://svcs.sandbox.paypal.com/AdaptivePayments/Pay");
$api_appid = 'APP-80W284485P519543T'; // para sandbox
//PayPal API Credentials
$API_UserName = "sbapi_1287090601_biz_api1.paypal.com"; //TODO
$API_Password = "1287090610"; //TODO
$API_Signature = "ANFgtzcGWolmjcm5vfrf07xVQ6B9AsoDvVryVxEQqezY85hChCfdBMvY"; //TODO
$receiver_email = "fake#email.com"; //TODO
$amount = 25; //TODO
//Default App ID for Sandbox
$API_AppID = "APP-80W284485P519543T";
$API_RequestFormat = "NV";
$API_ResponseFormat = "NV";
//Create request payload with minimum required parameters
$bodyparams = array ( "requestEnvelope.errorLanguage" => "en_US",
"actionType" => "PAY",
"cancelUrl" => "http://cancelUrl",
"returnUrl" => "http://returnUrl",
"currencyCode" => "EUR",
"receiverList.receiver.email" => $receiver_email,
"receiverList.receiver.amount" => $amount
);
// convert payload array into url encoded query string
$body_data = http_build_query($bodyparams, "", chr(38));
try
{
//create request and add headers
$params = array("http" => array(
"method" => "POST",
"content" => $body_data,
"header" => "X-PAYPAL-SECURITY-USERID: " . $API_UserName . "\r\n" .
"X-PAYPAL-SECURITY-SIGNATURE: " . $API_Signature . "\r\n" .
"X-PAYPAL-SECURITY-PASSWORD: " . $API_Password . "\r\n" .
"X-PAYPAL-APPLICATION-ID: " . $API_AppID . "\r\n" .
"X-PAYPAL-REQUEST-DATA-FORMAT: " . $API_RequestFormat . "\r\n" .
"X-PAYPAL-RESPONSE-DATA-FORMAT: " . $API_ResponseFormat . "\r\n"
));
//create stream context
$ctx = stream_context_create($params);
//open the stream and send request
$fp = #fopen($url, "r", false, $ctx);
//get response
$response = stream_get_contents($fp);
//check to see if stream is open
if ($response === false) {
throw new Exception("php error message = " . "$php_errormsg");
}
//close the stream
fclose($fp);
//parse the ap key from the response
$keyArray = explode("&", $response);
foreach ($keyArray as $rVal){
list($qKey, $qVal) = explode ("=", $rVal);
$kArray[$qKey] = $qVal;
}
//print the response to screen for testing purposes
If ( $kArray["responseEnvelope.ack"] == "Success") {
foreach ($kArray as $key =>$value){
echo $key . ": " .$value . "<br/>";
}
}
else {
echo 'ERROR Code: ' . $kArray["error(0).errorId"] . " <br/>";
echo 'ERROR Message: ' . urldecode($kArray["error(0).message"]) . " <br/>";
}
}
catch(Exception $e) {
echo "Message: ||" .$e->getMessage()."||";
}
?>
You have many examples here: https://www.x.com/developers/paypal/documentation-tools/paypal-code-samples

PayPal AdaptivePayments PaymentDetail PayKey

I am using the PayPal Pay API, with Adaptive (Chained) Payments. I am trying to forward a user to paypal and afterwards back to my predefined return_url.
The problem is: I need to have a PayKey within my return-url. Reason for that: I need to call a PaymentDetail API to review the payment within the return_url. And, I don't want to use IPN since I need the validation with some token right on my return Url.
The problem I have is: The PayKey is beeing generated with all the parameters, including the return-url (hence after I build the actual array from which I get my $response from. I can't put the PayKey in the return-Url since it's not generated at this point yet.
//Create request payload with minimum required parameters
$bodyparams = array ("requestEnvelope.errorLanguage" => "en_US",
"actionType" => "PAY",
"currencyCode" => "USD",
"cancelUrl" => "http://www.paypal.com",
"returnUrl" => $return_url . "&payKey=${payKey}", **// Does not work - PAYKEY NEEDED TO ADD???**
"receiverList.receiver(0).email" => "account1#hotmail.com", //TODO
"receiverList.receiver(0).amount" => $price, //TODO
"receiverList.receiver(0).primary" => "true", //TODO
"receiverList.receiver(1).email" => "account2#hotmail.com", //TODO
"receiverList.receiver(1).amount" => $receiver_gets, //TODO
"receiverList.receiver(1).primary" => "false" //TODO
);
// convert payload array into url encoded query string
$body_data = http_build_query($bodyparams, "", chr(38)); // Generates body data
try
{
//create request and add headers
$params = array("http" => array(
"method" => "POST",
"content" => $body_data,
"header" => "X-PAYPAL-SECURITY-USERID: " . $API_UserName . "\r\n" .
"X-PAYPAL-SECURITY-SIGNATURE: " . $API_Signature . "\r\n" .
"X-PAYPAL-SECURITY-PASSWORD: " . $API_Password . "\r\n" .
"X-PAYPAL-APPLICATION-ID: " . $API_AppID . "\r\n" .
"X-PAYPAL-REQUEST-DATA-FORMAT: " . $API_RequestFormat . "\r\n" .
"X-PAYPAL-RESPONSE-DATA-FORMAT: " . $API_ResponseFormat . "\r\n"
));
//create stream context
$ctx = stream_context_create($params);
//open the stream and send request
$fp = #fopen($url, "r", false, $ctx);
//get response
$response = stream_get_contents($fp);
//check to see if stream is open
if ($response === false) {
throw new Exception("php error message = " . "$php_errormsg");
}
fclose($fp);
//parse the ap key from the response
$keyArray = explode("&", $response);
foreach ($keyArray as $rVal){
list($qKey, $qVal) = explode ("=", $rVal);
$kArray[$qKey] = $qVal;
}
//set url to approve the transaction
$payPalURL = "https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=" . $kArray["payKey"]; **// Here it works fine, since the PayKey is generated at this point ...**
//print the url to screen for testing purposes
If ( $kArray["responseEnvelope.ack"] == "Success") {
echo '<p>' . $payPalURL . '</p>';
}
else {
echo 'ERROR Code: ' . $kArray["error(0).errorId"] . " <br/>";
echo 'ERROR Message: ' . urldecode($kArray["error(0).message"]) . " <br/>";
}
Can somebody help?
I was at this for ages too myself. I finally figured it out. Paypal docs are hard to follow. I found the answer in the paypal adaptive pdf guide which I downloaded. It specifies to add payKey=${payKey} to the end of your return_url. I just tried it there and the paypal get request to my return url now contains the paykey.
So in rails which I'm using the return_url looks like this. Writing a php variable (I think) into the url as instructed by the guide
:return_url => "http://***********.com/paypal-return?payKey=${payKey}"
It seems that you're missing a step in the sequence.
The first step is to send your transaction parameters to
https://svcs.paypal.com/AdaptivePayments/Pay&yourtransactionparameters=blah
[sandbox]https://svcs.sandbox.paypal.com/AdaptivePayments/Pay&yourtransactionparameters=blah
You'll get the paykey in this response.
Once you've retrieved the paykey successfully, you'll call:
https://www.paypal.com/webscr&cmd=_ap-payment&paykey=xxxx
[sandbox]https://www.sandbox.paypal.com/webscr&cmd=_ap-payment&paykey=xxxx
In the second call, the payKey represents the rest of your transaction so you don't have to build another giant query string.
Change your code for:
//Create request payload with minimum required parameters
$bodyparams = array ("requestEnvelope.errorLanguage" => "en_US",
"actionType" => "PAY",
"currencyCode" => "USD",
"cancelUrl" => "http://www.paypal.com",
"returnUrl" => $return_url . '&payKey=${payKey}', **// That's right**
"receiverList.receiver(0).email" => "account1#hotmail.com", //TODO
"receiverList.receiver(0).amount" => $price, //TODO
"receiverList.receiver(0).primary" => "true", //TODO
"receiverList.receiver(1).email" => "account2#hotmail.com", //TODO
"receiverList.receiver(1).amount" => $receiver_gets, //TODO
"receiverList.receiver(1).primary" => "false" //TODO
);
PHP interprets ${payKey} as variable between the double quotes.
Change double quotes (") for simple quotes (')
Apparently you can embed dynamic variables in the return URL: https://www.x.com/thread/49785
Unfortunately, {$payKey} is invalid. so it must be $paykey or $pay_key. Good luck!

Categories