Paypal IPN communcating...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kyoru
Forum Commoner
Posts: 26
Joined: Mon Feb 13, 2006 9:35 pm

Paypal IPN communcating...

Post by kyoru »

i've been trying to work on this for 4 days straight and cannot find the answer to this so i thought i would ask the helpful people on here...
so far i've been able to create acheckout that proccesses the information and send the invoice id and amount id to paypal for payment.
however i just cant seem to get the ipn verfication from paypal back.

heres the code...

payment.php (where the user is redirected if he wants to pay...)

Code: Select all

<?php 
/* 
    This page will submit the order information to paypal website. 
    After the customer completed the payment she will return to this site 
*/ 

	require_once 'includes/paypal.inc.php'; 
	$sid = session_id();

	//Connect to database
        //mySQL Connection that finds the $sid position
	$order_amount = mysql_result($result,$i_found,"total");
	
	$paypal['item_name'] = "Import Bible Purchases"; 
	$paypal['invoice']   = $sid; 
	$paypal['amount']    = $order_amount; 

?> 

<center> 
    <p>&nbsp;</p> 
    <p><font face="Verdana, Arial, Helvetica, sans-serif" size="2" color="333333">Processing 
        Transaction . . .</font></p> 
</center> 
<form action="<?php echo $paypal['url']; ?>" method="post" name="frmPaypal" id="frmPaypal"> 
<input type="hidden" name="amount" value="<?php echo $paypal['amount']; ?>"> 
<input type="hidden" name="invoice" value="<?php echo $paypal['invoice']; ?>"> 
<input type="hidden" name="item_name" value="<?php echo $paypal['item_name']; ?>"> 
<input type="hidden" name="business" value="<?php echo $paypal['business']; ?>"> 
<input type="hidden" name="cmd" value="<?php echo $paypal['cmd']; ?>"> 
<input type="hidden" name="return" value="<?php echo  $paypal['site_url'] . $paypal['success_url']; ?>"> 
<input type="hidden" name="cancel_return" value="<?php echo $paypal['site_url'] . $paypal['cancel_url']; ?>"> 
<input type="hidden" name="notify_url" value="<?php echo  $paypal['site_url'] . $paypal['notify_url']; ?>"> 

<input type="hidden" name="rm" value="<?php echo $paypal['return_method']; ?>"> 
<input type="hidden" name="currency_code" value="<?php echo $paypal['currency_code']; ?>"> 
<input type="hidden" name="lc" value="<?php echo $paypal['lc']; ?>"> 
<input type="hidden" name="bn" value="<?php echo $paypal['bn']; ?>"> 
<input type="hidden" name="no_shipping" value="<?php echo $paypal['display_shipping_address']; ?>"> 


</form> 
<script language="JavaScript" type="text/javascript"> 
window.onload=function() { 
    window.document.frmPaypal.submit(); 
} 
</script>
payment.ipn.php (contins the varibles used and transfered/returned)

Code: Select all

<?php
/*
* This file contain paypal settings and some functions.
* Taken from "PHP Toolkit for PayPal v0.50" with some stuff
* removed ( because i don't need them ) and slightly modified
*
*/

$paypal = array();

$paypal['business']      = "name@site.com";
$paypal['site_url']      = "http://www.site.com";
$paypal['image_url']     = "";
$paypal['success_url']   = "/new_ib/cart.php?page=success";
$paypal['cancel_url']    = "/index.php";
$paypal['notify_url']    = "/new_ib/includes/ipn.php";
$paypal['return_method'] = "2"; //1=GET 2=POST               --> Use post since we will need the return values to check if order is valid
$paypal['currency_code'] = "USD"; //['USD,GBP,JPY,CAD,EUR']
$paypal['lc']            = "US";

//$paypal['url'] = "http://www.paypal.com/cgi-bin/webscr";
//$paypal['url'] = "https://www.paypal.com/cgi-bin/webscr";
$paypal['url']           = "https://www.sandbox.paypal.com/cgi-bin/webscr";
$paypal['post_method']   = "fso"; //fso=fsockopen(); curl=curl command line libCurl=php compiled with libCurl support
$paypal['curl_location'] = "/usr/local/bin/curl";

$paypal['bn']  = "toolkit-php";
$paypal['cmd'] = "_xclick";

