Magento paypal chained payment (Adaptive payment)
Data.php
<?php
class Pixel_Paypalpayment_Helper_Data extends Mage_Core_Helper_Abstract
{
public $Env;
public $API_UserName ;
public $API_Password ;
public $API_Signature;
public $API_AppID = "APP-80W284485P519543T";
public $API_Endpoint = "";
public $USE_PROXY;
public $PROXY_HOST;
public $PROXY_PORT;
public function __construct()
{
/* $this->API_UserName = $vendormodel->getApiusername();
$this->API_Password =$vendormodel->getApipassword();
$this->API_Signature = $vendormodel->getApisignature();
$this->Env = $vendormodel->getSandbox();
if ($this->Env == 1)
{
$this->API_Endpoint = "https://svcs.sandbox.paypal.com/AdaptivePayments";
}
else
{
$this->API_Endpoint = "https://svcs.paypal.com/AdaptivePayments";
}
$this->USE_PROXY = false;*/
if (session_id() == "")
session_start();
}
function generateCharacter () {
$possible = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
return $char;
}
function generateTrackingID () {
$GUID = $this->generateCharacter().$this->generateCharacter().$this->generateCharacter().$this->generateCharacter().$this->generateCharacter();
$GUID .= $this->generateCharacter().$this->generateCharacter().$this->generateCharacter().$this->generateCharacter();
return $GUID;
}
function CallRefund( $payKey, $transactionId, $trackingId, $receiverEmailArray, $receiverAmountArray )
{
$nvpstr = "";
if ("" != $payKey)
{
$nvpstr = "payKey=" . $this->urlencode($payKey);
if (0 != count($receiverEmailArray))
{
reset($receiverEmailArray);
while (list($key, $value) = each($receiverEmailArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").email=" . urlencode($value);
}
}
}
if (0 != count($receiverAmountArray))
{
reset($receiverAmountArray);
while (list($key, $value) = each($receiverAmountArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").amount=" . urlencode($value);
}
}
}
}
elseif ("" != $trackingId)
{
$nvpstr = "trackingId=" . urlencode($trackingId);
if (0 != count($receiverEmailArray))
{
reset($receiverEmailArray);
while (list($key, $value) = each($receiverEmailArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").email=" . urlencode($value);
}
}
}
if (0 != count($receiverAmountArray))
{
reset($receiverAmountArray);
while (list($key, $value) = each($receiverAmountArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").amount=" . urlencode($value);
}
}
}
}
elseif ("" != $transactionId)
{
$nvpstr = "transactionId=" . urlencode($transactionId);
// the caller should only have 1 entry in the email and amount arrays
if (0 != count($receiverEmailArray))
{
reset($receiverEmailArray);
while (list($key, $value) = each($receiverEmailArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").email=" . urlencode($value);
}
}
}
if (0 != count($receiverAmountArray))
{
reset($receiverAmountArray);
while (list($key, $value) = each($receiverAmountArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").amount=" . urlencode($value);
}
}
}
}
/* Make the Refund call to PayPal */
$resArray = $this->hash_call("Refund", $nvpstr);
/* Return the response array */
return $resArray;
}
function CallPaymentDetails( $payKey, $transactionId, $trackingId )
{
/* Gather the information to make the PaymentDetails call.
The variable nvpstr holds the name value pairs
*/
$nvpstr = "";
// conditionally required fields
if ("" != $payKey)
{
$nvpstr = "payKey=" . $this->urlencode($payKey);
}
elseif ("" != $transactionId)
{
$nvpstr = "transactionId=" . $this->urlencode($transactionId);
}
elseif ("" != $trackingId)
{
$nvpstr = "trackingId=" . $this->urlencode($trackingId);
}
/* Make the PaymentDetails call to PayPal */
$resArray = $this->hash_call("PaymentDetails", $nvpstr);
/* Return the response array */
return $resArray;
}
function CallPay( $actionType, $cancelUrl, $returnUrl, $currencyCode, $receiverEmailArray, $receiverAmountArray,
$receiverPrimaryArray, $receiverInvoiceIdArray, $feesPayer, $ipnNotificationUrl,
$memo, $pin, $preapprovalKey, $reverseAllParallelPaymentsOnError, $senderEmail, $trackingId )
{
/* Gather the information to make the Pay call.
The variable nvpstr holds the name value pairs
*/
$standard = Mage::getModel('paypalpayment/standard');
$trans = $standard->getStandardCheckoutFormFields();
$productId = Mage::app()->getRequest()->getParam('id');
$_product= Mage::getSingleton('catalog/product')->load($productId);
$pro=$_product['vendorid'];
$vendor_model=Mage::getModel('vendorpayment/vendorpayment')->load($pro,'user_vendor');
$this->API_UserName = $vendor_model->getApiusername();
$this->API_Password = $vendor_model->getApipassword();
$this->API_Signature = $vendor_model->getApisignature();
$Env = $this->Env = 'sandbox';
$ItemName= $_product['name'];
$ItemNumber=$_product['sku'];
$ItemQty = 1;
$ItemPrice=$_product['price'];
$PayPalReturnURL= $trans['RedirectorSuccess'];
$PayPalCancelURL= $trans['RedirectorFailed'];
$orderId = Mage::getSingleton('checkout/session')->getLastOrderId();
$order = Mage::getModel('sales/order')->load($orderId);
$items = $order->getAllItems();
$itemcount=count($items);
$totalItems = Mage::getModel('checkout/cart')->getQuote()->getItemsCount();
$shipping_amt= $order->getData('shipping_amount');
$name=array();
$unitPrice=array();
$sku=array();
$ids=array();
$price = 0;
$qty=array();
foreach ($items as $itemId => $item)
{
$name[] = $item->getName();
$unitPrice[]=$item->getPrice();
$sku[]=$item->getSku();
$ids[]=$item->getProductId();
$qty[]=$item->getQtyToInvoice();
//$singleitem= $unitPrice * $qty;
$items_summary .=
'&L_PAYMENTREQUEST_0_QTY'.$itemId.'='.urlencode( $item->getQtyToInvoice() ).
'&L_PAYMENTREQUEST_0_AMT'.$itemId.'='.urlencode( (float)$item->getPrice() ).
'&L_PAYMENTREQUEST_0_NAME'.$itemId.'='.urlencode( $item->getName() ).
'&L_PAYMENTREQUEST_0_NUMBER'.$itemId.'='.urlencode( $item->getSku() );
$price += $item->getQtyToInvoice() * $item->getPrice();
//$new[] = $price;
}
// print_r($price);
//exit;
$totalQuantity = Mage::getModel('checkout/cart')->getQuote()->getItemsQty();
$subTotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();
$grandTotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal();
//print_r($grandTotal);exit;
//$ItemTotalPrice = $grandTotal;
//print_r($totalQuantity);exit;
$PayPalCurrencyCode="USD";
echo $nvpStr = $padata =
'&CURRENCYCODE='.urlencode($PayPalCurrencyCode).
'&PAYMENTACTION=Sale'.
'&ALLOWNOTE=1'.
'&PAYMENTREQUEST_0_SHIPPINGAMT='.urlencode((float)$shipping_amt).
'&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode).
'&PAYMENTREQUEST_0_AMT='.urlencode((float)$grandTotal).
'&PAYMENTREQUEST_0_ITEMAMT='.urlencode((float)$subTotal).
$items_summary.
'&AMT='.urlencode((float)$grandTotal).
'&RETURNURL='.urlencode($PayPalReturnURL ).
'&CANCELURL='.urlencode($PayPalCancelURL);
//print_r($ItemTotalPrice);exit;
/* $nvpStr = $padata = '&CURRENCYCODE='.urlencode($PayPalCurrencyCode).
'&PAYMENTACTION=Sale'.
'&ALLOWNOTE=1'.
'&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode).
'&PAYMENTREQUEST_0_AMT='.urlencode('300').
'&PAYMENTREQUEST_0_ITEMAMT='.urlencode('300').
'&L_PAYMENTREQUEST_0_QTY0='. urlencode('1').
'&L_PAYMENTREQUEST_0_AMT0='.urlencode('100').
'&L_PAYMENTREQUEST_0_NAME0='.urlencode($ItemName).
'&L_PAYMENTREQUEST_0_NUMBER0='.urlencode($ItemNumber).
'&L_PAYMENTREQUEST_0_QTY1='. urlencode('1').
'&L_PAYMENTREQUEST_0_AMT1='.urlencode('200').
'&L_PAYMENTREQUEST_0_NAME1='.urlencode('Test 1').
'&L_PAYMENTREQUEST_0_NUMBER1='.urlencode('2').
'&AMT='.urlencode('300').
'&RETURNURL='.urlencode($PayPalReturnURL).
'&CANCELURL='.urlencode($PayPalCancelURL);
//print_r($nvpStr);exit;*/
$httpParsedResponseAr = $this->PPHttpPost('SetExpressCheckout', $nvpStr,$this->API_UserName ,$this->API_Password,$this->API_Signature,$Env);
//print_r($httpParsedResponseAr);exit;
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
// Redirect to paypal.com.
$token = urldecode($httpParsedResponseAr["TOKEN"]);
echo $payPalURL = "https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=$token";
if("sandbox" === $Env || "beta-sandbox" === $Env) {
$payPalURL = "https://www.$Env.paypal.com/webscr&cmd=_express-checkout&token=$token";
}
header("Location: $payPalURL");
exit;
} else {
exit('SetExpressCheckout failed: ' . print_r($httpParsedResponseAr, true));
}
// required fields
$nvpstr = 'actionType=' . urlencode($actionType);
$nvpstr .= '¤cyCode=' . urlencode($currencyCode);
$nvpstr .= "&returnUrl=" . urlencode($returnUrl) . "&cancelUrl=" . urlencode($cancelUrl);
if (0 != count($receiverAmountArray))
{
reset($receiverAmountArray);
while (list($key, $value) = each($receiverAmountArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").amount=" . urlencode($value);
}
}
}
if (0 != count($receiverEmailArray))
{
reset($receiverEmailArray);
while (list($key, $value) = each($receiverEmailArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").email=" . urlencode($value);
}
}
}
if (0 != count($receiverPrimaryArray))
{
reset($receiverPrimaryArray);
while (list($key, $value) = each($receiverPrimaryArray))
{
if ("" != $value)
{
$nvpstr = $nvpstr . "&receiverList.receiver(" . $key . ").primary=" . urlencode($value);
}
}
}
if (0 != count($receiverInvoiceIdArray))
{
reset($receiverInvoiceIdArray);
while (list($key, $value) = each($receiverInvoiceIdArray))
{
if ("" != $value)
{
$nvpstr = $nvpstr . "&receiverList.receiver(" . $key . ").invoiceId=" . urlencode($value);
}
}
}
// optional fields
if ("" != $feesPayer)
{
$nvpstr .= "&feesPayer=" . urlencode($feesPayer);
}
if ("" != $ipnNotificationUrl)
{
$nvpstr .= "&ipnNotificationUrl=" . urlencode($ipnNotificationUrl);
}
if ("" != $memo)
{
$nvpstr .= "&memo=" . urlencode($memo);
}
if ("" != $pin)
{
$nvpstr .= "&pin=" . urlencode($pin);
}
if ("" != $preapprovalKey)
{
$nvpstr .= "&preapprovalKey=" . urlencode($preapprovalKey);
}
if ("" != $reverseAllParallelPaymentsOnError)
{
$nvpstr .= "&reverseAllParallelPaymentsOnError=" . urlencode($reverseAllParallelPaymentsOnError);
}
if ("" != $senderEmail)
{
$nvpstr .= "&senderEmail=" . urlencode($senderEmail);
}
if ("" != $trackingId)
{
$nvpstr .= "&trackingId=" . urlencode($trackingId);
}
/* Make the Pay call to PayPal */
$resArray = $this->hash_call("Pay", $nvpstr);
/* Return the response array */
return $resArray;
}
/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the PreapprovalDetails API Call.
' Inputs:
'
' Required:
' preapprovalKey: A preapproval key that identifies the agreement resulting from a previously successful Preapproval call.
' Returns:
' The NVP Collection object of the PreapprovalDetails call response.
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
function CallPreapprovalDetails( $preapprovalKey )
{
/* Gather the information to make the PreapprovalDetails call.
The variable nvpstr holds the name value pairs
*/
// required fields
$nvpstr = "preapprovalKey=" . urlencode($preapprovalKey);
/* Make the PreapprovalDetails call to PayPal */
$resArray = hash_call("PreapprovalDetails", $nvpstr);
/* Return the response array */
return $resArray;
}
/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the Preapproval API Call.
' Inputs:
'
' Required:
'
' Optional:
'
'
' Returns:
' The NVP Collection object of the Preapproval call response.
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
function CallPreapproval( $returnUrl, $cancelUrl, $currencyCode, $startingDate, $endingDate, $maxTotalAmountOfAllPayments,
$senderEmail, $maxNumberOfPayments, $paymentPeriod, $dateOfMonth, $dayOfWeek,
$maxAmountPerPayment, $maxNumberOfPaymentsPerPeriod, $pinType )
{
/* Gather the information to make the Preapproval call.
The variable nvpstr holds the name value pairs
*/
// required fields
$nvpstr = "returnUrl=" . urlencode($returnUrl) . "&cancelUrl=" . urlencode($cancelUrl);
$nvpstr .= "¤cyCode=" . urlencode($currencyCode) . "&startingDate=" . urlencode($startingDate);
$nvpstr .= "&endingDate=" . urlencode($endingDate);
$nvpstr .= "&maxTotalAmountOfAllPayments=" . urlencode($maxTotalAmountOfAllPayments);
// optional fields
if ("" != $senderEmail)
{
$nvpstr .= "&senderEmail=" . urlencode($senderEmail);
}
if ("" != $maxNumberOfPayments){
$nvpstr .= "&maxNumberOfPayments=" . urlencode($maxNumberOfPayments);
}
if ("" != $paymentPeriod){
$nvpstr .= "&paymentPeriod=" . urlencode($paymentPeriod);
}
if ("" != $dateOfMonth){
$nvpstr .= "&dateOfMonth=" . urlencode($dateOfMonth);
}
if ("" != $dayOfWeek)
{
$nvpstr .= "&dayOfWeek=" . urlencode($dayOfWeek);
}
if ("" != $maxAmountPerPayment)
{
$nvpstr .= "&maxAmountPerPayment=" . urlencode($maxAmountPerPayment);
}
if ("" != $maxNumberOfPaymentsPerPeriod)
{
$nvpstr .= "&maxNumberOfPaymentsPerPeriod=" . urlencode($maxNumberOfPaymentsPerPeriod);
}
if ("" != $pinType)
{
$nvpstr .= "&pinType=" . urlencode($pinType);
}
/* Make the Preapproval call to PayPal */
$resArray = hash_call("Preapproval", $nvpstr);
/* Return the response array */
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 associative array containing the response from the server.
'-------------------------------------------------------------------------------------------------------------------------------------------
*/
//function hash_call($methodName, $nvpStr)
function hash_call($methodName_, $nvpStr_) {
//global $Env;
// Set up your API credentials, PayPal end point, and API version.
$this->API_Endpoint .= "/" . $methodName;
// 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);
curl_setopt($ch,CURLOPT_POSTFIELDS,$request);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-PAYPAL-REQUEST-DATA-FORMAT: NV',
'X-PAYPAL-RESPONSE-DATA-FORMAT: NV',
'X-PAYPAL-SECURITY-USERID: ' . $this->API_UserName,
'X-PAYPAL-SECURITY-PASSWORD: ' .$this->API_Password,
'X-PAYPAL-SECURITY-SIGNATURE: ' . $this->API_Signature,
'X-PAYPAL-SERVICE-VERSION: 1.3.0',
'X-PAYPAL-APPLICATION-ID: ' . $this->API_AppID
));
if($USE_PROXY)
curl_setopt ($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT);
// RequestEnvelope fields
$detailLevel = urlencode("ReturnAll"); // See DetailLevelCode in the WSDL for valid enumerations
$errorLanguage = urlencode("en_US"); // This should be the standard RFC 3066 language identification tag, e.g., en_US
// NVPRequest for submitting to server
$nvpreq = "requestEnvelope.errorLanguage=$errorLanguage&requestEnvelope.detailLevel=$detailLevel";
$nvpreq .= "&$nvpStr";
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
//getting response from server
$response = curl_exec($ch);
//converting NVPResponse to an Associative Array
$nvpResArray=$this->deformatNVP($response);
$nvpReqArray=$this->deformatNVP($nvpreq);
$_SESSION['nvpReqArray']=$nvpReqArray;
if (curl_errno($ch))
{
// moving to display page to display curl errors
echo $_SESSION['curl_error_no']=curl_errno($ch) ;
echo $_SESSION['curl_error_msg']=curl_error($ch);
//Execute the Error handling module to display errors.
}
else
{
//closing the curl
curl_close($ch);
}
return $nvpResArray;
}
function RedirectToPayPal ( $cmd )
{
// Redirect to paypal.com here
global $Env;
$payPalURL = "";
if ($Env == "sandbox")
{
$payPalURL = "https://www.sandbox.paypal.com/webscr?" . $cmd;
}
else
{
$payPalURL = "https://www.paypal.com/webscr?" . $cmd;
}
header("Location: ".$payPalURL);
}
/*'----------------------------------------------------------------------------------
* 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[$this->urldecode($keyval)] =$this->urldecode( $valval);
$nvpArray[urldecode($keyval)]=urldecode( $valval);
$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
}
return $nvpArray;
}
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);
//$Env= $this->Env;
if($PayPalMode=='sandbox')
{
$paypalmode = '.sandbox';
}
else
{
$paypalmode = '';
}
$API_Endpoint = "https://api-3t".$paypalmode.".paypal.com/nvp";
$version = urlencode('76.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.
echo $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;
}
}
Data.php
<?php
class Pixel_Paypalpayment_Helper_Data extends Mage_Core_Helper_Abstract
{
public $Env;
public $API_UserName ;
public $API_Password ;
public $API_Signature;
public $API_AppID = "APP-80W284485P519543T";
public $API_Endpoint = "";
public $USE_PROXY;
public $PROXY_HOST;
public $PROXY_PORT;
public function __construct()
{
/* $this->API_UserName = $vendormodel->getApiusername();
$this->API_Password =$vendormodel->getApipassword();
$this->API_Signature = $vendormodel->getApisignature();
$this->Env = $vendormodel->getSandbox();
if ($this->Env == 1)
{
$this->API_Endpoint = "https://svcs.sandbox.paypal.com/AdaptivePayments";
}
else
{
$this->API_Endpoint = "https://svcs.paypal.com/AdaptivePayments";
}
$this->USE_PROXY = false;*/
if (session_id() == "")
session_start();
}
function generateCharacter () {
$possible = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
return $char;
}
function generateTrackingID () {
$GUID = $this->generateCharacter().$this->generateCharacter().$this->generateCharacter().$this->generateCharacter().$this->generateCharacter();
$GUID .= $this->generateCharacter().$this->generateCharacter().$this->generateCharacter().$this->generateCharacter();
return $GUID;
}
function CallRefund( $payKey, $transactionId, $trackingId, $receiverEmailArray, $receiverAmountArray )
{
$nvpstr = "";
if ("" != $payKey)
{
$nvpstr = "payKey=" . $this->urlencode($payKey);
if (0 != count($receiverEmailArray))
{
reset($receiverEmailArray);
while (list($key, $value) = each($receiverEmailArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").email=" . urlencode($value);
}
}
}
if (0 != count($receiverAmountArray))
{
reset($receiverAmountArray);
while (list($key, $value) = each($receiverAmountArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").amount=" . urlencode($value);
}
}
}
}
elseif ("" != $trackingId)
{
$nvpstr = "trackingId=" . urlencode($trackingId);
if (0 != count($receiverEmailArray))
{
reset($receiverEmailArray);
while (list($key, $value) = each($receiverEmailArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").email=" . urlencode($value);
}
}
}
if (0 != count($receiverAmountArray))
{
reset($receiverAmountArray);
while (list($key, $value) = each($receiverAmountArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").amount=" . urlencode($value);
}
}
}
}
elseif ("" != $transactionId)
{
$nvpstr = "transactionId=" . urlencode($transactionId);
// the caller should only have 1 entry in the email and amount arrays
if (0 != count($receiverEmailArray))
{
reset($receiverEmailArray);
while (list($key, $value) = each($receiverEmailArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").email=" . urlencode($value);
}
}
}
if (0 != count($receiverAmountArray))
{
reset($receiverAmountArray);
while (list($key, $value) = each($receiverAmountArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").amount=" . urlencode($value);
}
}
}
}
/* Make the Refund call to PayPal */
$resArray = $this->hash_call("Refund", $nvpstr);
/* Return the response array */
return $resArray;
}
function CallPaymentDetails( $payKey, $transactionId, $trackingId )
{
/* Gather the information to make the PaymentDetails call.
The variable nvpstr holds the name value pairs
*/
$nvpstr = "";
// conditionally required fields
if ("" != $payKey)
{
$nvpstr = "payKey=" . $this->urlencode($payKey);
}
elseif ("" != $transactionId)
{
$nvpstr = "transactionId=" . $this->urlencode($transactionId);
}
elseif ("" != $trackingId)
{
$nvpstr = "trackingId=" . $this->urlencode($trackingId);
}
/* Make the PaymentDetails call to PayPal */
$resArray = $this->hash_call("PaymentDetails", $nvpstr);
/* Return the response array */
return $resArray;
}
function CallPay( $actionType, $cancelUrl, $returnUrl, $currencyCode, $receiverEmailArray, $receiverAmountArray,
$receiverPrimaryArray, $receiverInvoiceIdArray, $feesPayer, $ipnNotificationUrl,
$memo, $pin, $preapprovalKey, $reverseAllParallelPaymentsOnError, $senderEmail, $trackingId )
{
/* Gather the information to make the Pay call.
The variable nvpstr holds the name value pairs
*/
$standard = Mage::getModel('paypalpayment/standard');
$trans = $standard->getStandardCheckoutFormFields();
$productId = Mage::app()->getRequest()->getParam('id');
$_product= Mage::getSingleton('catalog/product')->load($productId);
$pro=$_product['vendorid'];
$vendor_model=Mage::getModel('vendorpayment/vendorpayment')->load($pro,'user_vendor');
$this->API_UserName = $vendor_model->getApiusername();
$this->API_Password = $vendor_model->getApipassword();
$this->API_Signature = $vendor_model->getApisignature();
$Env = $this->Env = 'sandbox';
$ItemName= $_product['name'];
$ItemNumber=$_product['sku'];
$ItemQty = 1;
$ItemPrice=$_product['price'];
$PayPalReturnURL= $trans['RedirectorSuccess'];
$PayPalCancelURL= $trans['RedirectorFailed'];
$orderId = Mage::getSingleton('checkout/session')->getLastOrderId();
$order = Mage::getModel('sales/order')->load($orderId);
$items = $order->getAllItems();
$itemcount=count($items);
$totalItems = Mage::getModel('checkout/cart')->getQuote()->getItemsCount();
$shipping_amt= $order->getData('shipping_amount');
$name=array();
$unitPrice=array();
$sku=array();
$ids=array();
$price = 0;
$qty=array();
foreach ($items as $itemId => $item)
{
$name[] = $item->getName();
$unitPrice[]=$item->getPrice();
$sku[]=$item->getSku();
$ids[]=$item->getProductId();
$qty[]=$item->getQtyToInvoice();
//$singleitem= $unitPrice * $qty;
$items_summary .=
'&L_PAYMENTREQUEST_0_QTY'.$itemId.'='.urlencode( $item->getQtyToInvoice() ).
'&L_PAYMENTREQUEST_0_AMT'.$itemId.'='.urlencode( (float)$item->getPrice() ).
'&L_PAYMENTREQUEST_0_NAME'.$itemId.'='.urlencode( $item->getName() ).
'&L_PAYMENTREQUEST_0_NUMBER'.$itemId.'='.urlencode( $item->getSku() );
$price += $item->getQtyToInvoice() * $item->getPrice();
//$new[] = $price;
}
// print_r($price);
//exit;
$totalQuantity = Mage::getModel('checkout/cart')->getQuote()->getItemsQty();
$subTotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();
$grandTotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal();
//print_r($grandTotal);exit;
//$ItemTotalPrice = $grandTotal;
//print_r($totalQuantity);exit;
$PayPalCurrencyCode="USD";
echo $nvpStr = $padata =
'&CURRENCYCODE='.urlencode($PayPalCurrencyCode).
'&PAYMENTACTION=Sale'.
'&ALLOWNOTE=1'.
'&PAYMENTREQUEST_0_SHIPPINGAMT='.urlencode((float)$shipping_amt).
'&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode).
'&PAYMENTREQUEST_0_AMT='.urlencode((float)$grandTotal).
'&PAYMENTREQUEST_0_ITEMAMT='.urlencode((float)$subTotal).
$items_summary.
'&AMT='.urlencode((float)$grandTotal).
'&RETURNURL='.urlencode($PayPalReturnURL ).
'&CANCELURL='.urlencode($PayPalCancelURL);
//print_r($ItemTotalPrice);exit;
/* $nvpStr = $padata = '&CURRENCYCODE='.urlencode($PayPalCurrencyCode).
'&PAYMENTACTION=Sale'.
'&ALLOWNOTE=1'.
'&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode).
'&PAYMENTREQUEST_0_AMT='.urlencode('300').
'&PAYMENTREQUEST_0_ITEMAMT='.urlencode('300').
'&L_PAYMENTREQUEST_0_QTY0='. urlencode('1').
'&L_PAYMENTREQUEST_0_AMT0='.urlencode('100').
'&L_PAYMENTREQUEST_0_NAME0='.urlencode($ItemName).
'&L_PAYMENTREQUEST_0_NUMBER0='.urlencode($ItemNumber).
'&L_PAYMENTREQUEST_0_QTY1='. urlencode('1').
'&L_PAYMENTREQUEST_0_AMT1='.urlencode('200').
'&L_PAYMENTREQUEST_0_NAME1='.urlencode('Test 1').
'&L_PAYMENTREQUEST_0_NUMBER1='.urlencode('2').
'&AMT='.urlencode('300').
'&RETURNURL='.urlencode($PayPalReturnURL).
'&CANCELURL='.urlencode($PayPalCancelURL);
//print_r($nvpStr);exit;*/
$httpParsedResponseAr = $this->PPHttpPost('SetExpressCheckout', $nvpStr,$this->API_UserName ,$this->API_Password,$this->API_Signature,$Env);
//print_r($httpParsedResponseAr);exit;
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
// Redirect to paypal.com.
$token = urldecode($httpParsedResponseAr["TOKEN"]);
echo $payPalURL = "https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=$token";
if("sandbox" === $Env || "beta-sandbox" === $Env) {
$payPalURL = "https://www.$Env.paypal.com/webscr&cmd=_express-checkout&token=$token";
}
header("Location: $payPalURL");
exit;
} else {
exit('SetExpressCheckout failed: ' . print_r($httpParsedResponseAr, true));
}
// required fields
$nvpstr = 'actionType=' . urlencode($actionType);
$nvpstr .= '¤cyCode=' . urlencode($currencyCode);
$nvpstr .= "&returnUrl=" . urlencode($returnUrl) . "&cancelUrl=" . urlencode($cancelUrl);
if (0 != count($receiverAmountArray))
{
reset($receiverAmountArray);
while (list($key, $value) = each($receiverAmountArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").amount=" . urlencode($value);
}
}
}
if (0 != count($receiverEmailArray))
{
reset($receiverEmailArray);
while (list($key, $value) = each($receiverEmailArray))
{
if ("" != $value)
{
$nvpstr .= "&receiverList.receiver(" . $key . ").email=" . urlencode($value);
}
}
}
if (0 != count($receiverPrimaryArray))
{
reset($receiverPrimaryArray);
while (list($key, $value) = each($receiverPrimaryArray))
{
if ("" != $value)
{
$nvpstr = $nvpstr . "&receiverList.receiver(" . $key . ").primary=" . urlencode($value);
}
}
}
if (0 != count($receiverInvoiceIdArray))
{
reset($receiverInvoiceIdArray);
while (list($key, $value) = each($receiverInvoiceIdArray))
{
if ("" != $value)
{
$nvpstr = $nvpstr . "&receiverList.receiver(" . $key . ").invoiceId=" . urlencode($value);
}
}
}
// optional fields
if ("" != $feesPayer)
{
$nvpstr .= "&feesPayer=" . urlencode($feesPayer);
}
if ("" != $ipnNotificationUrl)
{
$nvpstr .= "&ipnNotificationUrl=" . urlencode($ipnNotificationUrl);
}
if ("" != $memo)
{
$nvpstr .= "&memo=" . urlencode($memo);
}
if ("" != $pin)
{
$nvpstr .= "&pin=" . urlencode($pin);
}
if ("" != $preapprovalKey)
{
$nvpstr .= "&preapprovalKey=" . urlencode($preapprovalKey);
}
if ("" != $reverseAllParallelPaymentsOnError)
{
$nvpstr .= "&reverseAllParallelPaymentsOnError=" . urlencode($reverseAllParallelPaymentsOnError);
}
if ("" != $senderEmail)
{
$nvpstr .= "&senderEmail=" . urlencode($senderEmail);
}
if ("" != $trackingId)
{
$nvpstr .= "&trackingId=" . urlencode($trackingId);
}
/* Make the Pay call to PayPal */
$resArray = $this->hash_call("Pay", $nvpstr);
/* Return the response array */
return $resArray;
}
/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the PreapprovalDetails API Call.
' Inputs:
'
' Required:
' preapprovalKey: A preapproval key that identifies the agreement resulting from a previously successful Preapproval call.
' Returns:
' The NVP Collection object of the PreapprovalDetails call response.
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
function CallPreapprovalDetails( $preapprovalKey )
{
/* Gather the information to make the PreapprovalDetails call.
The variable nvpstr holds the name value pairs
*/
// required fields
$nvpstr = "preapprovalKey=" . urlencode($preapprovalKey);
/* Make the PreapprovalDetails call to PayPal */
$resArray = hash_call("PreapprovalDetails", $nvpstr);
/* Return the response array */
return $resArray;
}
/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: Prepares the parameters for the Preapproval API Call.
' Inputs:
'
' Required:
'
' Optional:
'
'
' Returns:
' The NVP Collection object of the Preapproval call response.
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
function CallPreapproval( $returnUrl, $cancelUrl, $currencyCode, $startingDate, $endingDate, $maxTotalAmountOfAllPayments,
$senderEmail, $maxNumberOfPayments, $paymentPeriod, $dateOfMonth, $dayOfWeek,
$maxAmountPerPayment, $maxNumberOfPaymentsPerPeriod, $pinType )
{
/* Gather the information to make the Preapproval call.
The variable nvpstr holds the name value pairs
*/
// required fields
$nvpstr = "returnUrl=" . urlencode($returnUrl) . "&cancelUrl=" . urlencode($cancelUrl);
$nvpstr .= "¤cyCode=" . urlencode($currencyCode) . "&startingDate=" . urlencode($startingDate);
$nvpstr .= "&endingDate=" . urlencode($endingDate);
$nvpstr .= "&maxTotalAmountOfAllPayments=" . urlencode($maxTotalAmountOfAllPayments);
// optional fields
if ("" != $senderEmail)
{
$nvpstr .= "&senderEmail=" . urlencode($senderEmail);
}
if ("" != $maxNumberOfPayments){
$nvpstr .= "&maxNumberOfPayments=" . urlencode($maxNumberOfPayments);
}
if ("" != $paymentPeriod){
$nvpstr .= "&paymentPeriod=" . urlencode($paymentPeriod);
}
if ("" != $dateOfMonth){
$nvpstr .= "&dateOfMonth=" . urlencode($dateOfMonth);
}
if ("" != $dayOfWeek)
{
$nvpstr .= "&dayOfWeek=" . urlencode($dayOfWeek);
}
if ("" != $maxAmountPerPayment)
{
$nvpstr .= "&maxAmountPerPayment=" . urlencode($maxAmountPerPayment);
}
if ("" != $maxNumberOfPaymentsPerPeriod)
{
$nvpstr .= "&maxNumberOfPaymentsPerPeriod=" . urlencode($maxNumberOfPaymentsPerPeriod);
}
if ("" != $pinType)
{
$nvpstr .= "&pinType=" . urlencode($pinType);
}
/* Make the Preapproval call to PayPal */
$resArray = hash_call("Preapproval", $nvpstr);
/* Return the response array */
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 associative array containing the response from the server.
'-------------------------------------------------------------------------------------------------------------------------------------------
*/
//function hash_call($methodName, $nvpStr)
function hash_call($methodName_, $nvpStr_) {
//global $Env;
// Set up your API credentials, PayPal end point, and API version.
$this->API_Endpoint .= "/" . $methodName;
// 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);
curl_setopt($ch,CURLOPT_POSTFIELDS,$request);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-PAYPAL-REQUEST-DATA-FORMAT: NV',
'X-PAYPAL-RESPONSE-DATA-FORMAT: NV',
'X-PAYPAL-SECURITY-USERID: ' . $this->API_UserName,
'X-PAYPAL-SECURITY-PASSWORD: ' .$this->API_Password,
'X-PAYPAL-SECURITY-SIGNATURE: ' . $this->API_Signature,
'X-PAYPAL-SERVICE-VERSION: 1.3.0',
'X-PAYPAL-APPLICATION-ID: ' . $this->API_AppID
));
if($USE_PROXY)
curl_setopt ($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT);
// RequestEnvelope fields
$detailLevel = urlencode("ReturnAll"); // See DetailLevelCode in the WSDL for valid enumerations
$errorLanguage = urlencode("en_US"); // This should be the standard RFC 3066 language identification tag, e.g., en_US
// NVPRequest for submitting to server
$nvpreq = "requestEnvelope.errorLanguage=$errorLanguage&requestEnvelope.detailLevel=$detailLevel";
$nvpreq .= "&$nvpStr";
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
//getting response from server
$response = curl_exec($ch);
//converting NVPResponse to an Associative Array
$nvpResArray=$this->deformatNVP($response);
$nvpReqArray=$this->deformatNVP($nvpreq);
$_SESSION['nvpReqArray']=$nvpReqArray;
if (curl_errno($ch))
{
// moving to display page to display curl errors
echo $_SESSION['curl_error_no']=curl_errno($ch) ;
echo $_SESSION['curl_error_msg']=curl_error($ch);
//Execute the Error handling module to display errors.
}
else
{
//closing the curl
curl_close($ch);
}
return $nvpResArray;
}
function RedirectToPayPal ( $cmd )
{
// Redirect to paypal.com here
global $Env;
$payPalURL = "";
if ($Env == "sandbox")
{
$payPalURL = "https://www.sandbox.paypal.com/webscr?" . $cmd;
}
else
{
$payPalURL = "https://www.paypal.com/webscr?" . $cmd;
}
header("Location: ".$payPalURL);
}
/*'----------------------------------------------------------------------------------
* 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[$this->urldecode($keyval)] =$this->urldecode( $valval);
$nvpArray[urldecode($keyval)]=urldecode( $valval);
$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
}
return $nvpArray;
}
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);
//$Env= $this->Env;
if($PayPalMode=='sandbox')
{
$paypalmode = '.sandbox';
}
else
{
$paypalmode = '';
}
$API_Endpoint = "https://api-3t".$paypalmode.".paypal.com/nvp";
$version = urlencode('76.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.
echo $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;
}
}