messagebird / ruby-rest-api

MessageBird's REST API for Ruby
BSD 2-Clause "Simplified" License
37 stars 46 forks source link

Firing a Signed Webhook Request #64

Open gja opened 3 years ago

gja commented 3 years ago

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