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

@shopify/koa-shopify-webhooks

v5.1.1

Published

Receive webhooks from Shopify with ease

Downloads

17,112

Readme

@shopify/koa-shopify-webhooks

Build Status Build Status License: MIT npm version

Register and receive webhooks from Shopify with ease. This package was created primarily for use with @shopify/koa-shopify-auth and friends.

Installation

yarn add @shopify/koa-shopify-webhooks

API

registerWebhook

function registerWebhook(options: {
  address: string;
  topic: Topic;
  format: string;
  accessToken: string;
  shop: string;
  apiVersion: ApiVersion;
}): {success: boolean; result: any};

Registers a webhook for the given topic which will send requests to the given address. Returns an object with success true / false to indicate success or failure, as well as the parsed JSON of the response from Shopify. This function will throw if the fetch request it makes encounters an error.

receiveWebhook

function receiveWebhook({
  secret: string;
  // only respond to requests to this path
  path?: string;
  // call this function when a valid webhook is received
  onReceived?(ctx: Context, next: () => unknown);
}): Middleware;

Creates a middleware that will verify whether incoming requests are legitimately from Shopify. Extracts webhook data into context or terminates the middleware chain.

Usage

Example app

import 'isomorphic-fetch';

import Koa from 'koa';
import session from 'koa-session';
import shopifyAuth, {verifyRequest} from '@shopify/koa-shopify-auth';
// Import our package
import {receiveWebhook, registerWebhook} from '@shopify/koa-shopify-webhooks';

const {SHOPIFY_API_KEY, SHOPIFY_SECRET} = process.env;

const app = new Koa();

app.keys = [SHOPIFY_SECRET];

app.use(session(app));
app.use(
  shopifyAuth({
    apiKey: SHOPIFY_API_KEY,
    secret: SHOPIFY_SECRET,
    scopes: ['write_orders, write_products'],
    async afterAuth(ctx) {
      const {shop, accessToken} = ctx.session;

      // register a webhook for product creation
      const registration = await registerWebhook({
        // for local dev you probably want ngrok or something similar
        address: 'www.mycool-app.com/webhooks/products/create',
        topic: 'PRODUCTS_CREATE',
        accessToken,
        shop,
        apiVersion: 'unstable',
      });

      if (registration.success) {
        console.log('Successfully registered webhook!');
      } else {
        console.log('Failed to register webhook', registration.result);
      }

      ctx.redirect('/');
    },
  }),
);

app.use(
  // receive webhooks
  receiveWebhook({
    path: '/webhooks/products/create',
    secret: SHOPIFY_SECRET,
    // called when a valid webhook is received
    onReceived(ctx) {
      console.log('received webhook: ', ctx.state.webhook);
    },
  }),
);

app.use(verifyRequest());

app.use((ctx) => {
  /* app code */
});

koa-router and multiple webhooks

import 'isomorphic-fetch';

import Koa from 'koa';
import router from 'koa-router';
import session from 'koa-session';
import shopifyAuth, {verifyRequest} from '@shopify/koa-shopify-auth';
// Import our package
import {receiveWebhook, registerWebhook} from '@shopify/koa-shopify-webhooks';

const {SHOPIFY_API_KEY, SHOPIFY_SECRET} = process.env;

const app = new Koa();
const router = new Router();

app.keys = [SHOPIFY_SECRET];

app.use(session(app));
app.use(
  shopifyAuth({
    apiKey: SHOPIFY_API_KEY,
    secret: SHOPIFY_SECRET,
    scopes: ['write_orders, write_products'],
    async afterAuth(ctx) {
      const {shop, accessToken} = ctx.session;

      await registerWebhook({
        address: 'www.mycool-app.com/webhooks/products/create',
        topic: 'PRODUCTS_CREATE',
        accessToken,
        shop,
        apiVersion: 'unstable',
      });

      await registerWebhook({
        address: 'www.mycool-app.com/webhooks/orders/create',
        topic: 'ORDERS_CREATE',
        accessToken,
        shop,
        apiVersion: 'unstable',
      });

      ctx.redirect('/');
    },
  }),
);

const webhook = receiveWebhook({secret: SHOPIFY_SECRET});

router.post('/webhooks/products/create', webhook, () => {
  /* handle products create */
});
router.post('/webhooks/orders/create', webhook, () => {
  /* handle orders create */
});

router.get('*', verifyRequest(), () => {
  /* app code */
});

app.use(router.allowedMethods());
app.use(router.routes());

Gotchas

Make sure to install a fetch polyfill, since internally we use it to make HTTP requests.

In your terminal yarn add isomorphic-fetch

In your app import 'isomorphic-fetch'

OR

require('isomorphic-fetch')