How to verify POST data comes from PayPal ?
I am working on a store that sells some products. The payment gateway is PayPal.
Initially I set up a custom PayPal form and used the IPN responses to validate the data that is sent to me from PayPal.
Now my client has bought PayPal Advance Payment that uses PayPal PayFlow. The responses are not sent anymore through IPN (or are they?) instead they are returned by SILENT POST, basically when a transaction is perfomed on their end it is sent to a link of my choice and I process data through that link.
How do I validate the source of the POST data, so I know it is coming from PayPal and not a bad intentions user. I can not find any documentation on this. Also I want the same think when a users clicks "Cancel" button on paypal page and it is redirected to cancelation page on my website. I want that POST data source also verified.
Any thoughts on this ?
First solution than I found, also some PayPal support guy has mentioned something similar but he could not offer details as he said he is not an expert.
Basically you have to run a TRANSACTION of type INQUIRY with the received PNREF from SILENT POST, if the response returns ORIGRESULT equal to 0 then the transaction exists in PayPal database under your account.
I also send the SECURE TOKEN ID and SECURE TOKEN with the inquiry, I do not know if it helps or not, I saw this as a solution somewhere and I tried sending just TOKEN and TOKEN ID without ORIGID and sometimes it worked sometimes not.
On the developer reference from PayPal is specified that on a TRXTYPE=I (INQUIRY TRANSACTION) the ORIGID must be specified.
Code below:
//GET POST DATA FROM SILENT POST
$data = $_POST;
$result = $data['RESULT'];
$pnref = $data['PNREF'];
$secure_token = $data['SECURETOKEN'];
$secure_token_id = $data['SECURETOKENID'];
$fee_amount = $data['AMT'];
if(!isset($result) || $result != '0'){
//DO TRANSACTION FAILED OPERATIONS
exit;
}
//CHECK IF PNREF ID EXISTS ON PAYPAL
$post_data = "PARTNER=yourpartnerid"
."&VENDOR=your_vendor"
."&USER=your_user"
."&PWD=your_password"
."&SECURETOKENID=" . $secure_token_id
."&SECURETOKEN=" . $secure_token
."&ORIGID=" . $pnref
."&TRXTYPE=I"
."&VERBOSITY=HIGH";
$ch = curl_init('https://payflowpro.paypal.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$resp = curl_exec($ch);
$inquiry = array();
parse_str($resp, $inquiry);
//IF ORIGRESULT is 0 then PNREF/transaction exists.
if($inquiry['ORIGRESULT'] == '0' && $inquiry['RESPMSG'] == 'Approved'){ $validated = true; }
else{ $validated = false; }
if($result != 0 || $amount != 'your_correct_fee' || $validated == false){
// DO TRANSACTION NOT VALID OR HAS FAILED OPERATIONS
exit;
}
//DO TRANSACTION SUCCESSFULL OPERATIONS
The response from a INQUIRY looks this way:
RESULT=0&PNREF=ETHPC0BBF5FB&TRANSSTATE=8&ORIGRESULT=0&ORIGPNREF=ELFPB0E766F5&RESPMSG=Approved&AVSADDR=N&AVSZIP=N&ORIGPPREF=8GT035513B296200N&CORRELATIONID=97306f6456378&SETTLE_DATE=2014-07-09 14:11:36&TRANSTIME=2014-07-09 14:11:36&FIRSTNAME=John&LASTNAME=doe&AMT=0.0
Another way of doing it is checking the IP from which the SILENT POST is coming.
I noticed all SILENT POST data comes from 173.0.81.65
$ip_address = $_SERVER['REMOTE_ADDR'];
if($ip_address != '173.0.81.65'){ exit; }
#Andrew Angel
SILENT POST and NotifyURL is not the same thing.
From the NotifyURL you can use IPN and data verification it is done very differently there because you receive different kind of post data string back.
I talked with PayPal support and they said NotifyURL and IPN is not available for PayPal Advanced Payments only for PayPal Payments Pro.
Indeed they both do the same function, but they are different things and source validation is done differently.
Hope this helps someone, waiting on opinions.
Related
I have been trying to build a woocommerce plugin for Alipay from what I understand from their docs is:
I have request a payment through an url(consist of several params, like notify_url, return_url etc.)
Pay through their websit by loggin in.
Then they redirect me to the return_url submitted in the first step (with several new params along with old ones)
They send another request to notify_url with a notify_id and a notify_status and some other params.
After that I have to confirm I got the notification.
Now the issue here is, I am being redirected to return_url and getting expected values. But the code supposed to be triggered by notify_url is not being executed. But if I replace the return_url with notify_url, when alipay redirects me to return_url(in this case reuthn_url = notify_url) notification verification code executes properly.
I am using their demo code.
Here is the configuration:
$gateway = "https://openapi.alipaydev.com/gateway.do?";
$partner = "";
$security_code = "";
$_input_charset = "utf-8";
$sign_type = "MD5";
$transport= "http";
$notify_url = "http://localhost/code/notify_url.php";
$return_url = "http://localhost/code/return_url.php";
N.B. They say payment process is successful in thier website, before redirecting me to return_url.
I am trying to get the express checkout token for a PayPal one time purchase integration. I get this error when trying to make the cURL request:
ACK=Failure&L_ERRORCODE0=81002&L_SHORTMESSAGE0=Unspecified%20Method&L_LONGMESSAGE0=Method%20Specified%20is%20not%20Supported&L_SEVERITYCODE0=Error1
Here is my code
<?php
if(!isset($_GET['id'])) {
header("Location: index.php");
exit();
}
//Get paypal express checkout token
$ch = curl_init("https://api-3t.sandbox.paypal.com/nvp");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"USER: seller-v3rm_api1.test.com",
"PWD: <snip>",
"SIGNATURE: <snip>",
"METHOD: SetExpressCheckout",
"VERSION: 93",
"PAYMENTREQUEST_0_PAYMENTACTION: SALE",
"PAYMENTREQUEST_0_AMT: 25",
"PAYMENTREQUEST_0_CURRENCYCODE: USD",
"RETURNURL: http://test/buy.php",
"CANCELURL: http://test.com",
));
$token = curl_exec($ch);
echo $token;
Am i missing something?
You aren't setting up the request string correctly. I would really recommend taking a look at this PayPal PHP SDK.
First, it will eliminate your need to even mess with this sort of code because it handles it all for you. All you would need to do is open the SetExpressCheckout.php template file that it comes with and fill out the parameters, and then the same for the other calls you might use.
Also, though, if you want you could study the code to see how it's handling the cURL request. You need to build an actual NVP string (ie. &something=like&this=example). Then that is what you send to PayPal via cURL.
I'm using PHP.
Is it possible when paypal returns to my site after taken the payment that it could also pass me the email address (paypal username) so that I may use this to send them an email?
I'm trying to keep my site as simple as possible and I don't want to ask the customer for a load of information up front.
My ideal flow would be:
Take Payment > Add record to database > email customer with username and password
The customer can then log in and fill the rest in at their own leisure.
Is it possible to get this variable?
Thanks in advance.
Yes...see the receiver_email variable that was passed back.
Guide here: https://cms.paypal.com/cms_content/GB/en_GB/files/developer/IPNGuide.pdf
See Pages 42-43
This page shows the things you can get back from PayPal after they process a payment.
IPN and PDT Variables
Here is on example I made in Codeigniter.
/* Receives a form data from paypal that is processed after payment goes through.
* It will update the database entry with a transaction id.
*/
function epayment_notify(){
$this->load->model('pament_notice_model');
echo "Hi<br>";
$postvars = isset($_POST)? $_POST : array("no post");
/* echo "</pre>Post Vars:<br><pre>";
print_r($postvars);
echo "</pre>Refurl:<br><pre>";
Check for the transaction ID and put it in the pament_notice table if possible.
*/
if (isset($postvars['item_number']) && $postvars['item_number'] > 0 && isset($postvars['txn_id'])){
/* make sure that payment_number is empty on this row. */
log_message('info',"PayPal transaction received.");
if ($this->pament_notice_model->make_sure_payment_number_is_empty($postvars['item_number'])){
//writes the message to the local log file in CI
log_message('debug',"PayPal payment number is empty.");
/* set the txn_id in the slot */
$data = array('payment_number' => $postvars['txn_id']);
$this->db->where('entry_id',$postvars['item_number']);
$this->db->update('pament_notice',$data);
log_message('debug',"payment number updated. item:".$postvars['item_number']);
log_message('debug',"payment actual cost. payment_gross:".$postvars['payment_gross']);
} else {
log_message('error',"PayPal transaction attempted on non-empty payment number.");
if (isset($postvars['item_number']))
log_message('error',"failed request item_number :".$postvars['item_number']);
if (isset($postvars['txn_id']))
log_message('error',"failed request txn_id:". $postvars['txn_id']);
}
} else {
log_message('info',"PayPal payment transaction sent with invalid data.");
if (!isset($postvars['item_number']))
log_message('error',"item_number is not set");
if (isset($postvars['item_number']))
log_message('error',"failed request item_number :".$postvars['item_number']);
if (!isset($postvars['txn_id']))
log_message('error',"txn_id is not set\n");
if (isset($postvars['txn_id']))
log_message('error',"failed request txn_id:". $postvars['txn_id']);
}
}
There are a couple of way of handling this.
The easiest method is to collect that data prior to sending the user to paypal.
Store it in the users current session, and have paypal redirect the user back to your page automatically.
The second is to set up the Payment Data Transfer option. I haven't fully implemented this but there is Documentation on paypal's developer site. It basically sends a token back to your site when the user makes payment and you have to perform another HTTP post to retrieve the user data.
I need a brief explanation on how Paypal IPN works. Not anything in details just the basic stuff.
How should I set my HTML variables and how should I get the data to verify the payment from Paypal? This is all I need to know and I can't find a quick explanation on this one somewhere.
If possible, show me some code lines too, would definitely help.
Thanks.
IPN is a message service that PayPal uses to send notifications about specific events, such as:
Instant payments, including Express Checkout, direct credit card
payments and authorizations (transaction payments that are authorized
but have not yet been collected)
eCheck payments and associated status, such as pending, completed, or
denied, and payments pending for other reasons, such as those being
reviewed for potential fraud
Recurring payment and subscription actions
Chargebacks, disputes, reversals, and refunds associated with a
transaction
In many cases, the action that triggers an IPN event is a user-action on your website. However, other actions can trigger IPNs. For example, your site's back-office process might invoke a PayPal API that refunds a payment, or a customer might notify PayPal of a disputed charge.
You receive and process IPN messages with a listener (sometimes called a handler). This listener is basically a web page or web application that you create on your server that is always active and had code that allows it to accept and verify IPN messages sent from PayPal, and then invoke backend services on your server, based on the information from the IPN message. The web application waits for IPNs and (typically) passes them to an administrative process that responds appropriately. PayPal provides sample code that can be modified to implement a listener that handles the IPN sent from messages PayPal. For details, see Implementing an IPN listener.
For detailed information and help please visit: PayPal Instant Payment Notification Guide
Hope this helps.
Code
I've used the c# equivalent of this many times (and the PHP version looks quite similar).
https://www.x.com/developers/PayPal/documentation-tools/code-sample/216623
<?php
//reading raw POST data from input stream. reading pot data from $_POST may cause serialization issues since POST data may contain arrays
$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_exits = true;
}
foreach ($myPost as $key => $value)
{
if($get_magic_quotes_exits == true && get_magic_quotes_gpc() == 1)
{
$value = urlencode(stripslashes($value));
}
else
{
$value = urlencode($value);
}
$req .= "&$key=$value";
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.paypal.com/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);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: www.paypal.com'));
// In wamp like environment where the root authority certificate doesn't comes in the bundle, you need
// to 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');
$res = curl_exec($ch);
curl_close($ch);
// 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'];
if (strcmp ($res, "VERIFIED") == 0) {
// 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
}
else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
?>
Overview
Basically, PayPal contacts you and you respond; this allows you to validate that it was PayPal invoking your IPN handler and not a malicious party. After that validation step, you can proceed with processing the results. As I'm sure you know, an IPN call is made after a payment occurs (and also can be configured for other events in the payment lifecycle). You can use IPN to update a system status (e.g. unlocking a purchased product).
Other Stuff
The last development URL I used for PayPal was https://www.sandbox.paypal.com/cgi-bin/webscr (probably still valid)
The IPN page/handler needs to be publicly available for PayPal to invoke.
You'll need to configure IPN notifications in the PayPal developer UI (which mainly involves giving them the URL to your IPN page)
You can send custom information to PayPal with the original transaction that PayPal will send back to the IPN handler. I believe it is passed in a field called "custom".
I found very useful (and easy to use) this PHP class:
I'm at a complete loss. I think I might be getting "mis-informed", but I'll try explain my situation as best I can.
The Idea
We have a form for users to purchase credits. Type in credit number,
click pp button.
Upon click of button, a post is made to set the
transaction log information and set it as pending (works fine).
Upon valid post return it continues to submit the paypal form (works also).
The user is redirected to paypal page and makes payment (so far so good).
after payment made, they click the return and are directed toward the "success" page (still working).
upon reaching this page I take in post data from pp (uh oh, here's where it gets sticky)
verify the data is "true" pp data and update the transaction log (HOW!?)
What I'm being told & what i've tried
I was initially going to use IPN to do a post back to paypal to verify the recieved data (ensure it wasn't spoofed), however, I'm being told that for cost purposes and having to setup an "ipn server" we can't use IPN ....
Ok, so I was gonna use PDT, except either I missed a major step in my attempt or it ISNT working right at all because I'm not doing somthing right. Here is where I'm lost, i've tried a dozen different things, including a direct link post, using sparks (for CI) to set the data and call to paypal link, and etc ...
I've looked over every paypal question on here and a half dozen other forums and can't seem to get anything going.
Can anyone "clearly" tell me how I can verify the POST data of a successful paypal transaction and maybe even tell me if i'm being misinformed about the IPN, cause I looked over the docs and I can't find what i've been told, nor can I really find my solution.
I feel stupid, please help.
When your user clicks a PayPal button and goes to PayPal, when they complete the transaction, an IPN POST is made to a URL of your choosing. So you don't have to have another web server.
When the IPN request comes in, PayPal wants you to re-send the entire POST they made to you back to them, including all of the fields, in the exact order, at which point they will return the word 'VERIFIED' or 'INVALID.' If verified, then do whatever it is that you need to do to toggle your txn log from pending to verified. Also, any information you include in your button (your button is actually a form so you can include your own fields) is included in the POST. Useful for keeping a 'transaction id' or some other identifier for mapping back to your transaction.
If the IPN fails it will resend in n+4 minute increments (where n is how long it waited the last time - 4 minutes, next after 8 minutes, next after 12 minutes, etc) for a few days.
Finally made it work correctly thanks to the update in info on IPN.
My solution added the following line to my form:
<input type="hidden" name="notify_url" value="<?= site_url('payment/notifyTest'); ?>">
Then in the notifyTest function i ran this:
$pDat = $this->input->post(NULL, TRUE);
$isSandBox = array_key_exists('test_ipn', $pDat) && 1 === (int)$pDat['test_ipn'] ? TRUE : FALSE;
$verifyURL = $isSandBox ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr';
$token = random_string('unique');
$request = curl_init();
curl_setopt_array($request, array
(
CURLOPT_URL => $verifyURL,
CURLOPT_POST => 0,
CURLOPT_POSTFIELDS => http_build_query(array('cmd' => '_notify-validate') + $pDat),
CURLOPT_RETURNTRANSFER => 0,
CURLOPT_HEADER => 0,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_CAINFO => 'cacert.pem',
));
$response = curl_exec($request);
$status = curl_getinfo($request, CURLINFO_HTTP_CODE);
curl_close($request);
if($status == 200 && $response == 'VERIFIED') {
// SUCCESS
$data = array (
... => ...
);
$this->db->insert('transactions', $data);
}
else {
// FAILED
$data = array (
... => ...
);
$this->db->insert('transactions', $data);
};
THE IMPORTANT DIFFERENCE AS WE FOUND -> DO NOT SET YOUR CURL VARS TO TRUE OR FALSE
USE 0 FOR TRUE AND 1 FOR FALSE, IT MIGHT SOUND STUPID, BUT IT WOIKED!!!