Sha256: bedd0a83a9ded93b62324aa02b737e7d5779058aad3d1f26f10427ce1e92e00f

Contents?: true

Size: 1.2 KB

Versions: 3

Compression:

Stored size: 1.2 KB

Contents

module SquareEvent
  class Webhook

    # Initializes an webook Event object from a JSON payload.
    #
    # TODO: raise JSON::ParserError if the payload is not valid JSON, or
    # SignatureVerificationError if the signature verification fails.
    def self.construct_event(payload, signature, secret, notification_url, environment, timestamp)

      Signature.verify_header(payload, signature, secret, notification_url)

      data = JSON.parse(payload, symbolize_names: true)
      Event.construct_from(data, environment, timestamp)
    end

    module Signature
      # Computes a webhook signature given payload, and a signing secret
      def self.verify_header(payload, signature, secret, notification_url)
        combined_payload = notification_url + payload
        digest = OpenSSL::Digest.new('sha1')
        hmac = OpenSSL::HMAC.digest(digest, secret, combined_payload)

        # stripping the newline off the end
        found_signature = Base64.encode64(hmac).strip

        if found_signature != signature
          raise SignatureVerificationError.new(
            "Signature was incorrect for webhook at #{notification_url}",
            http_body: payload
          )
        end
      end

    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
square_event-1.0.2 lib/square_event/webhook.rb
square_event-1.0.1 lib/square_event/webhook.rb
square_event-1.0.0 lib/square_event/webhook.rb