Class: Tosspayments2::Rails::WebhookVerifier
- Inherits:
-
Object
- Object
- Tosspayments2::Rails::WebhookVerifier
- Defined in:
- lib/tosspayments2/rails/webhook_verifier.rb
Overview
Verifies incoming webhook using HMAC-SHA256 signature (Base64 encoded). Assumes TossPayments sends header 'X-TossPayments-Signature'.
Constant Summary collapse
- HEADER_NAME =
'X-TossPayments-Signature'
Instance Method Summary collapse
-
#compute_signature(body) ⇒ Object
Compute signature for a given body.
-
#initialize(secret_key: nil) ⇒ WebhookVerifier
constructor
A new instance of WebhookVerifier.
- #verify?(body, signature) ⇒ Boolean
Constructor Details
#initialize(secret_key: nil) ⇒ WebhookVerifier
Returns a new instance of WebhookVerifier.
13 14 15 16 17 18 19 |
# File 'lib/tosspayments2/rails/webhook_verifier.rb', line 13 def initialize(secret_key: nil) @secret_key = secret_key || ::Tosspayments2::Rails.configuration.secret_key return if @secret_key raise ::Tosspayments2::Rails::ConfigurationError, 'secret_key required for webhook verification' end |
Instance Method Details
#compute_signature(body) ⇒ Object
Compute signature for a given body
32 33 34 35 |
# File 'lib/tosspayments2/rails/webhook_verifier.rb', line 32 def compute_signature(body) digest = OpenSSL::HMAC.digest('sha256', @secret_key, body) Base64.strict_encode64(digest) end |
#verify?(body, signature) ⇒ Boolean
24 25 26 27 28 29 |
# File 'lib/tosspayments2/rails/webhook_verifier.rb', line 24 def verify?(body, signature) return false unless body && signature expected = compute_signature(body) secure_compare?(signature, expected) end |