Jump to content

Paypal Order Failed on return to cube cart FIX !!!!�


Guest foto-time

Recommended Posts

Guest Charles2005

As many of you paypal standard/IPN users, I have experienced the same infamous "your oder failed" error when customer is redirected back to my store. The root cause i found out is the timming - sometimes paypal calls IPN.php after paypal redirects customer to the confirmed.php. Another problem is, if customer pay it via echeck, even if ipn.php is called first, the order status will still be pending, thus customer will see "your order failed" too.

Long story in short, I have found a solution for it.

Here is how to:

you only need to modify confirmed.inc.php in includes/content directory.

find:

$cart = new cart();




after that, add:




///////////////////////////

// Added by paypal auto return fix

///////////////////////////

$logflag = TRUE;

///////////////////////////

// End

///////////////////////////




find:




################################################################################

############

// Following lines added for Sir William's PayPal AutoReturn Fix

} elseif(isset($_GET['tx']) && isset($_GET['st'])) {

 $basket['gateway'] = "PayPal";

################################################################################

############




after that, add:




///////////////////////////

// Added by paypal auto return fix

///////////////////////////

$module = fetchDbConfig("PayPal");

///////////////////////////

// End

///////////////////////////






find:




$success = success();




after that, add:




///////////////////////////

// Added by paypal auto return fix

///////////////////////////

if ( ( $success == FALSE ) && (isset($_GET['tx']) && isset($_GET['st'])) )

{

	$success = pdtcheck();

}

////////////////////////////////

// End

////////////////////////////////




finally, add the following 2 methods at the end of the file (just before the 
?>
):




////////////////////////////////

// Added by paypal auto return fix

////////////////////////////////

function pdtcheck()

{

	global $db, $glob, $module, $basket;

	// read the post from PayPal system and add 'cmd'

	$req = 'cmd=_notify-synch';



	$tx_token = $_GET['tx'];

	logMsg( "" );

	logMsg( "Using PDT to check order status for tx:".$tx_token );

	$auth_token = "this is provied by paypal - check your paypal PDT config";

	$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

		logMsg ("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;

				}

		}



		// 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 invoie, amount and receiver_email are correct

			 */

			$amount = $keyarray['payment_gross'];

			$invoiceId = $keyarray['invoice'];

			$receiver_email = $keyarray['receiver_email'];

			$sqlstat = "SELECT * FROM ".$glob['dbprefix']."CubeCart_order_sum WHERE cart_order_id = ".$db->mySQLSafe($invoiceId);

			$result = $db->select( $sqlstat );

			if ( ($result[0]['prod_total'] == $amount ) && ( strcmp( $module['email'], $receiver_email ) == 0 ) )

			{

				logMsg ("Verify Success");

				return TRUE;

			}

			else

			{

				logMsg ( "Verify Failed, Paypal response follows:" );

				logMsg ( "		Amount = " . $amount );

			  logMsg ( "	   Invoice = " . $invoiceId );

			  logMsg ( "Receiver Email = " . $receiver_email );

				return FALSE;

			}

		}

		else

		{

			logMsg ( "Payment Failed, Paypal response follows:" );

			logMsg ( $res );

			return FALSE;

		}

	}

	fclose ($fp);

}



function logmsg( $msg )

{

	global $logflag;

	if ( $logflag == FALSE )

	{

		return;

	}

	$today = date("Y-M-d");

	$myFile = "/location for my log files/".date("Y-M-d").".log";

	$fh = fopen($myFile, 'a') or die("can't open file");

	$stringData = date("[Y/M/d, G:i:s] ").$msg."\n";

	fwrite($fh, $stringData);

	fclose($fh);

}

////////////////////////////////

// End

////////////////////////////////






Let me explain how it works:



when user is transferred back to the confirmed.php, success() method is called first.  If IPN is called first, and if the status becomes "process", success() will return TRUE, then the payment is successful.



If IPN is not called yet, or customer sent an echeck, the status is pending, success() returns FALSE, then checkPDT() is called.



checkPDT() sends a request to paypal server with tx id received when paypal calls confirmed.php, then paypal sends back the transcation details, including invoice number, totoal amount and more.  So, in checkPDT() method, we do a db query, by using the invoice id, amount received from paypal and check wheter they matches, if everything is ok, return TRUE, otherwise, return FALSE.



