How to get Log with Stackdriver Logging API - google-apps-script

I'm developing a chatbot using Dialogflow and I need to get full conversation log from it.
I checked this page and I guessed it is able to achieve it by using Stackdriver Logging api.
I referred below page and I tried, however using this api, it occurs 403 error.
https://cloud.google.com/logging/docs/reference/v2/rest/v2/logs/list
Did I use this in a wrong way?
How can I resolve this problem?
This is the error message.
{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"status": "PERMISSION_DENIED"
}
}
This is my code where calling the api.
I used Google Apps Script.
function getLogs() {
//XXXXXXXX is my project_id
var output = UrlFetchApp.fetch('https://logging.googleapis.com/v2/projects/XXXXXXXX/logs');
Logger.log(output)
}

I've resolved this way.
Add my api key to http request.
var options = {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}};
var logs = UrlFetchApp.fetch("https://logging.googleapis.com/v2/projects/XXXXXXXX/logs?key=my_api_key", options)
Add scope to appscript.json.
"oauthScopes": ["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/script.external_request"]
Then I found logs.list methond is not appropriate for my goal so I need to change to v2.entries method.
function getLogs(){
var options = {
method: "post",
contentType: "application/json",
headers: {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()},
payload: JSON.stringify({
resourceNames: ['projects/XXXXXXX'],
filter: "timestamp >= searchdate",
orderBy: "timestamp desc",
pageSize: 1,
}),
}
var logs = UrlFetchApp.fetch("https://logging.googleapis.com/v2/entries:list?key=my_api_key", options);
Logger.log(logs);
}

Related

create an invoice stripe using google app script

