Handle deliveries

Tutorial on how to handle webhook deliveries from carbonregistry

When you create a webhook, you specify a URL and when an event occurs, carbonregistry will send an HTTP request with data about the event to the URL that you specified. If your server is set up to listen for webhook deliveries at that URL, it can take action when it receives one.

In this example we will go over how to setup the webhook and receive the data when an event happens. We will use expressJS for defining the webhook handler. Repository for the code is here.

Setup

In order to test your webhook locally, you can use a webhook proxy URL to forward webhooks from CarbonRegistry to your computer or codespace. This article uses ngrok.com to provide a webhook proxy URL and forward webhooks.

If you don't have ngrok installed, and want to use it, go install it here.

Our express server will run on port 4040 so we run:

ngrok http 4040

Which sets up a tunnel so the carbonregistry sandbox can send the webhook event to our locally running server through a public facing url.

Creating webhook

Go to the "General" tab in your app's dashboard and insert the url where the webhook should deliver the payload and save it.

Now when an event happens that is connected to the app this endpoint will be called by CarbonRegistry. Let's try it by installing our app on an organization we own. You can go to the path:

https://sandbox.carbonregistry.com/apps/{APP_NAME_ID}/installations/new

to install the app on your organization.

After installing the app on an organization your an admin of we can see we get a webhook POST request from CarbonRegistry in the ngrok dashboard.

The code for handling this event:

import express, { Request, Response } from "express";

const app = express();
app.use(express.json());
app.post("/webhook", (req: Request, res: Response) => {
  res.status(202).send("Accepted");
  const signature = req.header("x-icr-signature-256");
  
  //** Verify signature **//
  
  console.log("SIGNATURE:", signature);
  console.log("EVENT:", req.body.event);
  console.log("Installation:", req.body.installation);
  console.log("Organization:", req.body.installation.organization);
  console.log("Sender:", req.body.sender);
});

app.listen(4040, () => {
  console.log("Server is listening on port 4040");
});

Note: webhooks are currently not re-run on failure.

Now, you should not blindly accepts calls to this endpoint as coming from CarbonRegistry. Therefore we support signatures using a shared secret. See "Validate deliveries" for more info.

Last updated