RunUO Community

This is a sample guest message. Register a free account today to become a member! Once signed in, you'll be able to participate on this site by adding your own topics and posts, as well as connect with other members through your own private inbox!

[RunUO 2.0] Fully Automated Donation Store System

Vorspire

Knight
And your constructor code could be shortened a line too. =P

Code:
if( user.HasGump(this.GetType()) )
{ user.CloseGump(this.GetType()); }

There is no need to store the type in it's own variable as very few gumps would ever need that bit of code again. But at the same time...depends on the programmer and how they like to read their own code.

Actually, it's not a matter of style, the way I wrote it has efficiency in mind.
Calling GetType once and storing the reference is technically more efficient that calling it twice and creating the Type reference in memory twice.
It's common practice to learn how to cache variables for repetitive use.
 

Pure Insanity

Sorceror
The compiler is smart enough to use the same memory space for the same call twice I'd imagine.

That variable wouldn't really be repetitive use, as it's a type that's already stored as the class type...so I doubt there would be any extra memory overhead. But feel free to test it and prove me wrong.

Although I believe the C# compiler is pretty smart when it comes to stuff like that.
 

Vorspire

Knight
The C# compiler is smart, but no matter the clause, the returning object (Type) from the GetType method would be the same (equal to) every time it is called, but each time it is called, the method generates a new reference in memory, thus ending up with two separate objects that both equal the same Type and Value.
The C# compiler can not guarantee that the same object may be constructed with the exact same members or values and is the reason for which it doesn't cache the return reference for the next call.
Imagine if GetType had to set some sort of underlying property, for example a time-stamp, on the returned Type class, that value is never going to be the same because the compiler will not know until RunTime what that specific value should be. (This doesn't actually happen, it's just an example)
If the compiler behaved any other way, chances are nothing would work properly.

To digress further:
Code:
Account accountA = Accounts.GetAccount( "test" );
Account accountB = Accounts.GetAccount( "test" );

A == B
A_MemoryAddressRange != B_MemoryAddressRange
TotalMemoryUsed = A_MemoryBytes + B_MemoryBytes

t = total memory used.
n = number of concurrent method calls.
oX = object memory address range start
oY = object memory address range end.
oS = object memory address range total.

t = n( oX + oY )
t = n( oS )
 

Nockar

Sorceror
When I complete a transaction in the card and paypal completes it. Nothing seems to be sent to the database. The DB is empty.

I have the correct url path set to donation_paypal_ipn_handler.php in config.php. Have all the correct db info. The usr/pass has access to it.

What am I missing? The transactions from the IPN are not getting added to the database.
 

Vorspire

Knight
When I complete a transaction in the card and paypal completes it. Nothing seems to be sent to the database. The DB is empty.

I have the correct url path set to donation_paypal_ipn_handler.php in config.php. Have all the correct db info. The usr/pass has access to it.

What am I missing? The transactions from the IPN are not getting added to the database.

Does the user account you're using for MySQL have sufficient permissions to access and write data to MySQL?
If yes, check the IPN, it *should* be coded to check against manipulated data like price changes that do not match the price stated in your store (checkout).
It *should* also prevent the transactions being added to the database unless they are 100% "Completed" (see PayPal transaction status codes)

At least this is what my private system does :)

Also, make sure your PayPal account is not limited - If you haven't verified your account, you're limited to 10 transactions per month (IIRC) and this will really inhibit the donation process - only allowing for 10 per month, or (AFAIK) $500 total.
 

Vorspire

Knight
Well, looks like IPN has to be turned on in the paypal account for starters.

You shouldn't have to enablethe IPN in PayPAl - They give you a box you can type one URL into, but I'venever used that box - The PayPal Donate button can include a parameter for the IPN target - If this system doesn't have the IPN target in the button code, then you should reconsider even using this system :)
The IPN box that PayPal provides is more for large companies and fully fledged online stores where they can redirect certain transactions types via a single, complex IPN - To use that space for this system is silly really, but if that's what needs to be done.../sigh
 

Vorspire

Knight
I dont get why this does not work.

Well, my best guess is that it's not connecting to MySQL properly, has insufficient permissions to submit data, or the IPN php file itself is throwing an unhandled exception, in which case, check the directory (where the IPN is) for "error_log" and open it with a text editor.
 

Nockar

Sorceror
When I do the sandbox paypal thing. It puts this in the Invalid Transaction Logs but nothing shows up in the database.
Code:
today: 27/11/2011 16:43:06
item name: something
item number: AK-1234
item amount: 1
: 
custom: xyz123
payment status: Completed
payment amount: 12.34
payment currency: USD
transaction ID: 321128042
receiver email: [email protected]
receiver id: TESTSELLERID1
payer email: [email protected]

Also, all the info i send form the sandbox account shows up in the All Received Requests From PayPal IPN log

