PayPal Integration Not Working - php

I have PayPal integrated on my website. There's a form on my site which takes the customer to PayPal to finalise the payment then it returns them to my site. My site then sends a request back to PayPal with the transaction token for PDT so that I can run a few checks then auto-credit my customer's with the product they bought.
The system uses PHP and cURL to send process all this.
When I use: "www.sandbox.paypal.com/cgi-bin/webscr"
Along with the sandbox credentials everything works fine, everything.
Once I change it all to "www.paypal.com/cgi-bin/webscr"
It does not work, My code tells me that the request fails.
My Code:
$pp_hostname = "www.paypal.com";
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-synch';
$tx_token = $_GET['tx'];
$auth_token = "#######-hashed_out_here-########";
$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){
$this->twig->error("Request failed.");
}else{
$lines = explode("\n", $res);
$keyarray = array();
if (strcmp ($lines[0], "SUCCESS") == 0) {
for ($i='1'; $i<count($lines);$i++){
$test = explode("=", $lines[$i]);
if(empty($test[1])){
$keyarray[urldecode($test[0])] = '';
}else{
$keyarray[urldecode($test[0])] = urldecode($test[1]);
}
}
//give product
} else if (strcmp ($lines[0], "FAIL") == 0) {
$this->twig->error('Transaction failed!');
}
}
Not sure why I'm having a problem so I don't know how to go about fixing.
My PayPal Account is set up as Business, has PDT and IPN turned on as well as Auto-Return
EDIT: Also there isn't an error occurring with the cURL.
OK so if(!($res = curl_exec($ch))) is returning true, i.e its not working

Related

I am using paypal payment gateway, its working but some time on success auto return showing blank screen?

I am using paypal payment gateway (currently using sandbox), its working but some time on success auto return showing blank screen?? response url is pretty good, but some times after auto return its showing blank screen.
My code:
after success auto return redirect properly:
http://domainname/client/paypal/success?amt=9.24&cc=USD&item_name=Weight%20Loss%20Diet%20Program&st=Completed&tx=9CX31984H5808205U
after success auto return redirect properly but showing website blank screen:
http://domainname/client/paypal/success?amt=9.24&cc=USD&item_name=Weight%20Loss%20Diet%20Program&st=Completed&tx=9CX31984H5808205U
everything is looking good with code & return url, then why after return sometimes website showing blank screen??
My Code Snippet to execute paypal response:
switch($action){
case "success":
if(isset($_GET['tx']))
{
$tx_token = $_GET['tx'];
$req = 'cmd=_notify-synch';
$auth_token = PDT_IDENTITY_TOKEN;
$req .= "&tx=$tx_token&at=$auth_token";
$ch = curl_init();
if($sandbox==0){
curl_setopt($ch, CURLOPT_URL, "https://www.paypal.com/cgi-bin/webscr"); //Live
}else{
curl_setopt($ch, CURLOPT_URL, "https://www.sandbox.paypal.com/cgi-bin/webscr"); //Sandbox
}
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);
if($sandbox==0){
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: www.paypal.com")); //Live
}else{
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: www.sandbox.paypal.com")); //Sandbox
}
$res = curl_exec($ch);
curl_close($ch);
$lines = explode("\n", trim($res));
$keyarray = array();
if (strcmp ($lines[0], "SUCCESS") == 0)
{
for ($i = 1; $i < count($lines); $i++)
{
$temp = explode("=", $lines[$i],2);
$keyarray[urldecode($temp[0])] = urldecode($temp[1]);
}
$invoice_id = $keyarray['invoice'];
$transaction_id = $keyarray['txn_id'];
$payment_status = $keyarray['payment_status'];
if($payment_status=='Completed')
{
........
}
}
}
....
break;
....
}
During PayPal operations, the variables you are using are part of PDT (Paypal data transfer), which is PayPal a/c feature which needs to be enabled. Please check your PayPal a/c PDT settings once.

How can I prevent paypal duplicate payment using txn_id?

