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

Adding support for the new Usage Billing APIs #2184

Merged
merged 22 commits into from
Sep 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
049757f
Support new Usage Billing APIs
ramya-stripe Sep 24, 2024
88d3b93
Fix tests to use the billing endpoint
ramya-stripe Sep 24, 2024
b4934d1
Pull latest changes from spec
ramya-stripe Sep 25, 2024
1bf4c2e
Pull latest proto, V2 suffix is now gone from MeterEvent & MeterEvent…
ramya-stripe Sep 25, 2024
b4f78ec
preview version not needed anymore
ramya-stripe Sep 25, 2024
f79280d
Fix namespace issue in Event class
ramya-stripe Sep 25, 2024
e1b356f
added snippets folder with a project and instructions for getting sta…
jar-stripe Sep 25, 2024
5f56eaa
Merge branch 'sdk-release/next-major' into next-major-infra
prathmesh-stripe Sep 25, 2024
1a6573a
Update sdk version
ramya-stripe Sep 25, 2024
21e6577
added stripe_webhook_handler example
jar-stripe Sep 26, 2024
a08df1a
Merge branch 'next-major-infra' of github.com:stripe/stripe-node into…
jar-stripe Sep 26, 2024
c7ad0c3
added apiKey to Stripe constructor
jar-stripe Sep 26, 2024
9ab1416
Remove unused request authenticator
ramya-stripe Sep 26, 2024
31da0da
Add raw request (#2189)
prathmesh-stripe Sep 26, 2024
9c07835
print stack on failure in example
helenye-stripe Sep 26, 2024
4db10ac
Remove tests for unused request auth
ramya-stripe Sep 26, 2024
e1eb316
Edit test names
ramya-stripe Sep 26, 2024
ef9378d
Rename generate & generateV2 in Errors.ts to generateV1Error & genera…
ramya-stripe Sep 26, 2024
5bee3ce
updated README.me with clearer instructions
jar-stripe Sep 26, 2024
934e0fa
Update generated code
ramya-stripe Sep 27, 2024
2158114
fix ci
xavdid-stripe Sep 27, 2024
9d340c7
Add related_object field to event types, remove fetchRelatedObject() …
ramya-stripe Sep 27, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,40 @@ 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
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, you must delete your snippets `node_modules` folder and rerun these steps.

## 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. 👍
39 changes: 39 additions & 0 deletions examples/snippets/meter_event_stream.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
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);
});
7 changes: 7 additions & 0 deletions examples/snippets/new_example.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import {Stripe} from 'stripe';

const apiKey = '{{API_KEY}}';

console.log('Hello World');
// const client = new Stripe(apiKey);
// client.v2....
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"
}
}
36 changes: 36 additions & 0 deletions examples/snippets/stripe_webhook_handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
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;
// 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
Loading