Sha256: b1fd223fd4c98bbfac3cd4b593b2f74ba7f15ef5492a319d68255f176227a836

Contents?: true

Size: 1.76 KB

Versions: 4

Compression:

Stored size: 1.76 KB

Contents

# frozen_string_literal: true

require_relative 'webhook_event'

# ref: https://developer.intuit.com/app/developer/qbo/docs/develop/webhooks/managing-webhooks-notifications#validating-the-notification
module LedgerSync
  module Ledgers
    module QuickBooksOnline
      class Webhook
        attr_reader :notifications,
                    :original_payload,
                    :payload

        def initialize(payload:)
          @original_payload = payload
          @payload = payload.is_a?(String) ? JSON.parse(payload) : payload

          event_notifications_payload = @payload.dig('eventNotifications')
          raise 'Invalid payload: Could not find eventNotifications' unless event_notifications_payload.is_a?(Array)

          @notifications = []

          event_notifications_payload.each do |event_notification_payload|
            @notifications << WebhookNotification.new(
              payload: event_notification_payload,
              webhook: self
            )
          end
        end

        def events
          notifications.map(&:events)
        end

        def resources
          @resources ||= notifications.map(&:resources).flatten.compact
        end

        def valid?(signature:, verification_token:)
          self.class.valid?(
            payload: payload.to_json,
            signature: signature,
            verification_token: verification_token
          )
        end

        def self.valid?(payload:, signature:, verification_token:)
          raise 'Cannot verify non-String payload' unless payload.is_a?(String)

          digest = OpenSSL::Digest.new('sha256')
          hmac = OpenSSL::HMAC.digest(digest, verification_token, payload)
          base64 = Base64.encode64(hmac).strip
          base64 == signature
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
ledger_sync-1.4.4 lib/ledger_sync/ledgers/quickbooks_online/webhook.rb
ledger_sync-1.4.2 lib/ledger_sync/ledgers/quickbooks_online/webhook.rb
ledger_sync-1.4.1 lib/ledger_sync/ledgers/quickbooks_online/webhook.rb
ledger_sync-1.4.0 lib/ledger_sync/ledgers/quickbooks_online/webhook.rb