<?php
### LISTING OF ipn.php
define ("DBHOST", "localhost");
define ("DBNAME", "paypal_tutorial");
define ("DBUSER", "root");
define ("DBPASS", "triadpass");

### CONNECT TO THE DATABASE
function DatabaseConnect() {
    if (!($mylink = mysql_connect(DBHOST, DBUSER, DBPASS))) {
        echo mysql_error();
        exit;
    } //fi
    mysql_select_db(DBNAME) or die(mysql_error());
} // end function

DatabaseConnect(); // this will automatically connect us

// below supported vals that paypal posts to us, this list is exhaustive.. but
// without notify_version and verify_sign NOTE: if in is not in this array, it
// is not going in the database.

$paypal_vals = array("item_name", "receiver_email", "item_number",
    "invoice", "quantity", "custom", "payment_status",
    "pending_reason", "payment_date", "payment_gross", "payment_fee",
    "txn_id", "txn_type", "first_name", "last_name", "address_street",
    "address_city", "address_state", "address_zip", "address_country",
    "address_status", "payer_email", "payer_status", "payment_type",
    "subscr_date", "period1", "period2", "period3", "amount1",
    "amount2", "amount3", "recurring", "reattempt", "retry_at",
    "recur_times", "username", "password", "subscr_id", "option_name1",
    "option_selection1", "option_name2", "option_selection2",
    "num_cart_items"
);

// build insert statement
while (list ($key, $value) = each ($HTTP_POST_VARS)) {
    if (in_array ($key, $paypal_vals)) {
        if (is_numeric($value)) {
            $addtosql .= " $key=$value,";
        } else {
            $newval = urlencode($value);
            $topost .= "&$key=$newval"; //used later in reposting
            $value = addslashes($value);
            $addtosql .= " $key='$value',";
        } //fi
    } //fi
    $entirepost .= "[$key]='$value',";
} //wend

$entirepost = addslashes($entirepost); // just in case..

$addtosql = substr("$addtosql", 0, -1).";"; //chop trailing "," replace with ";"

$sql1 = "
    INSERT INTO accounting_paypal
    SET date=now(), entirepost='$entirepost',". $addtosql;
mysql_db_query(DBNAME, $sql1) or die($sql1);

// We could use this in a log, or to track which users have which payment.
$paypal_id = mysql_insert_id();

if ($HTTP_POST_VARS['payment_status'] == "Completed"
    || $HTTP_POST_VARS['payment_status'] == "Pending")
{
    $username = $HTTP_POST_VARS['payer_email'];
    $sql = "
        UPDATE user
        SET paid = 'Y'
        WHERE username = '$username'
    ";
    $result = mysql_db_query(DBNAME, $sql) or die($sql);
} //fi
### END LISTING OF ipn.php
?>