If you add the above two methods to your file, make sure to replace the auth_token with the ones provided by paypal.  Also, you need to change the log location.  You can just create a directoy inside your store, give it a wired name, such as 
.$ba_ufdkj

, and give it a 777. The reason for a wired name is, people cannot guess it. oh, also password protect the log directory...it will block all http accesses.

I hope this helps :-)

now i can get to work on the rest of the site WAHOO!

sorry if this is off topic but this needs to be pinned so people can get a fix quickley without going round in circles

I had applied the fix found on the CC Documentation Area and was still having problems with PayPal IPN. I used my CC on the first order and that went through but when I did another purchase with the same CC info it gave me the Sorry, O..... but it showed completed in PayPal and as processing in CubeCart. I found this fix and applied it and then did the same test again. I did 2 CC transactions back to back and they both went through and showed successful!!!

Thanks for posting this wonderful fix. Will this fix but added to the new CubeCart4?

Regards,

Charles

Link to comment
Share on other sites

  • Replies 66
  • Created
  • Last Reply

Top Posters In This Topic

Guest Charles2005

One thing that I did was change the code a little bit to work (i think) better.

Where it says to find

$success = success();


I replaced it with this bit of code:


//$success = success();

if($basket['gateway'] = "PayPal"){

	$success = pdtcheck();

}	else	{

	$success = success();

}

//PayPal AutoReturn Fix Found Here http://www.cubecart.com/site/forums/index.php?showtopic=23589 Mod Begin

//if ( ( $success == FALSE ) && (isset($_GET['tx']) && isset($_GET['st'])) )

//{

//	$success = pdtcheck();

//}

//PayPal AutoReturn Fix Found Here http://www.cubecart.com/site/forums/index.php?showtopic=23589 Mod End

That way if it is PayPal it will ALWAYS use the pdtcheck() function but if it is any other type of Gateway it will use the success() function. Basiclly it is not even looking at the success() function at all if it is PayPal. Using the pdtcheck() function I think would be a better solution instead of using both of the functions. Just my 3 cents worth here.

Link to comment
Share on other sites

Guest BenOByrne

If you add the above two methods to your file, make sure to replace the auth_token with the ones provided by paypal. Also, you need to change the log location. You can just create a directoy inside your store, give it a wired name, such as

.$ba_ufdkj

, and give it a 777. The reason for a wired name is, people cannot guess it. oh, also password protect the log directory...it will block all http accesses.

I hope this helps :-)

now i can get to work on the rest of the site WAHOO!

sorry if this is off topic but this needs to be pinned so people can get a fix quickley without going round in circles

Hi guys,

Many thanks for this excellant suggestion - one quick question for both foto-time and charles2005 - how do I replace the auth_token and where do I find the ones provided by PayPal?

Many thanks again, looking forward to this (hopefully) last resolution!

BenOByrne

Link to comment
Share on other sites

Guest Charles2005

If you add the above two methods to your file, make sure to replace the auth_token with the ones provided by paypal. Also, you need to change the log location. You can just create a directoy inside your store, give it a wired name, such as

.$ba_ufdkj
, and give it a 777.  The reason for a wired name is, people cannot guess it. oh, also password protect the log directory...it will block all http accesses.



I hope this helps :-)



now i can get to work on the rest of the site WAHOO!



sorry if this is off topic but this needs to be pinned so people can get a fix quickley without going round in circles
Hi guys, Many thanks for this excellant suggestion - one quick question for both foto-time and charles2005 - how do I replace the auth_token and where do I find the ones provided by PayPal? Many thanks again, looking forward to this (hopefully) last resolution! BenOByrne
BenOByrne

You put your token between the " "

Replace PUT YOUR TOKEN HERE!! with your

auth token found at PayPal.

To get your Auth. Token go to

Profile/Selling Preferences/Website Payment Preferences

Look Under the Payment Data Transfer (optional) area

There you will see a your Identity Token(Auth Token).

That is the token that you would use.

Hope this helps.

$auth_token = "PUT YOUR TOKEN HERE!!";
Link to comment
Share on other sites

  • 1 month later...

Hi Everyone

I've also been experiencing with my paypal.

Ok - i've made the changes as per the instructions set here. But now i'm absolutely stuck on the log thingi!

Where is this log file? as i can't find it in public_html.

Is the log file name .$ba_ufdkj and if so do i rename it or delete it?

What is it that i have to write into the log file for it to work....

Ummmmm seriously need some assistance here ;-)