So I am using PHP cURL and PayPal IPN.
I don't want my customer to pay twice by mistake. I have heard that I can do that using txn_id but I don't know how.
Here is my code ...
<?php
// connecting to database
// Prepare the URL to send via cURL
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($_POST 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";
}
// Initial cURL
$ch = curl_init();
// Set opt
curl_setopt($ch, CURLOPT_URL,"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);
// Return result
$result = curl_exec($ch);
// Close cURL connection
curl_close($ch);
// If condition
if($result == "VERIFIED"){
// perform database update
}
?>
How can I prevent the buyer from paying more than once?
The code you provided here is for PayPal IPN, which I think could help little to avoid duplicated payment. Instead, I recommend you adding invoice into your payment data. As PayPal system by default blocks payments with same Invoice ID, I hope this could help you avoid your customers from paying twice by mistake.
If you are integrating PayPal Payment Standard, please check below page for variable list.
https://developer.paypal.com/webapps/developer/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/
If you are integrating PayPal Express Checkout, please check below pages.
https://developer.paypal.com/docs/classic/api/merchant/SetExpressCheckout_API_Operation_NVP/
https://developer.paypal.com/docs/classic/api/merchant/DoExpressCheckoutPayment_API_Operation_NVP/

PayPal Integration HTTP Error

I have PayPal integrated on my website. There's a form on my site which takes the customer to PayPal to finalise the payment then it returns them to my site. My site then sends a request back to PayPal with the transaction token for PDT so that I can run a few checks then auto-credit my customer's with the product they bought.
The system uses PHP and cURL to send process all this.
When I use: "www.sandbox.paypal.com/cgi-bin/webscr"
Along with the sandbox credentials everything works fine, everything.
Once I change it all to "www.paypal.com/cgi-bin/webscr"
It does not work, My code tells me that the request fails.
My Code:
$pp_hostname = "www.paypal.com";
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-synch';
$tx_token = $_GET['tx'];
$auth_token = "#######-hashed_out_here-########";
$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){
$this->twig->error("Request failed.");
}else{
$lines = explode("\n", $res);
$keyarray = array();
if (strcmp ($lines[0], "SUCCESS") == 0) {
for ($i='1'; $i<count($lines);$i++){
$test = explode("=", $lines[$i]);
if(empty($test[1])){
$keyarray[urldecode($test[0])] = '';
}else{
$keyarray[urldecode($test[0])] = urldecode($test[1]);
}
}
//give product
} else if (strcmp ($lines[0], "FAIL") == 0) {
$this->twig->error('Transaction failed!');
}
}
Not sure why I'm having a problem so I don't know how to go about fixing.
My PayPal Account is set up as Business, has PDT and IPN turned on as well as Auto-Return
It appears that I'm receiving HTTP Error, but which I cannot say, if I log the curl_error it simply says " " and if I log the curl_errno I get 0.
I managed to get this fixed. It was due to my server not having the ssl certificates installed, once I did so it worked fine.

Paying my website user with paypal MassPay Paypal

