How to use dodirect payment paypal on form submission? - forms

I have to use dodirect payment method after the form submission. The form will be displayed on the site for all the card detail such as card type (visa or master), card card no, security number, expiration date, name on card, address, state, postal, country, phone, email etc.
I searched how to use the dodirect method and found as below
<?php
/** DoDirectPayment NVP example; last modified 08MAY23.
*
* Process a credit card payment.
*/
$environment = 'sandbox'; // or 'beta-sandbox' or 'live'
/**
* Send HTTP POST Request
*
* #param string The API method name
* #param string The POST Message fields in &name=value pair format
* #return array Parsed HTTP Response body
*/
function PPHttpPost($methodName_, $nvpStr_) {
global $environment;
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode('my_api_username');
$API_Password = urlencode('my_api_password');
$API_Signature = urlencode('my_api_signature');
$API_Endpoint = "https://api-3t.paypal.com/nvp";
if("sandbox" === $environment || "beta-sandbox" === $environment) {
$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
}
$version = urlencode('51.0');
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
// Set request-specific fields.
$paymentType = urlencode('Authorization'); // or 'Sale'
$firstName = urlencode('customer_first_name');
$lastName = urlencode('customer_last_name');
$creditCardType = urlencode('customer_credit_card_type');
$creditCardNumber = urlencode('customer_credit_card_number');
$expDateMonth = 'cc_expiration_month';
// Month must be padded with leading zero
$padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));
$expDateYear = urlencode('cc_expiration_year');
$cvv2Number = urlencode('cc_cvv2_number');
$address1 = urlencode('customer_address1');
$address2 = urlencode('customer_address2');
$city = urlencode('customer_city');
$state = urlencode('customer_state');
$zip = urlencode('customer_zip');
$country = urlencode('customer_country'); // US or other valid country code
$amount = urlencode('example_payment_amuont');
$currencyID = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
// Add request-specific fields to the request string.
$nvpStr = "&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
"&EXPDATE=$padDateMonth$expDateYear&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName".
"&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=$currencyID";
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('DoDirectPayment', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
exit('Direct Payment Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else {
exit('DoDirectPayment failed: ' . print_r($httpParsedResponseAr, true));
}
?>
I didn't get an idea how to use this code on submission of the form that I have on my site. Can anyone help me out how to use this after submitting form.
Thanks in advance :)

That's really not a very well built function. It's basically wanting you to just fill in the values within the function rather than pass them in. It's a pretty rough example and you can see it was last updated in 2008 according to the comments.
If you want to use it, though, you can simply fill in all those placeholders where they show things like "my_api_username" with the data that you want to actually include.
If you want something a lot easier to work with, I would recommend using this PHP library for PayPal that I developed and have maintained for years. It's current and contains straight forward samples for running DoDirectPayment. You could have it up-and-running within minutes.
I offer 30 min of free training via screen share, too, if you're interested in that.

Actually there are samples available for DoDirectPayment as part of the official SDKs available at https://www.x.com/developers/paypal/documentation-tools/paypal-sdk-index#expresscheckoutnew
Suggest using the official SDK and check the samples inside them. In case of any issues please post back here or open an issue at https://github.com/paypal/merchant-sdk-php/issues

Related

After issuing partial refund via PayPal RefundTransaction NVP API, IPN listener only shows payment status as "Refunded," not "Partially_Refunded"

