404 Error on Google Sheets API from HTTP Request - google-sheets

I am trying to append some data to a Google Sheets spreadsheet using a HTML POST Request. I am having some difficulty in solving the 404 error I get when sending the request. My request code is shown below:
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == XMLHttpRequest.DONE) {
alert(httpRequest.status);
}
}
var params = {
"values": [
[
"value1",
"value2"
]
]
}
httpRequest.open('POST', 'https://sheets.googleapis.com/v4/spreadsheets/' + spreadsheetID + 'values/Sheet1!B2:L2:append', true)
httpRequest.setRequestHeader('Authorization', 'Bearer ' + accessToken);
httpRequest.setRequestHeader('Content-Type', 'application/json');
httpRequest.send(JSON.stringify(params));
I have gained the necessary permissions in the access token, since I am able to create sheets, but I think there might be an issue with my url. Thanks in advance!

From the documentation sheets.append
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{range}:append
I think you are missing a / before values
'https://sheets.googleapis.com/v4/spreadsheets/' + spreadsheetID + '/values/Sheet1!B2:L2:append', true)
Try testing it using the Try this api on the documentation page here

Related

How do I send an SMS via the Twilio API (using HTTP POST in server-side javascript ) that includes accent characters (for instance ö)?

I'm trying to send an SMS via Twilio's API using an HTTP POST request that is called via server-side javascript in salesforce marketing cloud.
I can successfully send an SMS, the only problem is that accent characters (for instance ö, ü, à, è) are being omitted. So for instance if I send an SMS that should say "Dein persönlicher Rabatt", when I received the SMS, it says "Dein persnlicher Rabatt".
Here is my server-side javascript code:
`<script type="text/javascript" runat="server">
Platform.Load("core", "1");
var accountSid = [accountSid];
var authToken = [authToken];
var auth = Base64Encode(accountSid + ":" + authToken);
var phoneDE = DataExtension.Init("[Data Extension external key]");
var numbers = phoneDE.Rows.Retrieve();
var end = numbers.length;
for (var i=0; i<end; i++) {
var config = {
endpoint: "https://api.twilio.com/2010-04-01/Accounts/[accountSid]/Messages.json",
contentType: "application/x-www-form-urlencoded",
payload : "From=[phone]&To=" + numbers[i]["Phone"] + "&Body=Your cöntract is expiring today, you can sign it here: " + numbers[i]["URL"]
};
Write("Payload" + i + ": " + config.payload + " ");
try {
var httpResult = HTTP.Post(
config.endpoint,
config.contentType,
config.payload,
["Authorization"],
["Basic " + auth]
);
var result = Platform.Function.ParseJSON(httpResult.response);
Write(httpResult.StatusCode);
Write("result" + result);
} catch(error) {
Write("Error: " + Stringify(error));
}
}
</script>`
What do I need to do to ensure that my SMS includes the accent characters and that they are not omitted?
Thank you very much for your help.
Thanks for your answer Swimburger. I didn't get a chance to try it as I found another solution. However I do appreciate your feedback, your solution was the next approach I was going to try.
My solution was to modify the contentType of the POST request to include UTF-8 as the character set:
contentType: "application/x-www-form-urlencoded;charset=UTF-8"
Unfortunately, I don't have access to a Salesforce environment to try out your code, but here's a modified version of your code using node.js.
var accountSid = process.env.TWILIO_ACCOUNT_SID;
var authToken = process.env.TWILIO_AUTH_TOKEN;
var auth = Buffer.from(`${accountSid}:${authToken}`).toString('base64');
var body = new URLSearchParams();
body.append("From", "+12345678901");
body.append("To", "+12345678901");
body.append("Body", "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹");
const request = new Request(
`https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages.json`,
{
method: 'POST',
body: body.toString(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${auth}`
}
}
);
fetch(request)
.then(response => response.json())
.then(jsonBody => console.log(jsonBody))
.catch((error) => {
console.error(error);
});
You need to configure the Twilio Account SID and Auth Token as env variables.
After that, running this script sends an SMS and the SMS contains all the characters.
I'm not sure if you are able to use these node.js APIs, but if you don't, this proves that the issue is caused by Salesforce's Server Side JavaScript APIs.
HTTP.Post probably removes the ö character.
If you do have access to node.js/npm packages, you could also use the Twilio helper library for Node.js.

Search for Twitter handles using Google Apps Script and Twitter API - doesn't work

I'm trying to find Twitter handles from a spreadsheet containing names of people.
I can't get it work with this request, which I believe is the one I should be using as I only have peoples names (e.g. Adam Smith): api.twitter.com/1.1/users/search.json?q=
I get the following error:
Request failed for api.twitter.com/1.1/users/search.json?q=Name returned code 403. Truncated server response: {"errors":[{"message":"Your credentials do not allow access to this resource","code":220}]} (use muteHttpExceptions option to examine full response) (line 38).'
I've tried searching this error but that hasn't helped me so far.
If I use, for example, this request, it works: api.twitter.com/1.1/users/show.json?screen_name=
So I can get the screen_name back in the spreadsheet, but that's pointless obviously because it needs the screen name to work in the first place...
The whole thing is based on this work, all the requests in that code work for me. It's just this search request that doesn't work. What's going wrong?
var CONSUMER_KEY = 'x';
var CONSUMER_SECRET = 'x';
function getTwitterHandles(name) {
// Encode consumer key and secret
var tokenUrl = "https://api.twitter.com/oauth2/token";
var tokenCredential = Utilities.base64EncodeWebSafe(
CONSUMER_KEY + ":" + CONSUMER_SECRET);
// Obtain a bearer token with HTTP POST request
var tokenOptions = {
headers : {
Authorization: "Basic " + tokenCredential,
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
method: "post",
payload: "grant_type=client_credentials"
};
var responseToken = UrlFetchApp.fetch(tokenUrl, tokenOptions);
var parsedToken = JSON.parse(responseToken);
var token = parsedToken.access_token;
// Authenticate Twitter API requests with the bearer token
var apiUrl = 'https://api.twitter.com/1.1/users/search.json?q=screen_name='+name;
var apiOptions = {
headers : {
Authorization: 'Bearer ' + token
},
"method" : "get"
};
var responseApi = UrlFetchApp.fetch(apiUrl, apiOptions);
var result = "";
if (responseApi.getResponseCode() == 200) {
// Parse the JSON encoded Twitter API response
var tweets = JSON.parse(responseApi.getContentText());
return tweets.id
}
Logger.log(result);
}
Edit: deleted the https a few times because of the URL limit
You can not search for users using application-only authentication (bearer token). See https://dev.twitter.com/oauth/application-only. A user context (access token) is needed for that request. You can get your own access token from https://apps.twitter.com.

Venmo Oauth 2.0 Using Ionic Framework - 400 Bad Request Error

I am currently trying to login to my app that is built on Ionic Framework using Venmo's Oauth API. I am attempting to use the Server Side Flow so that I can have a longer term access token. I am able to receive a code and set it to a requestToken variable.
However, when I attempt to post to "https://api.venmo.com/v1/oauth/access_token" with my Client Id, Client Secret, and Request Token, I get the following error alert: "ERROR: [object Object]".
In checking my console, I see that the error is a 400 Bad Request error coming on my post request, although it does appear that I have a valid request token. The error message is as follows: "Failed to load resource: the server responded with a status of 400 (Bad Request)".
Below is the code of the login function I am using to login via Venmo's Oauth API:
//VENMO SERVER SIDE API FUNCTION
var requestToken = "";
var accessToken = "";
var clientId = "CLIENT_ID_HERE";
var clientSecret = "CLIENT_SECRET_HERE";
$scope.login = function() {
var ref = window.open('https://api.venmo.com/v1/oauth/authorize?client_id=' + clientId + '&scope=make_payments%20access_profile%20access_friends&response_type=code');
ref.addEventListener('loadstart', function(event) {
if ((event.url).startsWith("http://localhost/callback")) {
requestToken = (event.url).split("?code=")[1];
console.log("Request Token = " + requestToken);
$http({
method: "post",
url: "https://api.venmo.com/v1/oauth/access_token",
data: "client_id=" + clientId + "&client_secret=" + clientSecret + "&code=" + requestToken
})
.success(function(data) {
accessToken = data.access_token;
$location.path("/make-bet");
})
.error(function(data, status) {
alert("ERROR: " + data);
});
ref.close();
}
});
}
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function(str) {
return this.indexOf(str) == 0;
};
}
This function is from this helpful walkthrough article by Nic Raboy (https://blog.nraboy.com/2014/07/using-oauth-2-0-service-ionicframework/). I think that the problem may be in how I am presenting the data array, so if anyone has any experience in successfully implementing a Venmo API in Ionic, your help would be much appreciated!
I was actually able to solve this issue with the method described above. In my original code, I omitted the line used to set the content type to URL encoded (which was included in Nic's example). Once I added this line, the request functioned as expected. The line was as follows:
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

OAuth error when exporting Sheet as XLS in Google Apps Script

I had a Google Apps Script to take appointments from my Google Calendar, copy them into a Google Sheet, convert it to XLS and email it. It was working fine until this week.
The initial problem was a 302 error, probably caused by the new version of Sheets. This has been discussed here: Export (or print) with a google script new version of google spreadsheets to pdf file, using pdf options
I got the new location of the file by muting the HTTP exceptions and adjusting the URL accordingly. I also updated the OAuth scope to https://docs.google.com/feeds/ as suggested.
The program is failing with an "OAuth error" message. When muteHttpExceptions is set to true, the message is "Failed to authenticate to service: google".
I guess this is a scope problem but I really can't see what I've done wrong. Naturally, I've tried a few other possibilities without luck.
I've included the code below. Commented code is the instruction that worked until this week.
function getSSAsExcel(ssID)
{
var format = "xls";
//var scope = "https://spreadsheets.google.com/feeds/";
var scope = "https://docs.google.com/feeds/";
var oauthConfig = UrlFetchApp.addOAuthService("google");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=" + scope);
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
var requestData = {
//"muteHttpExceptions": true,
"method": "GET",
"oAuthServiceName": "google",
"oAuthUseToken": "always"
};
//var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + ssID
var url = "https://docs.google.com/spreadsheets/d/" + ssID
+ "/feeds/download/spreadsheets/Export?"
+ "&size=A4" + "&portrait=true" +"&fitw=true" + "&exportFormat=" + format;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
return contents;
}
Thanks for your help!
Instead of using OAuthConfig (which must be auth'ed in the Script Editor) you can pass an OAuth2 token instead, retrievable via ScriptApp.getOAuthToken().
The code snippet below uses the Advanced Drive service to get the export URL, but if you hand construct the URL you'll need to ensure that the Drive scope is still requested by your script (simply include a call to DriveApp.getRootFolder() somewhere in your script code).
function exportAsExcel(spreadsheetId) {
var file = Drive.Files.get(spreadsheetId);
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
return response.getBlob();
}

twitter request_token 401 unauthorized

ok after two days of tryouts i still cant my titanium application to play well with twitter request_token api 1.1, i am always getting 401 unauthorized error .below is my code. i am blocked so any help is appreciated.
var httpClient = Ti.Network.createHTTPClient({
onerror : function(e) {
alert(this.status + ":" + e.error);
},
onload : function(e) {
alert(this.responseText);
if (this.readyState == 4) {
var resposeText = this.responseText;
}
}
});
httpClient.open('POST', "https://api.twitter.com/oauth/request_token");
httpClient.setRequestHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
var now = new Date().getTime();
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var nonce = "";
for (var i = 0; i < 10; ++i) {
var rnum = Math.floor(Math.random() * chars.length);
nonce += chars.substring(rnum, rnum + 1);
}
var parameters = "oauth_callback=" + Ti.Network.encodeURIComponent("http://apicallback.stc.com.sa");
var signature = "POST&" + Ti.Network.encodeURIComponent("https://api.twitter.com/oauth/request_token") + "&" + Ti.Network.encodeURIComponent(parameters);
var header = "OAuth oauth_callback=\"" + Ti.Network.encodeURIComponent("http://apicallback.stc.com.sa") + "\",oauth_consumer_key=\"wPdlchopdYaqHhab8H8jMA\",oauth_nonce=\"" + nonce + "\",oauth_signature=\"" + signature + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + now + "\",oauth_version=\"1.0\"";
httpClient.setRequestHeader("Authorization", header);
httpClient.send(parameters);
There were several errors :
Your nonce seems to be built incorrectly. Generate a string with 32 letters and encode it with Base 64.
Your signature is not built correctly too. Refer to the Twitter Developers documentation about making signatures. Here are your errors :
All the OAuth arguments are missing but oauth_callback. The OAuth arguments which are used in the Authorize header have to be included in the parameters for the signature
You do not build the key to sign datas.
You do not use the signature method (oauth_signature_method which is set to "HMAC-SHA1") to sign your datas.
Your timestamp is too big. It is the number of seconds since the Unix Epoch time, not the milliseconds. Add a "/1000" :
var now = new Date().getTime() / 1000
More generally have a look at Twitter Developers documentation about authorizing requests : https://dev.twitter.com/docs/auth/authorizing-request
by chance i found javascript library posted in twitter list of libraries. check it out jsOAuth. there is also API doc for the library :). now i am able to get the authorization token but when i perform search by posting to https://api.twitter.com/1.1/search/tweets.json i get 401 (unauthorized) error. now i am stuck again. any idea what might be the problem...
There are multiple twitter libraries out there for appcelerator that already work, I would suggest starting with one of them.
http://www.clearlyinnovative.com/blog/post/33810421717/titanium-appcelerator-quickie-posting-images-to-twitter-with-social_plus-js
see link to github repo at bottom of posting

Resources