//Payment Page Settings
$paypal['display_comment']          = "0"; //0=yes 1=no
$paypal['comment_header']           = "Comments";
$paypal['continue_button_text']     = "Continue >>";
$paypal['background_color']         = ""; //""=white 1=black
$paypal['display_shipping_address'] = "1"; //""=yes 1=no     --> We already asked for the shipping address so tell paypal not to ask it again
$paypal['display_comment']          = "1"; //""=yes 1=no

//Product Settings
$paypal['item_name']     = isset($_POST['item_name']) ? $_POST['item_name']: "";
$paypal['item_number']   = isset($_POST['item_number']) ? $_POST['item_number']: "";
$paypal['amount']        = isset($_POST['amount']) ? $_POST['amount']: "";
$paypal['on0']           = isset($_POST['on0']) ? $_POST['on0']: "";
$paypal['os0']           = isset($_POST['os0']) ? $_POST['os0']: "";
$paypal['on1']           = isset($_POST['on1']) ? $_POST['on1']: "";
$paypal['os1']           = isset($_POST['os1']) ? $_POST['os1']: "";
$paypal['quantity']      = isset($_POST['quantity']) ? $_POST['quantity']: "";
$paypal['edit_quantity'] = ""; //1=yes ""=no
$paypal['invoice']       = isset($_POST['invoice']) ? $_POST['invoice']: "";
$paypal['tax']           = isset($_POST['tax']) ? $_POST['tax']: "";

//Shipping and Taxes
$paypal['shipping_amount']          = isset($_POST['shipping_amount']) ? $_POST['shipping_amount']: "";
$paypal['shipping_amount_per_item'] = "";
$paypal['handling_amount']          = "";
$paypal['custom_field']             = "";

//Customer Settings
$paypal['firstname'] = isset($_POST['firstname']) ? $_POST['firstname']: "";
$paypal['lastname']  = isset($_POST['lastname']) ? $_POST['lastname']: "";
$paypal['address1']  = isset($_POST['address1']) ? $_POST['address1']: "";
$paypal['address2']  = isset($_POST['address2']) ? $_POST['address2']: "";
$paypal['city']      = isset($_POST['city']) ? $_POST['city']: "";
$paypal['state']     = isset($_POST['state']) ? $_POST['state']: "";
$paypal['zip']       = isset($_POST['zip']) ? $_POST['zip']: "";
$paypal['email']     = isset($_POST['email']) ? $_POST['email']: "";
$paypal['phone_1']   = isset($_POST['phone1']) ? $_POST['phone1']: "";
$paypal['phone_2']   = isset($_POST['phone2']) ? $_POST['phone2']: "";
$paypal['phone_3']   = isset($_POST['phone3']) ? $_POST['phone3']: "";



/********************************************************************************
*
*                           PAYPAL FUNCTIONS
*
********************************************************************************/

//create variable names to perform additional order processing

