I'm using the Google Analytics API v3. I'll explain the flow of my application now
I used this documentation here: https://developers.google.com/accounts/docs/OAuth2WebServer
First, an OAUTH-URL is generated for the user. The URL looks like this
https://accounts.google.com/o/oauth2/auth?
client_id={CLIENT-ID}&
redirect_uri={REDIRECT-URL}&
state={CUSTOM-NUMBER}&
response_type=code&
access_type=offline&
approval_prompt=force&
scope=https://www.googleapis.com/auth/analytics
When the user clicks on the link he authenticates. Afterwards, with the code, I'm getting the access and refresh token.
I'm sending a request to https://www.googleapis.com/oauth2/v3/token
with the parameters
code = Code from Analytics
grant_type = authorization_code
client_secret = CLIENT_SECRET
client_id = CLIENT_ID
redirect_uri = REDIRECT_URI
The cURL options I send are the following:
CURLOPT_HTTPHEADER = array('Content-Type: application/x-www-form-urlencoded')
And of course, the post data is built with http_build_query so I can use that content-type header.
Then, I am getting all profiles of the user, with this URL
https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles
This works, and I'm listing all the profiles. The user then selects one of the profiles, and my library gets the current data for the user (pageviews, visits, etc.)
The problem I'm having now, is, that, when I want to refresh the data everyday with a cron, I'm getting the error message:
'error' => 'invalid_grant',
'error_description' => 'Bad Request'
But I have no idea, why?
I saved the access token and the refresh token for the profiles in my database. Then, when reaccessing data before I make requests to access data, I check if the token is valid. But even this fails.
I'm doing this request here
https://accounts.google.com/o/oauth2/tokeninfo?access_token=ya29.BwHqH8NOPVhafk3SnwbqjLZMXub4Q8bemC-8vKVwp-UjRqaIHRXrzEV3WjInhGzl1-phIn7XI4NnDA
It tells me, that the access token is invalid (Which is mysterious, since I just authenticated and 5 seconds later the token isn't valid anymore?
Anyway, then I try to refresh it with this request
URL: https://www.googleapis.com/oauth2/v3/token
Parameters:
client_secret = CLIENT_SECRET
client_id = CLIENT_ID
refresh_token = REFRESH_TOKEN From my database
grant_type = refresh_token
cURL Options: CURLOPT_HTTPHEADER = array('Content-Type: application/x-www-form-urlencoded')
Then, a post request with the params built with http_build_query
The response looks like this
string(67) "{ "error": "invalid_grant", "error_description": "Bad Request" } "
But I have no idea why. I'm using the access token and refresh token I got 5 minutes earlier and the ones which worked for the first request. Why doesn't it work 5 minutes later with the same tokens? And why can't I even refresh the token?