使用PHP转换WooCommerce Webhook Payload

时间:2016-10-03 05:25:34

标签: php json wordpress woocommerce webhooks

我已经使用WooCommerce设置了我的第一个Webhook,以便在下新订单时通知我的数据库服务器。 Webhook正在设置并由我的服务器发送/接收 - 我没有尝试编写将解析Webhook有效负载的PHP页面,因此我可以使用订单详细信息将新记录写入我的CRM数据库。 / p>

我无法获取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);

不会返回任何JSON数据。我正在寻求帮助:

  1. 检索Webhook在POST请求中发送的JSON数据
  2. 帮助解决如何解析JSON的每个元素以插入相应的数据库字段

2 个答案:

答案 0 :(得分:3)

这最终对我有用:

$webhookContent = "";

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

答案 1 :(得分:0)

<?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;
?>