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

Nockar

Sorceror
Am I going to need to change any of hte database tables names?

what do I do again with the "global" keyword ones?
 

Nockar

Sorceror
is this corect?

$request_log = $_SERVER['DOCUMENT_ROOT'].'/logs/paypal_request.log';
to this
define("REGUEST_LOG","$_SERVER['DOCUMENT_ROOT'].'/logs/paypal_request.log'");
 

Nockar

Sorceror
is this corect?

Code:
// PHP 4.1
require_once('config.php');

//customize your own handling
function handle_payment($post_data)
{
    $today = date('d/m/Y H:i:s', time());

    $today;
    $LOG;
    $ERROR_LOG;
    $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);
 

Nockar

Sorceror
This compiles. But the logs do not show up... harm..
Code:
//logs file location of your webserver
//$request_log = $_SERVER['DOCUMENT_ROOT'].'/logs/paypal_request.log';
define("REGUEST_LOG",$_SERVER["DOCUMENT_ROOT"]."/logs/paypal_request.log");
 
//$log = $_SERVER['DOCUMENT_ROOT'].'/logs/donation_paypal.log';
define("LOG",$_SERVER["DOCUMENT_ROOT"]."/logs/donation_paypal.log");
  
//$error_log = $_SERVER['DOCUMENT_ROOT'].'/logs/donation_paypal_error.log';
define("ERROR_LOG",$_SERVER["DOCUMENT_ROOT"]."/logs/donation_paypal_error.log");
 
//$invalid_txn_log = $_SERVER['DOCUMENT_ROOT'].'/logs/donation_paypal_invalid_txn.log';
define("INVALID_TXN_LOG",$_SERVER["DOCUMENT_ROOT"]."/logs/donation_paypal_invalid_txn.log");
 

Nockar

Sorceror
C:\Users\admin\Desktop\Donatin

Line 303: if ($REGUEST_LOG_fp = fopen($REGUEST_LOG, 'a+'))

Code:
Warning: fopen() [function.fopen]: Filename cannot be empty in /home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php on line 303
 
Warning: fsockopen() [function.fsockopen]: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php on line 324
 
Warning: fsockopen() [function.fsockopen]: unable to connect to :443 (php_network_getaddresses: getaddrinfo failed: Name or service not known) in /home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php on line 324
 
Warning: fopen() [function.fopen]: Filename cannot be empty in /home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php on line 345
 

Vorspire

Knight
Be careful if you're doing a mass rename:

PHP:
if ($reguest_log_fp = fopen(REGUEST_LOG, 'a+'))

Mke sure your constant variables don't have an $ prefixed - the above line has a $reguest_log_fp - don't change that one, it's the variable representing the file pointer.
 

Nockar

Sorceror
Hm. I tried getting rid of the $ and it added another error.

donation_paypal_ipn_handler.php
Code:
<?php

/***************************************************************************
*                      donation_paypal_ipn_handler.php
*                      -------------------------------
*  begin                : Oct 24, 2009
*  copyright            : (C) Antony Ho
*  email                : ntonyworksho[email protected]
*  website              : http://antonyho.net/
*
***************************************************************************/
 
// PHP 4.1
require_once('config.php');

