stripe
Version:
Stripe API wrapper
568 lines • 25.4 kB
JavaScript
import * as _Error from './Error.js';
import { RequestSender } from './RequestSender.js';
import { StripeResource } from './StripeResource.js';
import { StripeContext } from './StripeContext.js';
import { NodePlatformFunctions } from './platform/NodePlatformFunctions.js';
import { DEFAULT_BASE_ADDRESSES, } from './Types.js';
import { createWebhooks } from './Webhooks.js';
import { ApiVersion } from './apiVersion.js';
import { CryptoProvider } from './crypto/CryptoProvider.js';
import { HttpClient, HttpClientResponse } from './net/HttpClient.js';
import * as resources from './resources.js';
import { createApiKeyAuthenticator, detectAIAgent, determineProcessUserAgentProperties, pascalToCamelCase, validateInteger, } from './utils.js';
import { Decimal, } from './shared.js';
// StripeInstanceImports: The beginning of the section generated from our OpenAPI spec
import { AccountResource, } from './resources/Accounts.js';
import { AccountLinkResource, } from './resources/AccountLinks.js';
import { AccountSessionResource, } from './resources/AccountSessions.js';
import { ApplePayDomainResource, } from './resources/ApplePayDomains.js';
import { ApplicationFeeResource, } from './resources/ApplicationFees.js';
import { BalanceResource, } from './resources/Balance.js';
import { BalanceSettingResource, } from './resources/BalanceSettings.js';
import { BalanceTransactionResource, } from './resources/BalanceTransactions.js';
import { ChargeResource, } from './resources/Charges.js';
import { ConfirmationTokenResource, } from './resources/ConfirmationTokens.js';
import { CountrySpecResource, } from './resources/CountrySpecs.js';
import { CouponResource, } from './resources/Coupons.js';
import { CreditNoteResource, } from './resources/CreditNotes.js';
import { CustomerResource, } from './resources/Customers.js';
import { CustomerSessionResource, } from './resources/CustomerSessions.js';
import { DisputeResource, } from './resources/Disputes.js';
import { EphemeralKeyResource, } from './resources/EphemeralKeys.js';
import { ExchangeRateResource, } from './resources/ExchangeRates.js';
import { FileResource, } from './resources/Files.js';
import { FileLinkResource, } from './resources/FileLinks.js';
import { InvoiceResource, } from './resources/Invoices.js';
import { InvoiceItemResource, } from './resources/InvoiceItems.js';
import { InvoicePaymentResource, } from './resources/InvoicePayments.js';
import { InvoiceRenderingTemplateResource, } from './resources/InvoiceRenderingTemplates.js';
import { MandateResource, } from './resources/Mandates.js';
import { PaymentAttemptRecordResource, } from './resources/PaymentAttemptRecords.js';
import { PaymentIntentResource, } from './resources/PaymentIntents.js';
import { PaymentLinkResource, } from './resources/PaymentLinks.js';
import { PaymentMethodResource, } from './resources/PaymentMethods.js';
import { PaymentMethodConfigurationResource, } from './resources/PaymentMethodConfigurations.js';
import { PaymentMethodDomainResource, } from './resources/PaymentMethodDomains.js';
import { PaymentRecordResource, } from './resources/PaymentRecords.js';
import { PayoutResource, } from './resources/Payouts.js';
import { PlanResource, } from './resources/Plans.js';
import { PriceResource, } from './resources/Prices.js';
import { ProductResource, } from './resources/Products.js';
import { PromotionCodeResource, } from './resources/PromotionCodes.js';
import { QuoteResource, } from './resources/Quotes.js';
import { RefundResource, } from './resources/Refunds.js';
import { ReviewResource, } from './resources/Reviews.js';
import { SetupAttemptResource, } from './resources/SetupAttempts.js';
import { SetupIntentResource, } from './resources/SetupIntents.js';
import { ShippingRateResource, } from './resources/ShippingRates.js';
import { SourceResource, } from './resources/Sources.js';
import { SubscriptionResource, } from './resources/Subscriptions.js';
import { SubscriptionItemResource, } from './resources/SubscriptionItems.js';
import { SubscriptionScheduleResource, } from './resources/SubscriptionSchedules.js';
import { TaxCodeResource, } from './resources/TaxCodes.js';
import { TaxIdResource, } from './resources/TaxIds.js';
import { TaxRateResource, } from './resources/TaxRates.js';
import { TokenResource, } from './resources/Tokens.js';
import { TopupResource, } from './resources/Topups.js';
import { TransferResource, } from './resources/Transfers.js';
import { WebhookEndpointResource, } from './resources/WebhookEndpoints.js';
import { Apps } from './resources/Apps/index.js';
import { Billing } from './resources/Billing/index.js';
import { BillingPortal } from './resources/BillingPortal/index.js';
import { Checkout } from './resources/Checkout/index.js';
import { Climate } from './resources/Climate/index.js';
import { Entitlements } from './resources/Entitlements/index.js';
import { FinancialConnections } from './resources/FinancialConnections/index.js';
import { Forwarding } from './resources/Forwarding/index.js';
import { Identity } from './resources/Identity/index.js';
import { Issuing } from './resources/Issuing/index.js';
import { Radar } from './resources/Radar/index.js';
import { Reporting } from './resources/Reporting/index.js';
import { Sigma } from './resources/Sigma/index.js';
import { Tax } from './resources/Tax/index.js';
import { Terminal } from './resources/Terminal/index.js';
import { TestHelpers } from './resources/TestHelpers/index.js';
import { Treasury } from './resources/Treasury/index.js';
import { V2 } from './resources/V2/index.js';
// StripeInstanceImports: The end of the section generated from our OpenAPI spec
// V1EventImports: The beginning of the section generated from our OpenAPI spec
import { EventResource, } from './resources/Events.js';
// V1EventImports: The end of the section generated from our OpenAPI spec
import { OAuthResource } from './resources.js';
const DEFAULT_HOST = 'api.stripe.com';
const DEFAULT_PORT = '443';
const DEFAULT_BASE_PATH = '/v1/';
const DEFAULT_API_VERSION = ApiVersion;
const DEFAULT_TIMEOUT = 80000;
const MAX_NETWORK_RETRY_DELAY_SEC = 5;
const INITIAL_NETWORK_RETRY_DELAY_SEC = 0.5;
const APP_INFO_PROPERTIES = [
'name',
'version',
'url',
'partner_id',
];
const ALLOWED_CONFIG_PROPERTIES = [
'authenticator',
'apiVersion',
'typescript',
'maxNetworkRetries',
'httpAgent',
'httpClient',
'timeout',
'host',
'port',
'protocol',
'telemetry',
'appInfo',
'stripeAccount',
'stripeContext',
];
const defaultRequestSenderFactory = (stripe) => new RequestSender(stripe, StripeResource.MAX_BUFFERED_REQUEST_METRICS);
export class Stripe {
static initialize(platformFunctions, requestSenderFactory = defaultRequestSenderFactory) {
Stripe._platformFunctions = platformFunctions;
Stripe._requestSenderFactory = requestSenderFactory;
Stripe.webhooks = createWebhooks(platformFunctions);
Stripe.createNodeHttpClient = platformFunctions.createNodeHttpClient;
Stripe.createFetchHttpClient = platformFunctions.createFetchHttpClient;
Stripe.createNodeCryptoProvider =
platformFunctions.createNodeCryptoProvider;
Stripe.createSubtleCryptoProvider =
platformFunctions.createSubtleCryptoProvider;
}
constructor(key, config = {}) {
this._authenticator = null;
const props = this._getPropsFromConfig(config);
this._platformFunctions = Stripe._platformFunctions;
Object.defineProperty(this, '_emitter', {
value: this._platformFunctions.createEmitter(),
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);
const agent = props.httpAgent || null;
this._api = {
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: validateInteger('timeout', props.timeout, DEFAULT_TIMEOUT),
maxNetworkRetries: validateInteger('maxNetworkRetries', props.maxNetworkRetries, 2),
agent: agent,
httpClient: props.httpClient ||
(agent
? this._platformFunctions.createNodeHttpClient(agent)
: this._platformFunctions.createDefaultHttpClient()),
dev: false,
stripeAccount: props.stripeAccount || null,
stripeContext: props.stripeContext || 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._setAuthenticator(key, props.authenticator || null);
this.errors = _Error;
this.Decimal = Decimal;
this.webhooks = Stripe.webhooks;
this._prevRequestMetrics = [];
this._enableTelemetry = props.telemetry !== false;
this._requestSender = Stripe._requestSenderFactory(this);
// StripeInitInstanceVariables: The beginning of the section generated from our OpenAPI spec
this.accountLinks = new AccountLinkResource(this);
this.accountSessions = new AccountSessionResource(this);
this.accounts = new AccountResource(this);
this.applePayDomains = new ApplePayDomainResource(this);
this.applicationFees = new ApplicationFeeResource(this);
this.balance = new BalanceResource(this);
this.balanceSettings = new BalanceSettingResource(this);
this.balanceTransactions = new BalanceTransactionResource(this);
this.charges = new ChargeResource(this);
this.confirmationTokens = new ConfirmationTokenResource(this);
this.countrySpecs = new CountrySpecResource(this);
this.coupons = new CouponResource(this);
this.creditNotes = new CreditNoteResource(this);
this.customerSessions = new CustomerSessionResource(this);
this.customers = new CustomerResource(this);
this.disputes = new DisputeResource(this);
this.ephemeralKeys = new EphemeralKeyResource(this);
this.events = new EventResource(this);
this.exchangeRates = new ExchangeRateResource(this);
this.fileLinks = new FileLinkResource(this);
this.files = new FileResource(this);
this.invoiceItems = new InvoiceItemResource(this);
this.invoicePayments = new InvoicePaymentResource(this);
this.invoiceRenderingTemplates = new InvoiceRenderingTemplateResource(this);
this.invoices = new InvoiceResource(this);
this.mandates = new MandateResource(this);
this.paymentAttemptRecords = new PaymentAttemptRecordResource(this);
this.paymentIntents = new PaymentIntentResource(this);
this.paymentLinks = new PaymentLinkResource(this);
this.paymentMethodConfigurations = new PaymentMethodConfigurationResource(this);
this.paymentMethodDomains = new PaymentMethodDomainResource(this);
this.paymentMethods = new PaymentMethodResource(this);
this.paymentRecords = new PaymentRecordResource(this);
this.payouts = new PayoutResource(this);
this.plans = new PlanResource(this);
this.prices = new PriceResource(this);
this.products = new ProductResource(this);
this.promotionCodes = new PromotionCodeResource(this);
this.quotes = new QuoteResource(this);
this.refunds = new RefundResource(this);
this.reviews = new ReviewResource(this);
this.setupAttempts = new SetupAttemptResource(this);
this.setupIntents = new SetupIntentResource(this);
this.shippingRates = new ShippingRateResource(this);
this.sources = new SourceResource(this);
this.subscriptionItems = new SubscriptionItemResource(this);
this.subscriptionSchedules = new SubscriptionScheduleResource(this);
this.subscriptions = new SubscriptionResource(this);
this.taxCodes = new TaxCodeResource(this);
this.taxIds = new TaxIdResource(this);
this.taxRates = new TaxRateResource(this);
this.tokens = new TokenResource(this);
this.topups = new TopupResource(this);
this.transfers = new TransferResource(this);
this.webhookEndpoints = new WebhookEndpointResource(this);
this.apps = new Apps(this);
this.billing = new Billing(this);
this.billingPortal = new BillingPortal(this);
this.checkout = new Checkout(this);
this.climate = new Climate(this);
this.entitlements = new Entitlements(this);
this.financialConnections = new FinancialConnections(this);
this.forwarding = new Forwarding(this);
this.identity = new Identity(this);
this.issuing = new Issuing(this);
this.radar = new Radar(this);
this.reporting = new Reporting(this);
this.sigma = new Sigma(this);
this.tax = new Tax(this);
this.terminal = new Terminal(this);
this.testHelpers = new TestHelpers(this);
this.treasury = new Treasury(this);
this.v2 = new V2(this);
// StripeInitInstanceVariables: The end of the section generated from our OpenAPI spec
// hardcoded properties and resources
// account property is added for backward compatibility
this.account = this.accounts;
this.oauth = new OAuthResource(this);
// this._prepResources();
}
/**
* Allows for sending "raw" requests to the Stripe API, which can be used for
* testing new API endpoints or performing requests that the library does
* not support yet.
*
* @param method - HTTP request method, 'GET', 'POST', or 'DELETE'
* @param path - The path of the request, e.g. '/v1/beta_endpoint'
* @param params - The parameters to include in the request body.
* @param options - Additional request options.
*/
rawRequest(method, path, params, options) {
return this._requestSender._rawRequest(method, path, params, options);
}
/**
* @private
*/
_setAuthenticator(key, authenticator) {
if (key && authenticator) {
throw new Error("Can't specify both apiKey and authenticator");
}
if (!key && !authenticator) {
throw new Error('Neither apiKey nor config.authenticator provided');
}
this._authenticator = key ? createApiKeyAuthenticator(key) : authenticator;
}
/**
* @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 || {};
this._appInfo = APP_INFO_PROPERTIES.reduce((accum, prop) => {
if (typeof info[prop] == 'string') {
accum = accum || {};
accum[prop] = info[prop];
}
return accum;
}, {});
}
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];
}
resolveBaseAddress(apiBase) {
// can override host globally, but not locally
const instanceHost = this.getApiField('host');
if (instanceHost !== DEFAULT_HOST) {
return instanceHost;
}
return DEFAULT_BASE_ADDRESSES[apiBase];
}
getMaxNetworkRetries() {
return this.getApiField('maxNetworkRetries');
}
/**
* @private
* This may be removed in the future.
*/
_setApiNumberField(prop, n, defaultVal) {
// @ts-ignore
const val = validateInteger(prop, n, defaultVal);
this._setApiField(prop, val);
}
getMaxNetworkRetryDelay() {
return MAX_NETWORK_RETRY_DELAY_SEC;
}
getInitialNetworkRetryDelay() {
return INITIAL_NETWORK_RETRY_DELAY_SEC;
}
/**
* @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) {
const userAgent = {};
for (const field in seed) {
if (!Object.prototype.hasOwnProperty.call(seed, field)) {
continue;
}
userAgent[field] = encodeURIComponent(seed[field] ?? 'null');
}
const platformInfo = this._platformFunctions.getPlatformInfo();
if (platformInfo && this.getTelemetryEnabled()) {
userAgent.platform = encodeURIComponent(platformInfo);
}
else {
delete userAgent.platform;
}
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) {
if (!Object.prototype.hasOwnProperty.call(resources, name)) {
continue;
}
// @ts-ignore
this[pascalToCamelCase(name.replace('Resource', ''))] = 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;
}
/**
* @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];
}
parseEventNotification(payload, header, secret, tolerance, cryptoProvider, receivedAt
// this return type is ignored?? picks up types from `types/index.d.ts` instead
) {
// Verify the signature using the internal signature helper directly,
// bypassing constructEvent's v2 payload check (since v2 payloads are
// expected here).
if (!this.webhooks.signature) {
throw new Error('ERR: missing signature helper, unable to verify');
}
this.webhooks.signature.verifyHeader(payload, header, secret, tolerance || this.webhooks.DEFAULT_TOLERANCE, cryptoProvider || this._platformFunctions.createDefaultCryptoProvider(), receivedAt);
const eventNotification = payload instanceof Uint8Array
? JSON.parse(new TextDecoder('utf8').decode(payload))
: JSON.parse(payload);
if (eventNotification && eventNotification.object === 'event') {
throw new Error('You passed a webhook payload to stripe.parseEventNotification, which expects an event notification. Use stripe.webhooks.constructEvent instead.');
}
// Parse string context into StripeContext object if present
if (eventNotification.context) {
eventNotification.context = StripeContext.parse(eventNotification.context);
}
eventNotification.fetchEvent = () => {
return this._requestSender._rawRequest('GET', `/v2/core/events/${eventNotification.id}`, undefined, {
stripeContext: eventNotification.context,
headers: {
'Stripe-Request-Trigger': `event=${eventNotification.id}`,
},
}, ['fetch_event']);
};
eventNotification.fetchRelatedObject = () => {
if (!eventNotification.related_object) {
return Promise.resolve(null);
}
return this._requestSender._rawRequest('GET', eventNotification.related_object.url, undefined, {
stripeContext: eventNotification.context,
headers: {
'Stripe-Request-Trigger': `event=${eventNotification.id}`,
},
}, ['fetch_related_object']);
};
return eventNotification;
}
}
Stripe.PACKAGE_VERSION = '20.4.1';
Stripe.API_VERSION = ApiVersion;
Stripe.aiAgent = typeof process !== 'undefined' && process.env
? detectAIAgent(process.env)
: '';
Stripe.AI_AGENT = Stripe.aiAgent;
Stripe.USER_AGENT = {
bindings_version: Stripe.PACKAGE_VERSION,
lang: 'node',
typescript: false,
...determineProcessUserAgentProperties(),
...(Stripe.aiAgent ? { ai_agent: Stripe.aiAgent } : {}),
};
Stripe.StripeResource = StripeResource;
Stripe.resources = resources;
Stripe.HttpClient = HttpClient;
Stripe.HttpClientResponse = HttpClientResponse;
Stripe.CryptoProvider = CryptoProvider;
Stripe.StripeContext = StripeContext;
Stripe.errors = _Error;
Stripe.Decimal = Decimal;
Stripe._requestSenderFactory = defaultRequestSenderFactory;
// For backward compatibility, export createStripe as a factory function
export function createStripe(platformFunctions, requestSender = defaultRequestSenderFactory) {
// Initialize static properties
Stripe.initialize(platformFunctions, requestSender);
return Stripe;
}
Stripe.initialize(new NodePlatformFunctions());
export default Stripe;
//# sourceMappingURL=stripe.esm.node.js.map