使用 PHP 转换 WooCommerce Webhook 负载

Convert WooCommerce Webhook Payload using PHP

我已经使用 WooCommerce 设置了我的第一个 Webhook,以便它在下新订单时通知我的数据库服务器。 Webhook 已设置并由我的服务器 sent/received - 我不是要编写一个 PHP 页面来解析 Webhook 的有效负载,因此我可以使用以下命令将新记录写入我的 CRM 数据库订单详情。

我在获取 Webhook 的内容时遇到问题。根据 WooCommerce 中 Webhook 的日志,请求详细信息是(我已经缩写了内容 JSON 数据):

Headers:

 user-agent: WooCommerce/2.6.4 Hookshot (WordPress/4.6.1)
 content-type: application/json
 x-wc-webhook-source: http://example.com/
 x-wc-webhook-topic: order.created
 x-wc-webhook-resource: order
 x-wc-webhook-event: created
 x-wc-webhook-signature: xxxxxxxxxxxxxxxxxxx=
 x-wc-webhook-id: 3233
 x-wc-webhook-delivery-id: 94

Content:

{"order":{"id":3242,"order_number":3242,"order_key":"wc_order_57f1dbe5bcf03","created_at":"2016-10-03T04:17:41Z", .....

它正在执行 POST 请求,但我无法检索 POST 数据,例如

$postData = var_export($_POST, true);       
error_log($postData, 0);

没有 return 任何 JSON 数据。我正在寻求帮助:

  1. 正在检索 Webhook 在 POST 请求中发送的 JSON 数据
  2. 帮助了解如何解析 JSON 的每个元素以插入适当的数据库字段
<?php
while ( have_posts() ) : the_post();
$order = new WC_Order($order_id); 
$product = new WC_Product($order_id);
foreach($order->get_items() as $item) 
{
   $json['items'][] = array (
       'name' => $item['name'],
       'quantity' => $item['qty']
}

endwhile;
echo $result = json_format($json);
return $result;
?>

这最终对我有用:

$webhookContent = "";

    $webhook = fopen('php://input' , 'rb');
    while (!feof($webhook)) {
        $webhookContent .= fread($webhook, 4096);
    }
    fclose($webhook);