Thanks for your patience and your help :wacko:

Kindest Regards,

antz :(

Link to comment
Share on other sites

  • 3 weeks later...
  • 3 weeks later...
Guest sugarmouse

This is all fantastic and does a nice job of verifying a payment has gone through - Except that the confirmation email is not sent because ipn.php will not have set the status of the order to processing, and the stateUpdate flag is not set to TRUE.

so in includes/confirmed.inc.php find the line

if($success == TRUE){


and add underneath


$stateUpdate = TRUE; // this will mean we always send email and process the stock updates


The key change to the function below is the addition of the lines after we have logged the 'Verify Success' message and before we return TRUE.  So the full pdtcheck() function listing now looks like:


////////////////////////////////

// Added by paypal auto return fix

////////////////////////////////

function pdtcheck()

{

	global $db, $glob, $module, $basket;

	// read the post from PayPal system and add 'cmd'

	$req = 'cmd=_notify-synch';



	$tx_token = $_GET['tx'];

	logMsg( "" );

	logMsg( "Using PDT to check order status for tx:".$tx_token );

	$auth_token = "this is provied by paypal - check your paypal PDT config";

	$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

		logMsg ("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;

				}

		}



		// 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 invoie, amount and receiver_email are correct

			 */

			$amount = $keyarray['payment_gross'];

			$invoiceId = $keyarray['invoice'];

			$receiver_email = $keyarray['receiver_email'];

			$sqlstat = "SELECT * FROM ".$glob['dbprefix']."CubeCart_order_sum WHERE cart_order_id = ".$db->mySQLSafe($invoiceId);

			$result = $db->select( $sqlstat );

			if ( ($result[0]['prod_total'] == $amount ) && ( strcmp( $module['email'], $receiver_email ) == 0 ) )

			{

				logMsg ("Verify Success");

								logMsg ( "Invoice = " . $invoiceId );



								// MUST change the status to processing (we know we have payment) or conf email is NOT sent.

								$updateOrderTxn['sec_order_id'] = $db->mySQLSafe($_POST['txn_id']);

								$update = $db->update($glob['dbprefix']."CubeCart_order_sum", $updateOrderTxn,"cart_order_id=".$db->mySQLSafe($invoiceId));



				return TRUE;

			}

			else

			{

				logMsg ( "Verify Failed, Paypal response follows:" );

				logMsg ( "		Amount = " . $amount );

			  logMsg ( "	   Invoice = " . $invoiceId );

			  logMsg ( "Receiver Email = " . $receiver_email );

				return FALSE;

			}

		}

		else

		{

			logMsg ( "Payment Failed, Paypal response follows:" );

			logMsg ( $res );

			return FALSE;

		}

	}

	fclose ($fp);

}

This duplicates the full function of the ipn.php file.

Hope this works for you guys too, and saves you a weeks worth of long evenings!!

Best

Tim :)

Link to comment
Share on other sites

  • 2 weeks later...

Ok so the FAILED part is gone, but the email is not being sent to email clients such as gmail, yahoo etc. Its not my host because I can send an email using the admin area's "Email Customers"

Any ideas?

Link to comment
Share on other sites

  • 2 weeks later...

It may have been obvious to most people but in your PayPal account Website Payment Preferences the Return URL should NOT have https and should be http. I was going nuts trying to figure out why I couldn't get any of these fixes to work then almost as a last thing to try I changed the https://website.com/confirmed.php to http://website.com/confirmed.php and it freakin' worked! I think I probably entered it that way from the beginning when setting it up because I thought that's what it would have to be. I was wrong. :-)

Thought this might be helpful to anyone else going nuts having the same issues.

Thanks for the great help with this post by the way. Word.

Link to comment
Share on other sites

It may have been obvious to most people but in your PayPal account Website Payment Preferences the Return URL should NOT have https and should be http. I was going nuts trying to figure out why I couldn't get any of these fixes to work then almost as a last thing to try I changed the https://website.com/confirmed.php to http://website.com/confirmed.php and it freakin' worked! I think I probably entered it that way from the beginning when setting it up because I thought that's what it would have to be. I was wrong. :-)

Thought this might be helpful to anyone else going nuts having the same issues.

Thanks for the great help with this post by the way. Word.

So, after about a week it stopped working again with the "Sorry, order failed." bit and the first thing I did to test again was to change the http to https in PayPal setting and it worked. So, I guess disregard the above. I don't know what the heck happened but it works. My original thought that it had to be https is correct.

