Gathering detailed insights and metrics for stripe
Gathering detailed insights and metrics for stripe
Gathering detailed insights and metrics for stripe
Gathering detailed insights and metrics for stripe
npm install stripe
Typescript
Module System
Min. Node Version
Node Version
NPM Version
77.2
Supply Chain
99.2
Quality
95.2
Maintenance
100
Vulnerability
100
License
Updated on 06 Dec 2024
TypeScript (56.51%)
JavaScript (43.44%)
Makefile (0.05%)
Cumulative downloads
Total Downloads
Last day
62.2%
Compared to previous day
Last week
1.9%
Compared to previous week
Last month
2.1%
Compared to previous month
Last year
39.7%
Compared to previous year
2
22
The Stripe Node library provides convenient access to the Stripe API from applications written in server-side JavaScript.
For collecting customer and payment information in the browser, use Stripe.js.
See the stripe-node
API docs for Node.js.
See video demonstrations covering how to use the library.
Node 12 or higher.
Install the package with:
1npm install stripe 2# or 3yarn add stripe
The package needs to be configured with your account's secret key, which is available in the Stripe Dashboard. Require it with the key's value:
1const stripe = require('stripe')('sk_test_...'); 2 3stripe.customers.create({ 4 email: 'customer@example.com', 5}) 6 .then(customer => console.log(customer.id)) 7 .catch(error => console.error(error));
Or using ES modules and async
/await
:
1import Stripe from 'stripe'; 2const stripe = new Stripe('sk_test_...'); 3 4const customer = await stripe.customers.create({ 5 email: 'customer@example.com', 6}); 7 8console.log(customer.id);
As of 8.0.1, Stripe maintains types for the latest API version.
Import Stripe as a default import (not * as Stripe
, unlike the DefinitelyTyped version)
and instantiate it as new Stripe()
with the latest API version.
1import Stripe from 'stripe'; 2const stripe = new Stripe('sk_test_...'); 3 4const createCustomer = async () => { 5 const params: Stripe.CustomerCreateParams = { 6 description: 'test customer', 7 }; 8 9 const customer: Stripe.Customer = await stripe.customers.create(params); 10 11 console.log(customer.id); 12}; 13createCustomer();
You can find a full TS server example in stripe-samples.
Types can change between API versions (e.g., Stripe may have changed a field from a string to a hash), so our types only reflect the latest API version.
We therefore encourage upgrading your API version if you would like to take advantage of Stripe's TypeScript definitions.
If you are on an older API version (e.g., 2019-10-17
) and not able to upgrade,
you may pass another version and use a comment like // @ts-ignore stripe-version-2019-10-17
to silence type errors here
and anywhere the types differ between your API version and the latest.
When you upgrade, you should remove these comments.
We also recommend using // @ts-ignore
if you have access to a beta feature and need to send parameters beyond the type definitions.
expand
with TypeScriptExpandable fields are typed as string | Foo
,
so you must cast them appropriately, e.g.,
1const paymentIntent: Stripe.PaymentIntent = await stripe.paymentIntents.retrieve( 2 'pi_123456789', 3 { 4 expand: ['customer'], 5 } 6); 7const customerEmail: string = (paymentIntent.customer as Stripe.Customer).email;
The TypeScript types in stripe-node always reflect the latest shape of the Stripe API. When the Stripe API changes in a backwards-incompatible way, there is a new Stripe API version, and we release a new major version of stripe-node. Sometimes, though, the Stripe API changes in a way that weakens the guarantees provided by the TypeScript types, but that cannot result in any backwards incompatibility at runtime. For example, we might add a new enum value on a response, along with a new parameter to a request. Adding a new value to a response enum weakens the TypeScript type. However, if the new enum value is only returned when the new parameter is provided, this cannot break any existing usages and so would not be considered a breaking API change. In stripe-node, we do NOT consider such changes to be breaking under our current versioning policy. This means that you might see new type errors from TypeScript as you upgrade minor versions of stripe-node, that you can resolve by adding additional type guards.
Please feel welcome to share your thoughts about the versioning policy in a Github issue. For now, we judge it to be better than the two alternatives: outdated, inaccurate types, or vastly more frequent major releases, which would distract from any future breaking changes with potentially more disruptive runtime implications.
Every method returns a chainable promise which can be used instead of a regular callback:
1// Create a new customer and then create an invoice item then invoice it: 2stripe.customers 3 .create({ 4 email: 'customer@example.com', 5 }) 6 .then((customer) => { 7 // have access to the customer object 8 return stripe.invoiceItems 9 .create({ 10 customer: customer.id, // set the customer id 11 amount: 2500, // 25 12 currency: 'usd', 13 description: 'One-time setup fee', 14 }) 15 .then((invoiceItem) => { 16 return stripe.invoices.create({ 17 collection_method: 'send_invoice', 18 customer: invoiceItem.customer, 19 }); 20 }) 21 .then((invoice) => { 22 // New invoice created on a new customer 23 }) 24 .catch((err) => { 25 // Deal with an error 26 }); 27 });
As of 11.16.0, stripe-node provides a deno
export target. In your Deno project, import stripe-node using an npm specifier:
Import using npm specifiers:
1import Stripe from 'npm:stripe';
Please see https://github.com/stripe-samples/stripe-node-deno-samples for more detailed examples and instructions on how to use stripe-node in Deno.
The package can be initialized with several options:
1import ProxyAgent from 'https-proxy-agent'; 2 3const stripe = Stripe('sk_test_...', { 4 maxNetworkRetries: 1, 5 httpAgent: new ProxyAgent(process.env.http_proxy), 6 timeout: 1000, 7 host: 'api.example.com', 8 port: 123, 9 telemetry: true, 10});
Option | Default | Description |
---|---|---|
apiVersion | null | Stripe API version to be used. If not set, stripe-node will use the latest version at the time of release. |
maxNetworkRetries | 1 | The amount of times a request should be retried. |
httpAgent | null | Proxy agent to be used by the library. |
timeout | 80000 | Maximum time each request can take in ms. |
host | 'api.stripe.com' | Host that requests are made to. |
port | 443 | Port that requests are made to. |
protocol | 'https' | 'https' or 'http' . http is never appropriate for sending requests to Stripe servers, and we strongly discourage http , even in local testing scenarios, as this can result in your credentials being transmitted over an insecure channel. |
telemetry | true | Allow Stripe to send telemetry. |
Note Both
maxNetworkRetries
andtimeout
can be overridden on a per-request basis.
Timeout can be set globally via the config object:
1const stripe = Stripe('sk_test_...', { 2 timeout: 20 * 1000, // 20 seconds 3});
And overridden on a per-request basis:
1stripe.customers.create( 2 { 3 email: 'customer@example.com', 4 }, 5 { 6 timeout: 1000, // 1 second 7 } 8);
A per-request Stripe-Account
header for use with Stripe Connect
can be added to any method:
1// List the balance transactions for a connected account: 2stripe.balanceTransactions.list( 3 { 4 limit: 10, 5 }, 6 { 7 stripeAccount: 'acct_foo', 8 } 9);
To use stripe behind a proxy you can pass an https-proxy-agent on initialization:
1if (process.env.http_proxy) { 2 const ProxyAgent = require('https-proxy-agent'); 3 4 const stripe = Stripe('sk_test_...', { 5 httpAgent: new ProxyAgent(process.env.http_proxy), 6 }); 7}
As of v13 stripe-node will automatically do one reattempt for failed requests that are safe to retry. Automatic network retries can be disabled by setting the maxNetworkRetries
config option to 0
. You can also set a higher number to reattempt multiple times, with exponential backoff. Idempotency keys are added where appropriate to prevent duplication.
1const stripe = Stripe('sk_test_...', { 2 maxNetworkRetries: 0, // Disable retries 3});
1const stripe = Stripe('sk_test_...', {
2 maxNetworkRetries: 2, // Retry a request twice before giving up
3});
Network retries can also be set on a per-request basis:
1stripe.customers.create( 2 { 3 email: 'customer@example.com', 4 }, 5 { 6 maxNetworkRetries: 2, // Retry this specific request twice before giving up 7 } 8);
Some information about the response which generated a resource is available
with the lastResponse
property:
1customer.lastResponse.requestId; // see: https://stripe.com/docs/api/request_ids?lang=node 2customer.lastResponse.statusCode;
request
and response
eventsThe Stripe object emits request
and response
events. You can use them like this:
1const stripe = require('stripe')('sk_test_...'); 2 3const onRequest = (request) => { 4 // Do something. 5}; 6 7// Add the event handler function: 8stripe.on('request', onRequest); 9 10// Remove the event handler function: 11stripe.off('request', onRequest);
request
object1{ 2 api_version: 'latest', 3 account: 'acct_TEST', // Only present if provided 4 idempotency_key: 'abc123', // Only present if provided 5 method: 'POST', 6 path: '/v1/customers', 7 request_start_time: 1565125303932 // Unix timestamp in milliseconds 8}
response
object1{ 2 api_version: 'latest', 3 account: 'acct_TEST', // Only present if provided 4 idempotency_key: 'abc123', // Only present if provided 5 method: 'POST', 6 path: '/v1/customers', 7 status: 402, 8 request_id: 'req_Ghc9r26ts73DRf', 9 elapsed: 445, // Elapsed time in milliseconds 10 request_start_time: 1565125303932, // Unix timestamp in milliseconds 11 request_end_time: 1565125304377 // Unix timestamp in milliseconds 12}
Stripe can optionally sign the webhook events it sends to your endpoint, allowing you to validate that they were not sent by a third-party. You can read more about it here.
Please note that you must pass the raw request body, exactly as received from Stripe, to the constructEvent()
function; this will not work with a parsed (i.e., JSON) request body.
You can find an example of how to use this with various JavaScript frameworks in examples/webhook-signing
folder, but here's what it looks like:
1const event = stripe.webhooks.constructEvent( 2 webhookRawBody, 3 webhookStripeSignatureHeader, 4 webhookSecret 5);
You can use stripe.webhooks.generateTestHeaderString
to mock webhook events that come from Stripe:
1const payload = { 2 id: 'evt_test_webhook', 3 object: 'event', 4}; 5 6const payloadString = JSON.stringify(payload, null, 2); 7const secret = 'whsec_test_secret'; 8 9const header = stripe.webhooks.generateTestHeaderString({ 10 payload: payloadString, 11 secret, 12}); 13 14const event = stripe.webhooks.constructEvent(payloadString, header, secret); 15 16// Do something with mocked signed event 17expect(event.id).to.equal(payload.id);
If you're writing a plugin that uses the library, we'd appreciate it if you instantiated your stripe client with appInfo
, eg;
1const stripe = require('stripe')('sk_test_...', { 2 appInfo: { 3 name: 'MyAwesomePlugin', 4 version: '1.2.34', // Optional 5 url: 'https://myawesomeplugin.info', // Optional 6 }, 7});
Or using ES modules or TypeScript:
1const stripe = new Stripe(apiKey, {
2 appInfo: {
3 name: 'MyAwesomePlugin',
4 version: '1.2.34', // Optional
5 url: 'https://myawesomeplugin.info', // Optional
6 },
7});
This information is passed along when the library makes calls to the Stripe API.
We provide a few different APIs for this to aid with a variety of node versions and styles.
for-await-of
)If you are in a Node environment that has support for async iteration, such as Node 10+ or babel, the following will auto-paginate:
1for await (const customer of stripe.customers.list()) { 2 doSomething(customer); 3 if (shouldStop()) { 4 break; 5 } 6}
autoPagingEach
If you are in a Node environment that has support for await
, such as Node 7.9 and greater,
you may pass an async function to .autoPagingEach
:
1await stripe.customers.list().autoPagingEach(async (customer) => { 2 await doSomething(customer); 3 if (shouldBreak()) { 4 return false; 5 } 6}); 7console.log('Done iterating.');
Equivalently, without await
, you may return a Promise, which can resolve to false
to break:
1stripe.customers 2 .list() 3 .autoPagingEach((customer) => { 4 return doSomething(customer).then(() => { 5 if (shouldBreak()) { 6 return false; 7 } 8 }); 9 }) 10 .then(() => { 11 console.log('Done iterating.'); 12 }) 13 .catch(handleError);
autoPagingToArray
This is a convenience for cases where you expect the number of items
to be relatively small; accordingly, you must pass a limit
option
to prevent runaway list growth from consuming too much memory. Once the
limit
number of items have been fetched, auto-pagination will stop.
Returns a promise of an array of all items across pages for a list request.
1const allNewCustomers = await stripe.customers 2 .list({created: {gt: lastMonth}, limit: 100}) // 100 items per page 3 .autoPagingToArray({limit: 10000}); // Stop after 10000 items total
By default, the library sends request telemetry to Stripe regarding request latency and feature usage. These numbers help Stripe improve the overall latency of its API for all users, and improve popular features.
You can disable this behavior if you prefer:
1const stripe = new Stripe('sk_test_...', {
2 telemetry: false,
3});
Stripe has features in the beta phase that can be accessed via the beta version of this package. We would love for you to try these and share feedback with us before these features reach the stable phase. The beta versions can be installed in one of two ways
npm install stripe@beta --save
npm install stripe@1.2.3-beta.1 --save
Note There can be breaking changes between beta versions. Therefore we recommend pinning the package version to a specific beta version in your package.json file. This way you can install the same version each time without breaking changes unless you are intentionally looking for the latest beta version.
We highly recommend keeping an eye on when the beta feature you are interested in goes from beta to stable so that you can move from using a beta version of the SDK to the stable version.
The versions tab on the stripe page on npm lists the current tags in use. The beta
tag here corresponds to the the latest beta version of the package.
If your beta feature requires a Stripe-Version
header to be sent, use the apiVersion
property of config
object to set it:
1const stripe = new Stripe('sk_test_...', {
2 apiVersion: '2022-08-01; feature_beta=v3',
3});
If you would like to send a request to an undocumented API (for example you are in a private beta), or if you prefer to bypass the method definitions in the library and specify your request details directly, you can use the rawRequest
method on the StripeClient object.
1const client = new Stripe('sk_test_...'); 2 3client.rawRequest( 4 'POST', 5 '/v1/beta_endpoint', 6 { param: 123 }, 7 { apiVersion: '2022-11-15; feature_beta=v3' } 8 ) 9 .then((response) => /* handle response */ ) 10 .catch((error) => console.error(error));
Or using ES modules and async
/await
:
1import Stripe from 'stripe'; 2const stripe = new Stripe('sk_test_...'); 3 4const response = await stripe.rawRequest( 5 'POST', 6 '/v1/beta_endpoint', 7 { param: 123 }, 8 { apiVersion: '2022-11-15; feature_beta=v3' } 9); 10 11// handle response
New features and bug fixes are released on the latest major version of the stripe
package. If you are on an older major version, we recommend that you upgrade to the latest in order to use the new features and bug fixes including those for security vulnerabilities. Older major versions of the package will continue to be available for use, but will not be receiving any updates.
Run all tests:
1$ yarn install 2$ yarn test
If you do not have yarn
installed, you can get it with npm install --global yarn
.
The tests also depends on stripe-mock, so make sure to fetch and run it from a background terminal (stripe-mock's README also contains instructions for installing via Homebrew and other methods):
1go get -u github.com/stripe/stripe-mock 2stripe-mock
Run a single test suite without a coverage report:
1$ yarn mocha-only test/Error.spec.ts
Run a single test (case sensitive) in watch mode:
1$ yarn mocha-only test/Error.spec.ts --grep 'Populates with type' --watch
If you wish, you may run tests using your Stripe Test API key by setting the
environment variable STRIPE_TEST_API_KEY
before running the tests:
1$ export STRIPE_TEST_API_KEY='sk_test....' 2$ yarn test
Run prettier:
Add an editor integration or:
1$ yarn fix
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
all changesets reviewed
Reason
30 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 10
Reason
license file detected
Details
Reason
no binaries found in the repo
Reason
security policy file detected
Details
Reason
branch protection is not maximal on development and all release branches
Details
Reason
6 existing vulnerabilities detected
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More