我无法找到有关用于解码PHP中的WooCommerce webhook字段X-Wc-Webhook-Signature的算法的任何信息。有谁知道如何解码它?
谢谢!
答案 0 :(得分:2)
扩展当前答案,这是您需要的PHP代码段:
$sig = base64_encode(hash_hmac('sha256', $request_body, $secret, true));
$ secret是您的秘密,$ request_body是请求正文,可以使用file_get_contents('php://input');
获取
然后$ sig值应等于X-Wc-Webhook-Signature请求标头。
答案 1 :(得分: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
进行比较,看看它们是否匹配。
答案 2 :(得分:1)
这是我对这个问题的解决方案。您需要为[有效负载]发送的内容生成一个sha256哈希,并在base64中对其进行编码。然后只需将生成的哈希值与接收到的哈希值进行比较即可。
$secret = 'your-secret-here';
$payload = file_get_contents('php://input');
$receivedHeaders = apache_request_headers();
$receivedHash = $receivedHeaders['X-WC-Webhook-Signature'];
$generatedHash = base64_encode(hash_hmac('sha256', $payload, $secret, true));
if($receivedHash === $generatedHash):
//Verified, continue your code
else:
//exit
endif;
答案 3 :(得分:1)
为了扩展 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);
}
}
在 Kernel.php 中注册中间件
'webhook' => \App\Http\Middleware\ValidateWebhook::class,
使用中间件保护 webhook 路由
Route::post('webhook', 'PrintController@webhook')->middleware('webhook');
答案 4 :(得分:0)
这是我的laravel / lumen函数,用于验证webhook请求,希望对您有所帮助!
private function verifyWebhook(Request $request) {
$signature = $request->header('x-wc-webhook-signature');
$payload = $request->getContent();
$calculated_hmac = base64_encode(hash_hmac('sha256', $payload, 'WOOCOMMERCE_KEY', true));
if($signature != $calculated_hmac) {
abort(403);
}
return true;
}