Php Can´;t将paypal ipn值保存到数据库中
我已经实施了paypal ipn流程。我想从ipn中检索一些数据并将其保存在数据库表中。问题是它不起作用。我使用了教程中的步骤部分 Nelow是我用过的代码。 ipn.phpPhp Can´;t将paypal ipn值保存到数据库中,php,mysql,paypal-ipn,Php,Mysql,Paypal Ipn,我已经实施了paypal ipn流程。我想从ipn中检索一些数据并将其保存在数据库表中。问题是它不起作用。我使用了教程中的步骤部分 Nelow是我用过的代码。 ipn.php <?php require "paypal_integration_class/paypal.class.php"; require "config.php"; require "connect.php"; $p = new paypal_class; $p->paypal_url = $payPalURL
<?php
require "paypal_integration_class/paypal.class.php";
require "config.php";
require "connect.php";
$p = new paypal_class;
$p->paypal_url = $payPalURL;
if ($p->validate_ipn()) {
if($p->ipn_data['payment_status']=='Completed')
{
$amount = $p->ipn_data['mc_gross'] - $p->ipn_data['mc_fee'];
mysql_query(" INSERT INTO dc_donations (transaction_id,donor_email,amount,original_request)
VALUES (
'".esc($p->ipn_data['txn_id'])."',
'".esc($p->ipn_data['payer_email'])."',
".(float)$amount.",
'".esc(http_build_query($_POST))."'
)");
}
}
function esc($str)
{
global $link;
return mysql_real_escape_string($str,$link);
}
?>
/* Database config */
$db_host = "localhost";
$db_user = "egesachi_ipn";
$db_pass = "lollipop";
$db_database = "egesachi_ipn";
/* End config */
$link = @mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');
mysql_set_charset('utf8');
mysql_select_db($db_database,$link);
?>
<?php
// Fill your PayPal email below.
// This is where you will receive the donations.
$myPayPalEmail = 'ben@center.org';
// The paypal URL:
$payPalURL = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
// Your goal in USD:
$goal = 100;
// Demo mode is set - set it to false to enable donations.
// When enabled PayPal is bypassed.
$demoMode = false;
if($demoMode)
{
$payPalURL = 'demo_mode.php';
}
?>
config.php
<?php
require "paypal_integration_class/paypal.class.php";
require "config.php";
require "connect.php";
$p = new paypal_class;
$p->paypal_url = $payPalURL;
if ($p->validate_ipn()) {
if($p->ipn_data['payment_status']=='Completed')
{
$amount = $p->ipn_data['mc_gross'] - $p->ipn_data['mc_fee'];
mysql_query(" INSERT INTO dc_donations (transaction_id,donor_email,amount,original_request)
VALUES (
'".esc($p->ipn_data['txn_id'])."',
'".esc($p->ipn_data['payer_email'])."',
".(float)$amount.",
'".esc(http_build_query($_POST))."'
)");
}
}
function esc($str)
{
global $link;
return mysql_real_escape_string($str,$link);
}
?>
/* Database config */
$db_host = "localhost";
$db_user = "egesachi_ipn";
$db_pass = "lollipop";
$db_database = "egesachi_ipn";
/* End config */
$link = @mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');
mysql_set_charset('utf8');
mysql_select_db($db_database,$link);
?>
<?php
// Fill your PayPal email below.
// This is where you will receive the donations.
$myPayPalEmail = 'ben@center.org';
// The paypal URL:
$payPalURL = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
// Your goal in USD:
$goal = 100;
// Demo mode is set - set it to false to enable donations.
// When enabled PayPal is bypassed.
$demoMode = false;
if($demoMode)
{
$payPalURL = 'demo_mode.php';
}
?>
paypal\u integration\u class/paypal.class.php
下面是上面的脚本来自的URL。
class paypal_class {
var $last_error; // holds the last error encountered
var $ipn_log; // bool: log IPN results to text file?
var $ipn_log_file; // filename of the IPN log
var $ipn_response; // holds the IPN response from paypal
var $ipn_data = array(); // array contains the POST values for IPN
var $fields = array(); // array holds the fields to submit to paypal
function paypal_class() {
// initialization constructor. Called when class is created.
$this->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
$this->last_error = '';
$this->ipn_log_file = 'ipn_log.txt';
$this->ipn_log = true;
$this->ipn_response = '';
// populate $fields array with a few default values. See the paypal
// documentation for a list of fields and their data types. These defaul
// values can be overwritten by the calling script.
$this->add_field('rm','2'); // Return method = POST
$this->add_field('cmd','_xclick');
}
function add_field($field, $value) {
// adds a key=>value pair to the fields array, which is what will be
// sent to paypal as POST variables. If the value is already in the
// array, it will be overwritten.
$this->fields["$field"] = $value;
}
function submit_paypal_post() {
// this function actually generates an entire HTML page consisting of
// a form with hidden elements which is submitted to paypal via the
// BODY element's onLoad attribute. We do this so that you can validate
// any POST vars from you custom form before submitting to paypal. So
// basically, you'll have your own form which is submitted to your script
// to validate the data, which in turn calls this function to create
// another hidden form and submit to paypal.
// The user will briefly see a message on the screen that reads:
// "Please wait, your order is being processed..." and then immediately
// is redirected to paypal.
echo "<html>\n";
echo "<head><title>Processing Payment...</title></head>\n";
echo "<body onLoad=\"document.form.submit();\">\n";
echo "<center><h3>Please wait, your order is being processed...</h3></center>\n";
echo "<form method=\"post\" name=\"form\" action=\"".$this->paypal_url."\">\n";
foreach ($this->fields as $name => $value) {
echo "<input type=\"hidden\" name=\"$name\" value=\"$value\">";
}
echo "</form>\n";
echo "</body></html>\n";
}
function validate_ipn() {
// parse the paypal URL
$url_parsed=parse_url($this->paypal_url);
// generate the post string from the _POST vars aswell as load the
// _POST vars into an arry so we can play with them from the calling
// script.
$post_string = '';
foreach ($_POST as $field=>$value) {
$this->ipn_data["$field"] = $value;
$post_string .= $field.'='.urlencode($value).'&';
}
$post_string.="cmd=_notify-validate"; // append ipn command
// open the connection to paypal
$fp = fsockopen($url_parsed[host],"80",$err_num,$err_str,30);
if(!$fp) {
// could not open the connection. If loggin is on, the error message
// will be in the log.
$this->last_error = "fsockopen error no. $errnum: $errstr";
$this->log_ipn_results(false);
return false;
} else {
// Post the data back to paypal
fputs($fp, "POST $url_parsed[path] HTTP/1.1\r\n");
fputs($fp, "Host: $url_parsed[host]\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($post_string)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $post_string . "\r\n\r\n");
// loop through the response from the server and append to variable
while(!feof($fp)) {
$this->ipn_response .= fgets($fp, 1024);
}
fclose($fp); // close connection
}
if (eregi("VERIFIED",$this->ipn_response)) {
// Valid IPN transaction.
$this->log_ipn_results(true);
return true;
} else {
// Invalid IPN transaction. Check the log for details.
$this->last_error = 'IPN Validation Failed.';
$this->log_ipn_results(false);
return false;
}
}
function log_ipn_results($success) {
if (!$this->ipn_log) return; // is logging turned off?
// Timestamp
$text = '['.date('m/d/Y g:i A').'] - ';
// Success or failure being logged?
if ($success) $text .= "SUCCESS!\n";
else $text .= 'FAIL: '.$this->last_error."\n";
// Log the POST variables
$text .= "IPN POST Vars from Paypal:\n";
foreach ($this->ipn_data as $key=>$value) {
$text .= "$key=$value, ";
}
// Log the response from the paypal server
$text .= "\nIPN Response from Paypal Server:\n ".$this->ipn_response;
// Write to log
$fp=fopen($this->ipn_log_file,'a');
fwrite($fp, $text . "\n\n");
fclose($fp); // close file
}
function dump_fields() {
// Used for debugging, this function will output all the field/value pairs
// that are currently defined in the instance of the class using the
// add_field() function.
echo "<h3>paypal_class->dump_fields() Output:</h3>";
echo "<table width=\"95%\" border=\"1\" cellpadding=\"2\" cellspacing=\"0\">
<tr>
<td bgcolor=\"black\"><b><font color=\"white\">Field Name</font></b></td>
<td bgcolor=\"black\"><b><font color=\"white\">Value</font></b></td>
</tr>";
ksort($this->fields);
foreach ($this->fields as $key => $value) {
echo "<tr><td>$key</td><td>".urldecode($value)." </td></tr>";
}
echo "</table><br>";
}
}
class贝宝类{
var$last_error;//保存遇到的最后一个错误
var$ipn_log;//bool:将ipn结果记录到文本文件?
var$ipn_log_file;//ipn日志的文件名
var$ipn_response;//保存来自paypal的ipn响应
var$ipn_data=array();//数组包含ipn的POST值
var$fields=array();//array保存要提交给paypal的字段
函数paypal_class(){
//初始化构造函数。在创建类时调用。
$this->paypal\u url='1https://www.paypal.com/cgi-bin/webscr';
$this->last_error='';
$this->ipn_log_文件='ipn_log.txt';
$this->ipn_log=true;
$this->ipn\u响应=“”;
//使用一些默认值填充$fields数组。请参阅paypal
//字段及其数据类型列表的文档。这些
//调用脚本可以覆盖值。
$this->add_字段('rm','2');//返回方法=POST
$this->add_字段('cmd','xclick');
}
函数添加字段($field,$value){
//向字段数组中添加一个key=>value对,这将是
//作为POST变量发送到paypal。如果值已在
//数组,它将被覆盖。
$this->fields[“$field”]=$value;
}
函数submit\u paypal\u post(){
//此函数实际上生成一个完整的HTML页面,包括
//包含隐藏元素的表单,通过
//BODY元素的onLoad属性。我们这样做是为了让您可以验证
//在提交到paypal之前,任何来自您自定义表单的POST VAR。所以
//基本上,您将有自己的表单提交到脚本中
//验证数据,然后调用此函数创建
//另一个隐藏的表单并提交给贝宝。
//用户将在屏幕上短暂看到一条消息,内容如下:
//“请稍候,您的订单正在处理中…”然后立即
//被重定向到贝宝。
回音“\n”;
回显“正在处理付款…\n”;
回音“\n”;
echo“请稍候,您的订单正在处理中…\n”;
回显“paypal\uURL.”\“>\n”;
foreach($this->fields as$name=>$value){
回声“;
}
回音“\n”;
回音“\n”;
}
函数validate_ipn(){
//解析PayPalURL
$url\u parsed=parse\u url($this->paypal\u url);
//从_post变量生成post字符串并加载
//_把战车放到一个arry里,这样我们就可以在呼叫中心和他们一起玩了
//剧本。
$post_字符串=“”;
foreach($\作为$field=>$value发布){
$this->ipn_数据[“$field”]=$value;
$post_string.=$field.'='.urlencode($value)。'&';
}
$post\u string.=“cmd=\u notify-validate”;//追加ipn命令
//打开与paypal的连接
$fp=fsockopen($url_-parsed[host],“80”,$err_-num,$err_-str,30);
如果(!$fp){
//无法打开连接。如果loggin已打开,则会显示错误消息
//将在日志中。
$this->last_error=“fsockopen错误号$errnum:$errstr”;
$this->log_ipn_结果(false);
返回false;
}否则{
//将数据发回paypal
fputs($fp,“POST$url\u解析[path]HTTP/1.1\r\n”);
fputs($fp,“主机:$url\u解析的[Host]\r\n”);
fputs($fp,“内容类型:application/x-www-form-urlencoded\r\n”);
fputs($fp,“内容长度:”.strlen($post_string)。“\r\n”);
fputs($fp,“连接:关闭\r\n\r\n”);
fputs($fp,$post_字符串。“\r\n\r\n”);
//循环遍历来自服务器的响应并附加到变量
而(!feof($fp)){
$this->ipn_response.=fgets($fp,1024);
}
fclose($fp);//关闭连接
}
if(eregi(“已验证”,$this->ipn_响应)){
//有效的IPN事务。
$this->log_ipn_结果(true);
返回true;
}否则{
//无效的IPN事务。有关详细信息,请检查日志。
$this->last_error='IPN验证失败';
$this->log_ipn_结果(false);
返回false;
}
}
函数日志\u ipn\u结果($success){
如果(!$this->ipn\u log)返回;//日志记录是否关闭?
//时间戳
$text='['.日期('m/d/Y g:i A')。]-';
//正在记录成功或失败?
如果($success)$text.=“成功!\n”;
else$text.=“失败:”。$this->last\u错误。“\n”;
//记录POST变量
$text.=“来自Paypal的IPN POST变量:\n”;
foreach($key=>value形式的此->ipn_数据){
$text.=“$key=$value”;
}
//记录来自paypal服务器的响应
$text.=“\nIPN来自Paypal服务器的响应:\n”。$this->ipn\U响应;
//写入日志
$fp=fopen($this->ipn_log_文件,'a');
fwrite($fp,$text.\n\n”);
fclose($fp);//关闭文件
}
函数转储_字段(){
//用于调试,此函数将输出所有字段/值对
//当前在类的实例中使用
//add_field()函数。
echo“paypal_类->转储_字段()输出:”;
回声“
字段名
价值
";
ksort($this->fields);
foreach($此->字段为$key=>$value){