Accessing Highrise Data through API using GAS - javascript

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

Related

Is there any way to change User-Agent of Apps script?

I am trying to change User-Agent. But It seems like I can't change it.
I implemented like this:
{
'User-Agent': "my spreadsheet"
}
the value above passes API function like this:
function API(m_headers, method, data){
var options = {
'headers': m_headers,
'muteHttpExceptions' : false,
'method' : method,
'payload' : data
};
var url = base_url+api;
try{
var response = UrlFetchApp.fetch(url, options)
}catch(e){
return url+"\n"+JSON.stringify(e);
}
}
And I get Attribute provided with invalid value in Google Apps Script error.
{"message":"Attribute provided with invalid value: headers","name":"Exception","fileName":"Code","lineNumber":42,"stack":"\tat Code:42 (API)\n"}
How can I solve this?
Nope. The number of supported consistent headers is strictly limited.

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':{}
};

Can't parse JSON response

I'm trying to parse the following JSON response:
{
"AgApplyTableE*!": [
{
"Index": 1,
"StringVal": "Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done. Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"
}
]
}
Here's my code:
$('#applyfailreason').click(function (){
var t = $(this);
var DeviceName = $('.DeviceName').val();
var Username = $('.Username').val();
var Password = $('.Password').val();
$.ajax({
method: 'GET',
url: 'http://' + DeviceName + '/config/AgApplyTable',
headers: {
"Authorization": "Basic " + btoa('' + Username + '' + ":" + '' + Password + '')
},
dataType: 'json',
contentType: 'application/json',
success: function(data) {
var test = JSON.stringify(data);
console.log(test);
},
statusCode: {
406 : function() {
alert('There is an unexpected string in your data.\nFix the error and try again.');
},
401 : function() {
alert('Wrong username or password.');
}
},
});
});
I get the following on the console (which is ok):
{"AgApplyTableE*!":[{"Index":1,"StringVal":"Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done. Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"}]}
But I want to print only the "StringVal" out of the JSON response.
Tried:
var test2 = JSON.stringify(data.StringVal);
console.log(test2);
Gives:
undefined
I also tried the following (with dataType: 'jsonp',):
var test4 = JSON.parse(data.StringVal);
But then Chrome sends a GET request to a strange URI (which actually gives 200OK):
config/AgApplyTable?callback=jQuery111306132095118518919_1436256387242&_=1436256387244
And I get the following error:
Uncaught SyntaxError: Unexpected token :
Any idea how to print to console only "StringVal" out of the JSON response?
Thanks.
Your response is an object containing one property named "AgApplyTableE*!", which is an array that contains one element, which is an object that contains the property "StringVal".
So you'd have to access it by data["AgApplyTableE*!"][0].StringVal.
Use console.log(data['AgApplyTableE*!'][0].StringVal)
In your response, there is no such thing as StringVal as direct suboridnate of data. The property StringVal is inside the internal object AgApplyTableE*! therefore data.StringVal is undefined.
Also, another problem I see here is that you're stringifying the response and then trying to access the property StringVal.
If you stringify, you test variable will be a string and string doesnt have a property StringVal (unless you set that in your proto)
EDIT:
Added missing [0] index.
Try
var test2 = data["AgApplyTableE*!"][0].StringVal;
console.log(test2);
test ={"AgApplyTableE*!":[{"Index":1,"StringVal":"Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done. Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"}]};
console.log(test["AgApplyTableE*!"][0]["StringVal"]);
Demo
I think that is because you have two levels here, not only one. In order to get that value out, you probably would need something like
var test2 = JSON.parse(data);
console.log(test2["AgApplyTableE*!"][0].StringVal);
Altough I'm not sure AgApplyTableE*! is a really good identifier here. Probably you can change something else, and then you can also use . notation to reach the members.

twilio get message details (method not allowed )

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 :)

Categories

Resources