-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcallback.js
119 lines (95 loc) · 3.25 KB
/
callback.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// You can use express or any other framework to handle the callback.
router.post('/pay', async (req, res) => {
const { id, status } = req.body;
if (!id || !status) {
// Missing Paramaters
return;
}
/*
Note:
You should check if payment is already processed or not by saving its status in your database after receiving 'complete' status.
*/
switch (status) {
case 'expired': {
// Payment is expired.
break;
}
case 'confirmed': {
// Passed a confirmation.
break;
}
case 'paid': {
// sent the money, but not passed any confirmation
break;
}
// fully confirmed
case 'complete':
{
const resC = await axios.get(`https://api.bitcart.ai/invoices/${id}`);
const data = resC.data;
if (!data?.notification_url) {
// Invoice not found. Probably a fake request.
return;
}
const amountCrypto = data.sent_amount;
const amount = await get_price(data.currency, amountCrypto);
const txid = data.tx_hashes[0];
/* You can now execute final steps here.
// save to db etc.
*/
}
}
});
// You can use express or any other framework to handle the callback.
router.post('/pay', async (req, res) => {
const { id, status } = req.body;
if (!id || !status) {
// Missing Paramaters
return;
}
/*
Note:
You should check if payment is already processed or not by saving its status in your database after receiving 'complete' status.
*/
switch (status) {
case 'expired': {
// Payment is expired.
break;
}
case 'confirmed': {
// Passed a confirmation.
break;
}
case 'paid': {
// sent the money, but not passed any confirmation
break;
}
// fully confirmed
case 'complete':
{
const resC = await axios.get(`https://api.bitcart.ai/invoices/${id}`);
const data = resC.data;
if (!data?.notification_url) {
// Invoice not found. Probably a fake request.
return;
}
const amountCrypto = data.sent_amount;
const amount = await get_price(data.currency, amountCrypto); // amount as USD, eg, 7.65
const txid = data.tx_hashes[0];
/* You can now execute final steps here.
// save to db etc.
*/
}
}
});
async function get_price(coin, amount) {
const fiat = 'usd';
const { data } = await axios.get(`https://api.bitcart.ai/cryptos/rate?currency=${coin.toLowerCase()}&fiat_currency=${fiat}`);
const rate = parseFloat(data);
if (isNaN(rate)) {
throw new Error('Invalid rate value');
}
let p = rate * amount;
p = Math.round((p + Number.EPSILON) * 100) / 100;
return p;
}