-
Notifications
You must be signed in to change notification settings - Fork 23
/
index.js
executable file
·71 lines (66 loc) · 2.19 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
const STRIPE_URL = 'https://api.stripe.com/v1/';
const FORMURLENCODED = require('form-urlencoded');
module.exports = function(key) {
return {
createToken: async function (details) {
const keys = Object.keys(details);
const index = _findType(details, keys);
var token;
if (index == 0) {
let type = keys[index];
var newDetails = _convertDetails(type, details[type]);
token = await _createTokenHelper(newDetails, key);
} else {
token = await _createTokenHelper(details, key);
}
return _parseJSON(token);
}
}
}
// Stripe normally only allows for fetch format for the details provided.
// _findType allows the user to use the node format of the details by
// figuring out which format/type the details provided are.
function _findType(details, keys) {
if (details.card != null) {
return keys.indexOf("card");
} else if (details.bank_account != null) {
return keys.indexOf("bank_account");
} else if (details.pii != null) {
return keys.indexOf("pii");
} else if (details.account != null) {
return keys.indexOf("account");
} else return false;
}
// _convertDetails converts and returns the data in the given details
// to the correct Stripe format for the given type.
function _convertDetails(type, details) {
var convertedDetails = {}
for (var data in details) {
const string = type + '[' + data + ']';
convertedDetails[string] = details[data];
}
return convertedDetails;
}
// Stripe gives a JSON object with the token object embedded as a JSON string.
// _parseJSON finds that string in and returns it as a JSON object, or an error
// if Stripe threw an error instead. If the JSON does not need to be parsed, returns the token.
async function _parseJSON(token) {
if (token._bodyInit == null) {
return token;
} else {
const body = await token.json();
return body;
}
}
function _createTokenHelper(details, key) {
const formBody = FORMURLENCODED(details);
return fetch(STRIPE_URL + 'tokens', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + key
},
body: formBody
});
}