npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-stripe-webhook-middleware

v0.1.0

Published

You can easy to verify the Webhook request from Stripe.

Downloads

6

Readme

Express Stripe Webhook Middleware

You can easy to verify the Webhook request from Stripe.

Install

$ yarn add express-stripe-webhook-middleware

Usage

const Stripe = require('stripe');
const express = require('express');
const { StripeWebhookMiddlewareFactory } = require('express-stripe-webhook-middleware')
require('dotenv').config()

const stripe = new Stripe(process.env.STRIPE_SECRET_API_KEY, {
  apiVersion: '2020-08-27',
});

/**
 * Examples
 */
 const app = express();
 const webhookRouter = express.Router();
 const factory = new StripeWebhookMiddlewareFactory(process.env.STRIPE_WEBHOOK_SECRET_KEY, stripe)
 webhookRouter.use(
   '/webhook',
   factory.create()
 );
 
 webhookRouter.post('/webhook', (request, response) => {
   const payload = request.body;
   console.log('=====');
   console.log(payload);
   response.status(200).send('Webhook done!');
 });
 
 
 app.post('/webhook', webhookRouter);
 app.get('/', async (req, res) => {
   const data = stripe.customers.list();
   res.status(200).send(JSON.stringify(data));
 });
 app.listen(4242, () => console.log('start'));
 

Why?

Stripe recommend to check the Webhook signatures from Stripe. https://stripe.com/docs/webhooks/signatures

Stripe show us these example code to verify the signatures.

// Set your secret key. Remember to switch to your live secret key in production.
// See your keys here: https://dashboard.stripe.com/apikeys
const stripe = require('stripe')('sk_testXXXXXX');

// If you are testing your webhook locally with the Stripe CLI you
// can find the endpoint's secret by running `stripe listen`
// Otherwise, find your endpoint's secret in your webhook settings in the Developer Dashboard
const endpointSecret = 'whsec_...';

// This example uses Express to receive webhooks
const app = require('express')();

// Use body-parser to retrieve the raw body as a buffer
const bodyParser = require('body-parser');

// Match the raw body to content type application/json
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
  const sig = request.headers['stripe-signature'];

  let event;

  try {
    event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
  }
  catch (err) {
    response.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Handle the event
  switch (event.type) {
    case 'payment_intent.succeeded':
      const paymentIntent = event.data.object;
      console.log('PaymentIntent was successful!');
      break;
    case 'payment_method.attached':
      const paymentMethod = event.data.object;
      console.log('PaymentMethod was attached to a Customer!');
      break;
    // ... handle other event types
    default:
      console.log(`Unhandled event type ${event.type}`);
  }

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

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

When using this package, we can re-write the code like this.

require('dotenv').config()
const Stripe = require('stripe');
const express = require('express');
const { StripeWebhookMiddlewareFactory } = require('express-stripe-webhook-middleware')

const stripe = new Stripe(process.env.STRIPE_SECRET_API_KEY, {
  apiVersion: '2020-08-27',
});

const app = express();
const factory = new StripeWebhookMiddlewareFactory(process.env.STRIPE_WEBHOOK_SECRET_KEY, stripe)
app.post('/webhook', factory.create());
app.post('/webhook', async (request, response) => {
     const event = request.body
    // Handle the event
    switch (event.type) {
      case 'payment_intent.succeeded':
        const paymentIntent = event.data.object;
        console.log('PaymentIntent was successful!');
        break;
      case 'payment_method.attached':
        const paymentMethod = event.data.object;
        console.log('PaymentMethod was attached to a Customer!');
        break;
      // ... handle other event types
      default:
        console.log(`Unhandled event type ${event.type}`);
    }
  
    // Return a response to acknowledge receipt of the event
    response.json({received: true});
 });
 app.listen(4242, () => console.log('Running on port 4242'));

Try it out!

You can test the package on the example/ directory

Clone the project

$ git clone [email protected]:hideokamoto/express-stripe-webhook-middleware.git
$ cd express-stripe-webhook-middleware
$ npm install

Step1: Install packages

Install libraries.

$ cd example
$ npm install

Step2: Put your Stripe API keys

Open .env file, and replace api key from dummy to your account one.

$ vim .env
STRIPE_SECRET_API_KEY=sk_test_XXXXXXX
STRIPE_WEBHOOK_SECRET_KEY=whsec_XXXXXXX

Step3: Start the express server

You can start the demo server by this command.

$ node index.js

Step4: Listen and forward Stripe Webhook request by using Stripe CLI

Stripe CLI can forward the Webhook request to your localhost server.

$ stripe listen --forward-to localhost:4242/webhook

Step5: Execute Stripe Webhook event by using Stripe CLI

Trigger test webhook event from Stripe CLI.

$ stripe trigger payment_intent.created

Then, you can see the request body on the server log.

 % node index.js
start
=====
{
  id: 'evt_1JBeVwDHnG67uihbF0mxej38',
  object: 'event',
  api_version: '2020-08-27',
  created: 1625917112,
  data: {
    object: {
      id: 'pi_1JBeVwDHnG67uihb1LH7ioR2',
      object: 'payment_intent',
      amount: 2000,
      amount_capturable: 0,
      amount_received: 0,
      application: null,
      application_fee_amount: null,
...