function create_local_variables()
{
    $array_name = array();
    $array_name['business'] = $_POST['business'];
    $array_name['receiver_email'] = $_POST['receiver_email'];
    $array_name['receiver_id'] = $_POST['receiver_id'];
    $array_name['item_name'] = $_POST['item_name'];
    $array_name['item_number'] = $_POST['item_number'];
    $array_name['quantity'] = $_POST['quantity'];
    $array_name['invoice'] = $_POST['invoice'];
    $array_name['custom'] = $_POST['custom'];
    $array_name['memo'] = $_POST['memo'];
    $array_name['tax'] = $_POST['tax'];
    $array_name['option_name1'] = $_POST['option_name1'];
    $array_name['option_selection1'] = $_POST['option_selection1'];
    $array_name['option_name2'] = $_POST['option_name2'];
    $array_name['option_selection2'] = $_POST['option_selection2'];
    $array_name['num_cart_items'] = $_POST['num_cart_items'];
    $array_name['mc_gross'] = $_POST['mc_gross'];
    $array_name['mc_fee'] = $_POST['mc_fee'];
    $array_name['mc_currency'] = $_POST['mc_currency'];
    $array_name['settle_amount'] = $_POST['settle_amount'];
    $array_name['settle_currency'] = $_POST['settle_currency'];
    $array_name['exchange_rate'] = $_POST['exchange_rate'];
    $array_name['payment_gross'] = $_POST['payment_gross'];
    $array_name['payment_fee'] = $_POST['payment_fee'];
    $array_name['payment_status'] = $_POST['payment_status'];
    $array_name['pending_reason'] = $_POST['pending_reason'];
    $array_name['reason_code'] = $_POST['reason_code'];
    $array_name['payment_date'] = $_POST['payment_date'];
    $array_name['txn_id'] = $_POST['txn_id'];
    $array_name['txn_type'] = $_POST['txn_type'];
    $array_name['payment_type'] = $_POST['payment_type'];
    $array_name['for_auction'] = $_POST['for_auction'];
    $array_name['auction_buyer_id'] = $_POST['auction_buyer_id'];
    $array_name['auction_closing_date'] = $_POST['auction_closing_date'];
    $array_name['auction_multi_item'] = $_POST['auction_multi_item'];
    $array_name['first_name'] = $_POST['first_name'];
    $array_name['last_name'] = $_POST['last_name'];
    $array_name['payer_business_name'] = $_POST['payer_business_name'];
    $array_name['address_name'] = $_POST['address_name'];
    $array_name['address_street'] = $_POST['address_street'];
    $array_name['address_city'] = $_POST['address_city'];
    $array_name['address_state'] = $_POST['address_state'];
    $array_name['address_zip'] = $_POST['address_zip'];
    $array_name['address_country'] = $_POST['address_country'];
    $array_name['address_status'] = $_POST['address_status'];
    $array_name['payer_email'] = $_POST['payer_email'];
    $array_name['payer_id'] = $_POST['payer_id'];
    $array_name['payer_status'] = $_POST['payer_status'];
    $array_name['notify_version'] = $_POST['notify_version'];
    $array_name['verify_sign'] = $_POST['verify_sign'];
    
    return $array_name;
}


//this function creates a comma separated value file from an array.

function create_csv_file($file,$data)
{
    // the return value
    $success = false;
    
    //check for array
    if (is_array($data)) {
        $post_values = array_values($data);
        
        //build csv data
        foreach ($post_values as $i) {
            $csv.="\"$i\",";
        }
        
        //remove the last comma from string
        $csv = substr($csv,0,-1);
        
        //check for existence of file
        if(file_exists($file) && is_writeable($file)) {
            $mode="a";
        } else {
            $mode="w";
        }
        
        //create file pointer
        $fp=@fopen($file,$mode);
        
        //write to file
        fwrite($fp,$csv . "n");
        
        //close file pointer
        fclose($fp);
        
        $success = true;
    }
    
    return $success;    
}

//posts transaction data using fsockopen.
function fsockPost($url,$data)
{
    $postData = '';
    
    // return value
    $info = '';
    
    //Parse url
    $web=parse_url($url);
    
    //build post string
    foreach ($data as $i=>$v) {
        $postData.= $i . "=" . urlencode($v) . "&";
    }
    
    // we must append cmd=_notify-validate to the POST string
    // so paypal know that this is a confirmation post
    $postData .= "cmd=_notify-validate";
    
    //Set the port number
    if ($web['scheme'] == "https") {
        $web['port'] = "443";  
        $ssl       = "ssl://";
    } else {
        $web['port'] = "80";
        $ssl       = "";
    }  
    
    //Create paypal connection
    $fp = @fsockopen($ssl . $web[host], $web[port], $errnum, $errstr,30);
    
    //Error checking
    if(!$fp) {
        echo "$errnum: $errstr";
    } else {
        //Post Data
        fputs($fp, "POST $web[path] HTTP/1.1rn");
        fputs($fp, "Host: $web[host]rn");
        fputs($fp, "Content-type: application/x-www-form-urlencodedrn");
        fputs($fp, "Content-length: ".strlen($postData)."rn");
        fputs($fp, "Connection: closernrn");
        fputs($fp, $postData . "rnrn");
    
        // loop through the response from the server
        $info = array();
        while (!feof($fp)) {
            $info[] = @fgets($fp, 1024);
        }
        
        //close fp - we are done with it
        fclose($fp);
        
        // join the results into a string separated by comma
        $info = implode(",", $info);
        
    }
    
    return $info;

}

//Display Paypal Hidden Variables