When I issue a partial refund on my site using the RefundTransaction API operation, the refund is processed successfully. However, my IPN listener continually receives a payment status of just Refunded for this transaction. I am not sure why it isn't Partially_Refunded.
I have tested partial refunds with PayPal's IPN Simulator and my IPN listener returns Partially_Refunded every time during these tests.
Here's the beginning of my IPN listener file:
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// STEP 2: POST IPN data back to PayPal to validate
$ch = curl_init($paypal_url);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp-like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set
// the directory path of the certificate as shown below:
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
//mscampMail($my_email, 'MSCamp curl error', "Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// STEP 3: Inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// The IPN is verified, process it:
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process the notification
require_once ('includes/mysql_connect.php');
// Get payment status & parent_txn_id if refund
$payment_status = escape_data($_POST['payment_status']);
// Cart Items
$num_cart_items = isset($_POST['num_cart_items']) ? $_POST['num_cart_items'] : '';
$txn_id = escape_data($_POST['txn_id']);
$user_id = escape_data($_POST['custom']);
$order_total = escape_data($_POST['mc_gross']);
$shipping_fee = escape_data($_POST['mc_handling']);
$first_name = escape_data($_POST['first_name']);
$last_name = escape_data($_POST['last_name']);
// For guest orders, need name & address info for shipping
$guest = $user_id == 0 ? 'guest' : '';
$address_street = escape_data($_POST['address_street']);
$address_city = escape_data($_POST['address_city']);
$address_state = escape_data($_POST['address_state']);
$address_zip = escape_data($_POST['address_zip']);
And the function that posts partial refund data to PayPal:
function PPHttpPost($methodName_, $nvpStr_, $env) {
global $live;
// Set up your API credentials, PayPal end point, and API version.
if("sandbox" === $env)
$API_Endpoint = "https://api-3t.$env.paypal.com/nvp";
else
$API_Endpoint = "https://api-3t.paypal.com/nvp";
$version = urlencode('122');
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
And finally, code from the page that calls the function above when a user initiates the partial refund:
if ($live === false) $env = "sandbox";
// Set request-specific fields.
$item = urlencode($refund_detail['item']);
$amount = urlencode($refund_detail['cost']);
$inventory_num = urlencode($order_detail_id_for_refund);
$transactionID = urlencode($refund_detail['paypal_txn_id']);
$refundType = urlencode('Partial'); // or 'Partial'
$memo = urlencode("Refund of ".$refund_detail['item']); // required if Partial.
$currencyID = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
// Add request-specific fields to the request string.
$nvpStr = "&L_INVOICEITEMNAME0=$item&L_SKU0=$inventory_num&TRANSACTIONID=$transactionID&REFUNDTYPE=$refundType&CURRENCYCODE=$currencyID";
if(isset($memo)) {
$nvpStr .= "&NOTE=$memo";
}
if(strcasecmp($refundType, 'Partial') == 0) {
if(!isset($amount)) {
exit('Partial Refund Amount is not specified.');
} else {
$nvpStr = $nvpStr."&AMT=$amount";
}
if(!isset($memo)) {
exit('Partial Refund Memo is not specified.');
}
}
Any advice or nudge in the right direction would be greatly appreciated as my client needs to be able to process partial refunds on the site. I've scoured Stackoverflow and Google for more information to no avail. Thanks.
Mike,
The payment_status = Refunded txn will have a parent_txn_id field with the value of the transaction that was "partially" refunded.
Assuming you have stored that original payment in your database, the IPN listener can look up the original transaction and compare mc_gross from that record with the same field in the current IPN txn. If different, it is "partial" refund.
In PayPal IPN, refer to https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNandPDTVariables/. payment_status variable doesn't have 'Partially_refunded' value. For "Partially_refunded' transaction, the value is refunded. . The IPN Simulator appears to have some inaccurate variable values.

How to pay with paypal and then save parameters from my form?

I have a working website (HTML, bootstrap)
It has a form where I collect various data regarding the user (e.g. email, dates). Upon clicking "Finish" button, the form sends all data to server (which I have developed on python). The server registers the user by saving all the data collected from the form.
I would like to add a PayPal payment system so that the user will pay for registration and then my server-side script will be initiated and all the data that was in the form will be saved. i.e. the same as now, I just want the user to pay and then save the data.
As far members over here adviced, I have to do "Express Checkout Payment Method" (Am I right?). But the explanations I saw in the web were not clear and I cant figure out how to do it.
How can it be done?
Explanation of how Express Checkout works:
Express Checkout Method is a paypal transaction method which is basically split into 3 phases, namely:
SetExpressCheckout: To use Express Checkout, you would call the SetExpressCheckout API. In the API call, you specify the details of
the products, amounts, and the RETURNURL.
GetExpressCheckout: Once the buyer has agreed to your purchase, he is redirected back to the URL you specified in the RETURNURL. You
should now show the order confirmation, and call the
GetExpressCheckoutDetails API**. When calling
GetExpressCheckoutDetails, supply the token. In the
GetExpressCheckoutDetails API response you'll find a PayerID.
DoExpressCheckout: Now you're ready to call DoExpressCheckoutPayment, and charge the buyer. Remember to include both the token and the payerID when calling DoExpressCheckoutPayment.
First goes the cancel function. If a payment is cancelled, then this method will be called.
function payment_failure()
{
echo "payment cancelled by the user";
}
Now comes the payment successful method:
function payment_success()
{
// Obtain the token from PayPal.
if(!array_key_exists('token', $_REQUEST))
exit('Token is not received.');
// Set request-specific fields.
$token = urlencode(htmlspecialchars($_REQUEST['token']));
// Add request-specific fields to the request string.
$nvpStr = "&TOKEN=$token";
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = $this->PPHttpPost('GetExpressCheckoutDetails', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
$payerID = urlencode($httpParsedResponseAr["PAYERID"]);
$paymentType = urlencode('Sale'); // or 'Sale' or 'Order'
$paymentAmount = urlencode($_SESSION['total_amount']);
$currencyID = urlencode($_SESSION['cur']); // or other currency code ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
$nvpStr = "&TOKEN=$token&PAYERID=$payerID&PAYMENTACTION=$paymentType&AMT=$paymentAmount&CURRENCYCODE=$currencyID";
$httpParsedResponseAr = $this->PPHttpPost('DoExpressCheckoutPayment', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
$transaction_secret=md5(uniqid());
unset($_SESSION['fname']);
unset($_SESSION['lname']);
unset($_SESSION['email']);
unset($_SESSION['password']);
// save the data in the database along with a secret key to uniquely identify the user later(if needed).
}
else
{
exit('DoExpressCheckoutDetails failed: ' . print_r($httpParsedResponseAr, true));
//echo "Payment failed for unknown reason";
}
}
}
else
{
//exit('GetExpressCheckoutDetails failed: ' . print_r($httpParsedResponseAr, true));
echo "Payment failed for unknown reason";
}
}
The first two are the success method and the cancel methods.
Now comes the function which accepts the data from the submit form, and calls the ExpressCheckout methods by passing the parameter to the ExpressCheckout method...
function paypal_order()
{
$_SESSION['fname'] = $_POST['fname']; // fetching the data submitted from the form
$_SESSION['lname'] = $_SESSION['lname']);
$_SESSION['email'] = $_SESSION['email']);
$_SESSION['password'] = $_SESSION['password'];
if($_SESSION['cur']=='USD')
$currencyID = urlencode('USD');
else if($_SESSION['cur']=='INR')
{
$_SESSION['cur'] = 'USD';
$currencyID = urlencode('USD');
}
else if($_SESSION['cur']=='EUR')
$currencyID = urlencode('EUR');
else if($_SESSION['cur']=='GBP')
$currencyID = urlencode('GBP');
$paymentType = urlencode('Order');
$returnURL = (base_url()."paypal-payment-success"); // this call the payment_success() method using the router technique;
$cancelURL = (base_url()."paypal-payment-failure"); // this call the payment_failure() method using the router technique;
$nvpStr="&METHOD=SetExpressCheckout
&RETURNURL=$returnURL
&CANCELURL=$cancelURL";
$i=0;
$str = "
&L_PAYMENTREQUEST_0_NAME$i=User-Registration
&L_PAYMENTREQUEST_0_NUMBER$i=1
&L_PAYMENTREQUEST_0_AMT$i=20
&L_PAYMENTREQUEST_0_DESC$i=User-Registration";
$nvpStr=$nvpStr.$str;
$nvpStr=$nvpStr."&PAYMENTREQUEST_0_AMT=20&PAYMENTREQUEST_0_CURRENCYCODE=$currencyID";
$httpParsedResponseAr = $this->PPHttpPost('SetExpressCheckout', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
$token = urldecode($httpParsedResponseAr["TOKEN"]);
$payPalURL = "https://www.paypal.com/webscr&cmd=_express-checkout&token=$token";
if("sandbox" === $environment)
{
$payPalURL = "https://www.$environment.paypal.com/webscr&cmd=_express-checkout&token=$token";
}
header("Location: $payPalURL");
exit;
}
else
{
exit('SetExpressCheckout failed: ' . print_r($httpParsedResponseAr, true));
}
}
And ultimately, the following is the httppost method which is called by the pasing params like, SetExpressCheckout, GetExpressCheckout and DoExpressCheckout.
The following function is called thrice in a scuccessful Express Checkout Transaction:
private function PPHttpPost($methodName_, $nvpStr_)
{
// Set up your API credentials, PayPal end point, and API version.
$environment = "sandbox"; //or "live" for original live transaction;
$API_UserName = "expresscheckout API username goes here";
$API_Password = "expresscheckout API password goes here";
$API_Signature = "expresscheckout API signature goes here";
//$API_UserName = urlencode('saswat_paypay_business_api1.gmail.com');
//$API_Password = urlencode('1365495686');
//$API_Signature = urlencode('AfOa1sjCuxeiTRYj4tqlG6nUGUmhAvv0pzdavzgFM3272hn8CqS5OY0A');
$API_Endpoint = "https://api-3t.paypal.com/nvp";
if("sandbox" === $environment)
{
$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
}
$version = urlencode('65.0');
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse)
{
exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value)
{
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1)
{
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr))
{
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
Your form submission should make the data flow to, or redirect to the function paypal_order() which is responsible for calling all the other functions.

Separate Payment Integeration For Selected plan type using Drupal Form with Paypal API

I have used a normal class as an API and in that U am passing all the parameters to paypal and i am getting success.
Only thing i am missing is that amount is not being deducted from the sandbox account.
Where as if i pay amount for buying a product by using checkout with paypal the actual amount is being deducted in my sandbox account.
What could be the reason? Is there any other alternative way where i can able to use paypal to receive money through passed arguments in payment details form.
In the submit function of the drupal form i am calling like this.
$paypalDoDirect = new PaypalDoDirect();
// passing all parameters to $paypalDoDirect
$response= $paypalDoDirect->MakePayment();
I am getting transaction is successful and every parameters are getting passed sucessfully.
This is my class api-
class PaypalDoDirect
{
/**Declared all fields **/
function MakePayment()
{
$API_Endpoint = "https://api-3t.paypal.com/nvp";
if ("sandbox" === $this->environment || "beta-sandbox" === $this->environment) {
$API_Endpoint = "https://api-3t.$this->environment.paypal.com/nvp";
}
// Add request-specific fields to the request string.
$nvpStr = "&PAYMENTACTION=$this->paymentType&AMT=$this->amount&CREDITCARDTYPE=$this->cc_type&ACCT=$this->cc_number" .
"&EXPDATE=$this->expdate_month$this->expdate_year&CVV2=$this->cvv2_number&FIRSTNAME=$this->first_name&LASTNAME=$this->last_name&EMAIL=$this->email" .
"&STREET=$this->address1&CITY=$this->city&STATE=$this->state&ZIP=$this->zip&COUNTRYCODE=$this->country&CURRENCYCODE=$this->currencyID";
//$httpParsedResponseAr = PPHttpPost('DoDirectPayment', $nvpStr);
$methodName_ = 'DoDirectPayment';
$nvpStr_ = $nvpStr;
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$this->version&PWD=$this->API_Password&USER=$this->API_UserName&SIGNATURE=$this->API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if (!$httpResponse) {
return ("$methodName_ failed: " . curl_error($ch) . '(' . curl_errno($ch) . ')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if (sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if ((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
return "success";
} else {
return (urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]));
}
}
}
Yes there is a paypal API module in drupal. It's a nice structured module to extend paypal IPN in some custom module.
If you use this module, IPN callback will be handled by this module & you can get notification of it by hook_paypal_api_ipn() at your instance. If you go though paypal documentation about handling payment with paypal & look into the module code, you will understand the mechanism to use it well. I will recommend you to use this module.
Though you can create your own module to handle paypal payment either express or forward users there. I have done it once with drupal instance long ago. You will have to send users or data(for express) at given URL for your account with some information & what ever happens in there(pass/fail/terminate), paypal will inform you at your mentioned callback URL of your instance. Receive the info & do work accordingly..
This might be what you looking for,
Paypal Direct pay not working
Exerpt:
The DoDirectPayment call charges credit cards directly; it does not deduct from a PayPal account - even if that card is attached to an existing PayPal account. Therefore it doesn't show up as a transaction in our 'buyer' PayPal account.

