Skip to content

Commit

Permalink
Added typescript webhook example (#764)
Browse files Browse the repository at this point in the history
* Added typescript webhook example

* v8 updates.

* TypeScript options for eslint.

* README updates.

* Fix linting.

* Review changes.

* Wording

Co-authored-by: paulasjes-stripe <46610432+paulasjes-stripe@users.noreply.github.com>
  • Loading branch information
2 people authored and rattrayalex-stripe committed Jan 16, 2020
1 parent 20158db commit 8f3c3ec
Show file tree
Hide file tree
Showing 14 changed files with 712 additions and 56 deletions.
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.

### 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.

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

0 comments on commit 8f3c3ec

Please sign in to comment.