Jump to content
MakeWebGames

PayPal IPN help needed


Recommended Posts

To start,

1. Are you using SSL? I believe your endpoints for PayPal have to be served over HTTPS

2. Did you recently update your PHP version? You may be getting an error that is stopping page execution due to something that may now be considered an error.

3. Have you checked your error logs?

Link to post
Share on other sites

Basic checks;
Is there an input named "notify_url" in your donation form?
Do you currently have an IPN implemented into your site and, if so, did it previously work?
If applicable, does your IPN use its own certificate? If so, it may have expired.

Failing that, I could write up an IPN for you

  • Like 1
Link to post
Share on other sites
  • 1 year later...

Sorry for the late response this is the ipn file

<?php 
include('connect_db.php');
function in_event($player, $text) {
   $text = stripslashes($text);
   mysql_query("INSERT INTO `usr_events`
                VALUES('NULL', 
                       '".mysql_real_escape_string($player)."',
                       '".time()."',
                       '".mysql_real_escape_string($text)."',
                       'no')");
   add_live($player, "add_event();");
}

function add_live($id, $function) {
   $sql = "SELECT `usr_live`
           FROM `usr_tbl`
           WHERE `usr_id` = '".mysql_real_escape_string($id)."'";
   $live = mysql_fetch_array(mysql_query($sql));
   $live = $live['usr_live'];
   $live.= $function;
   $sql = "UPDATE `usr_tbl`
           SET `usr_live` = '".mysql_real_escape_string($live)."'
           WHERE `usr_id` = '".mysql_real_escape_string($id)."'";
   mysql_query($sql);
}

function item_add($item, $qty, $player) {
    $sql = "SELECT `ui_id` 
            FROM `usr_items` 
            WHERE `ui_user` = '".mysql_real_escape_string($player)."' 
            AND `ui_item` = '".mysql_real_escape_string($item)."'";
    $sql = mysql_query($sql);
    if(mysql_num_rows($sql))
    {
       $i = mysql_fetch_array($sql);
       mysql_query("UPDATE `usr_items` 
                    SET `ui_qty` = `ui_qty` + '".mysql_real_escape_string($qty)."' 
                    WHERE `ui_id` = '".mysql_real_escape_string($i['ui_id'])."'");
            }
            else
               {
               mysql_query("INSERT INTO `usr_items` 
                            VALUES ('NULL',
                                    '".mysql_real_escape_string($player)."',
                                    '".mysql_real_escape_string($item)."',
                                    '".mysql_real_escape_string($qty)."')");
               }
}
//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";
}

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

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


//error connecting to paypal
if (!$fp) {
    // HTTP ERROR
}
    
//successful connection    
if ($fp) {
    fputs ($fp, $header . $req);
    
    while (!feof($fp)) {
        $res = fgets ($fp, 1024);
        $res = trim($res); //NEW & IMPORTANT
                
        if (strcmp($res, "VERIFIED") == 0) {

            //insert order into database
            // check the payment_status is Completed
            if($payment_status != "Completed") { fclose ($fp);die(""); }
            // check that receiver_email is your Primary PayPal email
            if($receiver_email != '[email protected]') { fclose ($fp);die(""); }
            // check that payment_amount/payment_currency are correct
            if($payment_currency != 'USD') { fclose ($fp);die(""); }
            if($item_name != "Donator Pack") { fclose($fp);die(""); }
            $check_amnt = (5*$payment_qty) . ".00";
            if($payment_amount != "$check_amnt") { fclose ($fp);die(""); }
            // all seems to be in order, credit it.
            item_add(53, $payment_qty, $item_number);
            $msg = "Thank you for your donation of \$".$payment_amount.". ".$payment_qty." donator pack(s) have been credited to you.";
            in_event($item_number, $msg);
            in_event(1,'User['.$item_number.'] has donated x '.$payment_qty.' for a total of '.$settle_amount.'GBP!');
            $mess = "User[".$item_number."] has donated x ".$payment_qty." for a total of ".$settle_amount."GBP!";
            mail('[email protected]', "Donation", $mess, "From: [email protected]");
         $q_ry = "INSERT INTO `donations`
                  VALUES('NULL',
                         '".mysql_real_escape_string($item_number)."',
                         '".mysql_real_escape_string($payment_amount)."',
                         '".$txn_id."',
                         '".time()."')";
         mysql_query($q_ry);
         // process payment

         }

        }
        
    }

    fclose($fp);

?>

 

Link to post
Share on other sites
Posted (edited)
17 hours ago, AdamHull said:

The code is definitely out dated, but what issue are you getting except "it doesn't work" 

Also, this maybr of help

https://stackoverflow.com/questions/37589359/ipn-verification-postback-to-https

well basically it doesn't credit the user after they donate. It calls their ID in the paypal payment though. IPN link is setup on Paypal. 

Edited by UOTS-Owner
Link to post
Share on other sites

yeah they are matching after donating though they get logged out when returning to the game so that might affect it. 

Ok ignore that last part about getting logged out that has now been sorted. 

Link to post
Share on other sites
IPN.php
<?php
// CONFIG: Enable debug mode. This means we'll log requests into 'ipn.log' in the same directory.
// Especially useful if you encounter network errors or other intermittent problems with IPN (validation).
// Set this to 0 once you go live or don't require logging.
define("DEBUG", 1);
// Set to 0 once you're ready to go live
define("USE_SANDBOX", 1);
define("LOG_FILE", "ipn.log");
// Read POST data
// reading posted data directly from $_POST causes serialization
// issues with array data in POST. Reading raw POST data from input stream instead.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
	$keyval = explode ('=', $keyval);
	if (count($keyval) == 2)
		$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
	$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
	if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
		$value = urlencode(stripslashes($value));
	} else {
		$value = urlencode($value);
	}
	$req .= "&$key=$value";
}
// Post IPN data back to PayPal to validate the IPN data is genuine
// Without this step anyone can fake IPN data
if(USE_SANDBOX == true) {
	$paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
} else {
	$paypal_url = "https://www.paypal.com/cgi-bin/webscr";
}
$ch = curl_init($paypal_url);
if ($ch == FALSE) {
	return FALSE;
}
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
if(DEBUG == true) {
	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
}
// CONFIG: Optional proxy configuration
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
// Set TCP timeout to 30 seconds
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below. Ensure the file is readable by the webserver.
// This is mandatory for some environments.
//$cert = __DIR__ . "./cacert.pem";
//curl_setopt($ch, CURLOPT_CAINFO, $cert);
$res = curl_exec($ch);
if (curl_errno($ch) != 0) // cURL error
	{
	if(DEBUG == true) {	
		error_log(date('[Y-m-d H:i e] '). "Can't connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE);
	}
	curl_close($ch);
	exit;
} else {
		// Log the entire HTTP response if debug is switched on.
		if(DEBUG == true) {
			error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." for IPN payload: $req" . PHP_EOL, 3, LOG_FILE);
			error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
		}
		curl_close($ch);
}
// Inspect IPN validation result and act accordingly
// Split response headers and payload, a better way for strcmp
$tokens = explode("\r\n\r\n", trim($res));
$res = trim(end($tokens));
if (strcmp ($res, "VERIFIED") == 0) {
	// assign posted variables to local variables
	$item_name = $_POST['item_name'];
	$item_number = $_POST['item_number'];
	$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'];
	$payer_email = $_POST['payer_email'];
	
	include("DBController.php");
	$db = new DBController();
	
	// check whether the payment_status is Completed
	$isPaymentCompleted = false;
	if($payment_status == "Completed") {
		$isPaymentCompleted = true;
	}
	// check that txn_id has not been previously processed
	$isUniqueTxnId = false; 
	$param_type="s";
	$param_value_array = array($txn_id);
  
	$result = $db->runQuery("SELECT * FROM payment WHERE txn_id = ?",$param_type,$param_value_array);
	if(empty($result)) {
        $isUniqueTxnId = true;
	}	
	// check that receiver_email is your PayPal email
	// check that payment_amount/payment_currency are correct
	if($isPaymentCompleted) {
      
      
     ///ALTER THIS QUERY TO MATCH YOUR INSERT QUERY
	    $param_type = "sssdss";
	    $param_value_array = array($item_number, $item_name, $payment_status, $payment_amount, $payment_currency, $txn_id);
	    $payment_id = $db->insert("INSERT INTO payment(item_number, item_name, payment_status, payment_amount, payment_currency, txn_id) VALUES(?, ?, ?, ?, ?, ?)", $param_type, $param_value_array);
	    error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
	} 
	// process payment and mark item as paid.
	
	
	if(DEBUG == true) {
		error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
	}
	
} else if (strcmp ($res, "INVALID") == 0) {
	// log for manual investigation
	// Add business logic here which deals with invalid IPN messages
	if(DEBUG == true) {
		error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
	}
}
?> 

