-
Notifications
You must be signed in to change notification settings - Fork 724
/
stripe.js
372 lines (372 loc) · 11.1 KB
/
stripe.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
'use strict';
const _Error = require('./Error');
const resources = require('./resources');
const DEFAULT_HOST = 'api.stripe.com';
const DEFAULT_PORT = '443';
const DEFAULT_BASE_PATH = '/v1/';
const DEFAULT_API_VERSION = null;
const DEFAULT_TIMEOUT = 80000;
Stripe.PACKAGE_VERSION = require('../package.json').version;
const utils = require('./utils');
const {determineProcessUserAgentProperties, emitWarning} = utils;
Stripe.USER_AGENT = Object.assign(
{
bindings_version: Stripe.PACKAGE_VERSION,
lang: 'node',
publisher: 'stripe',
uname: null,
typescript: false,
},
determineProcessUserAgentProperties()
);
/** @private */
Stripe._UNAME_CACHE = null;
const MAX_NETWORK_RETRY_DELAY_SEC = 2;
const INITIAL_NETWORK_RETRY_DELAY_SEC = 0.5;
const APP_INFO_PROPERTIES = ['name', 'version', 'url', 'partner_id'];
const ALLOWED_CONFIG_PROPERTIES = [
'apiVersion',
'typescript',
'maxNetworkRetries',
'httpAgent',
'httpClient',
'timeout',
'host',
'port',
'protocol',
'telemetry',
'appInfo',
'stripeAccount',
];
const EventEmitter = require('events').EventEmitter;
const StripeResource = require('./StripeResource');
Stripe.StripeResource = StripeResource;
Stripe.resources = resources;
const {HttpClient, HttpClientResponse} = require('./net/HttpClient');
Stripe.HttpClient = HttpClient;
Stripe.HttpClientResponse = HttpClientResponse;
const CryptoProvider = require('./crypto/CryptoProvider');
Stripe.CryptoProvider = CryptoProvider;
function Stripe(key, config = {}) {
if (!(this instanceof Stripe)) {
return new Stripe(key, config);
}
const props = this._getPropsFromConfig(config);
Object.defineProperty(this, '_emitter', {
value: new EventEmitter(),
enumerable: false,
configurable: false,
writable: false,
});
this.VERSION = Stripe.PACKAGE_VERSION;
this.on = this._emitter.on.bind(this._emitter);
this.once = this._emitter.once.bind(this._emitter);
this.off = this._emitter.removeListener.bind(this._emitter);
if (
props.protocol &&
props.protocol !== 'https' &&
(!props.host || /\.stripe\.com$/.test(props.host))
) {
throw new Error(
'The `https` protocol must be used when sending requests to `*.stripe.com`'
);
}
const agent = props.httpAgent || null;
this._api = {
auth: null,
host: props.host || DEFAULT_HOST,
port: props.port || DEFAULT_PORT,
protocol: props.protocol || 'https',
basePath: DEFAULT_BASE_PATH,
version: props.apiVersion || DEFAULT_API_VERSION,
timeout: utils.validateInteger('timeout', props.timeout, DEFAULT_TIMEOUT),
maxNetworkRetries: utils.validateInteger(
'maxNetworkRetries',
props.maxNetworkRetries,
0
),
agent: agent,
httpClient: props.httpClient || Stripe.createNodeHttpClient(agent),
dev: false,
stripeAccount: props.stripeAccount || null,
};
const typescript = props.typescript || false;
if (typescript !== Stripe.USER_AGENT.typescript) {
// The mutation here is uncomfortable, but likely fastest;
// serializing the user agent involves shelling out to the system,
// and given some users may instantiate the library many times without switching between TS and non-TS,
// we only want to incur the performance hit when that actually happens.
Stripe.USER_AGENT.typescript = typescript;
}
if (props.appInfo) {
this._setAppInfo(props.appInfo);
}
this._prepResources();
this._setApiKey(key);
this.errors = _Error;
this.webhooks = require('./Webhooks');
this._prevRequestMetrics = [];
this._enableTelemetry = props.telemetry !== false;
// Expose StripeResource on the instance too
this.StripeResource = Stripe.StripeResource;
}
Stripe.errors = _Error;
Stripe.webhooks = require('./Webhooks');
Stripe.createNodeHttpClient = (agent) => {
const {NodeHttpClient} = require('./net/NodeHttpClient');
return new NodeHttpClient(agent);
};
/**
* Creates an HTTP client for issuing Stripe API requests which uses the Web
* Fetch API.
*
* A fetch function can optionally be passed in as a parameter. If none is
* passed, will default to the default `fetch` function in the global scope.
*/
Stripe.createFetchHttpClient = (fetchFn) => {
const {FetchHttpClient} = require('./net/FetchHttpClient');
return new FetchHttpClient(fetchFn);
};
/**
* Create a CryptoProvider which uses the built-in Node crypto libraries for
* its crypto operations.
*/
Stripe.createNodeCryptoProvider = () => {
const NodeCryptoProvider = require('./crypto/NodeCryptoProvider');
return new NodeCryptoProvider();
};
/**
* Creates a CryptoProvider which uses the Subtle Crypto API from the Web
* Crypto API spec for its crypto operations.
*
* A SubtleCrypto interface can optionally be passed in as a parameter. If none
* is passed, will default to the default `crypto.subtle` object in the global
* scope.
*/
Stripe.createSubtleCryptoProvider = (subtleCrypto) => {
const SubtleCryptoProvider = require('./crypto/SubtleCryptoProvider');
return new SubtleCryptoProvider(subtleCrypto);
};
Stripe.prototype = {
/**
* @private
*/
_setApiKey(key) {
if (key) {
this._setApiField('auth', `Bearer ${key}`);
}
},
/**
* @private
* This may be removed in the future.
*/
_setAppInfo(info) {
if (info && typeof info !== 'object') {
throw new Error('AppInfo must be an object.');
}
if (info && !info.name) {
throw new Error('AppInfo.name is required');
}
info = info || {};
const appInfo = APP_INFO_PROPERTIES.reduce((accum, prop) => {
if (typeof info[prop] == 'string') {
accum = accum || {};
accum[prop] = info[prop];
}
return accum;
}, undefined);
this._appInfo = appInfo;
},
/**
* @private
* This may be removed in the future.
*/
_setApiField(key, value) {
this._api[key] = value;
},
/**
* @private
* Please open or upvote an issue at github.com/stripe/stripe-node
* if you use this, detailing your use-case.
*
* It may be deprecated and removed in the future.
*/
getApiField(key) {
return this._api[key];
},
setClientId(clientId) {
this._clientId = clientId;
},
getClientId() {
return this._clientId;
},
/**
* @private
* Please open or upvote an issue at github.com/stripe/stripe-node
* if you use this, detailing your use-case.
*
* It may be deprecated and removed in the future.
*/
getConstant: (c) => {
switch (c) {
case 'DEFAULT_HOST':
return DEFAULT_HOST;
case 'DEFAULT_PORT':
return DEFAULT_PORT;
case 'DEFAULT_BASE_PATH':
return DEFAULT_BASE_PATH;
case 'DEFAULT_API_VERSION':
return DEFAULT_API_VERSION;
case 'DEFAULT_TIMEOUT':
return DEFAULT_TIMEOUT;
case 'MAX_NETWORK_RETRY_DELAY_SEC':
return MAX_NETWORK_RETRY_DELAY_SEC;
case 'INITIAL_NETWORK_RETRY_DELAY_SEC':
return INITIAL_NETWORK_RETRY_DELAY_SEC;
}
return Stripe[c];
},
getMaxNetworkRetries() {
return this.getApiField('maxNetworkRetries');
},
/**
* @private
* This may be removed in the future.
*/
_setApiNumberField(prop, n, defaultVal) {
const val = utils.validateInteger(prop, n, defaultVal);
this._setApiField(prop, val);
},
getMaxNetworkRetryDelay() {
return MAX_NETWORK_RETRY_DELAY_SEC;
},
getInitialNetworkRetryDelay() {
return INITIAL_NETWORK_RETRY_DELAY_SEC;
},
/**
* @private
*/
getUname(cb) {
if (!Stripe._UNAME_CACHE) {
Stripe._UNAME_CACHE = new Promise((resolve) => {
utils.safeExec('uname -a', (err, uname) => {
resolve(uname);
});
});
}
Stripe._UNAME_CACHE.then((uname) => cb(uname));
},
/**
* @private
* Please open or upvote an issue at github.com/stripe/stripe-node
* if you use this, detailing your use-case.
*
* It may be deprecated and removed in the future.
*
* Gets a JSON version of a User-Agent and uses a cached version for a slight
* speed advantage.
*/
getClientUserAgent(cb) {
return this.getClientUserAgentSeeded(Stripe.USER_AGENT, cb);
},
/**
* @private
* Please open or upvote an issue at github.com/stripe/stripe-node
* if you use this, detailing your use-case.
*
* It may be deprecated and removed in the future.
*
* Gets a JSON version of a User-Agent by encoding a seeded object and
* fetching a uname from the system.
*/
getClientUserAgentSeeded(seed, cb) {
this.getUname((uname) => {
const userAgent = {};
for (const field in seed) {
userAgent[field] = encodeURIComponent(seed[field]);
}
// URI-encode in case there are unusual characters in the system's uname.
userAgent.uname = encodeURIComponent(uname || 'UNKNOWN');
const client = this.getApiField('httpClient');
if (client) {
userAgent.httplib = encodeURIComponent(client.getClientName());
}
if (this._appInfo) {
userAgent.application = this._appInfo;
}
cb(JSON.stringify(userAgent));
});
},
/**
* @private
* Please open or upvote an issue at github.com/stripe/stripe-node
* if you use this, detailing your use-case.
*
* It may be deprecated and removed in the future.
*/
getAppInfoAsString() {
if (!this._appInfo) {
return '';
}
let formatted = this._appInfo.name;
if (this._appInfo.version) {
formatted += `/${this._appInfo.version}`;
}
if (this._appInfo.url) {
formatted += ` (${this._appInfo.url})`;
}
return formatted;
},
getTelemetryEnabled() {
return this._enableTelemetry;
},
/**
* @private
* This may be removed in the future.
*/
_prepResources() {
for (const name in resources) {
this[utils.pascalToCamelCase(name)] = new resources[name](this);
}
},
/**
* @private
* This may be removed in the future.
*/
_getPropsFromConfig(config) {
// If config is null or undefined, just bail early with no props
if (!config) {
return {};
}
// config can be an object or a string
const isString = typeof config === 'string';
const isObject = config === Object(config) && !Array.isArray(config);
if (!isObject && !isString) {
throw new Error('Config must either be an object or a string');
}
// If config is a string, we assume the old behavior of passing in a string representation of the api version
if (isString) {
return {
apiVersion: config,
};
}
// If config is an object, we assume the new behavior and make sure it doesn't contain any unexpected values
const values = Object.keys(config).filter(
(value) => !ALLOWED_CONFIG_PROPERTIES.includes(value)
);
if (values.length > 0) {
throw new Error(
`Config object may only contain the following: ${ALLOWED_CONFIG_PROPERTIES.join(
', '
)}`
);
}
return config;
},
};
module.exports = Stripe;
// expose constructor as a named property to enable mocking with Sinon.JS
module.exports.Stripe = Stripe;
// Allow use with the TypeScript compiler without `esModuleInterop`.
// We may also want to add `Object.defineProperty(exports, "__esModule", {value: true});` in the future, so that Babel users will use the `default` version.
module.exports.default = Stripe;