twilio get message details (method not allowed ) - javascript

url = 'https://api.twilio.com/2010-04-01/Accounts/'+ACCOUNT_SID+'/SMS/Messages/'+Sid+'.json';
var payLoadData = {
'SMSMessageSid' : Sid
};
var options =
{
method : "GET",
payload : payLoadData,
headers : {
'Authorization' : 'Basic ' + Utilities.base64Encode(ACCOUNT_SID + ':' + ACCOUNT_TOKEN)
}
};
var response = UrlFetchApp.fetch(url, options);
Why by using this google_script gives a Method_Not_Allowed
Request failed for https://api.twilio.com/2010-04-01/Accounts/XXXXXXXXXXXXX/SMS/Messages/XXXXXXXXXXXXXXXXXXXXX.json returned code 405. Server response: {"status":405,"message":"Method not allowed","code":20004,"more_info":"http:\/\/www.twilio.com\/docs\/errors\/20004"} (line 374, file "MakePhoneCall")
As we can see, https://www.twilio.com/user/account/developer-tools/api-explorer#GET/2010-04-01/Accounts/[AccountSid]/SMS/Messages/[SMSMessageSid].[format]
it's constructed according to this api ref

It seems that payload shouldn't be used while using GET method, hence using params would do the trick.
Still, the same method works when getting details of call, but not with message, interesting :)

Related

Asana Events API always returning invalid sync token in Apps Script

I am trying to call the Asana Events API - https://developers.asana.com/reference/getevents
This endpoint uses a 'Sync' token to track when you last called it, each call returns a new sync token which can then be stored and used for the next call to only retrieve events since the last call.
If you do not provide a sync token the API will return an 'invalid token' response and give you a new token to get started with.
However, I cannot seem to get it beyond the initial 'invalid token' call, when I used the token in the following call it still returns 'invalid token'
This is using Google's Apps Script, which is basically just JavaScript with some built-in Google functions
Here is my code:
This function makes a call without the ‘sync’ parameter, uses muteHttpExceptions to get the full response text, and sets the sync token as a property in Apps Script (just a key/value pair)
var asanaBaseUrl = 'https://app.asana.com/api/1.0'
function getSyncToken() {
var url = asanaBaseUrl + '/projects/' + asanaProject + '/events'
var headers = {
'Authorization': 'Bearer ' + asanaPAT
}
var options = {
'method': 'GET',
'headers': headers,
'muteHttpExceptions': true
}
var r = UrlFetchApp.fetch(url, options)
var data = JSON.parse(r.getContentText())
var newSyncToken = data.sync
userProps.setProperty('syncToken', newSyncToken)
}
This function uses the properties service to pull the sync token set in the previous call and makes a new call with the sync parameter
function asanaEventCall() {
var url = asanaBaseUrl + '/projects/' + asanaProject + '/events'
var syncToken = userProps.getProperty('syncToken')
var headers = {
'Authorization': 'Bearer ' + asanaPAT
}
var options = {
'method': 'GET',
'headers': headers,
'sync': syncToken,
'muteHttpExceptions': true
}
var r = UrlFetchApp.fetch(url, options)
var data = JSON.parse(r.getContentText())
return data
}
The second function always returns the following
{sync=[SYNC TOKEN HERE], errors=[{message=Sync token invalid or too old. If you are attempting to keep resources in sync, you must fetch the full dataset for this query now and use the new sync token for the next sync.}]}
I’ve confirmed that the token is being set, retrieved, and sent correctly using the logs.
I’ve confirmed the flow above works by manually using the URL, like this:
Go to https://app.asana.com/api/1.0/projects/[PROJECT GID]/events
Copy sync token
Go to https://app.asana.com/api/1.0/projects/[PROJECT GID]/events?sync=[SYNC TOKEN]
Events show properly
I've looked for other answers but haven't found anything specific that helped, and I asked on the Asana forum but haven't got an answer in a few days.
I'm sure I'm missing something painfully obvious here but just can't see it!
From Go to https://app.asana.com/api/1.0/projects/[PROJECT GID]/events?sync=[SYNC TOKEN] of I’ve confirmed the flow above works by manually using the URL, like this:, in your script, it seems that it is required to add 'sync': syncToken, as the query parameter. So, how about modifying your asanaEventCall() as follows?
Modified script:
function asanaEventCall() {
var syncToken = userProps.getProperty('syncToken')
var url = asanaBaseUrl + '/projects/' + asanaProject + '/events' + '?sync=' + syncToken;
var headers = {
'Authorization': 'Bearer ' + asanaPAT
}
var options = {
'method': 'GET',
'headers': headers,
'muteHttpExceptions': true
}
var r = UrlFetchApp.fetch(url, options)
var data = JSON.parse(r.getContentText())
return data
}
Note:
In this modification, it supposes that your values of asanaProject, asanaPAT and syncToken are valid values. Please be careful about this.

How to post an image to facebook page using Google App Script's facebook snippet?