function showVariables() {
    global $paypal;
?>

<!-- PayPal Configuration -->
<input type="hidden" name="business" value="<?php echo $paypal['business']?>">
<input type="hidden" name="cmd" value="<?php echo $paypal['cmd']?>">
<input type="hidden" name="image_url" value="<?php echo  "{$paypal['site_url']}{$paypal['image_url']}"; ?>">
<input type="hidden" name="return" value="<?php echo  "{$paypal['site_url']}{$paypal['success_url']}"; ?>">
<input type="hidden" name="cancel_return" value="<?php echo  "{$paypal['site_url']}{$paypal['cancel_url']}"; ?>">
<input type="hidden" name="notify_url" value="<?php echo  "{$paypal['site_url']}{$paypal['notify_url']}"; ?>">
<input type="hidden" name="rm" value="<?php echo $paypal['return_method']?>">
<input type="hidden" name="currency_code" value="<?php echo $paypal['currency_code']?>">
<input type="hidden" name="lc" value="<?php echo $paypal['lc']?>">
<input type="hidden" name="bn" value="<?php echo $paypal['bn']?>">
<input type="hidden" name="cbt" value="<?php echo $paypal['continue_button_text']?>">

<!-- Payment Page Information -->
<input type="hidden" name="no_shipping" value="<?php echo $paypal['display_shipping_address']?>">
<input type="hidden" name="no_note" value="<?php echo $paypal['display_comment']?>">
<input type="hidden" name="cn" value="<?php echo $paypal['comment_header']?>">
<input type="hidden" name="cs" value="<?php echo $paypal['background_color']?>">

<!-- Product Information -->
<input type="hidden" name="item_name" value="<?php echo $paypal['item_name']?>">
<input type="hidden" name="amount" value="<?php echo $paypal['amount']?>">
<input type="hidden" name="quantity" value="<?php echo $paypal['quantity']?>">
<input type="hidden" name="item_number" value="<?php echo $paypal['item_number']?>">
<input type="hidden" name="undefined_quantity" value="<?php echo $paypal['edit_quantity']?>">
<input type="hidden" name="on0" value="<?php echo $paypal['on0']?>">
<input type="hidden" name="os0" value="<?php echo $paypal['os0']?>">
<input type="hidden" name="on1" value="<?php echo $paypal['on1']?>">
<input type="hidden" name="os1" value="<?php echo $paypal['os1']?>">

<!-- Shipping and Misc Information -->
<input type="hidden" name="shipping" value="<?php echo $paypal['shipping_amount']?>">
<input type="hidden" name="shipping2" value="<?php echo $paypal['shipping_amount_per_item']?>">
<input type="hidden" name="handling" value="<?php echo $paypal['handling_amount']?>">
<input type="hidden" name="tax" value="<?php echo $paypal['tax']?>">
<input type="hidden" name="custom" value="<?php echo $paypal['custom_field']?>">
<input type="hidden" name="invoice" value="<?php echo $paypal['invoice']?>">

<!-- Customer Information -->
<input type="hidden" name="first_name" value="<?php echo $paypal['firstname']?>">
<input type="hidden" name="last_name" value="<?php echo $paypal['lastname']?>">
<input type="hidden" name="address1" value="<?php echo $paypal['address1']?>">
<input type="hidden" name="address2" value="<?php echo $paypal['address2']?>">
<input type="hidden" name="city" value="<?php echo $paypal['city']?>">
<input type="hidden" name="state" value="<?php echo $paypal['state']?>">
<input type="hidden" name="zip" value="<?php echo $paypal['zip']?>">
<input type="hidden" name="email" value="<?php echo $paypal['email']?>">
<input type="hidden" name="night_phone_a" value="<?php echo $paypal['phone_1']?>">
<input type="hidden" name="night_phone_b" value="<?php echo $paypal['phone_2']?>">
<input type="hidden" name="night_phone_c" value="<?php echo $paypal['phone_3']?>">

<?php
}
?>
ipn.php (the only problem i cannot get to work)

Code: Select all

<?php 
// this page only process a POST from paypal website 
// so make sure that the one requesting this page comes 
// from paypal. we can do this by checking the remote address 
// the IP must begin with 66.135.197. 
if (strpos($_SERVER['REMOTE_ADDR'], '66.135.197.') === false) { 
    exit; 
} 

require_once 'paypal.inc.php'; 

// repost the variables we get to paypal site 
// for validation purpose 
$result = fsockPost($paypal['url'], $_POST); 

