Class: Pobo::WebhookHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/pobo/webhook_handler.rb

Constant Summary collapse

SIGNATURE_HEADER =
"X-Webhook-Signature"

Instance Method Summary collapse

Constructor Details

#initialize(webhook_secret:) ⇒ WebhookHandler

Returns a new instance of WebhookHandler.



10
11
12
# File 'lib/pobo/webhook_handler.rb', line 10

def initialize(webhook_secret:)
  @webhook_secret = webhook_secret
end

Instance Method Details

#handle(payload:, signature:) ⇒ Object

Handle webhook with raw payload and signature



26
27
28
29
30
31
32
33
34
# File 'lib/pobo/webhook_handler.rb', line 26

def handle(payload:, signature:)
  raise WebhookError.missing_signature if signature.nil? || signature.empty?
  raise WebhookError.invalid_signature unless valid_signature?(payload, signature)

  data = JSON.parse(payload)
  DTO::WebhookPayload.from_hash(data)
rescue JSON::ParserError
  raise WebhookError.invalid_payload
end

#handle_request(request) ⇒ Object

Handle webhook from Rack request



15
16
17
18
19
20
21
22
23
# File 'lib/pobo/webhook_handler.rb', line 15

def handle_request(request)
  payload = request.body.read
  request.body.rewind if request.body.respond_to?(:rewind)

  signature = request.env["HTTP_X_WEBHOOK_SIGNATURE"] ||
              request.get_header("HTTP_X_WEBHOOK_SIGNATURE") rescue nil

  handle(payload: payload, signature: signature)
end