Google Analytics PHP API Redirect URI - php

I'm testing the Google Analytics API (with oauth 2.0) on my local machine and I want to know if it's possible to get it to work this way as they request me to insert a Redirect URI in the Google APIs Console and then enter it in my code but I do not know what this Redirect URI should be?
My current Redirect URI is https://localhost/oauth2callback and I tried https://gapi.local/oauth2callback but neither works for me.
I get this error message:
Fatal error: Call to undefined method apiClient::setClientRedirectUri() in C:\xampp\htdocs\webs\gapi\HelloAnalyticsApi.php on line 15
Any help would be appreciated.

The google-api-php-client library has no method setClientRedirectUri() in apiClient. The correct method is called setRedirectUri():
$client = new apiClient();
$client->setApplicationName('Hello Analytics API Sample');
// Visit //code.google.com/apis/console?api=analytics to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('insert_your_oauth2_client_id');
$client->setClientSecret('insert_your_oauth2_client_secret');
$client->setRedirectUri('insert_your_oauth2_redirect_uri');
$client->setDeveloperKey('insert_your_developer_key');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));

Related

Google OAuth 2 redirect URI mismatch

I am already using google app for authentication. Now I have added additional URLs to "Authorized redirect URIs" but those URL are not working. Old ones are working properly but when I am using new URL google returns below error instead of google auth token.
{"error":"redirect_uri_mismatch","error_description":"Bad Request"}
Please suggest me solution.
Here is my code to generate login url :
require_once "../vendor/autoload.php";
$gClient = new Google_Client();
$gClient->setClientId("clientID");
$gClient->setClientSecret("clientSECRET");
$gClient->setApplicationName("MY GOOGLE APP");
$gClient->setRedirectUri("https://example.com/TEST/authenticate/pages_authnicate_google.php");
$gClient->addScope("https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/spreadsheets");
$gClient->setAccessType("offline");
$gClient->setPrompt('consent');
$loginURL = $gClient->createAuthUrl();
Double-check that what you sent earlier in the authorization request matches what you send in the request to the token endpoint. You can use either URL that you've configured in the API Console but it must be the same in both requests.
Make sure redirect_uri: 'https://www.example.org/token' is same configured on Google Client API with 'Authorized redirect URIs' block.
In my case, it works...!!!

How to get RSS token for BitBucket by PHP CLI?

I want to get valid link https://bitbucket.org/{username}/rss/feed?token={token} (this is main problem) and then get valid response from this link in CLI.
I know my required parameters, e.g. consumer_key, consumer_secret, request_token_url, authenticate_url, access_token_url.
I tried to use StudioIbizz\OAuth\OAuth1, but is seems to be designed for Browser, not for CLI.
I tried to run:
$this->OAuth = new \StudioIbizz\OAuth\OAuth1($this->consumer_key,$this->consumer_secret);
$requestToken = $this->OAuth->getRequestToken($this->request_token_url,$this->authenticate_url);
$token = $requestToken['oauth_token_secret'];
and paste this $token to my RSS link, but then I see message You must have read access to access the RSS feed. from Bitbucket.
I need Step by Step instructions for serious dummies.
Edit: I tried this:
$accessToken = $this->OAuth->getAccessToken($this->access_token_url,$requestToken['oauth_token_secret'],$requestToken['oauth_token']);
But then I get this:
Fatal error: Uncaught exception 'StudioIbizz\OAuth\OAuthException' with message 'Unexpected HTTP status #400'
I don't see any function related with that on official documentation. Maybe that feature not exists.
For more information, you could use this link:
https://confluence.atlassian.com/bitbucket/use-the-bitbucket-cloud-rest-apis-222724129.html
You could use stevenmaguire's Bitbucket OAuth 2.0 support for the PHP League's OAuth 2.0 Client.
$provider = new Stevenmaguire\OAuth2\Client\Provider\Bitbucket([
'clientId' => '{bitbucket-client-id}',
'clientSecret' => '{bitbucket-client-secret}',
'redirectUri' => 'https://example.com/callback-url'
]);
$token = $_GET['code'];
To get an RSS token for Bitbucket via PHP CLI, you will need to use the OAuth 1.0a protocol to authenticate your request. Here are the steps you can follow:
Install an OAuth library for PHP that can be used in CLI, such as the league/oauth1-client package.
Create a new instance of the OAuth client by passing in your consumer key and consumer secret.
$client = new League\OAuth1\Client\Server\Bitbucket($consumerKey, $consumerSecret);
Get the request token by calling the getTemporaryCredentials method and passing in the callback URL.
$temporaryCredentials = $client->getTemporaryCredentials();
Get the authorization URL by calling the getAuthorizationUrl method and passing in the temporary credentials.
$authorizationUrl = $client->getAuthorizationUrl($temporaryCredentials);
Use this URL to authenticate the request via the browser.
After successful authentication, you will get a verifier code.
Get the access token by calling the getTokenCredentials method and passing in the temporary credentials and the verifier code.
$tokenCredentials = $client->getTokenCredentials($temporaryCredentials, $verifier);
$tokenCredentials = $client->getTokenCredentials($temporaryCredentials, $verifier);
Get the RSS token by calling the getRssToken method and passing in the token credentials
$rssToken = $client->getRssToken($tokenCredentials);
You can use this token to construct your RSS feed link:
https://bitbucket.org/{username}/rss/feed?token={$rssToken}
Note that, this is just a general idea of how to use the OAuth library and it may vary depending on the library you are using. It's also important to check the documentation of that library for more details.

