2015-04-07 137 views
3

我有一个Rails应用程序设置为从WooCommerce接收webhook。具体而言,我正在寻找何时创建订单。我已经测试并验证它在我创建protect_from_forgery时有效。现在我试图通过验证webhook来确保我的应用程序。 WooCommerce的文档指出以下秘密传入请求头:验证Webhook的请求

秘密:用于生成请求主体的HMAC-SHA256散列使接收器能验证Web钩

的真实性的可选的秘密密钥

WooCommerce github doc

此刻我不知道我是怎么想验证请求,然后采取行动。如果请求没有授权拒绝它与401。这是我正在尝试:

class HooksController < ApplicationController 

    protect_from_forgery 
    before_action :restrict_access 

    def order_created_callback 
    ... 
    end 

    private 

    SHARED_SECRET = 'my_secret_key' 

    def verify_webhook(data, hmac_header) 
     digest = OpenSSL::Digest::Digest.new('sha256') 
     calculated_hmac = Base64.encode64(OpenSSL::HMAC.digest(digest, SHARED_SECRET, data)).strip 
     calculated_hmac == hmac_header 
    end 

    def restrict_access 
     data = request.body.read 
     verified = verify_webhook(data, env["X-WC-Webhook-Signature"]) 
     head :unauthorized unless verified 

    end 
end 

但到目前为止,我一直没有成功。任何投入将不胜感激。谢谢。

+0

我无法提供解决方案,但您所做的似乎完全理智。大多数情况下,我遇到这个问题就像一个迷路的换行符,但我看到你最后称之为“strip”。 –

回答

3

好吧,我想出了我遇到的问题。如果其他人试图使用WooCommerce Web钩子,看起来我的问题是适当地抓取请求的头文件以匹配我的计算HMAC。

SHARED_SECRET = "my_secret" 

def verify_webhook(data, hmac_header) 
    hash = OpenSSL::Digest::Digest.new('sha256') 
    calculated_hmac = Base64.encode64(OpenSSL::HMAC.digest(hash, SHARED_SECRET, data)).strip 
    calculated_hmac == hmac_header 
end 

def restrict_access 
    data = request.body.read 
    head = request.headers["X-WC-Webhook-Signature"] 
    verified = verify_webhook(data, head) 
    if verified 
     return 
    else 
     render nothing: true, status: :unauthorized 
    end 
end 
+1

“摘要::摘要已弃用;使用摘要”(来自日志) – Cleverlemming