-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
77 lines (63 loc) · 1.94 KB
/
server.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
const Koa = require("koa");
const Router = require("@koa/router");
const cors = require("@koa/cors");
const ethers = require("ethers");
const PaymentProcessor = require("./sc/contracts/PaymentProcessor.json");
const { Payment } = require("./db");
const items = {
'1': { id: 1, url: 'http://urlTodownloadItem1' },
'2': { id: 2, url: 'http://urlTodownloadItem2' },
'3': { id: 3, url: 'http://urlTodownloadItem3' }
};
const app = new Koa();
const router = new Router();
router.get('/api/getPaymentId/:itemId', async ctx => {
const paymentId = (Math.random() * 1000).toFixed(0);
await Payment.create({
id: paymentId,
item: ctx.params.itemId,
paid: false
});
ctx.body = { paymentId };
});
router.get('/api/getitemUrl/:paymentId', async ctx => {
const payment = await Payment.findOne({ id: ctx.params.paymentId });
if (payment && payment.paid === true) {
ctx.body = {
url: items[payment.itemId].url,
};
}
else {
ctx.body = {
url: ''
}
}
});
app.use(cors())
.use(router.routes())
.use(router.allowedMethods());
app.listen(4000, () => {
console.log("Running on Port 4000");
});
const listenToEvents = () => {
const provider = new ethers.providers.JsonRpcProvider('http://localhost:9545');
const networkId = '5777';
const paymentProcessor = new ethers.Contract(
PaymentProcessor.networks[networkId].address,
PaymentProcessor.abi,
provider
)
paymentProcessor.on('PaymentDone', async (payer, amount, paymentId, date) => {
console.log(`
from: ${payer}
amount: ${amount},
paymentId: ${paymentId}
date: ${(new Date(date.toNumber() * 1000)).toLocaleString()}
`);
const payment = await Payment.findOne({ id: paymentId });
if (payment) {
payment.paid = true;
await payment.save();
}
})
}