Google Analytics API login required error

I've got a strange problem that I've tried to solve but I've tried a whole day and it just doesn't work, so I hope maybe someone else can help me with this.
I've build a CMS and after you login you see the dashboard.
On this dashboard you can click on a button to connect your account with Google - because I want my customers to be able to connect their Google Analytics account.
Everything works fine, I've got tokens and the refresh token and everything seems to work. Even when I request my user profile data I get it printed on my screen as an array. But when I try to get the accounts that are available to view for the connected user i get this error:
Uncaught exception 'Google_Service_Exception' with message 'Error calling GET
https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties
key=xxxxxxxxxxxxxxxxxxxxxxxxxx: (401) Login Required'
I just don't understand why I get the message 'Login required'.
Below you can see my script.
require_once('/Google/Client.php');
require_once('/Google/Service/Analytics.php');
// call object
$client = new Google_Client();
$client->setApplicationName("Google Analytics - CMS title");
$client->setClientId('xxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxx');
$client->setRedirectUri('xxxxxxxxxxxxxxxxxxx');
$client->setDeveloperKey('xxxxxxxxxxxxxxxxxxx');
$client->setApprovalPrompt('auto');
$client->setAccessType('offline');
$client->setScopes(array(
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/analytics'
));
// decode
$token = $token; // this comes from my database and it's json encoded
// connect
$client->setAccessToken($token);
// call service
$service = new Google_Service_Analytics($client);
// get accounts from analytics
$accounts = $service->management_accounts->listManagementAccounts();
When I try to var_dump $accounts I don't see anything because the error already occurred (Login required)
I think you are going to ask me now if my token is correct but it is because I tested it with other api calls.. it's just not working for this specific analytics request.
I hope someone can help me with this.
Thanks,
Pim vd Molen
UPDATE:
Something really strange just happened. I don't know how this is possible but the error just changed into another error:
Uncaught exception 'Google_Service_Exception' with message 'Error calling GET
https://www.googleapis.com/analytics/v3/management
/accounts?key=xxxxxxxxxxxxxxxxxx: (403) Access Not Configured.
Please use Google Developers Console to activate the API for your project.
I've enabled the Google Analytics service ofcourse, but don't know which one i also need to enable.
The 401 error clearly states that the credentials are wrong. The Token might be valid for retrieving Data, but for retrieving user management information, you need a particular grant when asking for that token, please look here in the table you see the additional value for the scope parameter to set in your OAuth request.
not sure if you have solved this yet, but I've documented the process, with photos here:
https://circlical.squarespace.com/blog/2014/7/18/getting-zend-framework-2-and-googles-api-to-play-nice

YouTube API OAuth invalid request

I simply don't really understand how this whole OAuth authentification thing works and I'm pretty much stuck. I'm trying to let a user authentificate his/her YouTube account to my server using the Google PHP Client API.
Here's my current code:
<?php
require_once app_path().'/google-apis/Google_Client.php';
require_once app_path().'/google-apis/contrib/Google_YouTubeService.php';
class SignupController extends BaseController {
public function showSignupForm() {
$client = new Google_Client();
$client->setClientId('CLIENTID');
$client->setClientSecret('CLIENTSECRET');
$client->setAccessType('offline');
$client->setDeveloperKey('DEVKEY');
$youtube = new Google_YoutubeService($client);
$client->authenticate(Input::get('code'));
$token = json_decode($client->getAccessToken());
return View::make('signup')->with('google_token', $token->access_token);
}
public function getYTAccess() {
$client = new Google_Client();
$client->setClientId('CLIENTID');
$client->setClientSecret('CLIENTSECRET');
$client->setAccessType('offline');
$client->setDeveloperKey('DEVKEY');
$client->setRedirectUri('REDIRECT_URI');
$youtube = new Google_YoutubeService($client);
$authUrl = $client->createAuthUrl();
return View::make('connect_youtube')->with('authUrl', $authUrl);;
}
}
?>
This is the code for the SignupController in the Laravel-based application I'm building. The relevant routes are as follows:
Route::get('signup/connect_youtube/return', 'SignupController#showSignupForm');
Route::get('signup', 'SignupController#getYTAccess');
I only get an invalid request error after getting redirected to my application and I know it has something to do with the access token, just don't know what.
Any help would be appreciated.
Thanks
Tobias Timpe
(Secrets omitted, obviously)
To put it simply, there are 2 steps (at least) you have to do:
1. pass the correct parameters to google. The parameters tell you 1. who you are (you need to present your client id and client secret), 2. what you ask for (in your case youtube scope) 3. redirect_uri which is where your user will be redirected back after she accepts your app's request. 4. other options like access_type=offline which specifies that you have a backend server to continue the auth flow.
To check that this step works correctly, you don't always need run the code. Just print out your auth_url that the sdk makes for you. All those parameters i mentioned should be embedded there. Copy-paste the url in the browser, if the parameters are correct, it will take you to Google's consent page. If not, most likely is because the parameters you set in Google Apis setting page are mismatched with your parameters scripted in the auth_url. Examples are mismatched domains, redirect_uris, client_ids, client_secrets. I'm not sure if this is the error that you are receiving.
If your parameters are good, Google will let your user to login and allow youtube scope access for your app ('consent'). It will redirect user's browser back to your specified 'redirect_uri' with the parameter code=. So this will get you to the step 2 your server script has to process.
The value shooted from Google in the parameter ?code is what you need to get access token. So your server route (redirect_uri) needs to extract the code parameter and pass to the google api to exchange for 'credentials'. Note that the auth code can be used only once. The response credentials will contain access_token and refresh_token. These are important for the api calling so you need to persist them in a storage, possibly with google sdk you are using.
Hope that helps.

