Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stripe-node v8.0.0 #742

Merged
merged 10 commits into from
Jan 10, 2020
1 change: 0 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ cache:
directories:
- node_modules
node_js:
- '6'
- '8'
- '10'
sudo: false
Expand Down
221 changes: 101 additions & 120 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,20 @@
The Stripe Node library provides convenient access to the Stripe API from
applications written in server-side JavaScript.

Please keep in mind that this package is for use with server-side Node that
uses Stripe secret keys. To maintain PCI compliance, tokenization of credit
card information should always be done with [Stripe.js][stripe-js] on the
client side. This package should not be used for that purpose.
For collecting customer and payment information in the browser, use [Stripe.js][stripe-js].

## Documentation

See the [`stripe-node` API docs](https://stripe.com/docs/api/node#intro) for Node.js.
See the [`stripe-node` API docs](https://stripe.com/docs/api?lang=node) for Node.js.

## Installation

Install the package with:

```sh
npm install stripe --save
# or
yarn add stripe
```

## Usage
Expand All @@ -32,76 +31,83 @@ The package needs to be configured with your account's secret key which is
available in your [Stripe Dashboard][api-keys]. Require it with the key's
value:

<!-- prettier-ignore -->
```js
const stripe = require('stripe')('sk_test_...');

const customer = await stripe.customers.create({
stripe.customers.create({
email: '[email protected]',
});
})
.then(customer => console.log(customer.id))
.catch(error => console.error(error));
```

Or using ES modules, this looks more like:
Or using ES modules and `async`/`await`:

```js
import Stripe from 'stripe';
const stripe = Stripe('sk_test_...');
//…
```
const stripe = new Stripe('sk_test_...');

On older versions of Node, you can use [promises](#using-promises)
or [callbacks](#using-callbacks) instead of `async`/`await`.
(async () => {
const customer = await stripe.customers.create({
email: '[email protected]',
});

## Initialize with config object
console.log(customer.id);
})();
```

The package can be initialized with several options:
### Usage with TypeScript

```js
import ProxyAgent from 'https-proxy-agent';
As of 8.0.0, Stripe maintains types for the latest [API version][api-versions].

const stripe = Stripe('sk_test_...', {
apiVersion: '2019-08-08',
maxNetworkRetries: 1,
httpAgent: new ProxyAgent(process.env.http_proxy),
timeout: 1000,
host: 'api.example.com',
port: 123,
telemetry: true,
Import Stripe as a default import (not `* as Stripe`, unlike the DefinitelyTyped version)
and instantiate it as `new Stripe()` with the latest API version.

```ts
import Stripe from 'stripe';
const stripe = new Stripe('sk_test_...', {
apiVersion: '2019-12-03',
typescript: true,
});
```

| Option | Default | Description |
| ------------------- | ----------------------------- | ------------------------------------------------------------------------------------- |
| `apiVersion` | `null` | Stripe API version to be used. If not set the account's default version will be used. |
| `maxNetworkRetries` | 0 | The amount of times a request should be [retried](#network-retries). |
| `httpAgent` | `null` | [Proxy](#configuring-a-proxy) agent to be used by the library. |
| `timeout` | 120000 (Node default timeout) | [Maximum time each request can take in ms.](#configuring-timeout) |
| `host` | `'api.stripe.com'` | Host that requests are made to. |
| `port` | 443 | Port that requests are made to. |
| `telemetry` | `true` | Allow Stripe to send latency [telemetry](#request-latency-telemetry) |
const createCustomer = async () => {
const params: Stripe.CustomerCreateParams = {
description: 'test customer',
};

Note: Both `maxNetworkRetries` and `timeout` can be overridden on a per-request basis. `timeout` can be updated at any time with [`stripe.setTimeout`](#configuring-timeout).
const customer: Stripe.Customer = await stripe.customers.create(params);

### Usage with TypeScript
console.log(customer.id);
};
createCustomer();
```

Stripe does not currently maintain typings for this package, but there are
community typings available from DefinitelyTyped.
#### Using old API versions with TypeScript

To install:
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.

```sh
npm install --dev @types/stripe
```
We therefore encourage [upgrading your API version][api-version-upgrading]
if you would like to take advantage of Stripe's TypeScript definitions.

To use:
If you are on an older API version (e.g., `2019-10-17`) and not able to upgrade,
you may pass another version or `apiVersion: null` to use your account's default API 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.

```ts
// Note `* as` and `new Stripe` for TypeScript:
import * as Stripe from 'stripe';
const stripe = new Stripe('sk_test_...');
#### Using `expand` with TypeScript

[Expandable][expanding_objects] fields are typed as `string | Foo`,
so you must cast them appropriately, e.g.,

const customer: Promise<
Stripe.customers.ICustomer
> = stripe.customers.create(/* ... */);
```ts
const charge: Stripe.Charge = await stripe.charges.retrieve('ch_123', {
expand: ['customer'],
});
const customerEmail: string = (charge.customer as Stripe.Customer).email;
const btId: string = charge.balance_transaction as string;
```

### Using Promises
Expand Down Expand Up @@ -135,84 +141,81 @@ stripe.customers
});
```

### Using callbacks
## Configuration

On versions of Node.js prior to v7.9:
### Initialize with config object

```js
var stripe = require('stripe')('sk_test_...');
The package can be initialized with several options:

stripe.customers.create(
{
email: '[email protected]',
},
function(err, customer) {
if (err) {
// Deal with an error (will be `null` if no error occurred).
}
```js
import ProxyAgent from 'https-proxy-agent';

// Do something with created customer object
console.log(customer.id);
}
);
const stripe = Stripe('sk_test_...', {
apiVersion: '2019-08-08',
maxNetworkRetries: 1,
httpAgent: new ProxyAgent(process.env.http_proxy),
timeout: 1000,
host: 'api.example.com',
port: 123,
telemetry: true,
});
```

### Configuring Timeout
| Option | Default | Description |
| ------------------- | ----------------------------- | ------------------------------------------------------------------------------------- |
| `apiVersion` | `null` | Stripe API version to be used. If not set the account's default version will be used. |
| `maxNetworkRetries` | 0 | The amount of times a request should be [retried](#network-retries). |
| `httpAgent` | `null` | [Proxy](#configuring-a-proxy) agent to be used by the library. |
| `timeout` | 120000 (Node default timeout) | [Maximum time each request can take in ms.](#configuring-timeout) |
| `host` | `'api.stripe.com'` | Host that requests are made to. |
| `port` | 443 | Port that requests are made to. |
| `telemetry` | `true` | Allow Stripe to send latency [telemetry](#request-latency-telemetry) |

Request timeout is configurable (the default is Node's default of 120 seconds):
Note: Both `maxNetworkRetries` and `timeout` can be overridden on a per-request basis.

```js
stripe.setTimeout(20000); // in ms (this is 20 seconds)
```
### Configuring Timeout

Timeout can also be set globally via the config object:
Timeout can be set globally via the config object:

```js
const stripe = Stripe('sk_test_...', {
timeout: 2000,
timeout: 20 * 1000, // 20 seconds
});
```

And on a per-request basis:
And overridden on a per-request basis:

```js
stripe.customers.create(
{
email: '[email protected]',
},
{
timeout: 1000,
timeout: 1000, // 1 second
}
);
```

If `timeout` is set globally via the config object, the value set in a per-request basis will be favored.

### Configuring For Connect

A per-request `Stripe-Account` header for use with [Stripe Connect][connect]
can be added to any method:

```js
// Retrieve the balance for a connected account:
stripe.balance
.retrieve({
// List the balance transactions for a connected account:
stripe.balanceTransactions.list(
{
limit: 10,
},
{
stripeAccount: 'acct_foo',
})
.then((balance) => {
// The balance object for the connected account
})
.catch((err) => {
// Error
});
}
);
```

### Configuring a Proxy

An [https-proxy-agent][https-proxy-agent] can be configured with
`setHttpAgent`.

To use stripe behind a proxy you can pass to sdk on initialization:
To use stripe behind a proxy you can pass an [https-proxy-agent][https-proxy-agent] on initialization:

```js
if (process.env.http_proxy) {
Expand Down Expand Up @@ -363,7 +366,6 @@ This information is passed along when the library makes calls to the Stripe API.

### Auto-pagination

As of stripe-node 6.11.0, you may auto-paginate list methods.
We provide a few different APIs for this to aid with a variety of node versions and styles.

#### Async iterators (`for-await-of`)
Expand Down Expand Up @@ -414,32 +416,6 @@ stripe.customers
.catch(handleError);
```

If you prefer callbacks to promises, you may also use a `next` callback and a second `onDone` callback:

```js
stripe.customers.list().autoPagingEach(
function onItem(customer, next) {
doSomething(customer, function(err, result) {
if (shouldStop(result)) {
next(false); // Passing `false` breaks out of the loop.
} else {
next();
}
});
},
function onDone(err) {
if (err) {
console.error(err);
} else {
console.log('Done iterating.');
}
}
);
```

If your `onItem` function does not accept a `next` callback parameter _or_ return a Promise,
the return value is used to decide whether to continue (`false` breaks, anything else continues).

#### `autoPagingToArray`

This is a convenience for cases where you expect the number of items
Expand All @@ -462,7 +438,9 @@ numbers help Stripe improve the overall latency of its API for all users.
You can disable this behavior if you prefer:

```js
stripe.setTelemetryEnabled(false);
const stripe = new Stripe('sk_test_...', {
telemetry: false,
});
```

## More Information
Expand Down Expand Up @@ -512,7 +490,10 @@ $ yarn fix
```

[api-keys]: https://dashboard.stripe.com/account/apikeys
[api-versions]: https://stripe.com/docs/api/versioning
[api-version-upgrading]: https://stripe.com/docs/upgrades#how-can-i-upgrade-my-api
[connect]: https://stripe.com/connect
[expanding_objects]: https://stripe.com/docs/api/expanding_objects
[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent
[stripe-js]: https://stripe.com/docs/stripe.js

Expand Down
Loading