DBController.php
<?php

class DBController
{

    private $host = "host";

    private $user = "username";

    private $password = "password";

    private $database = "dbname";

    private $conn;

    function __construct()
    {
        $this->conn = $this->connectDB();
    }

    function connectDB()
    {
        $conn = mysqli_connect($this->host, $this->user, $this->password, $this->database);
        return $conn;
    }

    function runQuery($query, $param_type, $param_value_array)
    {
        $sql = $this->conn->prepare($query);
        $this->bindQueryParams($sql, $param_type, $param_value_array);
        $sql->execute();
        $result = $sql->get_result();
        
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $resultset[] = $row;
            }
        }
        
        if (! empty($resultset)) {
            return $resultset;
        }
    }

    function bindQueryParams($sql, $param_type, $param_value_array)
    {
        $param_value_reference[] = & $param_type;
        for ($i = 0; $i < count($param_value_array); $i ++) {
            $param_value_reference[] = & $param_value_array[$i];
        }
        call_user_func_array(array(
            $sql,
            'bind_param'
        ), $param_value_reference);
    }

    function insert($query, $param_type, $param_value_array)
    {
        $sql = $this->conn->prepare($query);
        $this->bindQueryParams($sql, $param_type, $param_value_array);
        $sql->execute();
    }
}
?>