Link to comment
Share on other sites

Guest claimandcollect

Hi, I know a company called Claim and Collect Ltd which specialise in recovering losses incurred through Paypal on a no win no fee basis. This covers cases of chargebacks, reversed payments or goods not received in the last six years. Visit www.claimandcollect.com for full details or call them on 0800 030 4624.

Link to comment
Share on other sites

For anyone thinking about following the previous post, this is from their authorisation document:

"I understand that Claim and Collect will levy a fee of 19.5% from any claim settlement in the event that it is successful, subject to minimum fee of £50.00."

I can't see this being of much use unless you lose a lot of money (£0000s). Not many transaction will meet the £50 fee, and even if you lose £100 to PayPal, £50 will go to these people. If your transactions are of a high enough level, you'll probably gain by getting a merchant account.

For anyone having problems with PayPal, I'd suggest "paypalsucks.com for support and advice"

Back ontopic,

I've always had good experience with the PDT add-on code for Cubecart. This basically requests the payment status from paypal, and correctly sets the order status on the cart.

If you're a UK store, one of the variables changes, but the original thread is still valid and contains all the information you need, just read it all.

Jason

Link to comment
Share on other sites

  • 2 weeks later...
Guest z28melissa

I'm running into this problem too, but before I apply the fix (THANK YOU by the way!), I'm wondering if I should just make the jump to v4 now, as I plan to do it soon anyway. Is this problem just in version 3?

Link to comment
Share on other sites

  • 3 months later...

This worked for me!

thanks!!

Have any of you people having a lot of trouble tried NOT using IPN????

If you can not get IPN to work try this:

Go to your cube admin then gateways then "paypal standard and ipn" Change the drop down setting to "standard" and save your changes.

Log into your paypal account and click "profile"

Click "Instant Payment Notification Preferences" click edit and completely delete the url and turn off ipn then save.

Click "Back to Profile Summary"

Click "Website Payment Preferences" and set as follows

Auto Return: off

Return URL: delete it

Payment Data Transfer: off

Block Non-encrypted Website Payment: off

PayPal Account Optional: on

Contact Telephone : recommended to off

I have done this for several clients who were having issues.

The ONLY difference is, after the user pays they are taken to a Paypal screen that tells them they have paid.

Then they are given the choice of going to their paypal account or they can click the "return to merchant" button to go back to your site.

They still go back to the confirmed.php and the modules/gateway/paypal/ipn.php is still informed of the update and sets the order to processing not pending and reduces stock levels if you use them. This is coded into the transfer inc file already.

TRY IT when you click "return to merchant" you get the order success message every time. (if your cart is installed correctly :) )

IPN has always been problematic, while I am no programmer my guess is cube can not currently cope with the speed of all the info being sent from paypal.

Using the method above is one extra click for the client but results in a LOT LESS failed orders and emails complaining about errors.

Our clients have reported that they have fewer missed sales since we implemented this change. Please do let me know how you go if you try this.

Link to comment
Share on other sites

Guest dillingerink

2001web or others who have tried the fix of not using IPN - when I complete an order using a CC via paypal rather than using my paypal account (I haven't tried using a paypal account because I can't pay myself ;-) there is no link to return to merchant. I only get a "Go to paypal account overview" which is odd because I have completed payment with out using an account, and a View Printable Receipt.

???

The order then does not go to processing and when I go back to the website my cart is still full. The order is completed and listed in Order History but I can see this being very confusing for customers...

Thanks!

Rochelle

Link to comment
Share on other sites

I am new to CubeCart, but not PHP and MySQL.

I have recently been retained by a shop owner to help him figure out why an unusually high number of his customer orders are failing. He is using CubeCart 3.0.16, with ExpressCheckout and DirectPay enabled (not the PayPal standard or IPN option at the bottom of the list).

Some transactions fail for valid reasons (invalid expiration date, or such), but others don't seem to have valid reasons for failing.

The shop owner did not set this site up, he paid someone else to set it up, and they have moved on. He has asked me to look into it and try to fix it.

I have read that CC 3 has issues with PayPal, and that this particular fix seems to help some people, but I'm not sure if it will help in this case.

Does anyone know if it will?

If this fix will help, then I am willing to give it a shot. But since most of the people using it appear to be using either PayPal basic or IPN, I didn't know for sure if it would make any difference in this case.

