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

Added typescript webhook example #764

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 4 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,8 @@
// Extension settings
"eslint.autoFixOnSave": true,
"eslint.packageManager": "yarn",
"npm.packageManager": "yarn"
"npm.packageManager": "yarn",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ const customerEmail: string = (charge.customer as Stripe.Customer).email;
const btId: string = charge.balance_transaction as string;
```

### TypeScript examples

You can find a Node.js TypeScript server example in [stripe-samples](https://github.com/stripe-samples/accept-a-card-payment/tree/master/using-webhooks/server/node-typescript) and a webhook signing example in the [`examples/webhook-signing`](examples/webhook-signing) folder.

### Using Promises

Every method returns a chainable promise which can be used instead of a regular
Expand Down
3 changes: 3 additions & 0 deletions examples/webhook-signing/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Stripe keys
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
9 changes: 0 additions & 9 deletions examples/webhook-signing/.eslintrc.js

This file was deleted.

2 changes: 2 additions & 0 deletions examples/webhook-signing/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.env
express-ts.js
54 changes: 54 additions & 0 deletions examples/webhook-signing/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Checking webhook signatures

Verify the events that Stripe sends to your webhook endpoints. Additional details in the Stripe [docs](https://stripe.com/docs/webhooks/signatures).

You can find a Node.js TypeScript server example in [stripe-samples](https://github.com/stripe-samples/accept-a-card-payment/tree/master/using-webhooks/server/node-typescript).

### Requirements

You’ll need the following:

- [Node.js](http://nodejs.org) >=10.0.0
- Stripe account to accept payments ([sign up](https://dashboard.stripe.com/register) for free).
- [Stripe CLI](https://github.com/stripe/stripe-cli) or [ngrok](https://ngrok.com/) to tunnel requests to your local server.
thorsten-stripe marked this conversation as resolved.
Show resolved Hide resolved

### Setup

In this directory (`cd examples/webhook-signing/`), copy the environment variables file:

cp .env.example .env

Update `.env` with your own [Stripe API keys](https://dashboard.stripe.com/account/apikeys).

### Install and run

Install dependencies:

npm install

Next, follow [these installation steps](https://github.com/stripe/stripe-cli#installation) to install the Stripe CLI which we'll use for webhook forwarding.

After the installation has finished, authenticate the CLI with your Stripe account:

stripe login

To start the webhook forwarding run:

stripe listen --forward-to localhost:3000/webhook

The Stripe CLI will let you know that webhook forwarding is ready and output your webhook signing secret:

> Ready! Your webhook signing secret is whsec_xxx

Copy the webhook signing secret (`whsec_xxx`) to your `.env` file.
thorsten-stripe marked this conversation as resolved.
Show resolved Hide resolved

In a separate terminal window, start the local server:

npm run vanilla # Runs the vanilla JavaScript example.
npm run typescript # Compiles and runs the TypeScript example.

In another separate terminal window, trigger an event, for example:

stripe trigger payment_intent.succeeded

You should now see some webhook event details being logged to your Node.js console.
42 changes: 0 additions & 42 deletions examples/webhook-signing/express.js

This file was deleted.

10 changes: 10 additions & 0 deletions examples/webhook-signing/node-express/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = {
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
},
rules: {
'new-cap': 'off',
'no-console': 'off',
},
};
42 changes: 42 additions & 0 deletions examples/webhook-signing/node-express/express.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
require('dotenv').config();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const express = require('express');
const bodyParser = require('body-parser');

const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;

const app = express();

// Use JSON parser for all non-webhook routes
app.use((req, res, next) => {
if (req.originalUrl === '/webhook') {
next();
} else {
bodyParser.json()(req, res, next);
}
});

// Stripe requires the raw body to construct the event
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (req, res) => {
const sig = req.headers['stripe-signature'];

let event;

try {
event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
} catch (err) {
// On error, log and return the error message
console.log(`❌ Error message: ${err.message}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}

// Successfully constructed event
console.log('✅ Success:', event.id);

// Return a response to acknowledge receipt of the event
res.json({received: true});
});

app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});
Loading