處理 PayPal 的 IPN 返回


這程式早在十月份時已經完成.
是寫給當時應一位朋友用於學習和請教的.
原來還沒記錄在這裡..代碼節錄如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
// 載入必要的檔案,如 init.php / config.php 之類的 ....

$paypal_url = $config['payment']['paypal_url'];

// Parse url
$parsed_paypal_url = parse_url($paypal_url);

// Build post string
$post_data = http_build_query($_POST)."&cmd=_notify-validate";

// Set the port number
if($parsed_paypal_url['scheme'] == "https") {
$ssl = "ssl://";
$parsed_paypal_url['port'] = "443";
} else {
$parsed_paypal_url['port'] = "80";
}

//Create paypal connection
$fp = @fsockopen($ssl.$parsed_paypal_url['host'], $parsed_paypal_url['port'], $error_number, $error_string, 30);

//Error checking
if (!$fp) {
file_put_contents(CACHE_ROOT.'/ipn.txt', $error_number.' - '.$error_string);
}else{
fputs($fp, "POST {$parsed_paypal_url['path']} HTTP/1.1\r\n");
fputs($fp, "Host: {$parsed_paypal_url['host']}\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($post_data)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $post_data . "\r\n\r\n");

// Response from the server
while(!feof($fp)) {
$info[] = @fgets($fp, 1024);
}

fclose($fp);

$info = implode(",", $info);

// Get back the invoice info (Request::post like $_POST['KEYWORD'])
$item_name = Request::post('item_name');
$item_number = Request::post('item_number');
$payment_status = Request::post('payment_status');
$payment_amount = Request::post('mc_gross');
$payment_currency = Request::post('mc_currency');
$txn_id = Request::post('txn_id');
$receiver_email = Request::post('receiver_email');
$payer_email = Request::post('payer_email');
$invoice_number = Request::post('invoice');

// Check the response info have or not verified keyword
if (preg_match("/VERIFIED/i", $info)) {
file_put_contents(CACHE_ROOT.'/ipn.txt', 'Verified'); // Save to log

$table = new Table("payment", $invoice_number, "invoice_number");
$table->status = 'completed';
$table->update_at = time();
$table->renew();
}else{
file_put_contents(CACHE_ROOT.'/ipn.txt', 'Not Verified');

Session::set("payment_status", false);
}
}
?>