-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
82 lines (77 loc) · 1.89 KB
/
index.js
File metadata and controls
82 lines (77 loc) · 1.89 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
79
80
81
82
'use strict';
const request = require('request');
const OAuth2 = require('oauth').OAuth2;
let clientId;
let clientSecret;
let oauthUrl;
let apiUrl;
let timeout;
function parse(body) {
try {
return JSON.parse(body);
} catch (e) {
console.error(e);
return {};
}
}
function generateApiToken(authParams, next) {
let oauth2 = new OAuth2(clientId, clientSecret, oauthUrl,
null, '/oauth2/auth', null);
if (!authParams) {
authParams = {
grant_type: 'client_credentials'
};
}
oauth2.getOAuthAccessToken('', authParams, next);
};
function apiRequest(method, resource, payload, authParams, callback) {
generateApiToken(authParams, function(error, bearer) {
if (error) {
callback(error);
return;
}
let options = {
url: `${apiUrl}${resource}`,
timeout,
method,
headers: {
'Authorization': `Bearer ${bearer}`,
'User-Agent': 'ClassyPay Node.JS'
}
};
if (payload) {
options.headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(payload);
}
request(options, function(error, response, body) {
if (error || response.statusCode !== 200) {
callback(error ||
{
status: response.statusCode,
error,
response,
body,
object: parse(body)
}
);
} else {
callback(null, body ? JSON.parse(body) : {});
}
});
});
}
module.exports = (config) => {
if (!config || !config.clientId || !config.clientSecret ||
!config.oauthUrl || !config.apiUrl || !config.timeout) {
throw new Error(`You must provide clientId, clientSecret, oauthUrl,
apiUrl and timeout.`);
}
clientId = config.clientId;
clientSecret = config.clientSecret;
oauthUrl = config.oauthUrl;
apiUrl = config.apiUrl;
timeout = config.timeout;
return {
request: apiRequest
};
};