//customize your own handling
function handle_payment($post_data)
{
    $today = date('d/m/Y H:i:s', time());

        $TODAY;
        $LOG;
        $ERROR_LOG;
        $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 ($reguest_log_fp = fopen($REGUEST_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_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;
}
?>

Code:
[B]Warning[/B]: fopen() [[URL='http://www.runuo.com/community/function.fopen'][U][COLOR=#000080]function.fopen[/COLOR][/U][/URL]]: Filename cannot be empty in [B]/home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php[/B] on line [B]303[/B]

[B]Warning[/B]: fsockopen() [[URL='http://www.runuo.com/community/function.fsockopen'][U][COLOR=#000080]function.fsockopen[/COLOR][/U][/URL]]: php_network_getaddresses: getaddrinfo failed: Name or service not known in [B]/home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php[/B] on line [B]324[/B]

[B]Warning[/B]: fsockopen() [[URL='http://www.runuo.com/community/function.fsockopen'][U][COLOR=#000080]function.fsockopen[/COLOR][/U][/URL]]: unable to connect to :443 (php_network_getaddresses: getaddrinfo failed: Name or service not known) in [B]/home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php[/B] on line [B]324[/B]

[B]Warning[/B]: fopen() [[URL='http://www.runuo.com/community/function.fopen'][U][COLOR=#000080]function.fopen[/COLOR][/U][/URL]]: Filename cannot be empty in [B]/home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php[/B] on line [B]345[/B]
 

Vorspire

Knight
It wasn't just for that variable, you did the same for them all, the have $ prefixed when they shouldn't - try to apply C# code logic to PHP and you'll understand and don't do global renames unless you test the rename first :)
If you noticed I said "rename it exactly like this" hehe
 

Nockar

Sorceror
ok. I think I fixed all thoes. I can see the logs now and all that. getting smoething new here.

Code:
<?php
/***************************************************************************
 *                       donation_paypal_ipn_handler.php
 *                       -------------------------------
 *   begin                : Oct 24, 2009
 *   copyright            : (C) Antony Ho
 *   email                : [EMAIL][email protected][/EMAIL]
 *   website              : [URL]http://antonyho.net/[/URL]
 *
 ***************************************************************************/

// PHP 4.1
require_once('config.php');
//customize your own handling
function handle_payment($post_data)
{
 $today = date('d/m/Y H:i:s', time());
  $TODAY;
  $LOG;
  $ERROR_LOG;
  $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 ($reguest_log_fp = fopen(REGUEST_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_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;
}
?>

Code:
[B]Warning[/B]: fwrite(): supplied argument is not a valid stream resource in [B]/home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php[/B] on line [B]434[/B]

[B]Warning[/B]: fclose(): supplied argument is not a valid stream resource in [B]/home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php[/B] on line [B]317[/B]

[B]Warning[/B]: fsockopen() [[URL='http://www.runuo.com/community/function.fsockopen'][U][COLOR=#000080]function.fsockopen[/COLOR][/U][/URL]]: php_network_getaddresses: getaddrinfo failed: Name or service not known in [B]/home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php[/B] on line [B]324[/B]

[B]Warning[/B]: fsockopen() [[URL='http://www.runuo.com/community/function.fsockopen'][U][COLOR=#000080]function.fsockopen[/COLOR][/U][/URL]]: unable to connect to :443 (php_network_getaddresses: getaddrinfo failed: Name or service not known) in [B]/home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php[/B] on line [B]324[/B]
 

Vorspire

Knight
PHP:
$fp = fsockopen ($paypal_ipn_addr, 443, $errno, $errstr, 30);

$paypal_ipn_addr doesn't exist, I'm guessing that needs changed to a constant in the config too (if you missed it) and you'll have to update it like all the others - not sure about the file write errors though, but PHP's funny, you can fix one error ad the rest will fix themselves :) You're almost there though.

That IPN is about 200 lines longer than it needs to be too :p I know PHP and I know that this code is way beyond standards required for PHP these days.
I'd actually re-write it for you, but the code is far too gone for my tired eyes :(
 

Nockar

Sorceror
The only place $paypal_ipn_addr is found is in that one line in donation_paypal_ipn_handler.php. Its not anywhere else (never was in the config file).
would this make it a constanty? Puting this in the config file.
define("PAYPAL_IPN_ADDR");
 

Vorspire

Knight
The only place $paypal_ipn_addr is found is in that one line in donation_paypal_ipn_handler.php. Its not anywhere else (never was in the config file).
would this make it a constanty? Puting this in the config file.
define("PAYPAL_IPN_ADDR");

Yeah I'm surprised this thing works at all tbh.
Yes, define(); will make variables constant and available in the global scope.
If you define it, don't forget to change the name of the variable reference too, don't forge that define(); takes 2 arguments.
 

Nockar

Sorceror
k. let me go do that and give it a try

for all the other variables that are not defiend. do i need to do the same thing?
 

Vorspire

Knight
Yeah, or you'll be chasing errors all day :) - you don't need to change variables that are declared inside of functions though, they should work fine.
 

Nockar

Sorceror
Well, in the config I added
define("FD");
define("REQUEST_LOG_FP");
define("PAYPAL_IPN_ADDR");

Line 430: function write_to_log(FD, $string)


Code:
<?php
/***************************************************************************
*                      donation_paypal_ipn_handler.php
*                      -------------------------------
*  begin                : Oct 24, 2009
*  copyright            : (C) Antony Ho
*  email                : [EMAIL][email protected][/EMAIL]
*  website              : [URL]http://antonyho.net/[/URL]
*
***************************************************************************/

// PHP 4.1
require_once('config.php');
//customize your own handling
function handle_payment($post_data)
{
$today = date('d/m/Y H:i:s', time());
  $TODAY;
  $LOG;
  $ERROR_LOG;
  $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 ($reguest_log_fp = fopen(REGUEST_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_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;
}
?>

Code:
[B]Parse error[/B]: syntax error, unexpected ',', expecting '&' or T_VARIABLE in [B]/home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php[/B] on line [B]430[/B]
 

Vorspire

Knight
FD
and *_FP

- They represent file pointers, they can't be constants.

PHP:
function write_to_log(FD, $string)

//A function is the same as a method in C#, $fd and $string are parameter arguments.
function write_to_log($fd, $string)

//It would probably look like this in C#:
public void WriteToLog(Stream file, string line)
- Don't forget to fix al the instanced of FD to $fd too, make sureal of the *_FP instances are fixed too, they also don't need to be constants, they are file pointers.

Define takes two arguments, it's a Key<>Value function.
Actually, define can also be done like this, if it's easier to relate to C#..
PHP:
define( "MY_VAR_NAME", "a value" );

//Is the same as:
const MY_VAR_NAME = "a value";

Constants in PHP are global variables that can not be changed, they are read-only.
$vars in PHP are local variables, they can represent pretty much anything.

PHP is not a strongly-typed language like C#, where everything must be type-defined - an $var can represent a primitive data type (int, string, bool), custom class, stream (file pointer or connection) or delegate (anonymous function).
 

Nockar

Sorceror
I think that makes sence. Thanks for the info!

I changed back
FD to $fd
REQUEST_LOG_FP to $request_log_fp

Code:
<?php
/***************************************************************************
 *                       donation_paypal_ipn_handler.php
 *                       -------------------------------
 *   begin                : Oct 24, 2009
 *   copyright            : (C) Antony Ho
 *   email                : [EMAIL][email protected][/EMAIL]
 *   website              : [URL]http://antonyho.net/[/URL]
 *
 ***************************************************************************/

// PHP 4.1
require_once('config.php');
//customize your own handling
function handle_payment($post_data)
{
 $today = date('d/m/Y H:i:s', time());
  $TODAY;
  $LOG;
  $ERROR_LOG;
  $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 ($reguest_log_fp = fopen(REGUEST_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_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;
}
?>

Code:
[B]Warning[/B]: define() expects at least 2 parameters, 1 given in [B]/home/uorpsite/uoroleplay.com/web/config.php[/B] on line [B]63[/B]

[B]Warning[/B]: fwrite(): supplied argument is not a valid stream resource in [B]/home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php[/B] on line [B]434[/B]

[B]Warning[/B]: fclose(): supplied argument is not a valid stream resource in [B]/home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php[/B] on line [B]317[/B]

[B]Warning[/B]: fsockopen() [[URL='http://www.runuo.com/community/function.fsockopen'][U][COLOR=#000080]function.fsockopen[/COLOR][/U][/URL]]: php_network_getaddresses: getaddrinfo failed: Name or service not known in [B]/home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php[/B] on line [B]324[/B]

[B]Warning[/B]: fsockopen() [[URL='http://www.runuo.com/community/function.fsockopen'][U][COLOR=#000080]function.fsockopen[/COLOR][/U][/URL]]: unable to connect to PAYPAL_IPN_ADDR:443 (php_network_getaddresses: getaddrinfo failed: Name or service not known) in [B]/home/uorpsite/uoroleplay.com/web/donation_paypal_ipn_handler.php[/B] on line [B]324[/B]
 

romanthebrain

Sorceror
I got the problem that I configured all and I am able to add a donation reward to an account manually over the admin interface (php) . The user is able to claim the reward. But if anybody is donating over paypal, hes able to click the donate button and after he paid on paypal.... nothing happens. no payment in the database ... nothing. any solution ?
 

regnakhan

Sorceror
I got the problem that I configured all and I am able to add a donation reward to an account manually over the admin interface (php) . The user is able to claim the reward. But if anybody is donating over paypal, hes able to click the donate button and after he paid on paypal.... nothing happens. no payment in the database ... nothing. any solution ?

Hello !

Sorry to undig the topic, but I thought some other people like me might want to give a try at this script ... and spend hours (like me) trying to make it work. lol

I actually did ! It works now. If you want, I can try to help people who encounter problems.

In your specific problem, romanthebrain, I think you need to enable global variables in your php.ini, like said before. It worked for me.

Now, I will try to work on and "add to cart" system, or maybe optimize the code like tried above to remove the global variables.
And eventually, make a guide on all the problems one can encounter with this script.

btw, thank you to the maker of this script ! :)

-Rek-
 
Top