Find the mistake in my IF statements

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
synical21
Forum Contributor
Posts: 150
Joined: Tue Jul 28, 2009 8:44 am
Location: London UK

Find the mistake in my IF statements

Post by synical21 »

Hey Gurus been a while since i last posted here im starting to understand php more these days, but still dont understand enough which i need to :p. Basiacally i am trying to make a paypal IPN handler so i used paypals template and used internet tutorials to help me make one to suit my needs. Here is the result:

Code: Select all

 
// database settings
*****
// paypal email
$paypal_email = "****";
 
// email address where script should send notifications
$error_email = "*******";
 
// email header
$em_headers  = "From: from_name <from_email>\n";        
$em_headers .= "Reply-To: from_email\n";
$em_headers .= "Return-Path: from_email\n";
$em_headers .= "Organization: company_name\n";
$em_headers .= "X-Priority: 3\n";
 
 
// -----------------
 
 
require("ipn_cls.php");
// my variables
$valuebutton = $_POST['valuebutton'];
$buyer_id = $_POST['userid']; // this is done by $_SESSION[user_id]
 
$paypal_info = $HTTP_POST_VARS;
$paypal_ipn = new paypal_ipn($paypal_info);
 
foreach ($paypal_ipn->paypal_post_vars as $key=>$value) {
    if (getType($key)=="string") {
        eval("\$$key=\$value;");
    }
}
 
$paypal_ipn->send_response();
$paypal_ipn->error_email = $error_email;
 
if (!$paypal_ipn->is_verified()) {
    $paypal_ipn->error_out("Bad order (PayPal says it's invalid)" . $paypal_ipn->paypal_response , $em_headers);
    die();
}
 
 
switch( $paypal_ipn->get_payment_status() )
{
    case 'Pending':
        
        $pending_reason=$paypal_ipn->paypal_post_vars['pending_reason'];
                    
        if ($pending_reason!="intl") {
            $paypal_ipn->error_out("Pending Payment - $pending_reason", $em_headers);
            break;
        }
 
 
    case 'Completed':
        
        $qry= "SELECT i.mc_gross, i.mc_currency FROM item_table as i WHERE i.item_number='$item_number'";
        mysql_connect("$host","$ln","$pw") or die("Unable to connect to database");
        mysql_select_db("$db") or die("Unable to select database");
        $res=mysql_query ($qry);
        $config=mysql_fetch_array($res);
    
        if ($paypal_ipn->paypal_post_vars['txn_type']=="reversal") {
            $reason_code=$paypal_ipn->paypal_post_vars['reason_code'];
            $paypal_ipn->error_out("PayPal reversed an earlier transaction.", $em_headers);
            // you should mark the payment as disputed now
        } else {
                    
            if (
                (strtolower(trim($paypal_ipn->paypal_post_vars['business'])) == $paypal_email) && (trim($mc_currency)==$config['mc_currency']) && (trim($mc_gross)-$tax == $quantity*$config['mc_gross']) 
                ) {
 
                $qry="INSERT INTO paypal_table VALUES (0 , '$payer_id', '$payment_date', '$txn_id', '$first_name', '$last_name', '$payer_email', '$payer_status', '$payment_type', '$memo', '$item_name', '$item_number', $quantity, $mc_gross, '$mc_currency', '$address_name', '".nl2br($address_street)."', '$address_city', '$address_state', '$address_zip', '$address_country', '$address_status', '$payer_business_name', '$payment_status', '$pending_reason', '$reason_code', '$txn_type')";
                
                
                if (mysql_query($qry)) {
 
                    $paypal_ipn->error_out("This was a successful transaction", $em_headers);           
                    
                }
                if ($valuebutton = '5') {
                    $qry="UPDATE `users`
                          SET user_money = user_money + 5.00
                          WHERE users.id = $buyer_id";
                }
                if ($valuebutton = '10') {
                    $qry="UPDATE `users`
                          SET user_money = user_money + '10.00'
                          WHERE users.id = $buyer_id";
                }
                if ($valuebutton = '15') {
                    $qry="UPDATE `users`
                          SET user_money = user_money + 15.00
                          WHERE users.id = $buyer_id";
                
 
                } else {
                    $paypal_ipn->error_out("This was a duplicate transaction", $em_headers);
                } 
            } else {
                $paypal_ipn->error_out("Someone attempted a sale using a manipulated URL", $em_headers);
            }
        }
        break;
        
    case 'Failed':
        // this will only happen in case of echeck.
        $paypal_ipn->error_out("Failed Payment", $em_headers);
    break;
 
    case 'Denied':
        // denied payment by us
        $paypal_ipn->error_out("Denied Payment", $em_headers);
    break;
 
    case 'Refunded':
        // payment refunded by us
        $paypal_ipn->error_out("Refunded Payment", $em_headers);
    break;
 
    case 'Canceled':
        // reversal cancelled
        // mark the payment as dispute cancelled        
        $paypal_ipn->error_out("Cancelled reversal", $em_headers);
    break;
 
    default:
        // order is not good
        $paypal_ipn->error_out("Unknown Payment Status - " . $paypal_ipn->get_payment_status(), $em_headers);
    break;
 
} 
 
