简体   繁体   English

使用 Google Apps 脚本(WooCommerce Webhook)获取 JSON 数组中的 object 值

[英]Obtain object valus in a JSON array with Google Apps Script (WooCommerce Webhook)

I have a WooCommerce webshop, which sends the created orders to a Google Spreadsheet using a webhook.我有一个 WooCommerce 网上商店,它使用 webhook 将创建的订单发送到 Google 电子表格。 I managed to make it work, except for one (crucial) step: I cannot seem to properly loop through the meta data of the line items.我设法使它工作,除了一个(关键)步骤:我似乎无法正确循环遍历行项目的元数据。

To give a bit more context here: its a webshop that sells cakes and pies etc (the line items).在这里提供更多背景信息:它是一家销售蛋糕和馅饼等(行项目)的网上商店。 One order can have multiple products, and every product can have multiple meta data.一个订单可以有多个产品,每个产品可以有多个元数据。 For example: Product (line item): Cake, meta data: cake (key) size: (value) small, (key) text on cake: (value) Blue text, (key) text on cake text: "Hello World" (value).例如:产品(行项目):蛋糕,元数据:蛋糕(键)尺寸:(值)小,(键)蛋糕上的文字:(值)蓝色文本,(键)蛋糕上的文字:“Hello World” (价值)。

What I need to achieve is the following example of the order in the spreadsheet (simplified):我需要实现的是以下电子表格中的顺序示例(简化):

Name, email address, pick up date, pick up time, pick up location, order姓名、email地址、取件日期、取件时间、取件地点、订单

Joe Deer, joe@deer.com, 10/10/2020, 10:00,Bakery,1 x Red Velvet Cake, Small cake, Blue text on cake, "Hello World". Joe Deer,joe@deer.com,2020 年 10 月 10 日,10:00,面包店,1 x 红色天鹅绒蛋糕,小蛋糕,蛋糕上的蓝色文字,“Hello World”。 1 x Turtle Cake, Large Cake no text on cake. 1 x 海龟蛋糕,大蛋糕蛋糕上没有文字。

Please find an example of the JSON Object below for an overview.请在下面找到 JSON Object 的示例以获取概览。 The name of the Object is myData, and therefore he line items can be accessed using myData.line_items. Object 的名称是 myData,因此可以使用 myData.line_items 访问行项目。

