如何解码 WooCommerce Webhook Secret?

eri*_*ben 5 php webhooks woocommerce

我找不到关于使用什么算法来解码 PHP 中的 WooCommerce webhook 字段 X-Wc-Webhook-Signature 的任何信息。有人知道怎么解码吗?

谢谢!

小智 8

为了扩展 Laravel 解决方案,这就是我创建中间件来验证传入 Webhook 的方式。

创建中间件。我正在使用的应用程序将 WooCommerce 消费者密钥和秘密保存在分配给给定商店的表中。

class ValidateWebhook
{
    /**
     * Validate that the incoming request has been signed by the correct consumer key for the supplied store id
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $signature = $request->header('X-WC-Webhook-Signature');
        if (empty($signature)) {
            return response(['Invalid key'], 401);
        }

        $store_id = $request['store'];
        $consumer_key = ConsumerKeys::fetchConsumerSecretByStoreId($store_id);

        $payload = $request->getContent();
        $calculated_hmac = base64_encode(hash_hmac('sha256', $payload, $consumer_key, true));

        if ($signature != $calculated_hmac) {
            return response(['Invalid key'], 401);
        }

        return $next($request);
    }
}
Run Code Online (Sandbox Code Playgroud)

在 Kernel.php 中注册中间件

        'webhook' => \App\Http\Middleware\ValidateWebhook::class,
Run Code Online (Sandbox Code Playgroud)

使用中间件保护 webhook 路由

Route::post('webhook', 'PrintController@webhook')->middleware('webhook');
Run Code Online (Sandbox Code Playgroud)


小智 6

扩展当前的答案,这是您需要的 PHP 代码片段:

$sig = base64_encode(hash_hmac('sha256', $request_body, $secret, true));
Run Code Online (Sandbox Code Playgroud)

其中 $secret 是您的秘密, $request_body 是请求正文,可以使用file_get_contents('php://input'); $sig 值获取,然后 $sig 值应等于 X-Wc-Webhook-Signature 请求标头。


Dar*_*ron 1

根据文档:“有效负载的 base64 编码的 HMAC-SHA256 哈希值”

我猜测这种情况下的有效负载是您在 webhook 属性中提供的秘密。

来源:https ://woocommerce.github.io/woocommerce-rest-api-docs/v3.html#webhooks-properties

编辑

进一步挖掘表明有效负载是请求的正文。因此,您可以使用 HMAC 库使用 Webhook 密钥创建有效负载的 sha256 哈希值,然后对结果进行 Base64 编码,并进行比较并X-Wc-Webhook-Signature查看它们是否匹配。

您可以从以下 URL 生成密钥对:

/wc-auth/v1/authorize?app_name=my_app&scope=read_write&user_id=<a_unique_id_that_survives_the_roundtrip>&return_url=<where_to_go_when_the_flow_completes>&callback_url=<your_server_url_that_will_receieve_the_following_params>
Run Code Online (Sandbox Code Playgroud)

这些是回调 URL 在请求正文中接收的参数:

{
  consumer_key: string,
  consumer_secret: string,
  key_permissions: string,
  user_id: string,
}
Run Code Online (Sandbox Code Playgroud)