Paypal Express Checkout API not charging the money after payment - php

I'm using the Paypal Express Checkout API for processing Paypal and VISA payments.
My code redirects the user to the paypal page, and after presents form where authentication occurs. Then I proceed with authentication and click the Pay Now button.
I am redirected to the return URL. Apparently everything seems to be ok, but I never receive the money on the merchant account and the money is never charged from the buyer account.
Here is my code for requesting the the token:
private function _proceed_to_paypal($total_amount = false, $id_order = false, $description = false) {
if ($total_amount === false || $id_order === false) {
return false;
}
$this->load->library('paypal_functions');
$this->paypal_functions->init();
// ==================================
// PayPal Express Checkout Module
// ==================================
//'------------------------------------
//' The paymentAmount is the total value of
//' the shopping cart, that was set
//' earlier in a session variable
//' by the shopping cart page
//'------------------------------------
$paymentAmount = $total_amount;
//'------------------------------------
//' The currencyCodeType and paymentType
//' are set to the selections made on the Integration Assistant
//'------------------------------------
$currencyCodeType = "EUR";
$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 = site_url('payment/success');
//'------------------------------------
//' 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 = site_url('payment/cancel');
//'------------------------------------
//' Calls the SetExpressCheckout API call
//'
//' The CallShortcutExpressCheckout function is defined in the file PayPalFunctions.php,
//' it is included at the top of this file.
//'-------------------------------------------------
$resArray = $this->paypal_functions->CallShortcutExpressCheckout ($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $description);
$ack = strtoupper($resArray["ACK"]);
if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING") {
$this->paypal_functions->RedirectToPayPal($resArray["TOKEN"]);
} else {
$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 '<br />';
echo "Detailed Error Message: " . $ErrorLongMsg;
echo '<br />';
echo "Short Error Message: " . $ErrorShortMsg;
echo '<br />';
echo "Error Code: " . $ErrorCode;
echo '<br />';
echo "Error Severity Code: " . $ErrorSeverityCode;
echo '<br />';
}
}
The paypal_functions Lib:
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
class Paypal_functions {
private $PROXY_HOST = '127.0.0.1';
private $PROXY_PORT = '808';
// signals the test mode
private $SandboxFlag = false;
/* Paypal credentials */
private $API_UserName="xxx";
private $API_Password="xxx";
private $API_Signature="xxx";
// BN Code is only applicable for partners
private $sBNCode = "PP-ECWizard";
private $USE_PROXY = false;
private $version = 0;
private $API_Endpoint;
private $PAYPAL_URL;
private $gv_ApiErrorURL;
/*
' 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=
*/
public function init() {
if ($this->SandboxFlag == true) {
$this->API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
$this->PAYPAL_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
} else {
$this->API_Endpoint = "https://api-3t.paypal.com/nvp";
$this->PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
}
$this->USE_PROXY = false;
$this->version= "93";
}
/* 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.
' 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
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
public function CallShortcutExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $description) {
//------------------------------------------------------------------------------------------------------------------------------------
// Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
$nvpstr="&PAYMENTREQUEST_0_AMT=". $paymentAmount;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
$nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
$nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
$nvpstr = $nvpstr . "&SOLUTIONTYPE=" . 'Sole';
$nvpstr = $nvpstr . "&LANDINGPAGE=" . 'Billing';
//'---------------------------------------------------------------------------------------------------------------
//' 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 = $this->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 SetExpressCheckout API Call.
' 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
' shipToName: the Ship to name entered on the merchant's site
' shipToStreet: the Ship to Street entered on the merchant's site
' shipToCity: the Ship to City entered on the merchant's site
' shipToState: the Ship to State entered on the merchant's site
' shipToCountryCode: the Code for Ship to Country entered on the merchant's site
' shipToZip: the Ship to ZipCode entered on the merchant's site
' shipToStreet2: the Ship to Street2 entered on the merchant's site
' phoneNum: the phoneNum entered on the merchant's site
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
public function CallMarkExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL,
$cancelURL, $shipToName, $shipToStreet, $shipToCity, $shipToState,
$shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum
) {
//------------------------------------------------------------------------------------------------------------------------------------
// Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
$nvpstr="&PAYMENTREQUEST_0_AMT=". $paymentAmount;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
$nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
$nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
$nvpstr = $nvpstr . "&ADDROVERRIDE=1";
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTONAME=" . $shipToName;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET=" . $shipToStreet;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET2=" . $shipToStreet2;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCITY=" . $shipToCity;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTATE=" . $shipToState;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=" . $shipToCountryCode;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOZIP=" . $shipToZip;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOPHONENUM=" . $phoneNum;
$_SESSION["currencyCodeType"] = $currencyCodeType;
$_SESSION["PaymentType"] = $paymentType;
//'---------------------------------------------------------------------------------------------------------------
//' 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.
'-------------------------------------------------------------------------------------------
*/
public function GetShippingDetails( $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")
{
$_SESSION['payer_id'] = $resArray['PAYERID'];
}
return $resArray;
}
/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' 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.
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
public function ConfirmPayment( $FinalPaymentAmt )
{
/* Gather the information to make the final call to
finalize the PayPal payment. The variable nvpstr
holds the name value pairs
*/
//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']);
$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;
/* 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;
}
/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: This function makes a DoDirectPayment API call
'
' Inputs:
' paymentType: paymentType has to be one of the following values: Sale or Order or Authorization
' paymentAmount: total value of the shopping cart
' currencyCode: currency code value the PayPal API
' firstName: first name as it appears on credit card
' lastName: last name as it appears on credit card
' street: buyer's street address line as it appears on credit card
' city: buyer's city
' state: buyer's state
' countryCode: buyer's country code
' zip: buyer's zip
' creditCardType: buyer's credit card type (i.e. Visa, MasterCard ... )
' creditCardNumber: buyers credit card number without any spaces, dashes or any other characters
' expDate: credit card expiration date
' cvv2: Card Verification Value
'
'-------------------------------------------------------------------------------------------
'
' Returns:
' The NVP Collection object of the DoDirectPayment Call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
public function DirectPayment( $paymentType, $paymentAmount, $creditCardType, $creditCardNumber,
$expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip,
$countryCode, $currencyCode )
{
//Construct the parameter string that describes DoDirectPayment
$nvpstr = "&AMT=" . $paymentAmount;
$nvpstr = $nvpstr . "&CURRENCYCODE=" . $currencyCode;
$nvpstr = $nvpstr . "&PAYMENTACTION=" . $paymentType;
$nvpstr = $nvpstr . "&CREDITCARDTYPE=" . $creditCardType;
$nvpstr = $nvpstr . "&ACCT=" . $creditCardNumber;
$nvpstr = $nvpstr . "&EXPDATE=" . $expDate;
$nvpstr = $nvpstr . "&CVV2=" . $cvv2;
$nvpstr = $nvpstr . "&FIRSTNAME=" . $firstName;
$nvpstr = $nvpstr . "&LASTNAME=" . $lastName;
$nvpstr = $nvpstr . "&STREET=" . $street;
$nvpstr = $nvpstr . "&CITY=" . $city;
$nvpstr = $nvpstr . "&STATE=" . $state;
$nvpstr = $nvpstr . "&COUNTRYCODE=" . $countryCode;
$nvpstr = $nvpstr . "&IPADDRESS=" . $_SERVER['REMOTE_ADDR'];
$resArray=hash_call("DoDirectPayment", $nvpstr);
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.
* -------------------------------------------------------------------------------------------------------------------------------------------
*/
public function hash_call($methodName,$nvpStr)
{
//declaring of global variables
/*
global $API_Endpoint, $this->version, $API_UserName, $API_Password, $API_Signature;
global $this->USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $gv_ApiErrorURL;
global $sBNCode;
*/
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->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($this->USE_PROXY)
curl_setopt ($ch, CURLOPT_PROXY, $this->PROXY_HOST. ":" . $this->PROXY_PORT);
//NVPRequest for submitting to server
$nvpreq="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode($this->version) . "&PWD=" . urlencode($this->API_Password) . "&USER=" . urlencode($this->API_UserName) . "&SIGNATURE=" . urlencode($this->API_Signature) . $nvpStr . "&BUTTONSOURCE=" . urlencode($this->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 = $this->deformatNVP($response);
$nvpReqArray = $this->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:
----------------------------------------------------------------------------------
*/
public function RedirectToPayPal ( $token )
{
//global $PAYPAL_URL;
// Redirect to paypal.com here
$payPalURL = $this->PAYPAL_URL . $token . '&useraction=commit';
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.
----------------------------------------------------------------------------------
*/
public 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;
}
}
PS - This is the result of echoing $nvpstr before:
$resArray = $this->hash_call("SetExpressCheckout", $nvpstr);
-
&PAYMENTREQUEST_0_AMT=0.01&
PAYMENTREQUEST_0_PAYMENTACTION=Sale&
RETURNURL=http://localhost/site/payment/success&
CANCELURL=http://localhost/site/payment/cancel&
PAYMENTREQUEST_0_CURRENCYCODE=EUR&
SOLUTIONTYPE=Sole&
LANDINGPAGE=Billing
Thanks in advance!

Sounds like you're only completing the first part of the process. Express Checkout consists of 3 separate calls:
SetExpressCheckout
GetExpressCheckoutDetails
DoExpressCheckoutPayment
No money is processed until you've completed the final DoExpressCheckoutPayment call.
Review the Express Checkout Integration Guide for more details on this.

Related

curl_init issue in php

When i am going to access paypal(payment gateway) from local host i got an error like
Fatal error: Uncaught Error: Call to undefined function curl_init() in
/var/www/html/pp/temp/paypalfunctions.php:331 Stack trace: #0
/var/www/html/pp/temp/paypalfunctions.php(90):
hash_call('SetExpressCheck...', '&PAYMENTREQUEST...') #1
/var/www/html/pp/temp/expresscheckout.php(49):
CallShortcutExpressCheckout(NULL, 'USD', 'Sale', 'http://localhos...',
'http://localhos...') #2 {main} thrown in
/var/www/html/pp/temp/paypalfunctions.php on line 331
I have paypalfunctions.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
/* * ******************************************
PayPal API Module
Defines all the global variables and the wrapper functions
* ****************************************** */
$PROXY_HOST = '127.0.0.1';
$PROXY_PORT = '808';
$SandboxFlag = true;
//'------------------------------------
//' 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 = "APU_USERNAME";
$API_Password = "API_PASS";
$API_Signature = "API_SIGNATURE";
// 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=";
} else {
$API_Endpoint = "https://api-3t.paypal.com/nvp";
$PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
}
$USE_PROXY = false;
$version = "64";
if (session_id() == "")
session_start();
/* 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.
' 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 CallShortcutExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL) {
//------------------------------------------------------------------------------------------------------------------------------------
// Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
$nvpstr = "&PAYMENTREQUEST_0_AMT=" . $paymentAmount;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
$nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
$nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
//echo $nvpstr;exit;
$_SESSION["currencyCodeType"] = $currencyCodeType;
$_SESSION["PaymentType"] = $paymentType;
//'---------------------------------------------------------------------------------------------------------------
//' 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 SetExpressCheckout API Call.
' 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
' shipToName: the Ship to name entered on the merchant's site
' shipToStreet: the Ship to Street entered on the merchant's site
' shipToCity: the Ship to City entered on the merchant's site
' shipToState: the Ship to State entered on the merchant's site
' shipToCountryCode: the Code for Ship to Country entered on the merchant's site
' shipToZip: the Ship to ZipCode entered on the merchant's site
' shipToStreet2: the Ship to Street2 entered on the merchant's site
' phoneNum: the phoneNum entered on the merchant's site
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
function CallMarkExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $shipToName, $shipToStreet, $shipToCity, $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum
) {
//------------------------------------------------------------------------------------------------------------------------------------
// Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
// $nvpstr = "&PAYMENTREQUEST_0_AMT=" . $paymentAmount;
// $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
// $nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
// $nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
// $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
// $nvpstr = $nvpstr . "&ADDROVERRIDE=1";
// $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTONAME=" . $shipToName;
// $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET=" . $shipToStreet;
// $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET2=" . $shipToStreet2;
// $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCITY=" . $shipToCity;
// $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTATE=" . $shipToState;
// $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=" . $shipToCountryCode;
// $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOZIP=" . $shipToZip;
// $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOPHONENUM=" . $phoneNum;
$nvpstr = "&METHOD=SetExpressCheckout
&RETURNURL=http://localhost/trash/pp/response.php
&CANCELURL=http://localhost/trash/pp/response.php
&PAYMENTREQUEST_0_PAYMENTACTION=Sale
&L_PAYMENTREQUEST_0_NAME0=10% Decaf Kona Blend Coffee
&L_PAYMENTREQUEST_0_NUMBER0=623083
&L_PAYMENTREQUEST_0_DESC0=Size: 8.8-oz
&L_PAYMENTREQUEST_0_AMT0=9.95
&L_PAYMENTREQUEST_0_QTY0=2
&L_PAYMENTREQUEST_0_NAME1=Coffee Filter bags
&L_PAYMENTREQUEST_0_NUMBER1=623084
&L_PAYMENTREQUEST_0_DESC1=Size: Two 24-piece boxes
&L_PAYMENTREQUEST_0_AMT1=39.70
&L_PAYMENTREQUEST_0_QTY1=2
&PAYMENTREQUEST_0_ITEMAMT=99.30
&PAYMENTREQUEST_0_TAXAMT=2.58
&PAYMENTREQUEST_0_SHIPPINGAMT=3.00
&PAYMENTREQUEST_0_HANDLINGAMT=2.99
&PAYMENTREQUEST_0_SHIPDISCAMT=-3.00
&PAYMENTREQUEST_0_INSURANCEAMT=1.00
&PAYMENTREQUEST_0_AMT=105.87
&PAYMENTREQUEST_0_CURRENCYCODE=USD
&ALLOWNOTE=1";
$_SESSION["currencyCodeType"] = $currencyCodeType;
$_SESSION["PaymentType"] = $paymentType;
//'---------------------------------------------------------------------------------------------------------------
//' 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);
echo '<pre>';print_r($resArray);exit;
$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 GetShippingDetails($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") {
$_SESSION['payer_id'] = $resArray['PAYERID'];
}
return $resArray;
}
/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' 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($FinalPaymentAmt) {
/* Gather the information to make the final call to
finalize the PayPal payment. The variable nvpstr
holds the name value pairs
*/
//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']);
$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;
/* 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;
}
/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: This function makes a DoDirectPayment API call
'
' Inputs:
' paymentType: paymentType has to be one of the following values: Sale or Order or Authorization
' paymentAmount: total value of the shopping cart
' currencyCode: currency code value the PayPal API
' firstName: first name as it appears on credit card
' lastName: last name as it appears on credit card
' street: buyer's street address line as it appears on credit card
' city: buyer's city
' state: buyer's state
' countryCode: buyer's country code
' zip: buyer's zip
' creditCardType: buyer's credit card type (i.e. Visa, MasterCard ... )
' creditCardNumber: buyers credit card number without any spaces, dashes or any other characters
' expDate: credit card expiration date
' cvv2: Card Verification Value
'
'-------------------------------------------------------------------------------------------
'
' Returns:
' The NVP Collection object of the DoDirectPayment Call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
function DirectPayment($paymentType, $paymentAmount, $creditCardType, $creditCardNumber, $expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip, $countryCode, $currencyCode) {
//Construct the parameter string that describes DoDirectPayment
$nvpstr = "&AMT=" . $paymentAmount;
$nvpstr = $nvpstr . "&CURRENCYCODE=" . $currencyCode;
$nvpstr = $nvpstr . "&PAYMENTACTION=" . $paymentType;
$nvpstr = $nvpstr . "&CREDITCARDTYPE=" . $creditCardType;
$nvpstr = $nvpstr . "&ACCT=" . $creditCardNumber;
$nvpstr = $nvpstr . "&EXPDATE=" . $expDate;
$nvpstr = $nvpstr . "&CVV2=" . $cvv2;
$nvpstr = $nvpstr . "&FIRSTNAME=" . $firstName;
$nvpstr = $nvpstr . "&LASTNAME=" . $lastName;
$nvpstr = $nvpstr . "&STREET=" . $street;
$nvpstr = $nvpstr . "&CITY=" . $city;
$nvpstr = $nvpstr . "&STATE=" . $state;
$nvpstr = $nvpstr . "&COUNTRYCODE=" . $countryCode;
$nvpstr = $nvpstr . "&IPADDRESS=" . $_SERVER['REMOTE_ADDR'];
$resArray = hash_call("DoDirectPayment", $nvpstr);
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;
echo $payPalURL;exit;
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[urldecode($keyval)] = urldecode($valval);
$nvpstr = substr($nvpstr, $valuepos + 1, strlen($nvpstr));
}
return $nvpArray;
}
?>
I install curl using
sudo apt-get install php-curl
bu still the issue.Any help would be appreciated

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?

how to get transaction id from CreateRecurringPaymentsProfile paypal api

I am trying to create recurring payment with paypal. For that i am using this function,
function CallShortcutExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL)
{
$nvpstr="&AMT=". $paymentAmount;
$nvpstr = $nvpstr . "&PAYMENTACTION=" . $paymentType;
$nvpstr = $nvpstr . "&BILLINGAGREEMENTDESCRIPTION=".urlencode($_SESSION['cart']['total_amount']['name']);
$nvpstr = $nvpstr . "&BILLINGTYPE=RecurringPayments";
$nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
$nvpstr = $nvpstr . "&INVNUM=" . $_SESSION['cart']['inv'];
$nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
$nvpstr = $nvpstr . "&CURRENCYCODE=" . $currencyCodeType;
$_SESSION["currencyCodeType"] = $currencyCodeType;
$_SESSION["PaymentType"] = $paymentType;
$resArray=hash_call("SetExpressCheckout", $nvpstr);
$ack = strtoupper($resArray["ACK"]);
if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
{
$token = urldecode($resArray["TOKEN"]);
$_SESSION['TOKEN']=$token;
}
return $resArray;
}
Which returns the token, then i am creating recurring profile using this function
function CreateRecurringPaymentsProfile()
{
$token = urlencode($_SESSION['TOKEN']);
$email = urlencode($_SESSION['email']);
$shipToName = urlencode($_SESSION['shipToName']);
$shipToStreet = urlencode($_SESSION['shipToStreet']);
$shipToCity = urlencode($_SESSION['shipToCity']);
$shipToState = urlencode($_SESSION['shipToState']);
$shipToZip = urlencode($_SESSION['shipToZip']);
$shipToCountry = urlencode($_SESSION['shipToCountry']);
$nvpstr="&TOKEN=".$token;
#$nvpstr.="&EMAIL=".$email;
$nvpstr.="&SHIPTONAME=".$shipToName;
$nvpstr.="&SHIPTOSTREET=".$shipToStreet;
$nvpstr.="&SHIPTOCITY=".$shipToCity;
$nvpstr.="&SHIPTOSTATE=".$shipToState;
$nvpstr.= "&DESC=".$_SESSION['cart']['total_amount']['name'];
$nvpstr.="&SHIPTOZIP=".$shipToZip;
$nvpstr.="&SHIPTOCOUNTRY=".$shipToCountry;
/*$nvpstr.="&PROFILESTARTDATE=".urlencode("2015-12-01T0:0:0");*/
$nvpstr .= "&PROFILESTARTDATE=".date("Y-m-d", mktime(0, 0, 0, date("m", time()), date("d", time()), date("Y", time())))."T00:00:00Z";
$nvpstr.="&BILLINGPERIOD=Year";
$nvpstr.="&BILLINGFREQUENCY=1";
$nvpstr.="&AMT=".$_SESSION['cart']['total_amount']['total'];
$nvpstr.="&CURRENCYCODE=USD";
$nvpstr.="&IPADDRESS=" . $_SERVER['REMOTE_ADDR'];
$resArray=hash_call("CreateRecurringPaymentsProfile",$nvpstr);
$ack = strtoupper($resArray["ACK"]);
return $resArray;
}
But it returns me to profile-id not transaction-id. I read somewhere that we have to use DoExpressCheckoutPayment to complete the payment. But then amount deduct from paypal 2 times.
1)after doing DoExpressCheckoutPayment
2)after create recurring profile
I am doing anything wrong for recurring payment?
I just thinking, first i need to do expresscheckout then i need to create recurring profile and set startdate to next year. so first amount will deduct by DoExpressCheckoutPayment then from next year deduct by recurring profile.
Is there any better way to play with recurring payment using express checkout? Too much confusion to play with recurring payment in paypal.
Please help me to solve this. thanks in advance.
When you call CreateRecurringPaymentsProfile API with token value, there is no transaction id return.
Refer to https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/CreateRecurringPaymentsProfile_API_Operation_NVP/ (CreateRecurringPaymentsProfile Response Message part )
TRANSACTIONID The transaction ID from the direct credit card initial payment.(it doesn't apply to Pay with PayPal method)
CreateRecurringPaymentsProfile API will not deduct money from buyer if you don't set INITAMT parameter in API request.
In your example.
2)after create recurring profile, no money deducted from buyer.
1)after doing DoExpressCheckoutPayment , money will be deducted from buyer.
In general, it only deduct money once.
We call CreateRecurringPaymentsProfile (without the INITAMT value) to create a subscription. Then we wait for the first recurring_payment IPN notification which should arrive soon afterwards. This is a notification of the first payment and it contains a transaction id (txn_id).

