Extract data using Google Analytics API without login gmail account - javascript

I am using Googe Analytics API. I had successfully configured google analytics api and get successful data but issue is that when I use any other email account to login and view the page, it says authentication issue.
I want to access analytics api without gmail login. I will hard code credentials to for login, but how to do it with javaScript?
How to get analytics data without login in api?

So if I am correct, you want to retrieve data from a Google specific account without having to log in or sign in that account.
You could use tokens to connect the API rather than manually log in (if that is what you are referring). Other options could be extracting the data into a virtual repository that you can use for presentation layer on the client side so you don't have to deal with credentials or security flaws on having to log in or hard code the authentication.
This should be do-able on javascript and jquery to make your data viewable.

To query GA without authenticating each time you will need obtain and store the refresh token while authenticating GA.
(not sure if we can retrieve refresh token with Js)
Once we have refresh token we can query API for access token again.

Related

app.askForSignIn(); not working at all

Sign in intent doesn't work at the moment as clearly explained in the docs, it's just something you can use for test in the emulator, but it's not available in production.
My case is I'm using account linking and my token expires after one day, so if the user doesn't interact with the assistant, the token will no longer be valid. Then if the token is proved as invalid on the webhook I want to send back 'please link your account again' to the assistant from the webhook.
There is a method app.askForSignIn(); which seems similar to what I need but it looks like it is not available for Dialogflow and only available for the SDK.
So what I have done is:
Make an intent in Dialogflow with the name actions.intent.SIGN_IN and added actions_intent_SIGN_IN event to it
When any request comes to the webhook I check the token, then if I encounter an invalid token I call app.askForSignIn();
What is happening:
The app just left the conversation e.g: test app left the conversation
When I say again "talk to test app" it is behaving like the account is linked and does not ask for account linking until I manually reset the whole app using the reset button from test console
Update:
I tried to use the code snippet from the doc (https://developers.google.com/actions/reference/nodejs/AssistantApp#askForSignIn)
and it is not working as well, here is the response from the simulator when I call app.askForSignIn(); from the webhook
You can have 2 tokens, one being the access token, which is short-lived, and the other being the refresh token which is long-lived.
So, When Google needs to call one of your service's APIs, Google uses these endpoints together to get permission from your users to call these APIs on their behalf. A typical OAuth 2.0 session initiated by Google has the following flow:
First, Google opens your authorization endpoint in the user's browser. The user signs in if not signed in already, and grants Google permission to access their data with your API if they haven't already granted permission.
Then, your service creates an authorization code and returns it to Google by redirecting the user's browser back to Google with the authorization code attached to the request.
Next, Google sends the authorization code to your token exchange endpoint, which verifies the authenticity of the code and returns an access token and a refresh token. The access token is a short-lived token that your service accepts as credentials to access APIs. The refresh token is a long-lived token that Google can store and use to acquire new access tokens when they expire.
Finally, Google calls your service's APIs, attaching the access token with each request. Your service verifies that the access token grants Google authorization to access the API, then completes the API call.

getting a google analytics access token and how to use it in google sheets script

I am currently pulling data from the API query URI from the query explorer from google. https://ga-dev-tools.appspot.com/query-explorer/ It's possible here to include a 60 minute access token.
Now I want a non expiring access token and gotten as far as the API Project website from google and I have generated a client id and secret.
I tried to add the client_id and client_secret as parameters to the url like so:
url&client_id=xxx&client_secret=yyy
This does not work.
How can I generate a working access token in Google (Sheets) scripts?
Thanks
I think you need to start at the beginning.
To get an Access token you need to use a client id and client secret to request access of a user. When the user grants your application access then you will be given an access token. A good place to start Using OAuth 2.0 to Access Google APIs
Usage:
RestRequesturl?access_token=[yourtoken]
When you request access of the user you send scopes with it scopes denote what access your application will need. There is a large list of scopes for Google here in your case you will need to request the scope for Google analytics and the scope for google sheets this will allow you to access both the user google analytics account and their Google Sheets.
As you know access tokens expire after an hour for that you need a refresh token a refresh token will allow you to request a new access token of the authentication sever without having to request access for the user again. I am not a JS developer but i know you can get a refresh token with node.js but i don't think you can with pure js.
I have a tutorial series that may help you get up to speed. Google development for beginners reading the one on Oauth2 would probably help you. Google Developer console oauth2

Youtube Analytics Offline Access Request when Authenticated as Brand instead of User

Apps Script keeps asking for offline permission with Youtube's API
In Google Apps Script, access to YouTube Reporting API is Forbidden
These are very similar questions however, I am logged in as the owner. The script is in the owner's drive.
My problem
I have been trying to access YouTube Analytics Reports from the Content Owner using GAS(Google Apps Script). There are two accounts a Brand account (holds the data i.e. the video content) and a User account. They both use the same credentials(email & pwd). When authorizing as the user, I get a 403(forbidden). When authorizing as the brand, I am asked to authorize offline access again and again, stopping me from ever being able to make a request.
What I've tried...
Running from Node, using OAUTH Playground tokens, and it works. But I need to stick with GAS.
Using google-script-oauth2: to hard code credentials (similarly to the Node solution) but I couldn't set the refresh token. I got a 401(invalid credentials) - I believe the bearer token was expired
Setting up credentials for and enabling both youtube and youtube analytics APIs
scrapping old credentials and attaching a new project to GAS
removing auth in privacy settings and re-authenticating
toggling a use unsafe scripts option and repeating step 3
switching between contentOwner and channel parameters for the ids param
NOTE: I have two OAUTH2 credentials app script and the web client both are set as Web Applications.
GAS Code
function test(){
YouTubeAnalytics.Reports.query("contentOwner==id", "2017-03-01", "2017-03-31", "likes");
}
Final Thoughts
I believe there is a disconnect between the Brand and the user such that the brand is not given the same access to the OAUTH 2 token. Therefore, it never generates a refresh token. So, the request sees that I am the authorized channel owner but it can't finish the OAUTH flow.
If this is true, why, and how do I fix it? If not, what do you think could be the error?
I just realized the script is in the user account and not the brand account. Would that affect the validation?
Also on the actual channel, the user is listed as the Primary Owner.
I think the problem has to do with Apps Script's limited OAuth scopes. Open the Script Editor and navigate to Resources->Advanced Google Services and you'll see that YouTube's Reporting API is not supported. However, you can get around this by using Service Accounts. They are a pain to set up but once you get them up and running you can explicitly request the scopes required to make authorized calls on the API from GAS.
Here are a few links to get you started:
Using OAuth 2.0 for Server to Server Applications
OAuth 2.0 Scopes for Google APIs
For Using OAuth 2.0 for Server to Server Applications you'll want to scroll down to the section titled Preparing to make an authorized API call. Select the HTTP/REST tab and it should walk you thru the steps you'll need to setup a service account (you'll need to create a JWT - JSON Web Token from your Google console for use in your API calls). You'll also need to retrieve the needed OAuth scope urls for YouTube's Reporting API from the second link provided. Once you're all set up you'll be able to make requests to the API directly from Apps Script using URLFetchApp. Best of luck with your project.
One more thing. Check out Google's API Explorer listing for the YouTube Reporting API. You can get the URL endpoints (and request methods) you'll need to use in your UrlFetchApp calls by playing with the Explorer.
UPDATE 4/28/2017
Also be sure to enable the YouTube Reporting API from your Google API Console.

Is there any way that multiple users can upload to my Youtube channel via Youtube-api

I have used the Youtube-api and also created the oauth-clientId for some demo project. I also used the Client libraries (java & javascript) for uploading videos to my channel and i succeeded. But i don't want to share my login credentials and want my client users to upload videos to my channel. Is there any way, i mean documentation or procedure or youtube-implementations?
Assuming that you are using Java as you said. You should have a refresh token after your application has been authenticated.
The refresh token can be used to request a new access token. You should use this refresh token to allow others to upload to your channel. Note: To my knowledge you cant get a refresh token with the JavaScript client library due to security issues. You need to use a server sided language to do this.
For Refrence:
YouTube does not support service accounts so that wont work. API Key is only used for accessing public data so that wont work either.
I finally found an answer to my question and now my users[whom i give some authorizations] can directly upload to my youtube channel.
As per the comments i received for my question, i came to the conclusion that i have to do it at the server side because of the security issues.
The thing which came to rescue is namely Refresh Token.
I first created a simple application through which i logged & uploaded video [uploading is not necessary] into my youtube account and received the respected refresh token
Then i saved that refresh token through which i created a Credential object manually.
You can check the code provided by google :
UploadVideo.java
Credential credential = Auth.authorize(scopes, "uploadvideo");
This is what i replaced with this and obtained my own refresh token.Refresh token does not expire like normal access token, and is used to generate normal access token when needed. So, refresh token was the key to my question
Then at the backend, the only thing you have to do is just create the Credential manually. You can use this code
getCredential = new GoogleCredential.Builder()
.setJsonFactory(JSON_FACTORY)
.setTransport(HTTP_TRANSPORT)
.setClientSecrets(clientId, clientSecret)
.build()
.setRefreshToken(refreshToken)
// The refresh token here will be the same you received offline.
Here is the official google doc about this concept
Refreshing an access token (offline access)
Access tokens periodically expire. You can refresh an access token without prompting the user for permission (including when the user is not present) if you requested offline access to the scopes associated with the token.
If you use a Google API Client Library, the client object refreshes the access token as needed as long as you configure that object for offline access.
If you are not using a client library, you need to set the access_type HTTP query parameter to offline when redirecting the user to Google's OAuth 2.0 server. In that case, Google's authorization server returns a refresh token when you exchange an authorization code for an access token. Then, if the access token expires (or at any other time), you can use a refresh token to obtain a new access token.
Requesting offline access is a requirement for any application that needs to access a Google API when the user is not present. For example, an app that performs backup services or executes actions at predetermined times needs to be able to refresh its access token when the user is not present. The default style of access is called online.
Server-side web applications, installed applications, and devices all obtain refresh tokens during the authorization process. Refresh tokens are not typically used in client-side (JavaScript) web applications.

Google analytics credentials

I am currently new for Google analytics API throu Javascript.
I am implementing some of charts and for first load, page is redirecting me to google site to login with Analytics account and then returning to my orignal page, refresh & chart show.
Now, instead of redirecting to google analytics, is there any other way that I can store credentials on either in code behind or in config file and it will be read from there when page get loaded?
Let me know if there are any other ways/ ideas around?
I can give you some help.
Initially we need to authenticate the users, For that purpose we are redirecting the user to Google.[Mostly using Oauth]
After the authentication done. Google will redirect to your site with the access Token.
Access token is the key to fetch the analytics data from Google's database by using Management API and core reporting API.
You have to do some exchanges with google to make the token as permanent and you can store it your database.But based on some conditons this token may expire.
Visit this url : https://developers.google.com/analytics/devguides/ and understand the Google Analytics, Core Reporting API and Oauth Process
Down load this useful PHP client library for Google Analytics https://code.google.com/p/google-api-php-client/ and have fun.

Categories

Resources