Using token access for Google SpreadSheet API in Javascript - javascript

The question is simple.
I got the access_token by Oauth 2. and I want to access spreadsheet on google to read.
But When I read api from https://developers.google.com/sheets/ .
I don't get where to put access_token or do i even need it.
I tried to put my access-token on url and failed..
for instance: var sample_url = "https://spreadsheets.google.com/pub?key=0Ago31FFWG3xZrdHF2bWNjcTJFLXJ6UUHYT3dEakdEaXc&hl=en&output=html?accesstoken=" + accesstoken;
I got the response back. it says "{"data":{"error":{"code":403,"message":"The request cannot be identified with a client project. Please pass a valid API key with the request.","status":"PERMISSION_DENIED"}},"status":403,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"https://sheets.googleapis.com/v4/spreadsheets/1ZduILENRVcnzXTynV00j9puWJEvGgz-EcxOgoPRpOGI/values/A1:D3?ya29.Ci87A42OTqtIqXylTU7QxZALwJjRuf_oXf2FJ-MTY7QvXgWzPhZEKhi4Yhn7HVVV7g","headers":{"Accept":"application/json, text/plain, /"}},"statusText":""}"
I know I have to attach the access-token somehow, but i don't know how.
Do you guy have any idea for the spreadsheet api?
Thank you for reading this

I am not familiar with the ionic-framework, but to use the access token, you should either add that into the HTTP headers (e.g. Authorization: Bearer ya29.xxxxxxxxxxxxxxxxxx) or include that in your query string,
Ref: https://developers.google.com/identity/protocols/OAuth2InstalledApp#callinganapi
There is a mistake in your sample_url, it should be &access_token= instead of ?accesstoken=
It should be,
var sample_url = "https://spreadsheets.google.com/pub"
+ "?key=0Ago31FFWG3xZrdHF2bWNjcTJFLXJ6UUHYT3dEakdEaXc"
+ "&hl=en&output=html&access_token=" + accesstoken;

I had a same requirement of accessing the google spreadsheet from the ionic cellphone, and we have used tabletop.js. Using this we were able to read the spreadsheet completely.
Try this if it helps you anyway.
https://github.com/jsoma/tabletop

Related

How to consume the Open Weather App API in react

