Verifying webhooks

Ensure that the webhooks that you receive were sent by Pinpoint

How to verify a webhook

Webhooks can be verified using the signing secret displayed in the webhooks section of your Pinpoint company settings.

Each webhook request includes a base64-encoded PINPOINT-HMAC-SHA256 header. The value encoded is the computed HMAC digest which is generated using the SHA-256 hash function, the webhook signing secret, and the body of the request.

To verify that the request came from Pinpoint, compute this value and compare it to the value in the PINPOINT-HMAC-SHA256 header. If they match, then you can be sure that the webhook was sent from Pinpoint.

Examples

The following example uses the Ruby on Rails web framework to verify a webhook request:

# routes.rb
# Routing to define the controller method to handle incoming webhooks
Rails.application.routes.draw do
  resources :webhooks, only: [:create]
end

# app/controllers/webhooks_controller.rb
# Respond to HTTP POST requests sent to the /webhooks route defined above
class WebhooksController < ApplicationController
  skip_forgery_protection

  def create
    if verified_request?
	    # Process the webhook here
    end
  end

  private

  def verified_request?
    return false unless hmac_header

    ActiveSupport::SecurityUtils.secure_compare(computed_hmac, hmac_header)
  end

  def hmac_header
    request.headers['PINPOINT-HMAC-SHA256']
  end

  def computed_hmac
    digest = OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), signing_secret, request.body.read)
    Base64.strict_encode64(digest)
  end

  # Your signing secret would typcically be stored in encrypted credentials if running Rails 5.1 or later.
  def signing_secret
    Rails.application.credentials.dig(:signing_secret)
  end
end