Reputation: 1
I'm using the script below to import WooCommerce orders into Google Sheets via a webhook. The data is importing as expected, however only the first product of each order is being presented. How would i amend the script to include multiple product names and product quantities for each order?*****
//this is a function that fires when the webapp receives a GET request
function doGet(e) {
return HtmlService.createHtmlOutput("request received");
}
//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 first_name = myData.billing.first_name;
var last_name = myData.billing.last_name;
var address = myData.billing.address_1;
var town = myData.billing.city;
var postcode = myData.billing.postcode;
var product_name = myData.line_items[0].name;
var product_qty = myData.line_items[0].quantity;
var notes = myData.customer_note;
var timestamp = new Date();
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([timestamp, order_number, first_name, last_name, address, town, postcode, product_name, product_qty, notes]);
}
Thanks, Ben
Upvotes: 0
Views: 294
Reputation: 43
I hope you are doing fine.
The problem you are facing is because in a multi-product order, there are multiple variables in your JSON data with the name 'product title', so with your code, only the first product name is being read.
Solution:
In your code, replace your code
var product_name = myData.line_items[0].name;
With this code
for (var i = 0; i < myData.line_items.length; i++){
var product_name = myData.line_items[i].name;
var product_qty = myData.line_items[i].quantity;
quantity = quantity + product_qty;
if(i!=0)
{
description = description + " || " + product_name + " x " + product_qty;
}
else
{
description = product_name + " x " + product_qty;
}
}
This traverses through the JSON table, gets all product names, writes their quantities in front of them and then adds a little separator "||" between two different products. Usman
Upvotes: 1