I would like to add different API request on a spreadsheet where i already add some google app script code from here in oder to retrieve all orders from a woocommerce external source, however now i want to add another API calling request which allows me to list all products on my woocommerce source. So i type a new function below, modify the endpoint to /wp-json/wc/v3/products according to woocommerce API rest documentation here Woocommerce API rest doc. Here is the code i add to the Github code :
// Custom code to v2 Woocommerce API
function start_syncv2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(Products);
fetch_products(sheet)
}
function fetch_products(sheet) {
var ck = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B4").getValue();
var cs = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B5").getValue();
var website = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B3").getValue();
var surl = website + "/wp-json/wc/v3/sheet?consumer_key=" + ck + "&consumer_secret=" + cs + "&after=" + "&per_page=100";
var url = surl
Logger.log(url)
var options =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
Logger.log(result.getResponseCode())
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
Logger.log(result.getContentText());
}
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = SpreadsheetApp.getSheetByName(sheet);
var consumption = {};
var arrayLength = params.length;
Logger.log(arrayLength)
for (var i = 0; i < arrayLength; i++) {
Logger.log("dfsfsdfsf")
var a;
var container = [];
a = container.push(params[i]["id"]);
Logger.log(a)
a = container.push(params[i]["name"]);
a = container.push(params[i]["sku"]);
a = container.push(params[i]["price"]);
a = container.push(params[i]["tax_status"]);
a = container.push(params[i]["stock_status"]);
a = container.push(params[i]["categories"]["name"]);
a = container.push(params[i]["images"]);
a = container.push(params[i]["attributes"]["options"]);
a = container.push(params[i]["_links"]["self"]["href"]);
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet);
temp.appendRow(container);
}
}
I have issue using google sheets calling method describe here. As i want my new API call request, i think my main problem is to select the right sheet into the spreadsheet.
Here is a copy of my spreadsheet : Woocommerce-google sheets integration
Related
I need to change this code so that I have data from multiple sites in Analytics, ordered by date.
The code below works perfectly, but only for an Analytics account. I need to automate this, to get data from multiple sites in the same account.
function start(){
ScriptApp.newTrigger("getGoogleAnalyticsData").timeBased().everyDays(1).create();
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("Get external data")
.addItem("Google Analytics", "getGoogleAnalyticsData")
.addToUi();
}
function getGoogleAnalyticsData() {
var date = new Date();
var startDate = "2020-01-01";
var endDate = "2020-12-31";
var tableId = 'ga:201010452';
var metric = 'ga:totalPublisherRevenue';
var options = {
'dimensions': 'ga:date',
'sort': '-ga:date',
'filters': 'ga:medium!==organic',
'max-results': 425
};
var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,options);
if (report.rows) {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var headers = report.columnHeaders.map(function(columnHeader) {
return columnHeader.name;
});
sheet.appendRow(headers);
sheet.getRange(2, 1, report.rows.length, headers.length)
.setValues(report.rows);
} else {
Logger.log('No rows returned.');
}
}
You can use Analytics Management API (https://developers.google.com/analytics/devguides/config/mgmt/v3) to get profile list from your account and adapt the code to cycle and query the views of interest.
I want to retrieve data via Jenkins API using Google Sheet Script and store it in Google Sheet
1) Pull Jenkins Job Builds using Jenkins API to Google Sheet - DONE
2) Store data to Google Sheet ???
(need only "builds.subBuilds.buildNumber" and "builds.subBuilds.duration" values)
(need to correct mistake in the script)
function getJenkinsBuilds() {
// get the jenkins job
var response = UrlFetchApp.fetch('http://jenkins.[domain].co/job/Build+Deploy/api/json', {
'method': 'get',
'muteHttpExceptions' : true,
'headers' : {'Authorization' : 'Basic [tokan]'},
});
// parse the json reply and return builds
var data = JSON.parse(response);
var builds = data["builds"];
Logger.log(builds);
return builds;
};
// store predefined parameters from builds in the spreadsheet
function setDataToTable() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Jenkins');
var cell = sheet.getRange("A1");
var rows = [['buildNumber','duration'],['','']]; // I GUESS THE MISTAKE IS HERE?
sheet.getRange(cell.getRow(), cell.getColumn(), rows.length, rows[0].length).setValues(rows);
}
Actual result:
Log shows retrieved array with Builds objects, i.e.:
[19-10-10 16:18:16:937 AEDT] [{number=2081, subBuilds=[{jobName=...
'Jenkins' spreadsheet is empty.
Expected result:
Store "builds.subBuilds.buildNumber" and "builds.subBuilds.duration" values
in the Google Sheet ('Jenkins' spreadsheet), i.e.:
buildNumber duration
123 15sec
456 16sec
... ...
I was able to make it working in the next way:
function getJenkinsBuilds()
{
// get jenkins builds
var response = UrlFetchApp.fetch('http://jenkins.[domain].co/job/Build+Deploy/api/json', {
'method': 'get',
'muteHttpExceptions' : true,
'headers' : {'Authorization' : 'Basic [token]'}
});
// parse the json reply
var data = JSON.parse(response);
var builds = data["builds"];
var number = data['builds'][0]['number'];
var url = data['builds'][0]['url'];
Logger.log(number);
Logger.log(url);
// fill in the spreadsheet with data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Jenkins');
var cell = sheet.getRange('A1');
var rows = [['BUILD']];
for (var i = 0; i < builds.length; i++)
{
var number = data['builds'][i]['number'];
var url = data['builds'][i]['url'];
rows.push(['=HYPERLINK("'+url+'","'+number+'")']);
Logger.log(number);
Logger.log(url);
sheet.getRange(cell.getRow(), cell.getColumn(), rows.length, rows[0].length).setValues(rows);
}
};
In Google BigQuery WebUI, it shows query result screen after executing a query, and it shows the button of "Save as Google Sheets". I like this feature but would like to automate this, is there such function through the REST API that I could do?
It doesn’t seem like there is a straightforward way to do this directly with the BigQuery API. There are few workarounds for this though:
You can use the BigQuery API to query your data and then the GoogleSheets API to upload it to Google Sheets.
You can use Google Apps Script. If you go to this link, you click on “New Script”, you can run the code below. You can adapt this to your needs. You can also add a trigger to run the script every hour/minute …
Here the code snippet from this link:
function runQuery() {
// Replace this value with the project ID listed in the Google
// Cloud Platform project.
var projectId = 'XXXXXXXX';
var request = {
query: 'SELECT TOP(word, 300) AS word, COUNT(*) AS word_count ' +
'FROM publicdata:samples.shakespeare WHERE LENGTH(word) > 10;'
};
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
// Check on status of the Query Job.
var sleepTimeMs = 500;
while (!queryResults.jobComplete) {
Utilities.sleep(sleepTimeMs);
sleepTimeMs *= 2;
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId);
}
// Get all the rows of results.
var rows = queryResults.rows;
while (queryResults.pageToken) {
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId, {
pageToken: queryResults.pageToken
});
rows = rows.concat(queryResults.rows);
}
if (rows) {
var spreadsheet = SpreadsheetApp.create('BiqQuery Results');
var sheet = spreadsheet.getActiveSheet();
// Append the headers.
var headers = queryResults.schema.fields.map(function(field) {
return field.name;
});
sheet.appendRow(headers);
// Append the results.
var data = new Array(rows.length);
for (var i = 0; i < rows.length; i++) {
var cols = rows[i].f;
data[i] = new Array(cols.length);
for (var j = 0; j < cols.length; j++) {
data[i][j] = cols[j].v;
}
}
sheet.getRange(2, 1, rows.length, headers.length).setValues(data);
Logger.log('Results spreadsheet created: %s',
spreadsheet.getUrl());
} else {
Logger.log('No rows returned.');
}
}
I'm trying to save all of the sheets on my spreadsheet to google drive as one PDF (ultimately I would like to have them email as well). I'm having trouble saving more than just one of the sheets. I've tried multiple way of doing it. The code below is the best way I've found so far. Again the problem is that it only saves the first page as a PDF, I cant figure out how to get around the delete redundant sheets. All the posts I have seen only want to save 1 page, I have over 24 pages that need to be saved as one PDF. Thanks in advance for your help!
function PDF() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet();
var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
var ss = SpreadsheetApp.openByUrl(
'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***');
var pdfName = "MAR - " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var folder = DriveApp.getFolderById(folderID);
//Copy whole spreadsheet
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))
//delete redundant sheets
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
var destSheet = destSpreadsheet.getSheets()[0];
//repace cell values with text (to avoid broken references)
var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);
//save to pdf
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
var newFile = folder.createFile(theBlob);
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
By using Drive API, you can convert from a spreadsheet to a PDF which has all sheets in the spreadsheet. In order to use this, so please enable Drive API on Google API Console as follows.
In the script editor, select Resources > Cloud Platform Project
At the bottom of the dialog, click the link for the Google API Console.
In the console, click into the filter box and type part of the name of the API "Drive API", then click the name once you see it.
On the next screen, click Enable API.
Close the Developers Console and return to the script editor. Click OK in the dialog.
I prepared a sample script for creating PDF file from spreadsheet. Please use this to your script.
Script :
var spreadsheetId = "#####";
var folderId = "#####";
var outputFilename = "#####";
var url = "https://www.googleapis.com/drive/v3/files/" + spreadsheetId + "/export?mimeType=application/pdf";
var options = {
method: "GET",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options).getBlob();
DriveApp.getFolderById(folderId).createFile(response).setName(outputFilename);
About this script, although I confirmed this works fine, if it doesn't work at your environment, please tell me. And if I misunderstand your question, I'm sorry.
Added 1 :
function PDF() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet();
var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
var ss = SpreadsheetApp.openByUrl(
'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***');
var pdfName = "MAR - " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var folder = DriveApp.getFolderById(folderID);
//Copy whole spreadsheet
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))
//delete redundant sheets
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
var destSheet = destSpreadsheet.getSheets()[0];
//repace cell values with text (to avoid broken references)
var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);
//save to pdf
// var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
// var newFile = folder.createFile(theBlob);
// A sample script was added here.
var url = "https://www.googleapis.com/drive/v3/files/" + destSpreadsheet.getId() + "/export?mimeType=application/pdf";
var options = {
method: "GET",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options).getBlob();
DriveApp.getFolderById(folderID).createFile(response).setName(pdfName);
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
Added 2 :
function PDF() {
var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
var ss = SpreadsheetApp.openByUrl(
'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***');
var pdfName = "MAR - " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
var sourceSpreadsheet = SpreadsheetApp.getActive();
var folder = DriveApp.getFolderById(folderID);
// A sample script was added here.
var url = "https://www.googleapis.com/drive/v3/files/" + sourceSpreadsheet.getId() + "/export?mimeType=application/pdf";
var options = {
method: "GET",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options).getBlob();
DriveApp.getFolderById(folderID).createFile(response).setName(pdfName);
}
Here is the function that creates PDF file from google sheet and function that moves new created file into the folder that id you give to the parameter of the function.
function downloadPDF(fileId, folderId) {
var file = Drive.Files.get(fileId);
var url = file.exportLinks[MimeType.PDF];
var options = {
headers: {
Authorization:"Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions : true
}
var response = UrlFetchApp.fetch(url, options);
var status = response.getResponseCode();
var result = response.getContentText();
if (status != 200) {
// Get additional error message info, depending on format
if (result.toUpperCase().indexOf("<HTML") !== -1) {
var message = strip_tags(result);
}
else if (result.indexOf('errors') != -1) {
message = JSON.parse(result).error.message;
}
throw new Error('Error (' + status + ") " + message );
}
var doc = response.getBlob();
var newFileid = DriveApp.createFile(doc).setName(file.title + '.pdf').getId();
let id = moveFileTo(newFileid, folderId);
return id;
}
function moveFileTo(sourceId, folderId){
let file = DriveApp.getFileById(sourceId)
let blob = file.getBlob();
let id = DriveApp.getFolderById(folderId).createFile(blob).getId();
file.setTrashed(true)
return id;
}
I am trying to connect with my shopify shop through the google javascrip. The schema for authentication should be something similar to the one you can find on google documentation for twitter. I'am trying the following code, but I always get the error:{"errors":"[API] Invalid API key or access token (unrecognized login or wrong password)"}
function getInfofromshopify() {
var handle = "01-02-0316_cmt_utensili"
var urljson ="https://mysitename.myshopify.com/admin/products.json?handle="+handle;
var oAuthConfig = UrlFetchApp.addOAuthService("shopify");
oAuthConfig.setAccessTokenUrl("https://mysitename.myshopify.com/admin/oauth/access_token");
oAuthConfig.setRequestTokenUrl("https://mysitename.myshopify.com/admin/oauth/access_token");
oAuthConfig.setAuthorizationUrl("https://mysitename.myshopify.com/admin/oauth/authorize");
oAuthConfig.setConsumerKey(API_KEY);
oAuthConfig.setConsumerSecret(Shared_secret);
var options =
{
"oAuthServiceName" : "shopify",
"oAuthUseToken" : "always"
};
var response = UrlFetchApp.fetch(urljson,options);
var responsestr = response.getContentText();
var result = Utilities.jsonParse(responsestr)
}
This worked for me:
var url = "https://<YOUR_SHOP>.myshopify.com/admin/products.json";
var username = "<YOUR_SHOPIFY_API_KEY>";
var password = "<YOUR_SHOPIFY_API_PASSWORD>";
var response = UrlFetchApp.fetch(url, {"method":"get", "headers": {"Authorization": "Basic " + Utilities.base64Encode(username + ":" + password)}});