Fetch Google Calendar Events on PHP server after authenticating on iOS app

Okay so here's what I want to do...
user authorized the app on iPhone with read/write access to Google calendar
I get an auth token of some kind from Google
Pass on the token to my PHP server and save it in database
Use the token to regularly check on Google events and store them in server's database
Send the Google events data as json to the app
I want to implement the fetching of Google events on server, so that I can build additional functionality around them like sending remote push notifications.
I am stuck at the part of getting auth token and saving it on server and using it to fetch events from Google's calendar api, having not able to find the resources for same. Can somebody throw some light on this.
UPDATE
I have been able to successfully implement the scenario till step 3.
I get the auth token and refresh token from Google and save it in database. Now using the Google API php client, I am trying to connect to Google's calendar API using the access token that I got earlier. I am using the following code...
require_once(APPPATH . "libraries/Google/Google_Client.php");
require_once(APPPATH . "libraries/Google/contrib/Google_CalendarService.php");
$client = new Google_Client();
$client->setAccessToken($google_access_token);
$calendar = new Google_CalendarService($client);
$calendarList = $calendar->calendarList->listCalendarList();
echo print_r($calendarList, true);
But now I get this error...
PHP Fatal error: Uncaught exception 'Google_AuthException' with
message 'Could not json decode the token' in
/myserver/application/libraries/Google/auth/Google_OAuth2.php:162
Stack trace:
/myserver/application/libraries/Google/Google_Client.php(170): Google_OAuth2->setAccessToken('a_token...')
I understand that I am directly trying to set the access token in Google client api without specifying any redirect url or other params normally used when the user authorizes the access to Google calendars on server itself. Is this supposed to work like I am trying to?
UPDATE 2
Upon some further digging, I found out that directly setting the access token using setAccessToken does not work as Google client for API expects a JSON encoded string in the setAccessToken method. After some tweaks I changed my code to following....
require_once(APPPATH . "libraries/Google/Google_Client.php");
require_once(APPPATH . "libraries/Google/contrib/Google_CalendarService.php");
$client = new Google_Client();
$client->setAccessType('offline');
$client->refreshToken($google_refresh_token);
$newToken = $client->getAccessToken();
$client->setAccessToken($newToken);
$calendar = new Google_CalendarService($client);
$calendarList = $calendar->calendarList->listCalendarList();
echo print_r($calendarList, true);
Now the error that I am getting is that of an invalid_request.
Error refreshing the OAuth2 token, message: '{"error" : "invalid_request"}'
Finally I am able to answer my own question. Hope this helps someone else.
Step 1 & 2. I got the Google OAuth protocol working in my iOS App following the instructions in this excellent tutorial on mobiletuts.
Step 3. I saved the access token and refresh token in database on my web server.
Step 4. Using the refresh token I got from iOS App I connected to the Google calendar API with this code...
require_once(APPPATH . "libraries/Google/Google_Client.php");
require_once(APPPATH . "libraries/Google/contrib/Google_CalendarService.php");
/* setup google client object */
$client = new Google_Client();
$client->setClientId(GOOGLE_CLIENT_ID);
/* refresh access token */
$client->refreshToken($google_refresh_token);
$newToken = $client->getAccessToken();
$client->setAccessToken($newToken);
/* get google calendars list */
$calendar = new Google_CalendarService($client);
$calendarList = $calendar->calendarList->listCalendarList();
echo print_r($calendarList, true);

Categories