Skip to content

Commit

Permalink
Merge branch 'master' into dependabot/npm_and_yarn/micromatch-4.0.8
Browse files Browse the repository at this point in the history
  • Loading branch information
jar-stripe authored Jan 10, 2025
2 parents 47ea8a4 + ac941b9 commit 84052e7
Show file tree
Hide file tree
Showing 172 changed files with 9,385 additions and 518 deletions.
11 changes: 11 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
### Why?
<!-- Describe why this change is being made. Briefly include history and context, high-level what this PR does, and what the world looks like afterward. -->

### What?
<!--
List out the key changes made in this PR, e.g.
- implements the antimatter particle trace in the nitronium microfilament drive
- updated tests -->

### See Also
<!-- Include any links or additional information that help explain this change. -->
137 changes: 137 additions & 0 deletions CHANGELOG.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion OPENAPI_VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
v1267
v1412
68 changes: 67 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,39 @@ const customer = await stripe.customers.create({
console.log(customer.id);
```

> [!WARNING]
> If you're using `v17.x.x` or later and getting an error about a missing API key despite being sure it's available, it's likely you're importing the file that instantiates `Stripe` while the key isn't present (for instance, during a build step).
> If that's the case, consider instantiating the client lazily:
>
> ```ts
> import Stripe from 'stripe';
>
> let _stripe: Stripe | null = null;
> const getStripe = (): Stripe => {
> if (!_stripe) {
> _stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string, {
> // ...
> });
> }
> return _stripe;
> };
>
> const getCustomers = () => getStripe().customers.list();
> ```
>
> Alternatively, you can provide a placeholder for the real key (which will be enough to get the code through a build step):
>
> ```ts
> import Stripe from 'stripe';
>
> export const stripe = new Stripe(
> process.env.STRIPE_SECRET_KEY || 'api_key_placeholder',
> {
> // ...
> }
> );
> ```
### Usage with TypeScript
As of 8.0.1, Stripe maintains types for the latest [API version][api-versions].
Expand Down Expand Up @@ -197,7 +230,7 @@ const stripe = Stripe('sk_test_...', {
| `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](#telemetry). |
| `telemetry` | `true` | Allow Stripe to send [telemetry](#telemetry). |

> **Note**
> Both `maxNetworkRetries` and `timeout` can be overridden on a per-request basis.
Expand Down Expand Up @@ -517,6 +550,39 @@ const stripe = new Stripe('sk_test_...', {
});
```

### Custom requests

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.

```javascript
const client = new Stripe('sk_test_...');

client.rawRequest(
'POST',
'/v1/beta_endpoint',
{ param: 123 },
{ apiVersion: '2022-11-15; feature_beta=v3' }
)
.then((response) => /* handle response */ )
.catch((error) => console.error(error));
```

Or using ES modules and `async`/`await`:

```javascript
import Stripe from 'stripe';
const stripe = new Stripe('sk_test_...');

const response = await stripe.rawRequest(
'POST',
'/v1/beta_endpoint',
{param: 123},
{apiVersion: '2022-11-15; feature_beta=v3'}
);

// handle response
```

## Support

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.
Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
16.12.0
17.5.0
27 changes: 27 additions & 0 deletions examples/snippets/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
## Setup

1. From the stripe-node root folder, run `yarn build` to build the modules.
2. Then, from this snippets folder, run `yarn` to install node dependencies for the example snippets. This will reference the local Stripe SDK modules created in step 1.

If on step 2 you see an error `Error: unsure how to copy this: /Users/jar/stripe/sdks/node/.git/fsmonitor--daemon.ipc`:
run `rm /path/to/node/sdk/.git/fsmonitor--daemon.ipc && yarn`
This file is used by a file monitor built into git. Removing it temporarily does not seem to affect its operation, and this one liner will let `yarn` succeed.

Note that if you modify the stripe-node code, rerun step 1 and then run `yarn upgrade stripe` from this folder to pull in the new built package.

## Running an example

If your example is in typescript, run:
`yarn run ts-node your_example.ts`

If your example is in javascript, run:
`node your_example.js`
or
`node your_example.mjs`

## Adding a new example

1. Clone new_example.ts
2. Implement your example
3. Run it (as per above)
4. 👍
21 changes: 21 additions & 0 deletions examples/snippets/example_template.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* example_template.py - This is a template for defining new examples. It is not intended to be used directly.
* <describe what this example does>
* In this example, we:
* - <key step 1>
* - <key step 2
* - ...
* <describe assumptions about the user's stripe account, environment, or configuration;
* or things to watch out for when running>
*/

import {Stripe} from 'stripe';

const apiKey = '{{API_KEY}}';

console.log('Hello World');
// const client = new Stripe(apiKey);
// client.v2....
51 changes: 51 additions & 0 deletions examples/snippets/meter_event_stream.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* meter_event_stream.ts - Use the high-throughput meter event stream to report create billing meter events.
*
* In this example, we:
* - create a meter event session and store the session's authentication token
* - define an event with a payload
* - use the meterEventStream service to create an event stream that reports this event
*
* This example expects a billing meter with an event_name of 'alpaca_ai_tokens'. If you have
* a different meter event name, you can change it before running this example.
*/

import {Stripe} from 'stripe';

const apiKey = '{{API_KEY}}';
const customerId = '{{CUSTOMER_ID}}';

let meterEventSession: null | any = null;

async function refreshMeterEventSession() {
if (
meterEventSession === null ||
new Date(meterEventSession.expires_at * 1000) <= new Date()
) {
// Create a new meter event session in case the existing session expired
const client = new Stripe(apiKey);
meterEventSession = await client.v2.billing.meterEventSession.create();
}
}

async function sendMeterEvent(meterEvent: any) {
// Refresh the meter event session, if necessary
await refreshMeterEventSession();

// Create a meter event
const client = new Stripe(meterEventSession.authentication_token);
await client.v2.billing.meterEventStream.create({
events: [meterEvent],
});
}

// Send meter events
sendMeterEvent({
event_name: 'alpaca_ai_tokens',
payload: {
stripe_customer_id: customerId, // Replace with actual customer ID
value: '27',
},
}).catch((error) => {
console.error('Error sending meter event:', error);
});
13 changes: 13 additions & 0 deletions examples/snippets/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "snippets",
"version": "1.0.0",
"description": "example Stripe SDK code snippets",
"main": "index.js",
"license": "ISC",
"dependencies": {
"express": "^4.21.0",
"stripe": "file:../..",
"ts-node": "^10.9.2",
"typescript": "^5.6.2"
}
}
50 changes: 50 additions & 0 deletions examples/snippets/thinevent_webhook_handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* thinevent_webhook_handler.js - receive and process thin events like the
* v1.billing.meter.error_report_triggered event.
* In this example, we:
* - create a Stripe client object called client
* - use client.parseThinEvent to parse the received thin event webhook body
* - call client.v2.core.events.retrieve to retrieve the full event object
* - if it is a v1.billing.meter.error_report_triggered event type, call
* event.fetchRelatedObject to retrieve the Billing Meter object associated
* with the event.
*/

const express = require('express');
const {Stripe} = require('stripe');

const app = express();

const apiKey = process.env.STRIPE_API_KEY;
const webhookSecret = process.env.WEBHOOK_SECRET;

const client = new Stripe(apiKey);

app.post(
'/webhook',
express.raw({type: 'application/json'}),
async (req, res) => {
const sig = req.headers['stripe-signature'];

try {
const thinEvent = client.parseThinEvent(req.body, sig, webhookSecret);

// Fetch the event data to understand the failure
const event = await client.v2.core.events.retrieve(thinEvent.id);
if (event.type == 'v1.billing.meter.error_report_triggered') {
const meter = await event.fetchRelatedObject();
const meterId = meter.id;
console.log(`Success! ${meterId}`);

// Record the failures and alert your team
// Add your logic here
}
res.sendStatus(200);
} catch (err) {
console.log(`Webhook Error: ${err.stack}`);
res.status(400).send(`Webhook Error: ${err.message}`);
}
}
);

app.listen(4242, () => console.log('Running on port 4242'));
Loading

0 comments on commit 84052e7

Please sign in to comment.