When I use a real card and run in through the whole processes. It does the whol paypal thing & donates the money. This gets put in the Invalid Transaction Logs ... Nothing gets put in the database. And then a bunch of giberish gets spit out in the All Received Requests From PayPal IPN log
Code:
Our response packet:
POST /cgi-bin/webscr HTTP/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 20
cmd=_notify-validate
=====================================
today: 27/11/2011 14:27:35
item name: 
item number: 
item amount: 
: 
custom: 
payment status: 
payment amount: 
payment currency: 
transaction ID: 
receiver email: 
receiver id: 
payer email:
 

Nockar

Sorceror
There are no error logs in the IPN directory. The data base user has full permishiosn to do everything.
 

Vorspire

Knight
Looks like global variables are disabled in your PHP configuration, you'll have to enable them, I'm guessing the PHP for this system is pretty much out-dated if this is the case - judging by the fact that invalid log has no actual vars for item name, etc :/
 

Vorspire

Knight
I just looked and global variables are disabled. Can you give me a quick bit of instrucitons on how to change them?

http://wiki.dreamhost.com/Register_globals

You have to change the option in php.ini - It's doubtful you have access to that file if you're using a web-host and don't have root access to the php build yourself.

It's as simple as editing php.ini and setting register_globals to true, it's a big security risk tbh.

The IPN shouldn't even need to use globals as it receives information via the $_POST superglobal, my guess it it uses global in order to load the configuration data, like paypal server etc. - These globals could be converted to constants, or the config could be converted to a static class. PHP 4 supports OOP to an extent, PHP 5.1.3 introduced namespaces and other features AFAIK
 

Nockar

Sorceror
Ya I dont have access to the php.ini file.
I do see $_POST used in there.

My probably is going to be not being able to adintify what is global. If I dont know what is global I cant even begin to think about chaing it.

In donation_paypal_ipn_handler.php .. there are some these (they just happen to say global)... But I would guess that are other things that may be global that I dont know about.
global $today;
global $log;
global $error_log;
global $accepted_currency;
require_once('mysqldb_lib.php');
 

Vorspire

Knight
Yes, they are globals, when the global keyword is used in PHP, it declares the variable and imports the value if it was pre-defined by a script that ran just before it.

PHP is a bit different to C# when it comes to RunTime - PHP executes it's "scripts" one after the other, object variables only become available in a script if the previous script has declared it and assigned a value.

Would you care to post the entire IPN in code tags? I really don't want to download it :p

Yeah, PHPis my second language heh.
 

Nockar

Sorceror
This is it. Figured I might as well just post all the php stuff.

donation_paypal_ipn_handler.php
Code:
<?php

/***************************************************************************
*                      donation_paypal_ipn_handler.php
*                      -------------------------------
*  begin                : Oct 24, 2009
*  copyright            : (C) Antony Ho
*  email                : [email protected]
*  website              : http://antonyho.net/
*
***************************************************************************/
 
// PHP 4.1
require_once('config.php');
$today = date('d/m/Y H:i:s', time());
 