Thanks in advance.

Link to comment
Share on other sites

Guest Turbo123

*** I made it work with IPN!!! :rolly:

If the payment isn´t in USD, like euros in my case:

in the modified confirmed.inc.php where u put the function pdtcheck()

Find this:

$amount = $keyarray['payment_gross'];




Replace with:


$amount = $keyarray['mc_gross'];

Link to comment
Share on other sites

  • 4 months later...
Guest Bonesddrummer

*** I made it work with IPN!!! :)

If the payment isn´t in USD, like euros in my case:

in the modified confirmed.inc.php where u put the function pdtcheck()

Find this:

$amount = $keyarray['payment_gross'];




Replace with:


$amount = $keyarray['mc_gross'];

Why ? What does this do What does Mc_gross mean ?

I've followed all of the changes on this thread to the letter, I'm still getting the order failed message.It's doing my head in.

Not to worry just done this bit and all is working fine, thankyou to everybody who has contributed to this thread, you've made an old man happy :-)

Link to comment
Share on other sites

  • 4 months later...
Guest lolichka

To everyone who posted this fix - thank you! It was doing my head in until about 3am this morning when my eyes were way to bleary to stay awake anymore + the lil one arked up for a feed!!

I only applied the fix from the first post and changed the currency variable from a subsequent post and it now displays in AUS$. Also, I had a problem last night where order # in CC was not being generated once the payment had been made, however since applying the first fix all from this end seems to be ok as well as successful confirmation page and the back end being updated - yay!

Also, one other thing. Re the order that didn't generate the CC order #, it can't be deleted unless you go into MyPhp and find the order and manually delete it...

I'm a WAHM getting my business up and running and whilst I have invested in some mods and theme my hats off to all you folk who are experts in CC/MySQL/PHP and generous to offer your time & help.

Many thanks

Link to comment
Share on other sites

I seem to be getting the same issue using Authorize.net SIM integration - is there any chance this solution (properly adapted) could work there too?

Cheers!

Jason

Link to comment
Share on other sites

  • 4 months later...
Guest Tebulot

I have managed to get paypal working in version 3.0.18 thanks to the posts detailed here. It took me some time to read through them and understand what was required.

I have used the information posted to produced a step by step guide that worked for me here

Thanks to those who have posted in this thread. I now have a working cubecart installation with paypal.

I have tried many different scripts to get a decent shop/digital download store online. My requirements being download capability, paypal integration and easy sign up and cart features.

I was not happy with any of them.

The only issue I had found with cubcart was the paypal gateway not returning to the confirmed payment screen.

Try the guide and see if it helps you.

Link to comment
Share on other sites

  • 3 weeks later...
Guest dreamdancer

I have managed to get paypal working in version 3.0.18 thanks to the posts detailed here. It took me some time to read through them and understand what was required.

I have used the information posted to produced a step by step guide that worked for me here

Thanks to those who have posted in this thread. I now have a working cubecart installation with paypal.

I have tried many different scripts to get a decent shop/digital download store online. My requirements being download capability, paypal integration and easy sign up and cart features.

I was not happy with any of them.

The only issue I had found with cubcart was the paypal gateway not returning to the confirmed payment screen.

Try the guide and see if it helps you.

WOW, WOW, WOW!! THANK YOU!!!! I have been struggling with PayPal forever. I get it working then for some reason (probably something changing with PayPal) it breaks then I get frantic emails from clients that it isn't working. I followed your instructions and got two that were having issues just today fixed!!!

Of course I recommend that my clients upgrade to the paid version, but some just can't buy it just yet. This info saved the day! It is so helpful to have it all outlined clearly in one place.

THANK YOU!!!!

Link to comment
Share on other sites

  • 1 month later...

For the last 48 hours, every order on my store is now failing with the infamous "Your Order Has failed" message. Not had a problem before and I haven't changed anything on the store, the PayPal set-up, or the host. All has been working fine for >16 months.

I've tried the changes suggested on this thread & they didn't fix it for me :on2long: I've tried the 3.0.18 Paypal gateway, the 3.0.19 Paypal gateway & the Paypal gateway mod from Estelle. ALL Fail.

Currently I can't receive ANY orders into my store without the Order Failed message if I use IPN. So for the moment I've had to disable IPN as I can't fix this error. Frustrating as hell :)

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.




×
×
  • Create New...