Using Linkedin API with google apps script? - google-apps-script

aloha all,
Im create a integration with linkedin and google apps script, for post in company page.
All is good, in terms of oauth2, i have the tokens, but the problem is the body request, look:
var payload = {"visibility": {"code": "anyone"},"comment": "Testing a full company share!","content": {"submitted-­url": "https://www.google.com","title": "Test Share with Content","description": "content description","submitted‐image-­url": "https://www.wired.com/wp-content/uploads/2015/09/google-logo.jpg"}};
var headers = {Authorization': 'Bearer ' + Service.getAccessToken()};
var options = {method:'post',headers:headers,payload:payload,muteHttpExceptions:true};
var response = UrlFetchApp.fetch("https://api.linkedin.com/v1/companies/2414183/shares?format=json", options);
THE REQUES IS GOOD, BECAUSE I USE APIGEE FOR TEST MY JSON REQUEST. THIS IS THE RESPONSE OF THE SERVER:
[16-12-12 22:38:13:411 EST] {
"errorCode": 0,
"message": "Couldn't parse share document: error: Unexpected element: CDATA",
"requestId": "XNZ80U0LCX",
"status": 400,
"timestamp": 1481600293335
}
IN SEVERAL FORUMS SAY THAT THE HEARDER I SHOUD PUT:
'Content-Type': 'application/json', 'x-li-format': 'json'
BUT WHEN PUT THIS CODE ON HEADER THE ERROR OF SERVER IS:
[16-12-12 22:40:00:344 EST] {
"errorCode": 0,
"message": "Couldn't parse Json body: Unexpected character ('v' (code 118)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: java.io.StringReader#c3576e8; line: 1, column: 2]",
"requestId": "YQFPJKZTMC",
"status": 400,
"timestamp": 1481600400231
}
THANKS ALL

For payload you need to provide valid JSON e.g.:
var payload = JSON.stringify(object):
Not:
var payload = object;
I'd also add the content type to the headers, setting it to application/json:
var options = {
'contentType': 'application/json',
'payload': JSON.stringify(payload)
};
UrlFetchApp.fetch('https://www.example.com', options);

One change... Per the Linkedin developer docs:
If you opt to provide a JSON-formatted body, make sure your HTTP request includes the following headers:
Content-Type: application/json
x-li-format: json
https://developer.linkedin.com/docs/share-on-linkedin

Related

Google apps script function error with POST request

I have a site on webflow and I need to add elements to it by taking them from a google sheet, reading the webflow documentation (you can read it here) it is possible to add elements with a POST request by passing it the correct token and json.
I need to make this request via the app script from the google sheet where the data is, but I keep getting an error saying that the "fields" field is required, a field I pass it though.
I tried the token in a GET request, via the same sheet, and it works, and the json (and the token too) via postman, and that works too
This is the code in the script
var teamData = {
"fields": {
"name": "test",
"slug": "test",
"category": "WOMEN",
"nationality-iso-code": "Italy",
"payment-status": "Confirmed",
"_archived": "false",
"_draft": "false"
}
}
var options = {
'method': 'POST',
'muteHttpExceptions': true,
'headers': {
'accept': 'application/json',
'content-type': 'application/json',
'authorization':'Bearer ' + API_TOKEN
},
'body' : JSON.stringify(teamData)
};
var response = UrlFetchApp.fetch(URL, options);
I have the same problem if I try to make an update with a PUT request, via postman it works, via google script no
Of course, I defined API_TOKEN and URL as constants, and they are correct

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)

How to get Log with Stackdriver Logging API

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);
}

Slack API call to postMessage not working

I'm just trying to make a simple postMessage call from a google apps script with an image attached, but I get the following response:
"{"ok":false,"error":"invalid_arg_name"}"
Here is the function that creates the payload:
function getPostMessagePayload(fileUrl) {
var content = {
"channel":"#data-vis",
"token": ACCESS_TOKEN,
"text":"Chart update:",
"attachments": [
{
"title": "Chart",
"fallback": "Fallback",
"text": "Testing chart",
"image_url": fileUrl
}
]
};
return content;
}
And here is where I make the request:
var POST_MESSAGE_ENDPOINT = 'https://slack.com/api/chat.postMessage';
function performPostMessage(payload) {
var res = UrlFetchApp.fetch(
POST_MESSAGE_ENDPOINT,
{
method: "post",
payload: JSON.stringify(payload),
muteHttpExceptions: true,
}).getContentText();
return res;
}
It's impossible to tell what the actual problem is. I've tried making my token obviously incorrect, the URL obviously incorrect, and deleting/adding random args and it gives the same response every time.
When I use the webhook to do this rather than the API, it works fine.
My app has the following permissions in Slack:
chat:write:bot
incoming-webhook
Problem
You are sending a JSON object as payload with your POST request, whilst the contentType parameter of the fetch() method is defaulted to application/x-www-form-urlencoded.
Solution 1
In addition to JSON.stringify(), to ensure the payload is sent correctly, wrap it in an encodeURIComponent() built-in function. If the issue persists, continue to solution 2.
Update to solution 1
Nearly forgot how fetch() method treats objects passed to payload with default x-www-form-urlencoded content type. Remove the JSON.stringify() entirely (and add encodeURI() / encodeURIComponent() if needed).
Solution 2
Slack API supports application/json content type of POST requests. In your case it might be easier to send the request with contentType parameter set to application.json (note that you will have to move authorization from payload to headers):
//fetch part;
var res = UrlFetchApp.fetch(
POST_MESSAGE_ENDPOINT,
{
method : 'post',
contentType : 'application/json',
headers : {
Authorization : 'Bearer ' + ACCESS_TOKEN
},
payload : JSON.stringify(payload),
muteHttpExceptions : true,
})
//payload part;
var payload = {
"channel" : "#data-vis",
"text" : "Chart update:",
"attachments" : [
{
"title" : "Chart",
"fallback" : "Fallback",
"text" : "Testing chart",
"image_url" : fileUrl
}
]
};
Useful links
fetch() method reference;
postMessage method reference (Slack API);

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