//customize your own handling
function handle_payment($post_data)
{
    global $today;
    global $log;
    global $error_log;
    global $accepted_currency;
    require_once('mysqldb_lib.php');
    //your handling in here.

    /**** record the transaction ****/
    // check the existence of transaction record in our db
    $query = "SELECT 1 FROM paypal_transaction WHERE txn_id='{$post_data['txn_id']}'";
    $result = mysql_query($query);
    if ($result === FALSE)
    {
        //db failure

        if ($error_log_fp = fopen($error_log, 'a+'))
        {
            $error_log_string = "=====================================\n";
            $error_log_string .= "database failure\n";
            $error_log_string .= "transaction id: ".$post_data['txn_id']."\n";
            $error_log_string .= "today: ".$today."\n";
            $error_log_string .= "Error message: ".mysql_error()."\n";
            $error_log_string .= "=====================================\n";
            write_to_log($error_log_fp, $error_log_string);
            fclose($error_log_fp);
        }
        return;
    }

    if (mysql_num_rows($result) > 0)
    {
        //having existing record
        $query = "UPDATE paypal_transaction SET ";

        foreach ($post_data as $field => $value)
        {
            $query .= $field."=";
            if (empty($value))
                $query .= "NULL,";
            else
                $query .= $value.",";
        }
        $query = rtrim($query, ",");
        $query .= " WHERE txn_id='{$post_data['txn_id']}'";

        $result = mysql_query($query);
        if ($result === FALSE || mysql_affected_rows($result) != 1)
        {
            if ($error_log_fp = fopen($error_log, 'a+'))
            {
                $error_log_string = "=====================================\n";
                $error_log_string .= "database [UPDATE] failure\n";
                $error_log_string .= "transaction id: ".$post_data['txn_id']."\n";
                $error_log_string .= "today: ".$today."\n";
                $error_log_string .= "query string: ".$query."\n";
                $error_log_string .= "query succeed?: ".$result."\n";
                $error_log_string .= "affected rows: ".mysql_affected_rows($result)."\n";
                $error_log_string .= "Error message: ".mysql_error()."\n";
                $error_log_string .= "=====================================\n";
                write_to_log($error_log_fp, $error_log_string);
                fclose($error_log_fp);
            }
            return;
        }
    }
    else
    {
        //no existing record
        $query_field_string = "";
        $query_value_string = "";

        /* there are always unknown variables from PayPal IPN response, deprecated implementation
        foreach ($post_data as $field => $value)
        {
            $query_field_string .= $field.",";
            if (empty($value))
                $query_value_string .= "NULL,";
            else
                $query_value_string .= "'".$value."',";
        }
        */
        $result = mysql_query("SHOW COLUMNS FROM paypal_transaction");
        while ($db_fields = mysql_fetch_assoc($result))
        {
            $field_name = $db_fields['Field'];
            $field_type = $db_fields['Type'];
            $query_field_string .= $field.",";
            $response_value = $post_data[trim($field_name)];
            if (empty($response_value))
            {
                if (strpos($field_type, "varchar") === false)
                    $query_value_string .= "'0',";
                else
                    $query_value_string .= "'',";
            }
            else
            {
                $query_value_string .= "'".$response_value."',";
            }
        }

        $query_field_string = rtrim($query_field_string, ",");
        $query_value_string = rtrim($query_value_string, ",");

        $query = "INSERT INTO paypal_transaction ($query_field_string) VALUES ($query_value_string)";
        $result = mysql_query($query);
        if ($result === FALSE)
        {
            if ($error_log_fp = fopen($error_log, 'a+'))
            {
                $error_log_string = "=====================================\n";
                $error_log_string .= "database [INSERT] failure\n";
                $error_log_string .= "transaction id: ".$post_data['txn_id']."\n";
                $error_log_string .= "today: ".$today."\n";
                $error_log_string .= "query string: ".$query."\n";
                $error_log_string .= "Error message: ".mysql_error()."\n";
                $error_log_string .= "=====================================\n";
                write_to_log($error_log_fp, $error_log_string);
                fclose($error_log_fp);
            }
            return;
        }
    }
    mysql_free_result($result);

    // handle complete payment
    if (strcmp(trim($post_data['payment_status']), "Completed") == 0)
    {
        $txn_id = $post_data['txn_id'];
        $account_name = mysql_real_escape_string(trim($post_data['option_selection1']));
        if (empty($account_name))
            $account_name = mysql_real_escape_string(trim($post_data['custom']));
        $item_type_id = trim($post_data['item_number']);
        $item_quantity = trim($post_data['quantity']);

        $payment_amount = trim($post_data['mc_gross']);
        $payment_currency = trim($post_data['mc_currency']);
 
        $result = mysql_query("SELECT price FROM gift_type WHERE type_id='$item_type_id'");
        $row = mysql_fetch_assoc($result);
        $item_price = $row['price'];
        $payment_currency = trim($payment_currency);
        $accepted_currency = trim($accepted_currency);

        if ((strcmp(strtoupper($payment_currency), strtoupper($accepted_currency)) != 0 ) || $payment_amount != ($item_quantity*$item_price))
        {
            if ($error_log_fp = fopen($error_log, 'a+'))
            {
                $error_log_string = "=====================================\n";
                $error_log_string .= "currency or payment amount invalid\n";
                $error_log_string .= "transaction id: ".$txn_id."\n";
                $error_log_string .= "today: ".$today."\n";
                $error_log_string .= "account name: ".$account_name."\n";
                $error_log_string .= "local currency: ".$local_currency."\n";
                $error_log_string .= "IPN currency: ".$payment_currency."\n";
                $error_log_string .= "Payment amount: ".$payment_amount."\n";
                $error_log_string .= "quantity x price: ".$item_quantity." x ".$item_price."\n";
                $error_log_string .= "=====================================\n";
                write_to_log($error_log_fp, $error_log_string);
                fclose($error_log_fp);
            }
            return;
        }

        mysql_free_result($result);
        $check_txn_processed_query = "SELECT create_time FROM paypal_processed_txn WHERE txn_id='$txn_id'";
        $result = mysql_query($check_txn_processed_query);
        if (!$result || mysql_num_rows($result) > 0)
        {
            if ($error_log_fp = fopen($error_log, 'a+'))
            {
                $error_log_string = "=====================================\n";
                if (!result)
                    $error_log_string .= "database query problem[check transaction existence]\n";
                else
                    $error_log_string .= "processed transaction\n";
                $error_log_string .= "transaction id: ".$txn_id."\n";
                $error_log_string .= "today: ".$today."\n";
                $error_log_string .= "account name: ".$account_name."\n";
                if (!$result)
                {
                    $error_log_string .= "dababase query result: ".$result."\n";
                    $error_log_string .= "query: ".$check_txn_processed_query."\n";
                }
                else
                {
                    $row = mysql_fetch_assoc($result);
                    $error_log_string .= "last process time: ".$row['create_time']."\n";
                }
                $error_log_string .= "=====================================\n";
                write_to_log($error_log_fp, $error_log_string);
                fclose($error_log_fp);
            }
            return;
        }

        $now = time();

        mysql_free_result($result);
        $complete_transaction_query = "INSERT INTO paypal_processed_txn (txn_id) VALUES ('$txn_id')";
        $result = mysql_query($complete_transaction_query);
        if (!$result)
        {
            if ($error_log_fp = fopen($error_log, 'a+'))
            {
                $error_log_string = "=====================================\n";
                $error_log_string .= "database query problem[record processed transaction]\n";
                $error_log_string .= "transaction id: ".$txn_id."\n";
                $error_log_string .= "today: ".$today."\n";
                $error_log_string .= "account name: ".$account_name."\n";
                $error_log_string .= "query: ".$complete_transaction_query."\n";
                $error_log_string .= "Error message: ".mysql_error()."\n";
                $error_log_string .= "=====================================\n";
                write_to_log($error_log_fp, $error_log_string);
                fclose($error_log_fp);
            }
            return;
        }

        mysql_free_result($result);
        $add_gift_query = "INSERT INTO redeemable_gift (type_id,account_name,donate_time,paypal_txn_id) VALUES ('$item_type_id','$account_name','$now','$txn_id')";
        for ($i = 0; $i < $item_quantity; $i++)
        {
            mysql_free_result($result);
            $result = mysql_query($add_gift_query);
            if ($result === false)
            {
                if ($error_log_fp = fopen($error_log, 'a+'))
                {
                    $error_log_string = "=====================================\n";
                    $error_log_string .= "unable to insert all item into db\n";
                    $error_log_string .= "transaction id: ".$txn_id."\n";
                    $error_log_string .= "today: ".$today."\n";
                    $error_log_string .= "account name: ".$account_name."\n";
                    $error_log_string .= "total redeemable gift: ".$item_quantity."\n";
                    $error_log_string .= "inserted number of gift: ".($i+1)."\n";
                    $error_log_string .= "Error message: ".mysql_error()."\n";
                    $error_log_string .= "=====================================\n";
                    write_to_log($error_log_fp, $error_log_string);
                    fclose($error_log_fp);
                }
                break;
            }
        }
    }
}
   
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
 
