解析Woocommerce Webhook(JSON)

时间:2015-10-09 17:39:27

标签: json google-apps-script google-sheets woocommerce webhooks

当产品更新或下订单时,Wommcommerce会触发Webhook。我正试图通过作为WebApp发布的Google Apps脚本(GAS)来抓住这个Webhook。我最终想要实现的是将收到的订单写入Google电子表格。

我无法从这些webhook中获取正确(或至少一些)数据。我尝试了不同的方法将数据写入工作表,但我在工作表中遇到的唯一方法是“未定义”。老实说,我不知道如何处理JSON数据。我的测试功能现在是:

function doPost(e){ 
  var doc =     DocumentApp.openById('myDocId');
  var jstring = Utilities.jsonStringify(e);
  doc.appendParagraph(jstring);
}

当触发webhook(订单更新)时,我在文档中得到以下输出:

  

{ “参数”:{} “的contextPath”: “”, “CONTENTLENGTH”:1523, “的queryString”:NULL, “参数”:{}, “POSTDATA”: “文件上传”}

显然根本没有解析,但我尝试的所有(例如getContentText())都不起作用。 Webhook-Log in Woocommerce告诉我这是发送的:

  

{ “产品”:{ “标题”: “testprodukt”, “ID”:136, “created_at”: “2015-10-06T13:15:38Z”, “的updated_at”:“2015-10-09T15: 19:04Z “ ”类型“: ”简单“, ”状态“: ”发布“, ”下载“:真, ”虚拟“:真, ”永久“: ”http://MYDOMAIN/produkt/testprodukt/“, ”SKU“:” “ ”价格“: ”5.00“, ”REGULAR_PRICE“: ”5.00“, ”SALE_PRICE“:空, ”price_html“: ”€5,00“, ”征税“:假的, ”tax_status“: ”纳税“,” tax_class “:” “ ”managing_stock“:假的, ”stock_quantity“: ”“, ”IN_STOCK“:真实的, ”backorders_allowed“:假的, ”延期交货“:假的, ”sold_individually“:假的, ”可购买“:真”特色 “:假的,” 可见 “:真实的,” catalog_visibility “:” 可见”, “on_sale”:假的, “product_url”: “”, “BUTTON_TEXT”: “”, “重”:空, “尺寸”:{ “长度”: “”, “宽度”: “”, “高度”: “”, “单元”: “厘米”}, “shipping_required”:假 “shipping_taxable”:真 “shipping_class”: “”,” shipping_class_id “:空,” 说明 “:”

somedescription

N”, “SHORT_DESCRIPTION”: “”, “reviews_allowed”:假 “AVERAGE_RATING”: “0.00”, “RATING_COUNT”: 0 “related_ids”:[], “upsell_ids”:[], “cross_sell_ids”:[], “PARENT_ID”:0, “类别”:[] , “标签”:[], “图像”:[{ “ID”:0, “created_at”: “2015-10-09T15:19:05Z”, “的updated_at”:“2015-10-09T15:19:05Z ”, “SRC”: “http://MYDOMAIN/wp-content/plugins/woocommerce/assets/images/placeholder.png”, “标题”: “Platzhalter”, “ALT”: “Platzhalter”, “位置”:0}], “featured_src”:假, “属性”:[] , “下载”:[], “download_limit”:0 “download_expiry”:0 “download_type”: “”, “purchase_note”: “”, “TOTAL_SALES”:7, “变体”:[], “亲本” :[]}}

我正在寻找提示,链接,示例,向正确的方向推送如何将数据传输到webhook。

2 个答案:

答案 0 :(得分:2)

感谢Riel和plus.google的帮助,我明白了。这是我的代码作为示例,也许它有帮助:

function doPost(request) {     

var json = request.postData.getDataAsString(); 
var obj = JSON.parse(json);     


// getting some of the Woocommerce data just as an example
// Hook was fired after order.created
var id = obj.order.id;
var orderNumber = obj.order.order_number;
var payMethod = obj.order.payment_details.method_title;    


// write data in a document, not useful, but straightforward for testing   

var doc =     DocumentApp.openById('myDocumentId');
doc.appendParagraph("Id: " + id);
doc.appendParagraph("orderNumber: " + orderNumber);
doc.appendParagraph("payMethod: " + payMethod);

}

结果应如下所示:

  

Id:171

     

orderNumber:171

     

payMethod:Per Nachnahme

答案 1 :(得分:0)

位于e.postData.content

也可以使用JSON.parse而不是Utilities。