Connecting My Website With Paypal

I'm trying to connect my website with paypal.Have passed on the total amount which have set it in session and on running the setexpresscheckout.php i'm getting this error
'SetExpressCheckout API call failed. Detailed Error Message: Security header is not validShort Error Message: Security errorError Code: 10002Error Severity Code: Error'
How can i solve this problem
This is the paypal expresscheckout.php
<?php
$order_price='';
if(isset($_POST['order_price'])){
$order_price= $_POST['order_price'];
}
?>
<?php
require_once ("paypalfunctions.php");
// ==================================
// PayPal Express Checkout Module
// ==================================
//'------------------------------------
//' The paymentAmount is the total value of
//' the shopping cart, that was set
//' earlier in a session variable
//' by the shopping cart page
//'------------------------------------
$paymentAmount = $order_price;
//'------------------------------------
//' The currencyCodeType and paymentType
//' are 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://localhost/culdesign.preview/PayOrder.php";
//'------------------------------------
//' 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://localhost/culdesign.preview/PlaceAnOrder.php";
//'------------------------------------
//' Calls the SetExpressCheckout API call
//'
//' The CallShortcutExpressCheckout function is defined in the file PayPalFunctions.php,
//' it is included at the top of this file.
//'-------------------------------------------------
$resArray = CallShortcutExpressCheckout ($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL);
$ack = strtoupper($resArray["ACK"]);
if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
{
RedirectToPayPal ( $resArray["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;
}
?>
The code below is the paypalfunction.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;
//'------------------------------------
//' 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="<ytech008_api1.gmail.com>";
$API_Password="<WV6C69HAB5844H6S>";
$API_Signature="<AAv5.GyV.pgCRwdV-5hnE5G.F8BwAs81G0tx7YR7-B6ao3PiSeCn-kvN>";
// 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=";
}
else
{
$API_Endpoint = "https://api-3t.paypal.com/nvp";
$PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
}
$USE_PROXY = false;
$version="93";
if (session_id() == "")
session_start();
/* 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.
' 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 CallShortcutExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL)
{
//------------------------------------------------------------------------------------------------------------------------------------
// Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
$nvpstr="&PAYMENTREQUEST_0_AMT=". $paymentAmount;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
$nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
$nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
$_SESSION["currencyCodeType"] = $currencyCodeType;
$_SESSION["PaymentType"] = $paymentType;
//'---------------------------------------------------------------------------------------------------------------
//' 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 SetExpressCheckout API Call.
' 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
' shipToName: the Ship to name entered on the merchant's site
' shipToStreet: the Ship to Street entered on the merchant's site
' shipToCity: the Ship to City entered on the merchant's site
' shipToState: the Ship to State entered on the merchant's site
' shipToCountryCode: the Code for Ship to Country entered on the merchant's site
' shipToZip: the Ship to ZipCode entered on the merchant's site
' shipToStreet2: the Ship to Street2 entered on the merchant's site
' phoneNum: the phoneNum entered on the merchant's site
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
function CallMarkExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL,
$cancelURL, $shipToName, $shipToStreet, $shipToCity, $shipToState,
$shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum
)
{
//------------------------------------------------------------------------------------------------------------------------------------
// Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
$nvpstr="&PAYMENTREQUEST_0_AMT=". $paymentAmount;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
$nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
$nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
$nvpstr = $nvpstr . "&ADDROVERRIDE=1";
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTONAME=" . $shipToName;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET=" . $shipToStreet;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET2=" . $shipToStreet2;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCITY=" . $shipToCity;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTATE=" . $shipToState;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=" . $shipToCountryCode;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOZIP=" . $shipToZip;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOPHONENUM=" . $phoneNum;
$_SESSION["currencyCodeType"] = $currencyCodeType;
$_SESSION["PaymentType"] = $paymentType;
//'---------------------------------------------------------------------------------------------------------------
//' 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 GetShippingDetails( $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")
{
$_SESSION['payer_id'] = $resArray['PAYERID'];
}
return $resArray;
}
/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' 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( $FinalPaymentAmt )
{
/* Gather the information to make the final call to
finalize the PayPal payment. The variable nvpstr
holds the name value pairs
*/
//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']);
$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;
/* 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;
}
/*
'-------------------------------------------------------------------------------------------------------------------------------------------
' Purpose: This function makes a DoDirectPayment API call
'
' Inputs:
' paymentType: paymentType has to be one of the following values: Sale or Order or Authorization
' paymentAmount: total value of the shopping cart
' currencyCode: currency code value the PayPal API
' firstName: first name as it appears on credit card
' lastName: last name as it appears on credit card
' street: buyer's street address line as it appears on credit card
' city: buyer's city
' state: buyer's state
' countryCode: buyer's country code
' zip: buyer's zip
' creditCardType: buyer's credit card type (i.e. Visa, MasterCard ... )
' creditCardNumber: buyers credit card number without any spaces, dashes or any other characters
' expDate: credit card expiration date
' cvv2: Card Verification Value
'
'-------------------------------------------------------------------------------------------
'
' Returns:
' The NVP Collection object of the DoDirectPayment Call Response.
'--------------------------------------------------------------------------------------------------------------------------------------------
*/
function DirectPayment( $paymentType, $paymentAmount, $creditCardType, $creditCardNumber,
$expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip,
$countryCode, $currencyCode )
{
//Construct the parameter string that describes DoDirectPayment
$nvpstr = "&AMT=" . $paymentAmount;
$nvpstr = $nvpstr . "&CURRENCYCODE=" . $currencyCode;
$nvpstr = $nvpstr . "&PAYMENTACTION=" . $paymentType;
$nvpstr = $nvpstr . "&CREDITCARDTYPE=" . $creditCardType;
$nvpstr = $nvpstr . "&ACCT=" . $creditCardNumber;
$nvpstr = $nvpstr . "&EXPDATE=" . $expDate;
$nvpstr = $nvpstr . "&CVV2=" . $cvv2;
$nvpstr = $nvpstr . "&FIRSTNAME=" . $firstName;
$nvpstr = $nvpstr . "&LASTNAME=" . $lastName;
$nvpstr = $nvpstr . "&STREET=" . $street;
$nvpstr = $nvpstr . "&CITY=" . $city;
$nvpstr = $nvpstr . "&STATE=" . $state;
$nvpstr = $nvpstr . "&COUNTRYCODE=" . $countryCode;
$nvpstr = $nvpstr . "&IPADDRESS=" . $_SERVER['REMOTE_ADDR'];
$resArray=hash_call("DoDirectPayment", $nvpstr);
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;
}
/*'----------------------------------------------------------------------------------
* 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;
}
?>
Security header means that your API credentials are incorrect. You need to double check your credentials, and make sure you're not sending live credentials to the sandbox server or visa-verse. Each would have separate sets of API credentials.
You're doing it wrong in paypalfunction.php. No need for <>, enter your credentials in "" like following.
$API_UserName="data_api1.website.domain";
$API_Password="YOURAPIPASSWORD";
$API_Signature="NeV3r.g1Ve.AwAaAY-YOUUUR.DATA-OF-SUCHTYPE-inToPublic-Forums";

problem with my paypal express checkout payment?

im new to paypal express checkout and i have this code the payment to paypal
$resArray = CallShortcutExpressCheckout ($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL);
$ack = strtoupper($resArray["ACK"]);
if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
{
RedirectToPayPal ( $resArray["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;
}
and this the code for the CallShortcutExpressCheckout function
function CallShortcutExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL)
{
//------------------------------------------------------------------------------------------------------------------------------------
// Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
$nvpstr="&PAYMENTREQUEST_0_AMT=". $paymentAmount;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
$nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
$nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
$_SESSION["currencyCodeType"] = $currencyCodeType;
$_SESSION["PaymentType"] = $paymentType;
//'---------------------------------------------------------------------------------------------------------------
//' 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;
}
my problem that i don't know how to send the cart full info like the products title and code and that its what i need coz i have no orders sections into my shopping cart i want manage everything through email
so what i need is to send the products description through the order and once the order i receive the order email confirmation have the items description
I'm trying to do the very same thing.
Let me start by saying that I have been trying to get the complete checkout to work for 2 days now and I still haven't completely succeeded :(
However it looks like I'm one step further than you.
Not sure if it's the correct way though but I'll show you what I got now and what I still have a problem with.
What I did was the following:
If the user clicks the checkout button a php file is called (let's call it checkout.php).
In the checkout.php file I construct an array with the items the user wants to order.
// fill array with two products
// normally you would loop through all products in the basket to create this array
$items = array('L_PAYMENTREQUEST_0_NAME0'=>'Productname 1',
'L_PAYMENTREQUEST_0_NUMBER0'=>'Productcode 1',
'L_PAYMENTREQUEST_0_DESC0'=>'Productdescription 1',
'L_PAYMENTREQUEST_0_AMT0'=>39.99, // price per unit
'L_PAYMENTREQUEST_0_QTY0'=>2, // quantity
'L_PAYMENTREQUEST_0_NAME1'=>'Productname 2',
'L_PAYMENTREQUEST_0_NUMBER1'=>'Productcode 2',
'L_PAYMENTREQUEST_0_DESC1'=>'Productdescription 2',
'L_PAYMENTREQUEST_0_AMT1'=>200.99,
'L_PAYMENTREQUEST_0_QTY1'=>1,
);
// set total amount of order in session (this will be used by paypal throughout the payment process)
$_SESSION['Payment_Amount'] = 280.97;
// now normally call CallShortcutExpressCheckout only with the addition of the $items array
$resArray = CallShortcutExpressCheckout ($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $items);
Now for the file with the functions that actually make the requests to PayPal:
I've created an extra function (generate_nvp_string) and changed the CallShortcutExpressCheckout function to use this string.
function generate_nvp_string($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $items = array())
{
$params = array('PAYMENTREQUEST_0_AMT'=>$paymentAmount,
'PAYMENTREQUEST_0_PAYMENTACTION'=>$paymentType,
'RETURNURL'=>$returnURL,
'CANCELURL'=>$cancelURL,
'PAYMENTREQUEST_0_CURRENCYCODE'=>$currencyCodeType,
);
$params = array_merge($params, $items);
$nvp_string = '';
foreach($params as $name => $value) {
$nvp_string.= '&'.$name.'='.$value;
}
return $nvp_string;
}
function CallShortcutExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $items= array())
{
$_SESSION['currencyCodeType'] = $this->currency;
$_SESSION['PaymentType'] = $this->payment_type;
$result = $this->hash_call('SetExpressCheckout', $this->generate_nvp_string($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $items));
$ack = strtoupper($result['ACK']);
if ($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING') {
$_SESSION['TOKEN'] = urldecode($result['TOKEN']);
}
return $result;
}
Now when the user clicks the checkout button the request string would also include the products. And when the user is redirected to PayPal checkout they will have a nice overview of all the products ordered.
I started this answer with:
and what I still have a problem with.
The checkout process seems to work now however when the user finishes the checkout process and is redirected back to my site ($returnURL) and don't get a transaction ID for some reason.
The transaction ID is kinda vital to be able to further process the payment on the backend.
I was trying to loop through items using a Form Submission. PayPal's sample code was only working for 1 item. Instead of making a function like PeeHaa's, I just checked to see if L_PAYMENTREQUEST_0_NAME0 was set, if it was, add all the variables to the $nvpstr string. Then continue to on to see if L_PAYMENTREQUEST_0_NAME1 was set, if it was, add it to the string, etc. Here is the code for anyone who needs it:
for($i=0; $i<99999; $i++){
if(isset($paramsArray["L_PAYMENTREQUEST_0_NAME$i"])){
$nvpstr = $nvpstr . "&L_PAYMENTREQUEST_0_NAME$i=" . $paramsArray["L_PAYMENTREQUEST_0_NAME$i"];
}
if(isset($paramsArray["L_PAYMENTREQUEST_0_NUMBER$i"])){
$nvpstr = $nvpstr . "&L_PAYMENTREQUEST_0_NUMBER$i=" . $paramsArray["L_PAYMENTREQUEST_0_NUMBER$i"];
}
if(isset($paramsArray["L_PAYMENTREQUEST_0_DESC$i"])){
$nvpstr = $nvpstr . "&L_PAYMENTREQUEST_0_DESC$i=" . $paramsArray["L_PAYMENTREQUEST_0_DESC$i"];
}
if(isset($paramsArray["L_PAYMENTREQUEST_0_AMT$i"])){
$nvpstr = $nvpstr . "&L_PAYMENTREQUEST_0_AMT$i=" . $paramsArray["L_PAYMENTREQUEST_0_AMT$i"];
}
if(isset($paramsArray["L_PAYMENTREQUEST_0_QTY$i"])){
$nvpstr = $nvpstr . "&L_PAYMENTREQUEST_0_QTY$i=" . $paramsArray["L_PAYMENTREQUEST_0_QTY$i"];
}
if(!isset($paramsArray["L_PAYMENTREQUEST_0_NAME$i"])){
break;
}
}

Categories