This repository was archived by the owner on Jul 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 468
Expand file tree
/
Copy pathfirebase.js
More file actions
78 lines (62 loc) · 2.2 KB
/
firebase.js
File metadata and controls
78 lines (62 loc) · 2.2 KB
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
/**
* Sample PayPal IPN Listener implemented for Firebase Functions.
*/
const axios = require('axios');
const functions = require('firebase-functions');
/**
* @const {boolean} sandbox Indicates if the sandbox endpoint is used.
*/
const sandbox = true;
/** Production Postback URL */
const PRODUCTION_VERIFY_URI = 'https://ipnpb.paypal.com/cgi-bin/webscr';
/** Sandbox Postback URL */
const SANDBOX_VERIFY_URI = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
/**
* Determine endpoint to post verification data to.
*
* @return {String}
*/
function getPaypalURI() {
return sandbox ? SANDBOX_VERIFY_URI : PRODUCTION_VERIFY_URI;
}
/**
* @param {Object} req Firebase Function request context for IPN notification event.
* @param {Object} res Firebase Function response context.
*/
exports.ipnHandler = functions.https.onRequest(async (req, res) => {
console.log('IPN Notification Event Received');
if (req.method !== 'POST') {
console.error('Request method not allowed.');
res.status(405).send('Method Not Allowed');
} else {
// Return empty 200 response to acknowledge IPN post success.
console.log('IPN Notification Event received successfully.');
res.status(200).end();
}
// JSON object of the IPN message consisting of transaction details.
const ipnTransactionMessage = req.body;
// Build the body of the verification post message by prefixing 'cmd=_notify-validate'.
const verificationBody = `cmd=_notify-validate&${req.rawBody}`;
console.log(`Verifying IPN: ${verificationBody}`);
const verifyResponse = await axios({
method: 'post',
url: getPaypalURI(),
data: verificationBody,
});
if (verifyResponse.status !== 200) {
console.log(
`Invalid IPN: IPN message for ID: ${ipnTransactionMessage.txn_id} failed with code ${verifyResponse.status}`
);
return;
}
if (verifyResponse.data !== 'VERIFIED') {
console.error(
`Invalid IPN: Message for ID: ${ipnTransactionMessage.txn_id} is invalid (${verifyResponse.data}).`,
);
return;
}
console.log(
`Verified IPN: IPN message for ID: ${ipnTransactionMessage.txn_id} was verified.`
);
// TODO: Implement your custom post verification logic to handle this event here
});