I have been trying to fetch from the Open Weather API but an error message kept appearing on the console. It returned 'unauthorized' and 'message: keys does not exist' after persistent tries.
fetch("https://community-open-weather-map.p.rapidapi.com/weather?callback=test&id=2172797&units=%22metric%22%20or%20%22imperial%22&mode=xml%2C%20html&q=London%2Cuk", {
"method": "GET",
"headers": {
"x-rapidapi-host": "community-open-weather-map.p.rapidapi.com",
"x-rapidapi-key": "15XXXXXXXXXXXXXXXXXX"
}
I'm not sure why you are using rapidapi here, but if you simply want to fetch data from openweathermap, you need to do the following:
Sign up to get unique API key (free plan exist)
Provide the key as part of your URL, like:
http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID={APIKEY},
When APIKEY is your unique API key
Also make sure you do not use the API key from the demos provided by open weather map, as it will result with errors when used from domain other than openweathermap, And tha if you're using a free plan, you're limited to maxium of 60 request per minute.
Check out the docs about how to get started with openweathermap.
As per the fetch function response, it looks like that the API key you are using is invalid or expired.
I'm able to replicate the issue in my setup.
I found one working API key on rapidapi site and after using the key the issue is resolved.
The working Key Api key is : 490f920aa3msh1db5e8f1c73a050p1cbd06jsn83595422113e
You can also use the above key as a quick workaround.

Downloading a slack file just returns login page?

I'm trying to download a file from slack, using Node. I'm think what I've got should work in theory - but I just seem to keep getting the login page as a response and I can't work out why. I've also tested via postman too and get the same result.
I believe I've followed the correct steps according to https://api.slack.com/tutorials/working-with-files with the bearer token. I'm using my own token trying to download an image that I posted - so I should have permission to do so. I've used this same token with the node-sdk without any problems.
// file.url_private = https://files.slack.com/files-pri/TDGL0NYUE-FHQN2HRQQ/download/brian.jpg
// token = xoxp-4586..........
const options = {
url: file.url_private,
method: "GET",
headers: {
"Authorization": `Bearer ${this.token}`,
}
};
request(options).pipe(fs.createWriteStream(`c:/temp/test/${file.title}`));
The pipe etc is working correctly, but saving a login html page instead. I'm wondering if anyone can point me in the right direction?
So having set up my scopes a while ago, I forgot about them. Turns out the scope of the token I created didn't have the files.read permission required to download a file!

How to get around auth level when testing API on laravel project?

I am using the basic Auth from laravel that you get from running the following command.
php artisan make:auth
I have an API written so that the backend on the server can update/create services and statuses. The issue i'm running into is that the Admin also has a UI on the web app and can create a service, or update its status manually. Therefore, I have an Auth level on the methods where you have to be logged in to use them.
Now when I call the method in postman it redirects me to the login page, I was wondering if there was a way around this Auth level strictly for an API?
I was told of a way to do pre-request scripts directly in postman but i'm fairly lost when it comes to the whole java script part of that and feel like there is an easier way to do it. I also already tried to do 'basic auth' with the username and password, it didnt seem to work though.
Thank you for the help in advance!
Edit: Here is the screenshot from my header.
I am presuming if you have the API in place you have an api_token set for the specific user. You can use that inside Postman in one of two ways.
You will goto the Headers tab and add:
Key: Authorization
Value: Bearer API_TOKEN_VALUE
Edited: Added the screenshot of postman
You can amend the url for the request and add the token:
url_to_api_endpoint?api_token=API_TOKEN_VALUE
On the api routes if you have ->middleware('auth:api') Laravel will read the authorization token from the header or using the query parameter and check it to the database value.
Adding the api_token to the user table
If you don't have an api_token field in your user table then add one. It is not the same as remember_token, they are different. So add to your user migration the following:
$table->string('api_token', 60)->unique();
You will need to update the users api_token using something like the following:
$user = User::find(1);
$user->update(['api_token' => str_random(60)]);
That 60 character string you will use where I put VALUE_OF_TOKEN_FROM_DB

Can't correctly obtain OAuth to append to google sheet via Javascript http request

I can't for the life of me append to my google sheet via http request. More specifically I can't seem to get the Oauth formatting right. I don't want/need a uri or prompt for permission as its just me managing my own spreadsheet. First, I was trying with just my api key, but then found out that if you're editing data you need to obtain an access token. That's when I started trying to obtain the token through oauth2 following the TERRIBLE google api documentation. That's where I hit a wall and have just about given up. It's such a simple concept, I just want to add data to my spreadsheet on drive from an online script (housed on scriptr.io), but Google yet again makes things so unneccessarily complicated and don't help matters with their convoluted, misleading, and scattered documentation. Can someone please help me in accomplishing this? Here's where I'm at or what progress I've made thus far.
I've figured out how to correctly format the call to add a row of data to the spreadsheet.
POST https://sheets.googleapis.com/v4/spreadsheets/-/values/Raw%20Data!A1:D1:append?valueInputOption=USER_ENTERED
//Header
Authorization: Bearer {oauth_token}
//Payload
{"range": "Raw Data!A1:D1","majorDimension": "ROWS","values": [["Test", "$15", "2", "3/15/2016"]]}
I know the above works because I've successfully added the data using the OAuth 2.0 Playground. However, when trying it outside of the playground (on a rest client) I keep getting errors trying to obtain the token.
POST https://www.googleapis.com/oauth2/v4/token
scope=https://www.googleapis.com/auth/spreadsheets
client_id=------&
client_secret=-----&
refresh_token=-----&
grant_type=refresh_token&
access_type=offline
I use the client id & client secret from my api console and I use the refresh token I got by authorizing the spreadsheet api in the oauth playground, but the above POST request leads to the following error
Error 400
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: "
}
Can someone please help me figure out how to correctly do this?

How to get twitter oAuth token of a logged in user

I'm trying to set up a javascript function to post a status to a twitter account using POST statuses/update, details here: https://dev.twitter.com/docs/api/1/post/statuses/update. The goal is a Twitter post similar to the open graph actions on Facebook.
I'm using jQuery ajax to make the post request, here's what I have so far:
$.ajax
({
type: "POST",
url: "https://api.twitter.com/1/statuses/update.json",
headers: jsonData,
data: {},
dataType: "jsonp",
success: function( data )
{
}
});
I believe that I need to generate a header something like this for security:
Authorization: OAuth oauth_consumer_key=consumerKey, oauth_nonce=nonce,
oauth_signature=signature, oauth_signature_method="HMAC-SHA1",
oauth_timestamp=timestamp, oauth_token=userToken, oauth_version="1.0"
I have the consumer key for my app, I can generate a nonce, I'm generating the signature and timestamp using the methods from this question Twitter OAuth authentication in javascript. The only thing I have left is th oauth_token, which I believe is the token of the user whose feed I wish to post to. Please correct me if I'm wrong about that.
The problem is, I have absolutely no idea how to get this token from the user in order to post to their feed. I've spent the last 2 hours running around in circles through Twitter's oAuth documention without finding anything that looked useful; everything I've found was either flowcharts with no code examples or predicated on my code already having the user's oAuth token.
My question is this: how can I get the logged in user's oAuth token using javascript?
If that is not possible, I have another page where I am currently storing the user's twitter id in the database with their permission, getting their token and databasing it in PHP would also be satisfactory, assuming it doesn't change very frequently.
In order to obtain the oauth_token you need to follow the authentication process. Your application needs to be authorized to act on the behalf of the user.
I would recomend to take some time first and learn how OAuth exactly works (there is a lot of information available) and then implement it in your app. (http://hueniverse.com/oauth/)
You could also benefit from a library which will make your life easier. (in your case, look at: https://dev.twitter.com/docs/twitter-libraries#php).
Hope this has been useful.
Here is example for get twitter oauth token and post tweet in twitter .
Code sample is in php .
http://www.phpgang.com/how-to-post-tweet-on-twitter-with-php_414.html
1) to obtain the oauth token you need to follow the authentication process.
2) and your application needs to be authorized to act on the behalf of the user.
you can also see this twitter example for better understanding how it works
In this use can see the process of authorized user and post and get json result.
https://dev.twitter.com/rest/tools/console
I hope this will help you.
thanks

Categories

Resources