//check the ipn result received back from paypal 
if (eregi("VERIFIED", $result)) {    
                // check that the buyer sent the right amount of money 
				$sid = $_POST['invoice'];
				//mysql connection information

				//connection query
				mysql_connect('10.0.11.77',$username,$password);
				@mysql_select_db($database) or die( "Unable to select database");
				$query="SELECT * FROM order_complete";
				$result=mysql_query($query);
				$num=mysql_numrows($result);
				mysql_close();
				
				$i = 0;
				
				while($i < $result) {
					$user_id = mysql_result($result,$i,"order_id");
					if($user_id == $sid) {
						$i_found = $i;
					}
					$i++;
				}
				
				$order_status = mysql_result($result,$i_found,"status");
				if($order_status != 'new') {
					exit;
				}
				
				$order_total = mysql_result($result,$i_found,"total");
				
				if ($_POST['payment_gross'] != $order_total) {
					exit;
				}
				else {
					$memo = $_POST['memo'];
				}

				//remove items that are related in temp order and update stock.
				$loop_control = 0;
				while ($num > $loop_control) {
					$directory = mysql_result($result,$loop_control,"design");
					$currentsid = mysql_result($result,$loop_control,"sid");
						if (!in_array($directory,$directory_list) && $currentsid == $sid) {
							$directory_list[] = "$directory";
						}
					$loop_control++;
				}
				//Find all sizes of current design
				$array_count = count($directory_list);
				$loop_control = 0;
				while ($array_count > $loop_control) {
					$search_control = 0;
					$current_small = 0;
					$current_medium = 0;
					$current_large =  0;
					$current_xlarge = 0;
					//search for all related sizes of the item...			
					while ($num > $search_control) {
						$directory = mysql_result($result,$search_control,"design");
						$sessionid = mysql_result($result,$search_control,"sid");
						$size = mysql_result($result,$search_control,"size");
						$quantity = mysql_result($result,$search_control,"quantity");
						if ($directory == $directory_list[$loop_control] && $sessionid ==  $sid) {
							switch ($size) {
								case '0':
									$current_small = $quantity;
									break;
								case '1':
									$current_medium = $quantity;
									break;
								case '2':
									$current_large = $quantity;
									break;
								case '3':
									$current_xlarge = $quantity;
									break;
								}
						}
					$search_control++;
					}
						//mysql database
	
						//connection query
						mysql_connect('10.0.11.77',$username,$password);
						@mysql_select_db($database) or die( "Unable to select database");
						$query="SELECT * FROM shirt_designs";
						$result=mysql_query($query);
						$num=mysql_numrows($result);
						
						$i = 0;
						//Begin sort loop
						while($i < $num) {
						$currentdir = mysql_result($result,$i,"directory");
							if ( $currentdir == $design){
								$i_found = $i;
							}
							$i++;
						}
						
						$small_q = mysql_result($result,$i_found,"small_q");
						$medium_q = mysql_result($result,$i_found,"medium_q");
						$large_q = mysql_result($result,$i_found,"large_q");
						$xlarge_q = mysql_result($result,$i_found,"xlarge_q");
						
						$small_q -= $current_small;
						$medium_q -= $current_medium;
						$large_q -= $current_large;
						$xlarge_q -= $current_xlarge;
						//Update new quantities
						$query="UPDATE shirt_designs SET small_q = '$small_q', medium_q = '$medium_q', large_q = '$large_q', xlarge_q = 'xlarge_q' WHERE dir = '$directory_list[$loop_control]'"
						mysql_query($query) or die('Error, insert query failed');
						
						$query = "DELETE FROM temp_order WHERE id=$session_order_id";
						mysql_query($query) or die('Error, delete query failed');
						mysql_close();
						$loop_control++;
            } 
        } 
else { 
    exit; 
} 

?>
i've checked the sandbox site to make sure the IPN url is pointed at the right location and it is. I don't have any expearience writing to a flat file with php, is there a way to write into a log file so i know what's going on in ipn? thank you so much!
User avatar
ed209
Forum Contributor
Posts: 153
Joined: Thu May 12, 2005 5:06 am
Location: UK

Post by ed209 »

when I set up my IPN, I used the mail() function to send me a result. Is your IPN page receiving anything at all ?
Post Reply