简体   繁体   中英

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. 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).

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

Joe Deer, joe@deer.com, 10/10/2020, 10:00,Bakery,1 x Red Velvet Cake, Small cake, Blue text on cake, "Hello World". 1 x Turtle Cake, Large Cake no text on cake.

Please find an example of the JSON Object below for an overview. The name of the Object is myData, and therefore he line items can be accessed using 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. 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? 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.

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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