foreach ($_POST as $key => $value)
{
    $value = urlencode(stripslashes($value));
    $req .= "&$key=$value";
}

if (!function_exists('apache_request_headers'))
{
    eval('
        function apache_request_headers()
        {
            foreach($_SERVER as $key=>$value)
            {
                if (substr($key,0,5)=="HTTP_")
                {
                    $key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
                    $out[$key]=$value;
                }
            }
            return $out;
        }
    ');
}

$headers = apache_request_headers();

if ($request_log_fp = fopen($request_log, 'a+'))
{
    $request_log_string = "=====================================\n";
    $request_log_string .= "[HEADERS]\n";
    foreach ($headers as $key => $value)
        $request_log_string .= $key.": ".$value."\n";

    $request_log_string .= "=====================================\n";
    $request_log_string .= "[DATA]\n";
    foreach ($_POST as $key => $value)
        $request_log_string .= $key.": ".$value."\n";

    $request_log_string .= "=====================================\n";
    write_to_log($request_log_fp, $request_log_string);
    fclose($request_log_fp);
}

// 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 ($paypal_ipn_resp_addr, 443, $errno, $errstr, 30);

// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$item_amount = $_POST['quantity'];
$option_name1 = $_POST['option_name1'];        //we use this as game account name information
$custom = $_POST['custom'];                //we use this as alternative game account name information
$option_value1 = $_POST['option_selection1'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$receiver_id = $_POST['receiver_id'];
$payer_email = $_POST['payer_email'];

if (!$fp)
{
    // HTTP ERROR

    if ($log_fp = fopen($log, 'a+'))
    {
        write_to_log($log_fp, "=====================================\n".$today."\n".$header.$req."\n"."=====================================\n");
        fclose($log_fp);
    }
}
else
{
    $log_string = "=====================================\n";
    $log_string .= "today: ".$today."\n";
    $log_string .= "item name: ".$item_name."\n";
    $log_string .= "item number: ".$item_number."\n";
    $log_string .= "item amount: ".$item_amount."\n";
    $log_string .= $option_name1.": ".$option_value1."\n";
    $log_string .= "custom: ".$custom."\n";
    $log_string .= "payment status: ".$payment_status."\n";
    $log_string .= "payment amount: ".$payment_amount."\n";
    $log_string .= "payment currency: ".$payment_currency."\n";
    $log_string .= "transaction ID: ".$txn_id."\n";
    $log_string .= "receiver email: ".$receiver_email."\n";
    $log_string .= "receiver id: " .$receiver_id."\n";
    $log_string .= "payer email: ".$payer_email."\n";
    $log_string .= "=====================================\n";

    fputs ($fp, $header . $req);
    while (!feof($fp))
    {
        $res = fgets ($fp, 1024);
        if (strcmp ($res, "VERIFIED") == 0)
        {
            // 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
            if ($log_fp = fopen($log, 'a+'))
            {
                write_to_log($log_fp, $log_string);
                fclose($log_fp);
            }

            if ((strcmp($receiver_email, $my_email) !== 0) || (strcmp($receiver_id, $my_merchant_id) !== 0))
            {
                if ($invalid_txn_log_fp = fopen($invalid_txn_log, 'a+'))
                {
                    $invalid_log_string = "===============================================\n";
                    $invalid_log_string .= "Transaction ID: ".$txn_id."\n";
                    $invalid_log_string .= "Date: ".$today."\n";
                    $invalid_log_string .= "invalid email. transaction rejected\n";
                    $invalid_log_string .= "IPN receiver email: ".$receiver_email."\n";
                    $invalid_log_string .= "Our email: ".$my_email."\n";
                    $invalid_log_string .= "IPN receiver ID: ".$receiver_id."\n";
                    $invalid_log_string .= "Our merchant ID: ".$my_merchant_id."\n";
                    $invalid_log_string .= "===============================================\n";
                    write_to_log($invalid_txn_log_fp, $invalid_log_string);
                    fclose($invalid_txn_log_fp);
                    fclose($fp);
                }
                return;
            }

            $accepted_currency = $local_currency;

            handle_payment($_POST);
        }
        else if (strcmp ($res, "INVALID") == 0)
        {
            // log for manual investigation
            if ($invalid_txn_log_fp = fopen($invalid_txn_log, 'a+'))
            {
                $our_ipn_response = $header.$req;
                $invalid_log_string = "===============================================\n";
                $invalid_log_string .= "Our response packet:\n";
                $invalid_log_string .= $our_ipn_response."\n";
                $invalid_log_string .= $log_string;
                $invalid_log_string .= "===============================================\n";
                write_to_log($invalid_txn_log_fp, $invalid_log_string);
                fclose($invalid_txn_log_fp);
            }
        }
    }
    fclose ($fp);
}
 
function write_to_log($fd, $string)
{
    for ($written = 0; $written < strlen($string); $written += $fwrite)
    {
        $fwrite = fwrite($fd, substr($string, $written));
        if (!$fwrite)
            return $written;
    }
    return $written;
}
?>

get_button_code.php
Code:
<?php
session_start();
if (isset($_SESSION['login_succeed']) && $_SESSION['login_succeed'] === true)
{
 $id = $_GET['id'];
 $name = $_GET['name'];
 $price = $_GET['price'];
 
 if (!(empty($id) || empty($name) || empty($price)))
 {
  require_once('config.php');
  $pp_uri = str_replace("ssl", "http", $paypal_ipn_resp_addr)."/cgi-bin/webscr";
 }
}
$temp = "<form action='$pp_uri' method='post'>
<!-- Identify your business so that you can collect the payments. -->
<input type='hidden' name='business' value='$my_merchant_id'>
<!-- Specify a Donate button. -->
<input type='hidden' name='cmd' value='_xclick'>
<!-- Specify details about the contribution -->
<input type='hidden' name='item_name' value='$name'>
<input type='hidden' name='item_number' value='$id'>
<input type='hidden' name='amount' value='$price'>
<input type='hidden' name='undefined_quantity' value='1'>
<input type='hidden' name='currency_code' value='$local_currency'>
<input type='hidden' name='tax' value='0'>
<input type='hidden' name='no_shipping' value='1'>
<input type='hidden' name='notify_url' value='$ipn_handler_url'>
Game account name: <input type='text' name='custom'><strong><font style='color: red;'>Remeber to fill your account name here!</font></strong><br/>
<!-- Display the payment button. -->
<input type='image' name='submit' border='0' src='https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif' alt='PayPal - The safer, easier way to pay online'>
<img alt='' border='0' width='1' height='1' src='https://www.paypal.com/en_US/i/scr/pixel.gif' >
</form>";
$output = htmlspecialchars($temp);
?>
<?php echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; ?>
<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "[URL]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd[/URL]">
<html xmlns="[URL]http://www.w3.org/1999/xhtml[/URL]" xml:lang="en">
 <head>
  <title>Donation Gift Button PayPal HTML Code</title>
 </head>
 <body>
  Copy the HTML code below:<br/>
  <textarea cols="80" rows="20" onclick="select()" readonly><?php print($output); ?></textarea>
 </body>
</html>

mysqldb_lib.php
Code:
<?php
/******
* MySQL connection library
******/
 require_once('config.php');
 
 function connect_mysql()
 {
  $database = mysql_connect(DB_HOST,DB_USER,DB_PASS) or die();
  mysql_select_db(DB_NAME, $database);
   
  return $database;
 }
 
 if (!$database) {
  $database = connect_mysql();
 }
?>

config.php
Code:
<?php
/*** MYSQL DATABASE SETTINGS ***/
//IP or domain name of your MySQL host
define("DB_HOST","mysql.site.com");
//The database name which we are using
define("DB_NAME","sitename");
//user that can access to your MySQL database, be careful that this account should be CREATE TABLE privilege
define("DB_USER","sqluser");
//password
define("DB_PASS","pass");


/*** ADMIN PANEL SETTINGS ***/
//administrator login name
define("ADMIN_USER","user");
//password
define("ADMIN_PASS","pass");

/*** PAYPAL IPN SETTINGS ***/
//your email account for PayPal
$my_email = [EMAIL]'[email protected]'[/EMAIL];
//your PayPal merchant ID
$my_merchant_id = '1231231231';
//The currency of donation
$local_currency = "USD";
//IPN handler URL, modify the domain name and the directory path to suit your site
$ipn_handler_url = "[URL]http://www.site.com/donation_paypal_ipn_handler.php[/URL]";
// do not edit below URL if you don't know what it is doing
$paypal_ipn_resp_addr = 'ssl://www.paypal.com';
//$paypal_ipn_resp_addr = 'ssl://www.sandbox.paypal.com'; /** for testing purpose **/
//logs file location of your webserver
$request_log = $_SERVER['DOCUMENT_ROOT'].'/logs/paypal_request.log';
$log = $_SERVER['DOCUMENT_ROOT'].'/logs/donation_paypal.log';
$error_log = $_SERVER['DOCUMENT_ROOT'].'/logs/donation_paypal_error.log';
$invalid_txn_log = $_SERVER['DOCUMENT_ROOT'].'/logs/donation_paypal_invalid_txn.log';
?>

adminpage.php
Code:
<?php
session_start();
if ($_GET['logout'] == 1)
 session_destroy();
require_once('admin_util.php');
if (isset($_SESSION['login_succeed']) && $_SESSION['login_succeed'] === true)
{
 //todo: options
 //add donation items
 //view transactions in database
 //view logs
 $output = "<a href=\"#info\" onclick=\"load('admin_ops.php?t=1')\">Add donation items</a><br/>";
 $output .= "<a href=\"#info\" onclick=\"load('admin_ops.php?t=4')\">Remove donation items</a><br/>";
 $output .= "<a href=\"#info\" onclick=\"load('admin_ops.php?t=2')\">View all transactions in database</a><br/>";
 $output .= "<a href=\"#info\" onclick=\"load('admin_ops.php?t=3')\">View all logs</a><br/>";
 $output .= "<a href=\"#info\" onclick=\"load('admin_ops.php?t=5')\">Get donation buttons HTML code</a><br/>";
 $output .= "<a href=\"#info\" onclick=\"load('admin_ops.php?t=6')\">Manual add gift to account</a><br/>";
 $output .= "<a href=\"adminpage.php?logout=1\">Logout</a><br/>";
}
else
{
 if (isset($_POST['username']) && isset($_POST['password']))
 {
  admin_login($_POST['username'], $_POST['password']);
  header("Location: adminpage.php");
  return;
 }
 else
 {
  $output = "<form method=\"POST\" action=\"adminpage.php\">";
  $output .= "Username: <input type=\"text\" name=\"username\" /><br/>";
  $output .= "Password: <input type=\"password\" name=\"password\" /><br/>";
  $output .= "<input type=\"submit\" value=\"Login\" />";
  $output .= "</form>";
 }
}
?>
<?php echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; ?>
<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "[URL]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd[/URL]">
<html xmlns="[URL]http://www.w3.org/1999/xhtml[/URL]" xml:lang="en">
 <head>
  <title>Donation Store Back-office</title>
  <script type="text/javascript">
   function GetXmlHttpObject()
   {
    if (window.XMLHttpRequest)
    {
     // code for IE7+, Firefox, Chrome, Opera, Safari
     return new XMLHttpRequest();
    }
    if (window.ActiveXObject)
    {
     // code for IE6, IE5
     return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
   }
   
   function load(uri)
   {
    xmlhttp = GetXmlHttpObject();
    if (xmlhttp == null)
     alert("Your browser does not support XMLHTTP!");
    xmlhttp.onreadystatechange = loading;
    xmlhttp.open("GET", uri, true);
    xmlhttp.send();
   }
   
   function submitForm(formId,uri)
   {
    xmlhttp = GetXmlHttpObject();
    if (xmlhttp == null)
    {
     alert("Your browser does not support XMLHTTP!");
    }
    var form = document.getElementById(formId);
    var inputs = form.getElementsByTagName("input");
    var post_value = "";
    var i;
    for (i in inputs) {
     post_value += inputs[i].name + "=" + inputs[i].value + "&";
    }
    var selects = form.getElementsByTagName("select");
    for (j in selects)
    {
     post_value += selects[j].name + "=" + selects[j].value + "&";
    }
    xmlhttp.onreadystatechange = loading;
    xmlhttp.open("POST", uri, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", post_value.length);
    xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.send( post_value );
   }
   
   function loading()
   {
    var targ_div = document.getElementById("lower");
    if ( xmlhttp.readyState < 4 )
     targ_div.innerHTML = "Loading...";
    else if ( (xmlhttp.readyState == 4) && (xmlhttp.status == 200) )
     targ_div.innerHTML = xmlhttp.responseText;
   }
  </script>
 </head>
 <body>
  <div style="width: 100%; height: 100%;" id="outter">
   <div style="border: solid 2px; padding: 10px;" id="upper">
    <?php print($output); ?>
   </div>
   <a name="info">
   <div style="border: solid 2px; padding: 10px;" id="lower">
   </div>
   </a>
  </div>
 </body>
</html>

admin_util.php
Code:
<?php
session_start();
//shows all the transaction response from IPN in a table
function query_to_table($query)
{
 require_once('mysqldb_lib.php');
 
 $result = mysql_query($query);
 
 $table = "<table border=\"1\">\n";
 $table_header = "<tr>";
 for ($i = 0; $i < mysql_num_fields($result); $i++)
 {
  $meta = mysql_fetch_field($result, $i);
  $table_header .= "<th>".$meta->name."</th>";
 }
 $table_header .= "</tr>\n";
 
 $table_rows = "";
 while ($row = mysql_fetch_assoc($result))
 {
  $table_rows .= "<tr>";
  foreach($row as $field_value)
  {
   $table_rows .= "<td>$field_value</td>";
  }
  $table_rows .= "</tr>\n";
 }
 $table .= $table_header.$table_rows;
 $table .= "</table>\n";
 
 return $table;
}
function add_new_gift($name, $class_name, $price)
{
 require_once('mysqldb_lib.php');
 
 $query = "INSERT INTO gift_type (type_name,class_name,price) VALUES ('$name','$class_name','$price')";
 
 return mysql_query($query);
}
function remove_gift($id)
{
 require_once('mysqldb_lib.php');
 
 $query = "DELETE FROM gift_type WHERE type_id='$id'";
 
 return mysql_query($query);
}
function get_gift_code_table()
{
 require_once('mysqldb_lib.php');
 
 $query = "SELECT * FROM gift_type";
 
 $result = mysql_query($query);
 
 $table = "<table border=\"1\">\n";
 $table_header = "<tr>";
 for ($i = 0; $i < mysql_num_fields($result); $i++)
 {
  $meta = mysql_fetch_field($result, $i);
  $table_header .= "<th>".$meta->name."</th>";
 }
 $table_header .= "<th>Get Code</th>";
 $table_header .= "</tr>\n";
 
 $table_rows = "";
 while ($row = mysql_fetch_assoc($result))
 {
  $table_rows .= "<tr>";
  foreach($row as $field_value)
  {
   $table_rows .= "<td>$field_value</td>";
  }
  $table_rows .= "<td><a href=\"get_button_code.php?id={$row['type_id']}&name={$row['type_name']}&price={$row['price']}\" target=\"_blank\">[Get]</a></td>";
  $table_rows .= "</tr>\n";
 }
 $table .= $table_header.$table_rows;
 $table .= "</table>\n";
 
 return $table;
}
function manual_add_gift($type_id, $account_name, $quantity)
{
 require_once('mysqldb_lib.php');
 
 $now = time();
 $query = "INSERT INTO redeemable_gift (type_id,account_name,donate_time,paypal_txn_id) VALUES ('$type_id','$account_name','$now','0000000000')";  // use 0000000000 as manual added gifts
 for ($i=0; $i < $quantity; $i++)
 {
  mysql_query($query);
 }
}
function get_gift_types()
{
 require_once('mysqldb_lib.php');
 
 $query = "SELECT type_id, type_name FROM gift_type";
 $result = mysql_query($query);
 $gift_types = array();
 while ($row = mysql_fetch_assoc($result))
  array_push($gift_types, $row);
 
 return $gift_types;
}
function admin_login($username, $password)
{
 require_once('config.php');
 
 if (strcmp($username, ADMIN_USER) === 0 && strcmp($password, ADMIN_PASS) === 0)
 {
  $_SESSION['login_succeed'] = true;
 }
 else
 {
  $_SESSION['login_succeed'] = false;
 }
}
?>

admin_ops.php
Code:
<?php
session_start();
//shows all the transaction response from IPN in a table
function query_to_table($query)
{
 require_once('mysqldb_lib.php');
 
 $result = mysql_query($query);
 
 $table = "<table border=\"1\">\n";
 $table_header = "<tr>";
 for ($i = 0; $i < mysql_num_fields($result); $i++)
 {
  $meta = mysql_fetch_field($result, $i);
  $table_header .= "<th>".$meta->name."</th>";
 }
 $table_header .= "</tr>\n";
 
 $table_rows = "";
 while ($row = mysql_fetch_assoc($result))
 {
  $table_rows .= "<tr>";
  foreach($row as $field_value)
  {
   $table_rows .= "<td>$field_value</td>";
  }
  $table_rows .= "</tr>\n";
 }
 $table .= $table_header.$table_rows;
 $table .= "</table>\n";
 
 return $table;
}
function add_new_gift($name, $class_name, $price)
{
 require_once('mysqldb_lib.php');
 
 $query = "INSERT INTO gift_type (type_name,class_name,price) VALUES ('$name','$class_name','$price')";
 
 return mysql_query($query);
}
function remove_gift($id)
{
 require_once('mysqldb_lib.php');
 
 $query = "DELETE FROM gift_type WHERE type_id='$id'";
 
 return mysql_query($query);
}
function get_gift_code_table()
{
 require_once('mysqldb_lib.php');
 
 $query = "SELECT * FROM gift_type";
 
 $result = mysql_query($query);
 
 $table = "<table border=\"1\">\n";
 $table_header = "<tr>";
 for ($i = 0; $i < mysql_num_fields($result); $i++)
 {
  $meta = mysql_fetch_field($result, $i);
  $table_header .= "<th>".$meta->name."</th>";
 }
 $table_header .= "<th>Get Code</th>";
 $table_header .= "</tr>\n";
 
 $table_rows = "";
 while ($row = mysql_fetch_assoc($result))
 {
  $table_rows .= "<tr>";
  foreach($row as $field_value)
  {
   $table_rows .= "<td>$field_value</td>";
  }
  $table_rows .= "<td><a href=\"get_button_code.php?id={$row['type_id']}&name={$row['type_name']}&price={$row['price']}\" target=\"_blank\">[Get]</a></td>";
  $table_rows .= "</tr>\n";
 }
 $table .= $table_header.$table_rows;
 $table .= "</table>\n";
 
 return $table;
}
function manual_add_gift($type_id, $account_name, $quantity)
{
 require_once('mysqldb_lib.php');
 
 $now = time();
 $query = "INSERT INTO redeemable_gift (type_id,account_name,donate_time,paypal_txn_id) VALUES ('$type_id','$account_name','$now','0000000000')";  // use 0000000000 as manual added gifts
 for ($i=0; $i < $quantity; $i++)
 {
  mysql_query($query);
 }
}
function get_gift_types()
{
 require_once('mysqldb_lib.php');
 
 $query = "SELECT type_id, type_name FROM gift_type";
 $result = mysql_query($query);
 $gift_types = array();
 while ($row = mysql_fetch_assoc($result))
  array_push($gift_types, $row);
 
 return $gift_types;
}
function admin_login($username, $password)
{
 require_once('config.php');
 
 if (strcmp($username, ADMIN_USER) === 0 && strcmp($password, ADMIN_PASS) === 0)
 {
  $_SESSION['login_succeed'] = true;
 }
 else
 {
  $_SESSION['login_succeed'] = false;
 }
}
?>
 

Vorspire

Knight
PHP:
/*** PAYPAL IPN SETTINGS ***/
//your email account for PayPal
$my_email = '[email protected]';

//your PayPal merchant ID
$my_merchant_id = '1231231231';

//The currency of donation
$local_currency = "USD";

//IPN handler URL, modify the domain name and the directory path to suit your site
$ipn_handler_url = "http://www.site.com/donation_paypal_ipn_handler.php";

// do not edit below URL if you don't know what it is doing
$paypal_ipn_resp_addr = 'ssl://www.paypal.com';
//$paypal_ipn_resp_addr = 'ssl://www.sandbox.paypal.com'; /** for testing purpose **/

//logs file location of your webserver
$request_log = $_SERVER['DOCUMENT_ROOT'].'/logs/paypal_request.log';
$log = $_SERVER['DOCUMENT_ROOT'].'/logs/donation_paypal.log';
$error_log = $_SERVER['DOCUMENT_ROOT'].'/logs/donation_paypal_error.log';
$invalid_txn_log = $_SERVER['DOCUMENT_ROOT'].'/logs/donation_paypal_invalid_txn.log';

All of that stuff sets the globals used in the rest of the scripts, the task ahead is not an easy one.
For the sake of simplicity, you should convert all of those vars to constants, like all of the settings above this code.

$my_email
define("MY_EMAIL", "[email protected]");

The for every instance of
$my_email
replace it exactly with
MY_EMAIL
except when the reference is
global $my_email

Rinse and repeat for all global vars.
When you're done, remove the references declared with the "global" keyword and you should be good to go.

The most secure method would be to use a static class to store the config, but that be perplexing if you're new to PHP.

Also, in the IPN, this line:
$today = date('d/m/Y H:i:s', time());
Just move the value to inside the PHP function where "global" $today is declared, and remove the global keyword.
 
Top