Hi I followed this documentation regarding on creating an invoice on stripe
it says here that The ID of the customer who will be billed.
so I created a test customer manually on stripe and now I tried this code
function testDataInvoices()
{
var url = "https://api.stripe.com/v1/invoices";
var params = {
method: "post",
headers: {Authorization: "Basic " + Utilities.base64Encode("sk_testXXXXX:")},
payload:
{
customer: "cus_JLKM93Pc6j2mxB",
}
};
var res = UrlFetchApp.fetch(url, params);
Logger.log(res.getContentText())
}
but I am getting this error
Exception: Request failed for https://api.stripe.com returned code 400. Truncated server response: {
"error": {
"code": "invoice_no_customer_line_items",
Can someone please enlighten me about this stripe I really just new to this API and their API is just only for node.js
#TRIED
I tried following this link
and change my code to this
function testDataInvoices()
{
var url = "https://api.stripe.com/v1/invoices";
var params = {
method: "post",
headers: {Authorization: "Basic " + Utilities.base64Encode("sk_test_XXXXXX:")},
payload:
{
"email": "paul.kevin#senren.page",
"payment_settings": 'pm_1FWS6ZClCIKljWvsVCvkdyWg',
"invoice_settings[default_payment_method]":'pm_1FWS6ZClCIKljWvsVCvkdyWg'
}
};
var res = UrlFetchApp.fetch(url, params);
Logger.log(res.getContentText())
}
and got this error
A few things:
I'm not familiar with Google App Scripts — are you sure it's safe to store a secret key in such a script and you don't need an actual backend server instead? That key has to be kept private since it can be used to do anything on your Stripe account.
In the first case, you get an error because to issue an Invoice, you have to first call /v1/invoiceitems to add some items to the customer. Then when you call /v1/invoices, which will pull those in to charge for them: https://stripe.com/docs/invoicing/integration#create-invoice-code
in the second case you get an error because those are not valid parameters for that endpoint(if you check the link you posted, those parameters are for /v1/customers, not /v1/invoices).
I'd suggest following https://stripe.com/docs/invoicing/integration .

Authentication error when attempting to fetch google analytics 4 with app script

I would like to connect a community connector to a google analytics 4 account so that I can easily modify the data and send it to data studio. However, My code is returning an authentication error:
{ error:
{ code: 401,
message: 'Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.',
status: 'UNAUTHENTICATED' } }
I have included the token, but I am unsure if I am making the correct url call or if there is some other issue that I am unaware of. I don't believe I need an API key to connect from community connector to a google API, but I may be wrong. I did create an API key but the result was the same.
function testFetch(){
var url = "https://analyticsdata.googleapis.com/v1alpha:runReport"
var token = ScriptApp.getOAuthToken();
var options = {
"method" : 'POST',
"entity": { "propertyId": "263290444" },
"dateRanges": [{ "startDate": "2020-12-01", "endDate": "2021-03-01" }],
"dimensions": [{ "name": "country" }],
"metrics": [{ "name": "activeUsers" }],
'muteHttpExceptions': true,
headers: {
Authorization: 'Bearer' + token,
},
};
var response = UrlFetchApp.fetch(url, options);
var result = JSON.parse(response.getContentText());
}
Here is a small guide on how to do what you are trying to achieve:
Set explicit OAuth scopes (see documentation) to your Apps Script project manifest (appsscript.json). In this case you need to add the following:
{
...
"oauthScopes": [
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/analytics.readonly"
}
}
Then you need to separate the method parameters from the fetch options. The fetch options need to be stringified and added to payload. You also need to set the contentType to JSON.
const options = {
entry: { propertyId: "263290444"},
// etc.
}
const response = UrlFetchApp.fetch(
'https://analyticsdata.googleapis.com/v1alpha:runReport',
{
method: 'POST',
muteHttpExceptions: true,
headers: {
'Authorization': `Bearer ${ScriptApp.getOAuthToken()}`
},
contentType: 'application/json; charset=utf-8',
payload: JSON.stringify(options)
}
)
After that, you may use the response as you were doing before.
Note that Bearer and the token need to be separated by a space, which your code does not have. It's hard to see because of the concatenation and that why I usually use template literals (see documentation).
References
Authorization scopes | Set explicit scopes (Google Apps Script Guides)
UrlFetchApp.fetch(url, params) (Google Apps Script Reference)
Template literals (MDN)

Trying to alter 'createdTime' in google docs with Google Apps Script. Getting Error 403 ..."field not writable". Any workaround?

Full error message:
Request failed for https://www.googleapis.com returned code 403. Truncated server response: { "error": { "errors": [ { "domain": "global", "reason": "fieldNotWritable", "message": "The resource body includes fields which ... (use muteHttpExceptions option to examine full response). (line 13, file "Code")
The code below worked with 'viewedByMeTime' & 'modifiedTime'
function myFunction() {
var newModifiedTime = "2019-01-01T00:00:00.000Z";
var fileId = "1LaKH-wsjgGrCyG6zpbyzsBgsgTah2jQRIIDvDKaaRio";
var url = "https://www.googleapis.com/drive/v3/files/" + fileId;
var params = {
method: "patch",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},//Last time opend by you
payload: JSON.stringify({createdTime: newModifiedTime}),
contentType: "application/json",
};
UrlFetchApp.fetch(url, params);
You appear to be trying to do a file.update
"fieldNotWritable"
means exactly that not all of the fields can be writen to. which means you cant update every fields. and create time is one of the fields that you cant update. if you check the documentation under request body you will see the fields you are allowed to update.

Apps Script API returning 404 error for existing project. Error returned as HTML rather than JSON

I was attempting to run an Apps Script function using the Apps Script API. I set up the script in the console, and created an oauth client ID for the script. I configured the authorisation screen and deployed the script as API executable. I tested the api function calling in the same script but got a 404 error saying:
The Requested URL /v1/scripts/{{my_script_id}}:run was not found on this server.
The response came back as HTML. I also noticed that the script seems to make it's own client ID when it's called from the API.
I tried disabling and re-enabling the API which didn't work. I think it may be a problem with the calling application not being in the same project but I'm not sure how to do that as the Google documentation is unclear.
function trigger(){
var bogus = DriveApp.getRootFolder();
var argument = ["Value0", "Value1", "Value2", "Value3", "Value4", "Value5"];
// https://www.googleapis.com/auth/script.external_request
// https://www.googleapis.com/auth/spreadsheets
var postRequest = {
"Content-Type": "application/json",
"headers": { "Authorization" : "Bearer " + ScriptApp.getOAuthToken()},
"function": "setStatus",
"muteHttpExceptions": true,
"parameters": [argument],
"devMode": false
};
try{
var response = UrlFetchApp.fetch("https://script.googleapis.com/v1/scripts/{{my_script_id}}:run", postRequest);
Logger.log(response);
}catch(err){
Logger.log(err);
}
}
I expected some form of error in the form of JSON or maybe even for the function to run, what I got was a HTML document which displayed a 404 error when displayed.
You're not POSTing the request. Default .fetch method is GET.
Add this in postRequest object:
method: "POST",
payload is also missing from your postRequest.
Snippet:
var postRequest = {
"method":"POST", //added
"contentType": "application/json", //key changed
"headers": { "Authorization" : "Bearer " + ScriptApp.getOAuthToken()},
"muteHttpExceptions": true,
"payload": JSON.stringify({ //added
"function": "setStatus",
"parameters": argument, //removed []
"devMode": false
})
};
References:
UrlfetchApp
Script:run

Correct syntax for Google API PATCH request using UrlFetchApp for HTTPS Request

I'm trying to use UrlFetchApp.fetch(url) method in Apps Script to PATCH a groups resource using the Google Groups Settings API.
The code below allows me to GET the groups properties, but I'm unable to figure out the syntax for a PATCH request.
function doSomething (accessToken) {
var options = {
method: "GET",
headers: {
authorization: "Bearer " + accessToken
},
};
var result = UrlFetchApp.fetch("https://www.googleapis.com/groups/v1/groups/test_group_5#student.vis.ac.at", options);
return HtmlService.createHtmlOutput (result.getContentText());
}
A PATCH request needs a Header Override. You actually need to use a PUT request, and then override it to a PATCH request.
var payload = "{\"" + PropertyOne + "\":\"" + "Proptery Value" + "\"}";
Logger.log('payload: ' + payload);
var options = {"method" : "put", "headers": {"X-HTTP-Method-Override": "PATCH"}, "payload" : payload};
if (payload.length > 2) {
UrlFetchApp.fetch("https://www.googleapis.com/groups/v1/groups/test_group_5#student.vis.ac.at", options );
};
The code above won't be exactly what you want, and might not be error free, but the structure of it should be what you need. I'm sure the payload isn't configured correctly, because I don't know what the format is. It looks like the documentation calls it Patch body with an object.
Google Documentation - Group Settings API Patch
Key words: "Apps Script", patch