?>
 
It is around line 82 the broken IF statments do not work. Basically they update the users table depending on which paypal "buy now" button is pressed as the information is posted by form. Then this script will get that POST and know which button was pressed resulting in what query to run on the DB. I tested this by posting back the variables to my email and all was working (results):
valuebutton: 10
userid: 50
So why won't my IF statements work. Some advice would help i have tried a few fixs and got no where.

EDIT: Oh i forgot, the problem is the user table never gets updated. The paypal side of the script fuctions fine.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Find the mistake in my IF statements

Post by requinix »

First problem:

Code: Select all

if ($valuebutton = '5') {
if ($valuebutton = '10') {
if ($valuebutton = '15') {
= is for assignment, == is for comparison.

Second problem: you have the $qry but you never execute it.
synical21
Forum Contributor
Posts: 150
Joined: Tue Jul 28, 2009 8:44 am
Location: London UK

Re: Find the mistake in my IF statements

Post by synical21 »

Ok thanks for the reply, i tried by execute do you mean this?

Code: Select all

 
if ($valuebutton == '5') {
$qry2 = mysql_query("UPDATE `users`
    SET user_money = user_money + 5.00
    WHERE users.id = $buyer_id") or die( mysql_error() );
 
I still got no updated user table so i must be executing it wrong? I changed the $qry variable to qry2 aswell incase it was interfearing with the original $qry
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Find the mistake in my IF statements

Post by iankent »

How are you testing that your script works? I assume you're using the paypal Sandbox? If you're manually submitting values to your script it wont work because the paypal validation will fail.

If you are using sandbox to test it, how are you checking for script errors? am I right in thinking the IPN bit is the script that PayPal requests to confirm a payment was successful? I.e., not a page that the actual 'shopper' gets to see? if so, you wont see your errors where you've used die() unless they're going to your servers error log because its paypal that gets to see the output of the script.

hth

edit: just noticed this bit 'The paypal side of the script fuctions fine.' - do you mean that the paypal notification bit works? if so, thats where you should be updating your database - only when paypal sends confirmation that the payment was genuine and successful should you finally update your main database tables, otherwise your script will add the value to the users account regardless of what paypal says happens.
synical21
Forum Contributor
Posts: 150
Joined: Tue Jul 28, 2009 8:44 am
Location: London UK

Re: Find the mistake in my IF statements

Post by synical21 »

Thanks for the reply, to test the script i use sandbox. This helps test the verification side of the script and successful payments/ errors. As far as the variables i added i change the Buy Now button to send to a webpage instead of paypal so it displays all the variable. Just done another test this morning and "the paypal side" works fine the IPN sends this email:

This was a successful transaction

The following data was received from PayPal:

mc_gross: 10.00
protection_eligibility: Eligible
address_status: confirmed
payer_id: 75XSUG8M7BY5A
tax: 0.00
address_street: 1 Main St
payment_date: 15:48:54 Nov 20, 2009 PST
payment_status: Completed
there is alot more but you get the point it is successful

Also when it is successful the "paypal" table in my DB is updated with all the IPN information. So why does it skip the IF statements if it is inserting into the paypal table

Here is the information being inserted when successful transactiom:

Code: Select all

 
    $qry="INSERT INTO paypal_table VALUES (0 , '$payer_id', '$payment_date', '$txn_id', '$first_name', '$last_name', '$payer_email', '$payer_status', '$payment_type', '$memo', '$item_name', '$item_number', $quantity, $mc_gross, '$mc_currency', '$address_name', '".nl2br($address_street)."', '$address_city', '$address_state', '$address_zip', '$address_country', '$address_status', '$payer_business_name', '$payment_status', '$pending_reason', '$reason_code', '$txn_type')";
                
                
                if (mysql_query($qry)) {
 
                    $paypal_ipn->error_out("This was a successful transaction", $em_headers);           
                    
                    
                }
                if ($valuebutton == '5') {
                    $qry2 = mysql_query("UPDATE `users`
                          SET user_money = user_money + 5.00
                          WHERE users.id = $buyer_id") or die( mysql_error() );
                        
                }
 

then my IF statements follow. Do i need to move the IF statements just under the INSERT query instead of below the error_out?

EDIT: When the verification fails for example a duplicate transaction the paypal table does not update. Which is good, just dont understand your point about always updating the DB
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Find the mistake in my IF statements

Post by iankent »

You can ignore my comment about always inserting. I thought the code you posted originally was part of your UI 'buy' process, not the bit where paypal sends the IPN notification. Was just confused thats all :P

It could be as you say that calling error_out ends the script so possibly its not getting run. You should probably deal with all your database updates first then finally send the successful transaction message at the end.

One thing I'd say is in your IF statements you're only using elseif on the last one. I.e., if $valuebutton is any value other than 15, it will always run the line sending the duplicate error message. Not sure if that's what you wanted to do, and not sure how $valuebutton even determines whether it was a duplicate or not?

Perhaps line 77 - 100 should be more like this:

Code: Select all

 
// first run the insert query but don't send the message
mysql_query($qry);
// check success using mysql_affected_rows
$success = (mysql_affected_rows() > 0) ? true : false;
 
if(!$success) {
    // send the duplicate notice
    $paypal_ipn->error_out("This was a duplicate transaction", $em_headers);
    // possibly exit?
}
 
// check the value of $valuebutton
if ($valuebutton == '5') {
    $qry="UPDATE `users`
        SET user_money = user_money + 5.00
        WHERE users.id = $buyer_id";
    // run the query here
    mysql_query($qry);
}
if ($valuebutton == '10') {
    $qry="UPDATE `users`
        SET user_money = user_money + 10.00
        WHERE users.id = $buyer_id";
    // run the query here
    mysql_query($qry);
}
if ($valuebutton == '15') {
    $qry="UPDATE `users`
        SET user_money = user_money + 15.00
        WHERE users.id = $buyer_id";
    // run the query here
    mysql_query($qry);
}
 
// send the successful notice
$paypal_ipn->error_out("This was a successful transaction", $em_headers);          
 
synical21
Forum Contributor
Posts: 150
Joined: Tue Jul 28, 2009 8:44 am
Location: London UK

Re: Find the mistake in my IF statements

Post by synical21 »

Thanks for the help i will try implement your method now see how i get on. As for the duplicate im confused, $valuebutton does not determine duplicate the paypal server does i believe. I didnt use elseif on the valuebutton == 15. Any way i apreciate the added code ill crack on with it
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Find the mistake in my IF statements

Post by iankent »

I was referring to this bit on your first post:

Code: Select all

 
if (mysql_query($qry)) {
    $paypal_ipn->error_out("This was a successful transaction", $em_headers);                          
}
 
if ($valuebutton = '5') {
    $qry="UPDATE `users`
        SET user_money = user_money + 5.00
        WHERE users.id = $buyer_id";
}
if ($valuebutton = '10') {
    $qry="UPDATE `users`
        SET user_money = user_money + '10.00'
        WHERE users.id = $buyer_id";
}
if ($valuebutton = '15') {
    $qry="UPDATE `users`
        SET user_money = user_money + 15.00
        WHERE users.id = $buyer_id";
} else {
    $paypal_ipn->error_out("This was a duplicate transaction", $em_headers);
} 
 
If you look at that, you'll see that if the value of $valuebutton isn't 15 then it will send the message 'This was a duplicate transaction'. Doesn't matter what else has happened, if $valuebutton != '15', it will always send it.

With the rearranged code in my last post it should avoid that problem. As long as $valuebutton is being set correctly somewhere (i.e., from data coming back from PayPal) then it should work.
synical21
Forum Contributor
Posts: 150
Joined: Tue Jul 28, 2009 8:44 am
Location: London UK

Re: Find the mistake in my IF statements

Post by synical21 »

Oh yes of course my bad i was being blind. Good shout
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Find the mistake in my IF statements

Post by iankent »

one other thing :) you might want to check after updating the users table with the new amount that the update query was successful, i.e. using another mysql_affected_rows().

If it fails, you've written the transaction to the database but failed to update the users table, so somebody has lost out on their transaction. In that scenario you could send a 'Was successful but couldn't update, please contact us' type message

You could even go a step further and add a boolean column on your transactions table to track whether its been successfully added to the users table. If mysql_affected_rows() on the users update query returns 1, mark the column in the transactions table as true. If not, you know the update to the users table failed because the column will remain false. Makes it easier if people email you to say a transaction failed, you know if they're lying or not :P
Post Reply