-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathindex.js
97 lines (85 loc) · 2.2 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
require('dotenv').config();
const express = require('express');
const { getPaymentDriver } = require('monopay');
const app = express();
app.use(express.urlencoded({ extended: true }));
const port = 3000;
/**
* A mock database for storing a payment
*/
const db = {
paymentID,
amount,
};
/** @type {import('monopay').ConfigObject} */
const monopayConfiguration = {
zibal: {
merchantId: 'your-merchant-id',
sandbox: true,
},
zarinpal: {
merchantId: 'your-merchant-id',
sandbox: true,
},
sadad: {
merchantId: 'your-merchant-id',
terminalId: 'your-terminal-id',
terminalKey: 'your-terminal-key',
},
payir: {
apiKey: 'your-api-key',
sandbox: true,
},
nextpay: {
apiKey: 'your-api-key',
},
};
/** @type {import('monopay').DriverName} */
const chosenDriver = 'nextpay';
/**
* The purchase route that will redirect the user to the payment gateway
*/
app.get('/purchase', async (req, res) => {
try {
const driver = getPaymentDriver(chosenDriver)(monopayConfiguration[chosenDriver]);
const paymentInfo = await driver.request({
amount: 20000,
callbackUrl: process.env.APP_URL + '/callback',
});
// Save the payment info in database
db.paymentID = paymentInfo.referenceId;
db.amount = 20000;
res.send(`<html>
<body>
<h1> We're redirecting you to the payment gateway... </h1>
<script>${paymentInfo.getScript()}</script>
</body>
</html>`);
} catch (e) {
console.log(e.message);
}
});
/**
* The callback URL that was given to `request`
*/
app.all('/callback', async (req, res) => {
try {
const driver = getPaymentDriver(chosenDriver)(monopayConfiguration[chosenDriver]);
const receipt = await driver.verify(
{
amount: db.amount, // from database
referenceId: db.paymentID, // from database
},
{ ...req.query, ...req.body },
); // support both GET and POST
res.json({
transactionId: receipt.transactionId, // Is probably null if you're using sandbox
success: true,
});
} catch (e) {
console.log(e.message);
}
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});