I am trying to setup a small application based on Google App Script and Google sheets
So far I am able to get the facebook page feed and able to connect to facebook app through Oauth2 library and got the tokens
So I am struggling to write the code for posting to facebook ,
Currently I got the facebook page feeds but the post format documentation from facebook is referring to javascript SDK , and here I am not using SDK and graph API refers with POST and GET requests I think that also didn't work here .
So this is my Codes for getting facebook token and page feed .
Some one referred this as a duplicate but those question and answer doesn't fit in my question , I want facebook post format if it is with payload kindly include those payload options or someone can edit below code for POST
I am able to post to pages with the page access token not user access token
and pasting that page access token also throws the same error .
Updated Code But error appears as follows
Request failed for https://graph.facebook.com/v3.2/PAGE/feed?message=hello?access_token=TOKEN returned code 403. Truncated server response: {"error":{"message":"(#200) If posting to a group, requires app being installed in the group, and \\n either publish_to_groups permission... (use muteHttpExceptions option to examine full response) (line 53, file "FB postinf")
code updated
function example() {
var service = getService();
if (service.hasAccess())
var data = {
"message" : "Me Testing",
//"slug" : "me-testing",
// "text_to_subscribe" : "true"
};
var payload = JSON.stringify(data);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
var url = "https://graph.facebook.com/v3.2/PAGENAME/feed?message=hello?access_token=ManuallyPastedTOKEN";
// + '?access_token=' + encodeURIComponent(service.getAccessToken());
var response = UrlFetchApp.fetch(url, options);
}
This is using OAuth2 GET FEED
function sasublish(){
var service= getService()
if (service.hasAccess()) {
var url = 'https://graph.facebook.com'
+ '/pagename/feed'
+'?fields='+ encodeURIComponent("name,full_picture,message,attachments{subattachments,url}")
+'&access_token='+ service.getAccessToken();
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var jsondata = JSON.parse(json);
}
Need oAuth2 And Facebook.gs snippet you can use
.setScope('publish_pages,manage_pages,pages_show_list')
should be added to facebook.gs link to facebook.gs snippet
function example() {
var service = getService();
if (service.hasAccess())
var urls ='https://graph.facebook.com/v2.6/PAGEID?fields=access_token'; //specified page token
// var url = 'https://graph.facebook.com/v2.6/me/accounts?'; //tokens along with pages
var response = UrlFetchApp.fetch(urls, { //make url and urls changes
headers: {
'Authorization': 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result , null, 2));
//Logger.log(JSON.stringify(result.data[0].access_token))
var datas = {
"message" : "Me Testing",
//"slug" : "me-testing",
// "text_to_subscribe" : "true"
};
var payload = JSON.stringify(datas);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
var url = "https://graph.facebook.com/v3.2/PAGEID/feed"
+ '?access_token=' + encodeURIComponent(result.data[0].access_token);
// + '?access_token=' + encodeURIComponent(result.access_token);//direct pagetoken
var response = UrlFetchApp.fetch(url, options);
Logger.log('successfully posted to facebook page ',response)
}

Connecting to Bitfinex API from Google Sheets

I'm trying to connect my google sheet to Bitfinex through the 'authenticated' section of the API so I can access my account information. Here is the API link.
I haven't been able to get the 'request' or 'crypto' libraries to work so I've been trying to use other available functions in google sheets, but am having trouble.
Following is the code snippet I'm using:
var completeURL = "https://api.bitfinex.com/v1/account_infos";
var nonce = Math.floor(new Date().getTime()/1000);
var body = {
'request' : completeURL,
'nonce' : nonce
};
var payload = JSON.stringify(body).toString('base64');
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_384,
payload,
secret);
signature = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
var params = {
headers: {
'X-BFX-APIKEY': key,
'X-BFX-PAYLOAD': payload,
'X-BFX-SIGNATURE': signature
},
}
Logger.log(completeURL);
Logger.log(params);
var response = UrlFetchApp.fetch(completeURL, params);
var json = JSON.parse(response.getContentText());
I get the following error from the API:
Request failed for https://api.bitfinex.com/v1/account_infos returned code 400. Truncated server response: {"message":"Invalid json."} (use muteHttpExceptions option to examine full response). (line 209, file "Code")
And the following are the values from the Logger.log calls:
[17-09-24 16:22:28:170 AEST] https://api.bitfinex.com/v1/account_infos
[17-09-24 16:22:28:171 AEST] {headers={X-BFX-PAYLOAD={"request":"https://api.bitfinex.com/v1/account_infos","nonce":1506234148}, X-BFX-SIGNATURE=06d88a85098aefbf2b56af53721506863978f9350b1b18386c23f446254789dbbfc1eeb520bdfc7761b30f98ea0c21a2, X-BFX-APIKEY=ak6UoPiwaLjwt2UqDzZzZGjpb9P2opvdPCAIqLy0eVq}}
I'm stuck and not sure what else to try?
Can anyone spot what I'm doing wrong?
How about this modification? Since I have no secret, I couldn't debug this sample. So I don't know whether this modified sample works. I'm sorry.
Modification points :
secret is not defined.
When POST method is used, it requires to include method: "post" to UrlFetchApp.fetch().
When it reads Javascript sample of the document, signature has to be modified.
When it reads Javascript sample of the document, body: JSON.stringify(body) is included in the request parameters.
There is an error message of {"message":"Invalid json."}.
The script which was reflected above modifications is as follows.
Modified script :
var secret = "#####"; // Please input this.
var completeURL = "https://api.bitfinex.com/v1/account_infos";
var nonce = Math.floor(new Date().getTime()/1000);
var body = {
'request' : completeURL, // I don't know whether this is the correct value.
'nonce' : nonce
};
var payload = Utilities.base64Encode(Utilities.newBlob(JSON.stringify(body)).getDataAsString());
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_384, payload, secret);
signature = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
var params = {
method: "post",
headers: {
'X-BFX-APIKEY': key,
'X-BFX-PAYLOAD': payload,
'X-BFX-SIGNATURE': signature
},
payload: JSON.stringify(body),
contentType: "application/json",
muteHttpExceptions: true
}
var response = UrlFetchApp.fetch(completeURL, params);
var json = JSON.parse(response.getContentText());
If this was not useful for you, I'm sorry.
I am not sure if I am understanding your code, but if I do, there is at least one oddity at first sight:
In computeHmacSignature(...), you are using the variable secret which has not been initialized or even declared anywhere.
That's how it works
var body = {
'request' : "/v1/balances",
'nonce' : nonce,
'options':{}
};