Is it possible to pass the amount back to my site

I am new to developer.paypal.com and i am creating a subscribe button in www.sandbox.paypal.com,is it possible to pass back the amount paid for the subscription by the customer to my website or the details that have been made in www.sandbox.paypal.com?if it is, can you show me some example on how to do this.
after i tried the subscription button this are the value returned i could not find some value in the link that you provided.or the subscription variable how can i show them up?
I could not get the start date and the ending date of my subscription
Thank you.
You could do this one of two ways. You could use IPN or PDT to return information to your site once a payment completes. The better of the two ways, would be to use IPN, or atleast use IPN in conjunction with PDT.
Instant Payment Notification (IPN) is a message service that notifies you of events related to PayPal transactions. You can use it to automate back-office and administrative functions, such as fulfilling orders, tracking customers, and providing status and other information related to a transaction.
You can find more on IPN the page here. Also on that page, off to the left hand side are some more links that are useful as well. There are pages for creating a listener, setup, testing, IPN history, IPN with FMF, IPN/PDT variables, and sample code here. There are also a few more examples of sample code here as well.
PayPal’s PDT system sends order confirmations to merchant sites that use PayPal Payments Standard and lets them authenticate this information. Such sites can then display this data locally in an “order confirmation” page. IPN is more reliable than PDT, and also with PDT it is dependent on the buyer clicking a button to return to your site. If they they dont click on the button to return to your site, no information is sent back and you can not resend this information like you can with IPN. You can find more on PDT here.
I personally only use PDT for crating a dynamic thank you page on my site, and use IPN for updating my database and automating some tasks. Hope this helps. :)
SAMPLE PHP (v5.2) IPN SCRIPT
<?php
// STEP 1: Read POST data
// reading posted data from directly from $_POST causes serialization
// issues with array data in POST
// reading raw POST data from input stream instead.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// STEP 2: Post IPN data back to paypal to validate
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below.
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// STEP 3: Inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
?>
SAMPLE PDT PHP (v5.3) SCRIPT
<?php
$pp_hostname = "www.paypal.com"; // Change to www.sandbox.paypal.com to test against sandbox
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-synch';
$tx_token = $_GET['tx'];
$auth_token = "GX_sTf5bW3wxRfFEbgofs88nQxvMQ7nsI8m21rzNESnl_79ccFTWj2aPgQ0";
$req .= "&tx=$tx_token&at=$auth_token";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://$pp_hostname/cgi-bin/webscr");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
//set cacert.pem verisign certificate path in curl using 'CURLOPT_CAINFO' field here,
//if your server does not bundled with default verisign certificates.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: $pp_hostname"));
$res = curl_exec($ch);
curl_close($ch);
if(!$res){
//HTTP ERROR
}else{
// parse the data
$lines = explode("\n", $res);
$keyarray = array();
if (strcmp ($lines[0], "SUCCESS") == 0) {
for ($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
$firstname = $keyarray['first_name'];
$lastname = $keyarray['last_name'];
$itemname = $keyarray['item_name'];
$amount = $keyarray['payment_gross'];
echo ("<p><h3>Thank you for your purchase!</h3></p>");
echo ("<b>Payment Details</b><br>\n");
echo ("<li>Name: $firstname $lastname</li>\n");
echo ("<li>Item: $itemname</li>\n");
echo ("<li>Amount: $amount</li>\n");
echo ("");
}
else if (strcmp ($lines[0], "FAIL") == 0) {
// log for manual investigation
}
}
?>
Your transaction has been completed, and a receipt for your purchase has been emailed to you.<br> You may log into your account at <a href='https://www.paypal.com'>www.paypal.com</a> to view details of this transaction.<br>

PayPal how to get post back params if response is FAIL

Could I get post back params if in scenario to a buyer click 'cancel and return to xxx store'? below code is how I tried to have post back params echo out after buyer click cancel during the palpal webscr process:
$req = 'cmd=_notify-synch';
$pp_hostname = "www.sandbox.paypal.com";
$tx_token = $_GET['tx'];
$auth_token = "Ti-bfX-sv-zNDXZS";
$req .= "&tx=".$tx_token."&at=".$auth_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://".$pp_hostname."/cgi-bin/webscr");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
//set cacert.pem verisign certificate path in curl using 'CURLOPT_CAINFO' field here,
//if your server does not bundled with default verisign certificates.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: ".$pp_hostname));
$res = curl_exec($ch);
curl_close($ch);
if(!$res){
//HTTP ERROR
}else{
// parse the data
$lines = explode("\n", $res);
$keyarray = array();
if(strcmp($lines[0], "SUCCESS") == 0){
for($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
//process payment
}else if(strcmp($lines[0], "FAIL") == 0){
$lines = explode("\n", $res);
$keyarray = array();
for($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
// echo post back params if FAIL
echo "<p><h3>Transaction ".$keyarray['payment_status']."!</h3></p>";
}
}
Is that possible to get post back params if response FAIL? I need some data to process in db if buyer cancel the transaction.
Thanks.
PayPal would not pass back any parameters to your cancel your, but you could pass back your own. You could dynamically populate the cancel URL that helps you to identify the user or order, and then read that on the cancel URL. For example, you could dynamically populate the cancel URL to something like https://www.mysite.com/cancel.php?orderid=483723 and then you would do your own look up in your system based on the order id, or what ever you pass over and back to your cancel URL.
paypal provide all things about transaction information for more information check below link info
reason_code
https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNandPDTVariables/