-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (59 loc) · 2.45 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
exports.BlackCoinCallback = class {
constructor (callbackSecret) {
if(!callbackSecret) throw new Error(`BlackCoin Callback: Вы не передали параметр callback_secret.`);
this.callbackSecret = callbackSecret;
this.callbacks = [];
this.fastify = new require('fastify')();
this.fastify.post('/', request => {
const { body } = request;
if(!this.#check(body)) return { ok: false };
this.callbacks.map(callback => callback(body));
return { ok: true };
});
};
#check (body) {
const { sign } = body;
delete body.sign;
return (require('js-md5')(Object.keys(body).sort((a, b) => a.localeCompare(b)).reduce((_, key) => (_ + `&${key}=${body[key]}`), '') + `&${this.callbackSecret}`) === sign);
};
on (callback) {
if(typeof callback !== 'function') throw new Error('BlackCoin Callback: Callback must be a function.');
this.callbacks.push(callback);
};
start (port = 3000, host = '0.0.0.0') {
return this.fastify.listen({ port, host });
};
stop () {
return this.fastify.close();
};
};
exports.BlackCoin = class {
constructor (options = {}) {
const { token, version } = options;
if(!token) throw new Error('BlackCoin: Вы не передали ключ авторизации (token).');
this.api = {
token,
headers: { Authorization: 'Bearer ' + token },
url: 'http://black-coin.ru/black_coin/api/',
version: version || 'v1'
};
};
callApi (method, data = {}, type = 'get') {
return require('axios')[type](this.api.url + `${this.api.version}/` + method, { [type === 'get' ? 'params' : 'data']: data, headers: this.api.headers }).then(({ data }) => data);
};
getBalance () {
return this.callApi('balance');
};
getTransactions (type = 'all', afterId = 0, limit = 20) {
return this.callApi('transactions', { type, after_id: afterId, limit });
};
sendCoins (recipientId, amount) {
return this.callApi('send_coins', { recipient_id: recipientId, amount }, 'post');
};
setCallback (url = '') {
return this.callApi('callback', { url }, 'post');
};
dropCallback () {
return this.callApi('callback', {}, 'delete');
};
};