Hi

I am trying to get my a paypal system working, where users pay for a product and the information is then stored in a database. I had it working but it has now stopped entering the information into the database and I am not sure why.
One reason I suspect is that I changed .htaccess to always go to http://www. not http:// , can anyone see where this would have affected the script?

It all seems to work when using paypal sandbox etc. all right info and price is there but nothing goes into the db.

I apologise for the lack of line numbers, I seem unable to put these in, can someone tell me how and I will repost?

payments30.php

<?php
// Database variables
$host = ""; //database location
$user = ""; //database username
$pass = ""; //database password
$db_name = ""; //database name

// PayPal settings
$paypal_email = '';
$return_url = 'http://www.example.com/example/payment/payment-successful.php';
$cancel_url = 'http://www.example.com/example/payment/payment-cancelled.php';
$notify_url = 'http://www.example.com/example/payment/payment30.php';

$item_name = 'Featured Listing';
$item_amount = 19.99;

// Include Functions
include("functions.php");

//Database Connection
$link = mysql_connect($host, $user, $pass);
mysql_select_db($db_name);

// Check if paypal request or response
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){

    // Firstly Append paypal account to querystring
    $querystring .= "?business=".urlencode($paypal_email)."&";  

    // Append amount& currency (£) to quersytring so it cannot be edited in html

    //The item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable.
    $querystring .= "item_name=".urlencode($item_name)."&";
    $querystring .= "amount=".urlencode($item_amount)."&";

    //loop for posted values and append to querystring
    foreach($_POST as $key => $value){
        $value = urlencode(stripslashes($value));
        $querystring .= "$key=$value&";
    }

    // Append paypal return addresses
    $querystring .= "return=".urlencode(stripslashes($return_url))."&";
    $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
    $querystring .= "notify_url=".urlencode($notify_url);

    // Append querystring with custom field
    //$querystring .= "&custom=".USERID;

    // Redirect to paypal IPN
    header('location:https://www.sandbox.paypal.com/cgi-bin/webscr'.$querystring);
    exit();

}else{

    // Response from Paypal

    // read the post from PayPal system and add 'cmd'
    $req = 'cmd=_notify-validate';
    foreach ($_POST as $key => $value) {
        $value = urlencode(stripslashes($value));
        $value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}',$value);// IPN fix
        $req .= "&$key=$value";
    }

    // assign posted variables to local variables
    $data['item_name']          = $_POST['item_name'];
    $data['item_number']        = $_POST['item_number'];
    $data['payment_status']     = $_POST['payment_status'];
    $data['payment_amount']     = $_POST['mc_gross'];
    $data['payment_currency']   = $_POST['mc_currency'];
    $data['txn_id']             = $_POST['txn_id'];
    $data['receiver_email']     = $_POST['receiver_email'];
    $data['payer_email']        = $_POST['payer_email'];
    $data['custom']             = $_POST['custom'];

    // 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 ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30); 

    if (!$fp) {
        // HTTP ERROR
    } else {    

        fputs ($fp, $header . $req);
        while (!feof($fp)) {
            $res = fgets ($fp, 1024);
            if (strcmp($res, "VERIFIED") == 0) {

                // Used for debugging
                @mail("", "PAYPAL DEBUGGING", "Verified Response<br />data = <pre>".print_r($post, true)."</pre>");

                // Validate payment (Check unique txnid & correct price)
                $valid_txnid = check_txnid($data['txn_id']);
                $valid_price = check_price($data['payment_amount'], $data['item_number']);
                // PAYMENT VALIDATED & VERIFIED!
                if($valid_txnid && $valid_price){               
                    $orderid = updatePayments($data);       
                    if($orderid){                   
                        echo 'Payment has been made & successfully inserted into the Database';                             
                    }else{                              
                        //Error inserting into DB
                        //E-mail admin or alert user
                    }
                }else{                  
                    //Payment made but data has been changed
                    //E-mail admin or alert user
                }                       

            }else if (strcmp ($res, "INVALID") == 0) {

                //PAYMENT INVALID & INVESTIGATE MANUALY! 
                //E-mail admin or alert user

                @mail("", "PAYPAL DEBUGGING", "Invalid Response<br />data = <pre>".print_r($post, true)."</pre>");
            }       
        }       
    fclose ($fp);
    }   
}
?>

Here is the part I think is most likely affected by htacces:

// 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";

Functions.php

<?php
// functions.php
function check_txnid($tnxid){
    global $link;
    return true;
    $valid_txnid = true;
    //get result set
    $sql = mysql_query("SELECT * FROM `payments` WHERE txnid = '$tnxid'", $link);       
    if($row = mysql_fetch_array($sql)) {
        $valid_txnid = false;
    }
    return $valid_txnid;
}

function check_price($price, $id){
    $valid_price = false;
    //you could use the below to check whether the correct price has been paid for the product

    /* 
    $sql = mysql_query("SELECT amount FROM `products` WHERE id = '$id'");       
    if (mysql_numrows($sql) != 0) {
        while ($row = mysql_fetch_array($sql)) {
            $num = (float)$row['amount'];
            if($num == $price){
                $valid_price = true;
            }
        }
    }
    return $valid_price;
    */
    return true;
}

function updatePayments($data){ 
    global $link;
    if(is_array($data)){                
        $sql = mysql_query("INSERT INTO `payments` (txnid, payment_amount, payment_status, itemid, pdate, createdtime) VALUES (
                '".$data['txn_id']."' ,
                '".$data['payment_amount']."' ,
                '".$data['payment_status']."' ,
                '".$data['item_number']."' ,
'".$data['custom']."' ,
                '".date("Y-m-d H:i:s")."' 
                )", $link);
    return mysql_insert_id($link);
    }
}
?>

But I am not sure if that is the problem, and if it is how to correct it?

I may be completely wrong though and the problem is else where.

Member Avatar for LastMitch

@gilgil2

I had it working but it has now stopped entering the information into the database and I am not sure why.

I am bit confused when you mention that. Did it work right from the start? Did you move your file in a different location?

Did you enable IPN?

When you create a db to store customer info and connect paypal did it work?

When the customer is at the checkout sheet, once they fill everything out and click Submit the data is in the db and also the info appear in the Merchant account.

My question is what changes you made?

Here is a link about paypal notification replace the example you have and used this:

https://github.com/Quixotix/PHP-PayPal-IPN

or you can used paypal samples:

https://www.x.com/developers/paypal/documentation-tools/paypal-code-samples

or you need to a tutorial to example the steps:

http://www.geekality.net/2011/05/28/php-tutorial-paypal-instant-payment-notification-ipn/

Hi, thanks for the reply I haven't moved the file or anything, the only thing I can think of is the htaccess, I haven't disabled IPN, how do I check if it is enabled?

I think the problem must be when Paypal post it back to the notify URL something has gone wrong there, but I don't know what.

Could you explain to me what this part does:

 $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";

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.