ruby-rest-api icon indicating copy to clipboard operation
ruby-rest-api copied to clipboard

Firing a Signed Webhook Request

Open gja opened this issue 3 years ago • 0 comments

There is no way to use this library currently to trigger a web hook to start a flow with message bird. Here is the code I'm using for this. I'll try to open a PR incorporating this sometime in the future.

module MessageBirdWebhook
  def self.build_payload(time, body)
    parts = []
    parts.push(time)
    parts.push("")
    parts.push(Digest::SHA256.new.digest(body))
    parts.join("\n")
  end

  def self.sign_webhook_request(signing_key, body, now = Time.now)
    now = now.getutc.to_i
    signature = OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), signing_key, build_payload(now, body))

    {
      "MessageBird-Request-Timestamp" => now.to_s,
      "MessageBird-Signature" => Base64.encode64(signature).strip,
    }
  end

  def self.trigger_webhook(signing_key, webhook_id, params)
    body = params.to_json
    client = Faraday.new(url: "https://flows.messagebird.com", headers: { 'Content-Type' => 'application/json' })
    client.post("/flows/#{webhook_id}/invoke", body, sign_webhook_request(signing_key, body))
  end
end

gja avatar Jul 04 '21 13:07 gja