In my site I want to integrate a paypal subscription method in which I want to transfer a particular amount from a user's paypal account to an admin's paypal account daily, weekly or monthly depending on the choice. For that i use the below code:
$obj=new paypal_recurring;
$obj->environment = 'sandbox'; // or 'beta-sandbox' or 'live'
$obj->paymentType = urlencode('Authorization'); // or 'Sale' or 'Order'
// Set request-specific fields.
$obj->startDate = urlencode("2011-9-6T0:0:0");
$obj->billingPeriod = urlencode("Month"); // or "Day", "Week", "SemiMonth", "Year"
$obj->billingFreq = urlencode("4"); // combination of this and billingPeriod must be at most a year
$obj->paymentAmount = urlencode('10');
$obj->currencyID = urlencode('USD'); // or other currency code ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
/* PAYPAL API DETAILS */
$obj->API_UserName = urlencode('sdfsdfsdfbiz_api1.website.us');
$obj->API_Password = urlencode('543564353');
$obj->API_Signature = urlencode('sdfsdfsdf ');
$obj->API_Endpoint = "https://api-3t.paypal.com/nvp";
/*SET SUCCESS AND FAIL URL*/
$obj->returnURL = urlencode("http://www.mysite.com/index.php?task=getExpressCheckout");
$obj->cancelURL = urlencode('http://www.mysite.comindex.php?task=error');
$task="setExpressCheckout"; //set initial task as Express Checkout
switch($task)
{
case "setExpressCheckout":
$obj->setExpressCheckout();
exit;
case "getExpressCheckout":
$obj->getExpressCheckout();
exit;
case "error":
echo "setExpress checkout failed";
exit;
}
But in this code how can i add the admin's paypal email id so that i can transfer funds to that account?
You need to create an account with paypal,sign up for the API keys, and then the money would go to your account. You can't transfer it to an arbitrary account.
Related
when i am paying to pay-pal business account, I got transaction-id(tx) & payment status(st) in return URL. but when i am paying to buyers/personal account then I did not get anything in return URL.
//paypal.php ($ll_pp_email will be buyers email id)
$this_script = BASE_URL.'admin/ukorder/paypal';
$this->paypal_class->add_field('business', $ll_pp_email);
$this->paypal_class->add_field('cmd', '_xclick');
$this->paypal_class->add_field('upload', '1');
$this->paypal_class->add_field('amount', $landlord_amount);
$this->paypal_class->add_field('item_name', this->input->post('prop_title'));
$this->paypal_class->add_field('return', $this_script.'/success');
$this->paypal_class->add_field('cancel_return', $this_script.'/cancel');
$this->paypal_class->add_field('notify_url', $this_script.'/ipn');
$this->paypal_class->add_field('currency_code', 'GBP');
$this->paypal_class->add_field('invoice', $invoice);
$this->paypal_class->add_field('email', ADMIN_EMAIL_ADD);
$this->paypal_class->submit_paypal_post($sandbox);
//on success
if(!empty($_GET['st']) && !empty($_GET['tx']))
{
$payment_status = $_GET['st'];
$transaction_id = $_GET['tx'];
if($payment_status=='Completed')
{
//further coding
}
}
But when I am paying from business to personal/buyer account, I didn't get paypal parameters in return url.
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?
Im using PayPal REST API with PHP, I have created a rest app in sandbox and everything as in documentation.
but it returns error
Got Http response code 401 when accessing https://api.sandbox.paypal.com/v1/oauth2/token.
not sure where Im going wrong on this, tried many other sample codes using rest api but same error everywhere.
can some one help me on this?
code is here
define('CLIENT_ID', 'MY CLIENT ID'); //your PayPal client ID
define('CLIENT_SECRET', 'MY SECRET'); //PayPal Secret
define('RETURN_URL', 'http://domain.com/order_process.php'); //return URL where PayPal redirects user
define('CANCEL_URL', 'http://domain.com/payment_cancel.html'); //cancel URL
define('PP_CURRENCY', 'USD'); //Currency code
define('PP_CONFIG_PATH', ''); //PayPal config path (sdk_config.ini)
include_once "vendor/autoload.php"; //include PayPal SDK
include_once "functions.inc.php"; //our PayPal functions
$item_name = 'Test Product'; //get item code
$item_code = 'sku123'; //get item code
$item_price = '10'; //get item price
$item_qty = '1'; //get quantity
/*
Note: DO NOT rely on item_price you get from products page, in production mode get only "item code"
from the products page and then fetch its actual price from Database.
Example :
$results = $mysqli->query("SELECT item_name, item_price FROM products WHERE item_code= '$item_code'");
while($row = $results->fetch_object()) {
$item_name = $row->item_name;
$item_price = item_price ;
}
*/
//set array of items you are selling, single or multiple
$items = array(
array('name'=> $item_name, 'quantity'=> $item_qty, 'price'=> $item_price, 'sku'=> $item_code, 'currency'=>PP_CURRENCY)
);
//calculate total amount of all quantity.
$total_amount = ($item_qty * $item_price);
try{ // try a payment request
//if payment method is paypal
$result = create_paypal_payment($total_amount, PP_CURRENCY, '', $items, RETURN_URL, CANCEL_URL);
//if payment method was PayPal, we need to redirect user to PayPal approval URL
if($result->state == "created" && $result->payer->payment_method == "paypal"){
$_SESSION["payment_id"] = $result->id; //set payment id for later use, we need this to execute payment
header("location: ". $result->links[1]->href); //after success redirect user to approval URL
exit();
}
}catch(PPConnectionException $ex) {
echo parseApiError($ex->getData());
} catch (Exception $ex) {
echo $ex->getMessage();
}
Ok, here is what I did:
Created a PayRequest
SetPaymentOptions - https://developer.paypal.com/webapps/developer/docs/classic/api/adaptive-payments/SetPaymentOptions_API_Operation/
ExecutePayment - "This payment request must be authorized by the sender". I have ran out of idea on why am I not able to execute the payment. From what I understand, once I execute the payment successfully, I will be given a payKey which I shall use this to redirect user to paypal. https://developer.paypal.com/webapps/developer/docs/classic/api/adaptive-payments/ExecutePayment_API_Operation/
Attached are the source codes that I used. The values are all hardcoded. I have tried my best to look through at similar questions, and it makes no sense to me as it contradicts what I understand. Some answers were pointing out that the buyer needs to approve the payment first before you executePayment.
I just want to see the details of all items when I reach the paypal login page.
//1. Obtain endpoint. For live, no need sandbox?
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay";
//2. Format the HTTP headers needed to make the call.
$appID = "xxx"; //Sandbox test AppID:
$username = "xxx;
$password = "xxx";
$signature = "xxx";
$paypalHeaders = array(
"X-PAYPAL-SECURITY-USERID :" . $username,
"X-PAYPAL-SECURITY-PASSWORD :" . $password,
"X-PAYPAL-SECURITY-SIGNATURE :" . $signature,
"X-PAYPAL-APPLICATION-ID :" . $appID,
"X-PAYPAL-REQUEST-DATA-FORMAT : JSON",
"X-PAYPAL-RESPONSE-DATA-FORMAT : JSON"
);
$data = array();
$data['actionType'] = "CREATE"; //PAY
$data['currencyCode'] = "SGD";
$receiver['amount'] = $orderTotal;
$receiver['email'] = $receiverEmail;
$data['receiverList'] = array();
$data['receiverList']['receiver'][] = $receiver;
$data['returnUrl'] = $returnURL;
$data['cancelUrl'] = $cancleURL;
$requestEnvelope = array();
$requestEnvelope['errorLanguage'] = "en_US";
$data['requestEnvelope'] = $requestEnvelope;
//I omitted the POST call
//print_r($returnedData);
$payKey = $returnedData->payKey;
$paymentStatus = $returnedData->paymentExecStatus;
/*
* Set payment options
*/
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/SetPaymentOptions";
//paymentDetailsData
$paymentDetailsData = array();
//set payKey
echo "payKey: " . $payKey;
$paymentDetailsData['payKey'] = $payKey;
//displayOptions
$displayOptions['businessName'] = "My Business";
$paymentDetailsData['displayOptions'] = $displayOptions;
//senderOptions
$senderOptions = array();
$senderOptions['requireShippingAddressSelection'] = true; //set to true if courier is chosen
$senderOptions['shippingAddress']['addresseeName'] = "Ny Name";
$senderOptions['shippingAddress']['street1'] = "Address 1Avenue 3";
$senderOptions['shippingAddress']['street2'] = "#xx-112";
$senderOptions['shippingAddress']['city'] = "Singapore";
$senderOptions['shippingAddress']['state'] = "Singapore";
$senderOptions['shippingAddress']['zip'] = "123456";
$senderOptions['shippingAddress']['country'] = "Singapore";
$paymentDetailsData['senderOptions'] = $senderOptions;
//item
$item = array();
$item['name'] = "Korea";
$item['itemPrice'] = 11;
//there is still price, and itemcount
//invoiceData
$invoiceData = array();
$invoiceData['item'] = $item;
//receiverOptions
$receiverOptions = array();
$receiverOptions['description'] = "Product description.";
$receiverOptions['invoiceData'] = $invoiceData;
$paypalEmail = "test#test.com"; //I may need to change this
$receiver['email'] = $paypalEmail;
$receiverOptions['receiver'] = $receiver;
$paymentDetailsData['receiverOptions'] = $receiverOptions;
//requestEnvelope. I have set the request envelope above. It is the same. Can still be used.
$paymentDetailsData['requestEnvelope'] = $requestEnvelope;
makePaypalCall($endPoint, $paypalHeaders, $paymentDetailsData);
/*
* Get payment options. I can see the result of get payment options correctly,
*/
echo "GETTING PAYMENT OPTIONS";
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/GetPaymentOptions";
$getPaymentData['payKey'] = $payKey;
$getPaymentData['requestEnvelope'] = $requestEnvelope;
makePaypalCall($endPoint, $paypalHeaders, $getPaymentData);
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/ExecutePayment";
/*
* ExecutePayment. Ok, I get the error here. This payment request must be authorized by the sender
*/
$executePaymentData = array();
echo "paykey: " . $payKey;
$executePaymentData['payKey'] = $payKey;
//$executePaymentData['actionType'] = "PAY";
$executePaymentData['requestEnvelope'] = $requestEnvelope;
I hope I understand you correctly.
To me it seems like you are skipping the step where the user needs to authorize the payment. When you do a Pay (Create) operation you should see get a RedirectURL in the response from PayPal. You need to redirect the user to this URL for them to authorize the payment on PayPal.
Once they have approved the payment, then you'll be able to execute the payment.
Your steps need to change to:
Create PayRequest
Set PaymentOptions
Redirect to PayPal (RedirectURL from the PayRequest response) for user authorization
If authorized, ExecutePayment
PayPal hints at this on the Pay API operation page
URL to redirect the sender's browser to after the sender has logged into PayPal and approved a payment; it is always required but only used if a payment requires explicit approval
After the step 3, the user will be returned to the URL your provided in $data['returnUrl'] = $returnURL;
I am using Delayed Chained Payment and often i end up with this error "This payment request must be authorized by the sender". Actually it was due to a small mistake in the logic.
wrong procedure (# step 3)
generate a payKey successfully
save it to database
refresh the page for some reason which results in generating new payKey (this new payKey doesn't update to database)
payRequest = pay();
.....
if(empty(db_record)) {
.....
db_record->payKey = payRequest->payKey;
db_record->save();
}
paid with new payKey ( ie. payment approved by sender)
trying to execute payment with payKey from database (which is indeed old one. That payKey was not used to make payment)
Solution
update database with last payKey which used for making payment by getting approval of sender
step 3 should be like
if(empty(db_record) || is_expired(db_record->payKey)) {
payRequest = pay();
.....
.....
db_record->payKey = payRequest->payKey;
db_record->save();
}
Im using the authorize.net recurring transaction.
What Im trying to do is give the an option to check off a donation if they want it recurring for the next 12 months.
So before the ARB - I want to verify the card but 0.00 isn't a valid amount. so if i made the amount 0.01 - how can I void the transaction after the card is verified?
Also - when a subscription is made I dont get an email from authorize.net telling me a transaction was made like when a regular transaction is processed.
My code:
$authorization = new AuthnetAIM($apilogin, $apitranskey, true);
$authorization->setTransaction($creditcard, $expiration, '0.01');
$authorization->setTransactionType('AUTH_ONLY');
$authorization->process();
if ($authorization->isApproved())
{
$subscription = new AuthnetARB($apilogin, $apitranskey, AuthnetARB::USE_DEVELOPMENT_SERVER);
// Set subscription information
$subscription->setParameter('amount', $amount);
$subscription->setParameter('cardNumber', $creditcard);
$subscription->setParameter('expirationDate', $expiration);
$subscription->setParameter('firstName', $business_firstname);
$subscription->setParameter('lastName', $business_lastname);
$subscription->setParameter('address', $business_address);
$subscription->setParameter('city', $business_city);
$subscription->setParameter('state', $business_state);
$subscription->setParameter('zip', $business_zipcode);
$subscription->setParameter('email', $email);
// Set the billing cycle for every three months
$subscription->setParameter('interval_length', 1);
$subscription->setParameter('startDate', date("Y-m-d", strtotime("+ 1 months")));
// Create the subscription
$subscription->createAccount();
// Check the results of our API call
if ($subscription->isSuccessful())
{
// Get the subscription ID
$subscription_id = $subscription->getSubscriberID();
Send_email();
}
else
{
$transError = 'your subscription was not created';
$hasError = true;
}
}
else if ($authorization->isDeclined())
{
$transError = 'This card is not valid';
$hasError = true;
}
}
catch (AuthnetARBException $e)
{
$transError = 'There was an error processing the transaction. Here is the error message:<br/> ';
echo $e->__toString();
$hasError = true;
}
}
With the new SDK for authorize this would work
$authorize = new AuthorizeNetAIM(self::AUTHNET_LOGIN, self::AUTHNET_TRANSKEY);
$authorize->setFields(array(
'amount' => '0.01',
'card_num' => $cardNumber,
'exp_date' => $expDate
));
$response = $authorize->authorizeOnly();
if ($response->response_code == 1) {
// good card
}else{
// bad card
}
Not only is 0.00 a valid amount, but if you're just trying to verify a credit card is legitimate you are required by Visa and Mastercard to use that amount. A few years ago they stopped allowing pre-auths of any real value to be done for this reason. I think there are fines for merchants who fail to do so.
Having said that, if you're going to take the "charge $.01 and then void the transaction" route, the following code should work:
$transaction_id = $authorization->getTransactionID();
$void = new AuthnetAIM($apilogin, $apitranskey, true);
$void->setTransactionType("VOID");
$void->setParameter('x_trans_id', $transaction_id);
$void->process();