read the comments in it as you have sandbox testing mode and a debug file logger to configure at the top, you ipn is like mine was old!

Is the IPN.php and a files called DBController.php that found very handy to adapt

 

Edited by Placebo
Link to post
Share on other sites
On 4/9/2021 at 12:06 PM, AdamHull said:

Is there any thing in your error log? 

Does your receiver email match what is in the code? 

I am still around buddy thx for mention but IPNS I used to turn to @Magictallguyhe was really good at pp IPN but ill take a look.

14 minutes ago, UOTS-Owner said:

I've never used sandbox before https://developer.paypal.com/developer/accounts/

 

15 minutes ago, UOTS-Owner said:

I've never used sandbox before 

Also is ur ipn set up on PayPal and linking to your IPN listener file

Link to post
Share on other sites
Posted (edited)

 

18 minutes ago, SwiftGameR said:

I am still around buddy thx for mention but IPNS I used to turn to @Magictallguyhe was really good at pp IPN but ill take a look.

 

Also is ur ipn set up on PayPal and linking to your IPN listener file

yeah IPN link setup on paypal 

 

when i run my current ipn on that sandbox mode I just get this 

 

IPN was sent and the handshake was verified.

Edited by UOTS-Owner
Link to post
Share on other sites
On 2/13/2020 at 3:12 PM, Dayo said:

I have a working IPN for sale but for the GL game engine, you should be able to alter the IPN for your game though

 

https://makewebgames.io/files/file/10-buy-points/

nice system would be cooler if you added a donator for someone else say something like a drop down list of whos onine or depending on there select option 

  • Select box 3 Options (For yourself, Someone who is online in past 15 minutes and something like gift which be like there id or username.)
  • Some simple jQuery to hide show / hide box for id / name 
  • Simple check to make sure its not being used and a is_numeric() and not empty.

just some ideas for ya 🙂

 

Link to post
Share on other sites
12 minutes ago, UOTS-Owner said:

IPN was not sent, and the handshake was not verified. Review your information.

reading info now from where I got mentioned missed all the convo above me lol but yes when i was playing with rc engine the ipn was screwed I have a credits on for old grpg but from what I remember the engine is that out dated depending what php version your using and what code is being used. for example your running php 6 but code is built for php4 some functions etc might not work. Have you fully updated your code so its not the MySQL now.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...