-
Notifications
You must be signed in to change notification settings - Fork 56
/
functions.php
94 lines (79 loc) · 2.32 KB
/
functions.php
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
/**
* Verify transaction is authentic
*
* @param array $data Post data from Paypal
* @return bool True if the transaction is verified by PayPal
* @throws Exception
*/
function verifyTransaction($data) {
global $paypalUrl;
$req = 'cmd=_notify-validate';
foreach ($data as $key => $value) {
$value = urlencode(stripslashes($value));
$value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i', '${1}%0D%0A${3}', $value); // IPN fix
$req .= "&$key=$value";
}
$ch = curl_init($paypalUrl);
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_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
$res = curl_exec($ch);
if (!$res) {
$errno = curl_errno($ch);
$errstr = curl_error($ch);
curl_close($ch);
throw new Exception("cURL error: [$errno] $errstr");
}
$info = curl_getinfo($ch);
// Check the http response
$httpCode = $info['http_code'];
if ($httpCode != 200) {
throw new Exception("PayPal responded with http code $httpCode");
}
curl_close($ch);
return $res === 'VERIFIED';
}
/**
* Check we've not already processed a transaction
*
* @param string $txnid Transaction ID
* @return bool True if the transaction ID has not been seen before, false if already processed
*/
function checkTxnid($txnid) {
global $db;
$txnid = $db->real_escape_string($txnid);
$results = $db->query('SELECT * FROM `payments` WHERE txnid = \'' . $txnid . '\'');
return ! $results->num_rows;
}
/**
* Add payment to database
*
* @param array $data Payment data
* @return int|bool ID of new payment or false if failed
*/
function addPayment($data) {
global $db;
if (is_array($data)) {
$stmt = $db->prepare('INSERT INTO `payments` (txnid, payment_amount, payment_status, itemid, createdtime) VALUES(?, ?, ?, ?, ?)');
$stmt->bind_param(
'sdsss',
$data['txn_id'],
$data['payment_amount'],
$data['payment_status'],
$data['item_number'],
date('Y-m-d H:i:s')
);
$stmt->execute();
$stmt->close();
return $db->insert_id;
}
return false;
}