Google Script GET request issue

I'm trying to get a Google script (on a Google Sheet) to retrieve data from Float API. The endpoint and key are fine (tested and all works as expected on Postman) but it keeps returning 401.
Below is my code:
var API_KEY = "{ENTER YOUR KEY HERE}";
var ENDPOINT_PROJECTS = "https://api.float.com/api/v1/projects";
function getProjects() {
var headers = {
"Authorization" : "Bearer " + API_KEY,
};
var requestData = {
"method" : "GET",
"headers": headers,
"muteHttpExceptions": false
};
// Get the data
var fetchResponse = UrlFetchApp.fetch(ENDPOINT_PROJECTS);
var responseCode = fetchResponse.getResponseCode();
if (responseCode == "200") {
var result = JSON.parse(fetchResponse.getContentText());
} else {
ui.alert("Error when attempting to fetch the list of spaces.");
}
}
Okay looked like I completely missed a small yet very important part...even though I created an object to hold the method and headers I was not passing this into the actual fetch!!! (This is what happens when you attempt to do a quick script at the end of the day)
So instead of this
var fetchResponse = UrlFetchApp.fetch(ENDPOINT_PROJECTS);
we have this:
var fetchResponse = UrlFetchApp.fetch(ENDPOINT_PROJECTS, requestData);

Accessing Highrise Data through API using GAS

As the title says, I am having issues accessing data in Highrise through their API using Google Script. I am new to google script, so some of the functions are not entirely clear to me. I understand that for the actual use of the API, I will be using UrlFetchApp.fetch(url) and that the url I will be using is foocompanyname.highrisehq.com/partofhighriseyouwishtoaccess.xml. From there I am lost however. The API documentation explains the process of authentication using curl (something I have never used before) and I cannot think of analogous functions in Google Script to accomplish this.
Here is the curl example they use to simply gain access
curl -u 605b32dd:X https://example.highrisehq.com/people/1.xml
And here is part of the function I am using that is trying to accomplish the same thing. The whole function is designed to obtain all of the notes from the companies visible to the user whose credentials are being used.
function obtainData(){
//enter subject-id of admin
// |
// V
var userid = "123456789"
var payload =
{
"action" : "/companies.xml"
};
var options =
{
"headers" : { "USER-AGENT" : "name#company.com",
"Authorization" : "Basic" + Utilities.base64Encode( "APIkey_from_Highrise_website" + ":" + "Dummy_password" )
},
"method" : "GET",
"payload" : payload,
muteHttpExceptions : true
};
var xmlCompanies = UrlFetchApp.fetch("https://foocompany.highrisehq.com/companies.xml", options).getContentText();
Logger.log(xmlCompanies);
However, when I run this I receive the error "[HTTP Basic: Access denied.
]" which I assume means that I have not passed on the credentials correctly. Could anyone perhaps tell me what I am doing wrong? After this step I am fairly confident about getting the data, it's the authorization that is getting me.
Try this, note the space after "Basic"
function obtainData(){
//enter subject-id of admin
// |
// V
var userid = "123456789"
var payload =
{
"action" : "/companies.xml"
};
var options =
{
"headers" : { "USER-AGENT" : "name#company.com",
"Authorization" : "Basic " + Utilities.base64Encode( "APIkey_from_Highrise_website" + ":" + "Dummy_password" )
},
"method" : "GET",
"payload" : payload,
muteHttpExceptions : true
};
var xmlCompanies = UrlFetchApp.fetch("https://foocompany.highrisehq.com/companies.xml", options).getContentText();
Logger.log(xmlCompanies);

Categories

Resources