Verifying subscription payloads


info

Verifying the payload is an optional step to ensure the authenticity of the payload.

This confirms the event payload originated from Tray and was not sent by a malicious third party.

Hence, although this step is optional, it is recommended that you do this.

Once a subscription is created, you will receive a signingKey in the response.

The signingKey should be stored in your database against the subscription ID.

The sigingKey is used by Tray to generate a HMAC code by signing the event payload.

This HMAC code will be sent as a header (x-tray-signature) along with the event payload to the endpoint you specified in Create Subscription request.

When you receive the event, you should verify the HMAC code before processing the payload.

Here is how you can do it in Node.js:

Copy
Copied
const crypto = require("crypto");

const generateHMAC = (signingKey, requestBody) => {
  const signingKeyBuffer = Buffer.from(signingKey, "base64");
  return crypto
    .createHmac("sha256", signingKeyBuffer)
    .update(requestBody, "utf-8") //requestBody is your event payload in plain text
    .digest("base64");
};

In the above code block, signingKey is what you get from upon creating subscription the first time.

requestBody will be the event payload (in plain text) that is sent to your endpoint.

The HMAC code generated using the function above should be equal to x-tray-signature header in the request.

warning

The signingKey will only be sent the first time you create a subscription and never again.

The signingKey can NOT be obtained through GET Subscriptions or GET Subscriptions by Id calls.