I am Trying to Pay users with Paypal MassPay API from my website.
public function PPHttppost($methodName,$nvpstr){
$setting = $this->globalsetting();
// Set up your API credentials, PayPal end point, and API version.
$API_Username = $setting->paypal_api_username;
$API_Password = $setting->paypal_api_password;
$API_Signature = $setting->paypal_api_signature;
$API_Environment = $setting->paypal_mode;
$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
$API_Version = '116.0';
if('sandbox' === $API_Environment || 'beta-sandbox' === $API_Environment){
$API_Endpoint = "https://api-3t.$API_Environment.paypal.com/nvp";
}
$version = urlencode($API_Version);
//set curl paramaeter
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//Turn of server and pakagemanager
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,API signature in requrest
$nvpreq = "METHOD=$methodName&VERSION=$version&PWD=$API_Password&USER=$API_Username&SIGNATURE=$API_Signature&$nvpstr";
//set the request as POST field for curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
//get the response from server
$httpResponse = curl_exec($ch);
if(!$httpResponse){
exit("$methodName failed:".curl_error($ch).'('.curl_errno($ch).')');
}
//Extract the response details
$httpResponseArray = explode('&', $httpResponse);
$httpParsedResponseArray = array();
foreach ($httpResponseArray as $i=>$value){
$tmpArray = explode('=', $value);
if(sizeof($tmpArray) > 1){
$httpParsedResponseArray[$tmpArray[0]] = $tmpArray[1];
}
}
if((0 == sizeof($httpParsedResponseArray)) || !array_key_exists('ACK',$httpParsedResponseArray)){
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseArray;
}
$nvpstr = "RECEIVERTYPE=EmailAddress&EMAILSUBJECT=Your withdraw request was processed&L_EMAIL0=seller#gmail.com&L_AMT0=$amt&CURRENCYCODE=$currency";
public function doMassPay($nvpstr){
$httpParsedResponseArray = $this->PPHttppost('MassPay', $nvpstr);
pr($httpParsedResponseArray);exit;
}
When, I call MassPay api of paypal , it returns me success
Array
(
[TIMESTAMP] => 2014%2d09%2d12T07%3a18%3a12Z
[CORRELATIONID] => c4c61215cdd72
[ACK] => Success
[VERSION] => 116%2e0
[BUILD] => 12786467
)
but when I check my account log, it shows receptitant was unable to accept ammount, transaction was denied.
I checked it with different test account, everytime it returns same response. Can anyone guide me where and what I am doing wrong? I am using cakephp framwork and using no library for calling Paypal API.

Paypal PDT error 4003

After many hours of messing about and trying to set up what should be the relatively simple process of sending a payment to www.sandbox.paypal.com and being redirected back to a page on my site with a transaction id in the querystring, I have finally achieved it.
I am now receiving an error message 'FAIL Error 4003'.
Here is the code I am using. It is pretty much the same as the paypal example (all I have done is echo out the responses):
<?php
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-synch';
$tx_token = $_GET['tx'];
$auth_token = "ZdoN6q4GLiRniR2BbOzEEF22GJOWHpVOXRtP7fAhBpvwwm5GyWcTzO_sSSO";
$req .= "&tx=$tx_token&at=$auth_token";
// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
// If possible, securely post back to paypal using HTTPS
// Your PHP server will need to be SSL enabled
// $fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fp)
{
// HTTP ERROR
echo "HTTP Error";
}
else
{
fputs ($fp, $header . $req);
// read the body data
$res = '';
$headerdone = false;
while (!feof($fp))
{
$line = fgets ($fp, 1024);
if (strcmp($line, "\r\n") == 0) {
// read the header
$headerdone = true;
}
else if ($headerdone)
{
// header has been read. now read the contents
$res .= $line;
echo $line;
}
}
// 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) {
echo "Failure: " . $lines[0];
// log for manual investigation
}
}
fclose ($fp);
?>
<br />
Thank you for your payment. Your transaction has been completed, and a receipt for your purchase has been emailed to you. You may log into your account at www.sandbox.paypal.com/ie to view details of this transaction.
I have made sure to confirm the email addresses for both my sandbox merchant and buyer accounts and enabled PDT.
The client is redirected correctly back to my 'thank you' page with the following querystring paramaters - ?tx=4FU63684496248523&st=Pending&amt=29.90&cc=EUR&cm=&item_number=
Has anyone else encountered this error message? If so, what are the usual causes?
The problem was that I was sending my test http request to paypal.com rather than sandbox.paypal.com. The answer was in the FAQ left by Jukebox.
Check the script.When testing Payment Data Transfer (PDT) in the
Sandbox, make sure your PDT script POSTs back information to
www.sandbox.paypal.com. If testing on the Live PayPal site, make sure
the script POSTs data back to www.paypal.com. Currently, all sample
code on the Live and Sandbox sites "point" back to the live PayPal
site.
Hope it helps someone else get up and running quicker than I did. I am now onto my next issue which is the token being returned as empty rather than an error.. sigh..
Make sure your transaction ID is not expired. 4003 PDT error code also comes when your transaction ID is expired.
Here's what solved it for me...
In the Buy Now button, I had a business email address associated with my LIVE PayPal account whereas I need to use the business email address associated with my SANDBOX PayPal account as in:
<input type="hidden" name="business" value="user#host.com">
The value attribute needed to reflect the business email address associated with my sandbox account.
By the way, here's an alternate PHP cURL version of the above script that also does the trick of eliciting a response from PayPal's sandbox:
if (isset($_GET['tx'])) {
$tx = $_GET['tx'];
$identity_token = "INSERT_YOUR_IDENTITY_TOKEN_HERE";
//echo $tx;
$url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
$nvpString="cmd=_notify-synch".
"&tx=$tx".
"&at=$identity_token";
//echo $nvpString;
//define where the data is going to
$curl = curl_init($url);
//tell cURL to fail if an error occurs
curl_setopt($curl, CURLOPT_FAILONERROR, 1);
//allow for redirects
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//assign the returned data to a variable
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//set the timeout
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
//use POST
curl_setopt($curl, CURLOPT_POST, 1);
//set the POST data
curl_setopt($curl, CURLOPT_POSTFIELDS, $nvpString);
//execute the transaction
$response = curl_exec($curl);
//show errors
curl_error($curl);
//close the connection
curl_close($curl);
echo '<pre>';
print_r($response);
echo '</pre>';
}//end if (isset($_GET['tx']))
The Identity Token of my test seller account changed without notification. Using the new (correct) Identity Token fixed the problem.
Some more information on Paypal’s PTD can be found here:
http://www.secure-ebook.com/help/payment:paypal:fail_4003
$tx=$_REQUEST['tx'];
$paypal_url='https://www.paypal.com/cgi-bin/webscr?cmd=_notify-synch&tx='.$tx.'&at=token here';
$curl = curl_init($paypal_url);
$data = array(
"cmd" => "_notify-synch",
"tx" => $tx,
"at" => "token here"
);
$data_string = json_encode($data);
curl_setopt ($curl, CURLOPT_HEADER, 0);
curl_setopt ($curl, CURLOPT_POST, 1);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_SSL_VERIFYHOST, 1);
$headers = array (
'Content-Type: application/x-www-form-urlencoded',
'Host: www.paypal.com',
'Connection: close'
);
curl_setopt ($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt ($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
$lines = explode("\n", $response);
$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);
}
$first_name=$keyarray['first_name'];
$last_name=$keyarray['last_name'];
$payment_status=$keyarray['payment_status'];
$business=$keyarray['business'];
$payer_email=$keyarray['payer_email'];
$payment_gross=$keyarray['payment_gross'];
$mc_currency=$keyarray['mc_currency'];
}

Categories