"line_items": [
{
  "id": 61458,
  "name": "Cupcake Mix 12 stuks",
  "product_id": 627,
  "variation_id": 0,
  "quantity": 1,
  "tax_class": "gereduceerd-tarief",
  "subtotal": "27.52",
  "subtotal_tax": "2.48",
  "total": "27.52",
  "total_tax": "2.48",
  "taxes": [
    {
      "id": 2,
      "total": "2.477064",
      "subtotal": "2.477064"
    }
  ],
  "meta_data": [
    {
      "id": 540340,
      "key": "Vanilla Buttercream Cupcake",
      "value": "yes"
    },
    {
      "id": 540341,
      "key": "Vanilla Confetti Cupcake",
      "value": "yes"
    },

What I (believe that I) need to achieve is to add a loop within the loop that iterates through the meta_data of the line_items object.我(相信我)需要实现的是在循环中添加一个循环,该循环遍历 line_items object 的 meta_data。 However, I tried it (using the code below), but couldn't make it work.但是,我尝试了它(使用下面的代码),但无法使其工作。

    //this is a function that fires when the webapp receives a GET request
function doGet(e) {
  return HtmlService.createHtmlOutput("request received");
  Logger.log('GET received at: ' + timestamp);
}

//this is a function that fires when the webapp receives a POST request
function doPost(e) {
  var myData                 = JSON.parse([e.postData.contents]);
  var order_number           = myData.number;
  var order_created          = myData.date_created;
  var order_status           = myData.status;
  var product_name           = myData.line_items[0].name;
  var product_qty            = myData.line_items[0].quantity;
  var product_total          = myData.line_items[0].total;
  var order_total            = myData.total;
  var billing_email          = myData.billing.email;
  var billing_first_name     = myData.billing.first_name;
  var billing_last_name      = myData.billing.last_name;
  var payment_method         = myData.payment_method_title;
  var shipping_method        = myData.shipping_lines[0].method_title;
  var pick_up_location       = myData.meta_data[0]["value"];
  var pick_up_date           = myData.meta_data[1]["value"];
  var pick_up_time           = myData.meta_data[2]["value"];

  var pick_up_time_array     = pick_up_time.split(" - ");
  var pick_up_time_start     = pick_up_time_array[0];
  var pick_up_time_end       = pick_up_time_array[1];
  var shipping_total         = myData.shipping_lines[0].total;

  var lineitems=""
  for (i in myData.line_items)
  {
    var product_name         = myData.line_items[i].name;
    var itemName             = myData.line_items[i].name;
    var quantity             = myData.line_items[i].quantity;

     for (j in myData.line_items[1][j]) {
        var decorationitems = "Item: " + myData.line_items[1][j].key + " Optie: " + myData.line_items[1][j].value + '\n';
        var decoration = decoration+decorationitems; 
      }

    var product_items = quantity + " x " + itemName + '\n' + decoration + '\n';  
    var lineitems = lineitems+product_items;
}

var timestamp = new Date();
  var sheetActive = SpreadsheetApp.openById("<ID>");
  var sheet = sheetActive.getSheetByName("<NAME>");
  sheet.appendRow([timestamp,order_number,order_created,product_name,product_qty,product_total,order_total,billing_email,billing_first_name,billing_last_name,payment_method,shipping_method,pick_up_location,pick_up_date,pick_up_time,pick_up_time_start,pick_up_time_end,shipping_total,lineitems]);

}

Could you guys help me out with the part of the for loop?你们能帮我解决for循环的部分吗? I sincerely hope that I made my question clear.我真诚地希望我把我的问题说清楚了。 If you have any further questions, please let me know!如果您还有任何问题,请告诉我!

Here is a loop that iterates through the meta_data of the line_items object, based on the code you supplied.这是一个循环,它根据您提供的代码遍历 line_items object 的 meta_data。

  var lineitems="";
  var decoration = "";
  for (var i in myData.line_items)
  {
    var product_name = myData.line_items[i].name;
    var itemName = myData.line_items[i].name;
    var quantity = myData.line_items[i].quantity;
    var metaData = myData.line_items[i].meta_data;

     for (var j in metaData) 
     {
       for (var key in metaData[j])
       {
         var decorationitems = "Item: " + key + " Optie: " + metaData[j][key] + '\n';
         decoration = decoration + decorationitems; 
       }
     }
    var product_items = quantity + " x " + itemName + '\n' + decoration + '\n';  
    lineitems = lineitems + product_items;

  }
//this is a function that fires when the webapp receives a GET request
function doGet(e) {
  return HtmlService.createHtmlOutput("request received bla");
}

//this is a function that fires when the webapp receives a POST request
function doPost(e) {
  var myData             = JSON.parse([e.postData.contents]);
  var currency           = myData.currency;
  var order_number       = myData.number;
  var order_created      = myData.date_created;
  var order_status       = myData.status;
  var billing_name       = myData.billing.first_name +  " " + myData.billing.last_name;
  var username           = myData.billing.first_name;
  var billing_email      = myData.billing.email;
  var billing_phone      = myData.billing.phone;
  var billing_country    = myData.billing.country;
  var city               = myData.shipping.city;
  var billing_address    = myData.billing.address_1 + ", " + myData.billing.address_2 ;
  var shipping_address   = myData.shipping.address_1 +  ", " + myData.shipping.address_2 ;
  var shipping_post_code = myData.shipping.postcode;
  var payment_method     = myData.payment_method_title;
  var shipping_total     = (myData.shipping_lines.length > 0) ? myData.shipping_lines[0].total : '0';
  var product_total      = (myData.line_items.length>1) ? myData.line_items[0].meta_data[3].value.total_payable_amount : '-';
  var total_amount       = myData.total;
  var remaining_amount   = (myData.line_items.length>1) ? myData.line_items[0].meta_data[3].value.remaining_payable_amount : '-';
  var coupon_name        = (myData.coupon_lines.length>0) ? myData.coupon_lines[0].code : '-';
  var payment_plan       = (myData.line_items.length>1) ? myData.line_items[0].meta_data[0].value : '-';
  var next_payment       = (myData.line_items.length>1) ? myData.line_items[0].meta_data[3].value.next_installment_amount : '-';
  var next_payment_date  = (myData.line_items.length>1) ? myData.line_items[0].meta_data[3].value.next_payment_date : '-';
  

  for (var i = 0; i < myData.line_items.length; i++){

  var product_id = myData.line_items[i].product_id;
  var product_name = myData.line_items[i].name;
  var product_qty = myData.line_items[i].quantity;
  var variation_id = myData.line_items[i].variation_id;
   

 }

  if (currency == 'SGD')
  sheet = SpreadsheetApp.getActive().getSheetByName('sg');
  else if (currency == 'MYR')
  if(product_id =='8348')
  sheet = SpreadsheetApp.getActive().getSheetByName('msia_else');
  else if(product_id =='8108 ')
  sheet = SpreadsheetApp.getActive().getSheetByName('msia_else');
  else if(product_id =='9312')
  sheet = SpreadsheetApp.getActive().getSheetByName('msia_else');
  else if(product_id =='8091')
  sheet = SpreadsheetApp.getActive().getSheetByName('msia_else');
  else if(product_id =='8054')
  sheet = SpreadsheetApp.getActive().getSheetByName('msia_else');
  else if(product_id =='7817')
  sheet = SpreadsheetApp.getActive().getSheetByName('msia_else');
  else
  sheet = SpreadsheetApp.getActive().getSheetByName('msia');
  else //if (currency == 'THB')
  sheet = SpreadsheetApp.getActive().getSheetByName('thai');

  if (order_status == "pending") return '';



 sheet.appendRow([order_number,order_created,order_status,billing_name,username,billing_email,billing_phone,billing_country,city,billing_address,shipping_address,shipping_post_code,payment_method,product_name,shipping_total,product_qty,product_total,total_amount,remaining_amount,coupon_name,payment_plan,next_payment,next_payment_date,product_id,variation_id]);

}

Can someone help me with this?I am trying to get multiple product_name and product id but i am not getting using the code above.I am doing anything wrong有人可以帮我吗?我正在尝试获取多个产品名称和产品 ID,但我没有使用上面的代码。我做错了什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM