-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathclient_token_gateway.js
75 lines (58 loc) · 2.22 KB
/
client_token_gateway.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
'use strict';
let Gateway = require('./gateway').Gateway;
let ErrorResponse = require('./error_response').ErrorResponse;
let Util = require('./util').Util;
let exceptions = require('./exceptions');
let wrapPrototype = require('@braintree/wrap-promise').wrapPrototype;
let DEFAULT_VERSION = 2;
class ClientTokenGateway extends Gateway {
constructor(gateway) {
super();
this.gateway = gateway;
this.config = this.gateway.config;
}
generate(params) {
let err;
params = params || {};
if (!params.version) { params.version = DEFAULT_VERSION; }
err = Util.verifyKeys(this._generateSignature(), params);
if (!err) {
err = this.validateParams(params);
}
if (err) {
return Promise.reject(err);
}
params = {client_token: params}; // eslint-disable-line camelcase
return this.gateway.http.post(`${this.config.baseMerchantPath()}/client_token`, params).then(this.responseHandler());
}
validateParams(params) {
if (params.customerId || !params.options) { return; }
let options = ['makeDefault', 'verifyCard', 'failOnDuplicatePaymentMethod'];
let invalidOptions = options.filter((name) => params.options[name]).map((name) => name);
if (invalidOptions.length > 0) {
return exceptions.UnexpectedError(`A customer id is required for the following options: ${invalidOptions.join(', ')}`); // eslint-disable-line consistent-return, new-cap
}
return null; // eslint-disable-line consistent-return
}
responseHandler() {
return function (response) { // eslint-disable-line consistent-return
if (response.clientToken) {
response.success = true;
response.clientToken = response.clientToken.value;
return response;
} else if (response.apiErrorResponse) {
return new ErrorResponse(response.apiErrorResponse);
}
};
}
_generateSignature() {
return {
valid: [
'addressId', 'customerId', 'proxyMerchantId', 'merchantAccountId',
'version', 'sepaMandateAcceptanceLocation', 'sepaMandateType',
'options', 'options[makeDefault]', 'options[verifyCard]', 'options[failOnDuplicatePaymentMethod]'
]
};
}
}
module.exports = {ClientTokenGateway: wrapPrototype(ClientTokenGateway)};