-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
76 lines (65 loc) · 2.38 KB
/
index.js
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
var https = require('https');
var querystring = require('querystring');
var LIVE_HOST = 'www.paypal.com';
var SANDBOX_HOST = 'www.sandbox.paypal.com';
module.exports = {
validator: function validator(callback, productionMode) {
productionMode = Boolean(productionMode);
if (typeof callback != 'function') {
console.error('Cannot use provided callback - it was not a function.');
console.error('Callback received: ' + callback);
return;
}
return function validateIpn(req, res) {
acknowledgeReceipt(res);
sendVerificationRequest(req, callback, productionMode);
};
}
};
function acknowledgeReceipt(res) {
res.sendStatus(200);
}
function sendVerificationRequest(req, callback, productionMode) {
var ipnContent = req.body;
if (productionMode === Boolean(ipnContent.test_ipn)) {
var modeState = productionMode ? "on" : "off";
var ipnEnv = productionMode ? "sandbox" : "live";
var error = new Error("Production mode is " + modeState + ", cannot handle " + ipnEnv + " IPNs.", ipnContent);
callback(error, null, req);
} else {
var body = querystring.stringify(ipnContent) + '&cmd=_notify-validate';
var requestParams = buildRequestParams(productionMode, body);
var request = https.request(requestParams, handleResponse);
request.write(body);
request.on('error', function(err) {
callback(err, null, req);
});
request.end();
}
function handleResponse(response) {
var responseData = [];
response.on('data', function dataReceived(data) {
responseData.push(data);
});
response.on('end', function reponseDone() {
var message = responseData.join('');
if (message === 'VERIFIED') {
callback(null, ipnContent, req);
} else {
var error = new Error("IPN verification failed, message: " + message);
callback(error, ipnContent, req);
}
});
}
}
function buildRequestParams(productionMode, body) {
return {
host: productionMode ? LIVE_HOST : SANDBOX_HOST,
method: 'POST',
path: '/cgi-bin/webscr',
headers: {
'Content-Length': body.length,
'Content-Type': 'application/x-www-form-urlencoded'
}
};
}