I am testing the Gmail API.
So far I have done the following:
I have created the project in the Google Developers Console
I have enabled the Gmail API.
I have created a new Client ID and the client secret.
In my PHP script I have installed the PHP Client library and followed
the instructions for the setup in PHP.
So now when I run the file quickstart.php it gives a link. When I open it, it appears an authorization page where I authorize my application to access the Gmail API.
Then it redirects to the Redirect URIs that I have declared in the setup (adding the code parameter).
In the address bar it appears exactly this:
http://localhost/main/gmail_callback?code=MY_CODE
Where main is my controller and gmail_callback so far is just a blank function.
And it should be correct since these are my settings:
Javascript origins: http://localhost
Redirect URIs: http://localhost/main/gmail_callback
What do I do next?
The next step in the flow is to exchange the Authorization Code for an Access Token (which will also include a Refresh Token if you requested offline access). If you use the https://developers.google.com/oauthplayground/ to execute the flow manually, you'll be able to see the URLs involved. There is a php library call to do the same thing, but I personally prefer to send my own HTTP rather than use a library. Even if you do use a library, it will still be worth spending a little time to understand the HTTP flow so you can more easily debug any problems you encounter.
Basically I was approaching wrongly. Following these instructions is enough to get the tokens:
https://developers.google.com/gmail/api/quickstart/php
The main point is to access the file from the command line and not from the app.
I made a Oauth Gmail some months ago, I got something like this :
In my callback function :
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
return $this->redirect($auth_url);
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = Router::url('/', true).'Users/gmail';
return $this->redirect($redirect_uri);
}
And in my gmail() function :
public function gmail(){
require APPLIBS.'Google/src/Google'.DS.'autoload.php';
$client = new Google_Client();
$client->setAuthConfigFile('../Config/client_secrets.json');
$client->addScope(Google_Service_Oauth2::PLUS_LOGIN);
$client->addScope(Google_Service_Oauth2::USERINFO_EMAIL);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$oauth_service = new Google_Service_Oauth2($client);
$data['Profile']['last_name'] = $oauth_service->userinfo->get()->familyName;
}
}
$data['Profile']['last_name'] contain the last_name of the user, for example.
Related
I am trying to get a refresh token for the Google API's, using the PHP SDK. I am authenticating the user with Javascript, retrieving a code, and exchanging it for an access_token server side, but this doesn't grant me an access token. What am I doing wrong? Here is the code I use:
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->addScope('https://www.googleapis.com/auth/plus.me');
$client->addScope('https://www.google.com/m8/feeds');
$client->setRedirectUri('postmessage');
$client->setAccessType('offline');
if (isset($_REQUEST['code'])) {
$client->authenticate($_REQUEST['code']);
if ($client->getAccessToken()) {
$_SESSION['access_token'] = $client->getAccessToken();
$token_data = $client->verifyIdToken()->getAttributes();
$result['data']=$token_data;
$result['access_token']=json_decode($_SESSION['access_token']);
}
}
debug($result); //my own function, var_dumps the content of an array
Here is the result of the array:
$result['access_token'] contains:
access_token: TOKEN
created: 1434380576
expires_in: 3594
id_token: IDTOKEN
token_type:"Bearer"
If I am not mistaken the first access token should also contain the refresh token, what am I doing wrong?
First check the settings in the developer console of Google to see if your RedirectUri is the same and that the API is activated (although if you already got that .json, then I assume it is.
You have to go through the Google Auth Prompt Screen at least 1 time to get a refresh token in your .json, and if your RedirectUri is taking you nowhere, you won't be able to get your refresh token or even the access validated.
You can also try a service account if you're doing small file transactions and don't need a user validation for the process of your script. Good Luck.
The problem was that I had to specify that I want offline access in the authentication process, the client side... The Google API's are horribly documented!!!
I am novice to Google Analytics Api. I just started working on a small project where I want to pull data from the API and display it on each user’s Dashboard, using one single Google Analytics Account. I tried to follow the tutorial provided by google and made adjustments where required due to update to the library.
I am working on a codeigniter based platform and I was able to create a Google Client Object and also to make use of a refresh token which is saved in the database. I use the refresh token in order to have the data available on the dashboard without having to manually login every time.
The access token is there every time when I am logged in, and I can use it to set the client access token and create a Google Service Analytics object ($service = new Google_Service_Analytics($client);). I am printing the service and I can see the client id, client secret, etc and the access token being passed to it; but other like Google_Service_Analytics_DataGa_Resource Object are empty ( I do not know if they should be like that or not at this particular step ?).
When I am trying to request the user accounts
$accounts = $analytics->management_accounts->listManagementAccounts();,
I get a blank screen and my view is not being rendered.
I could not find such a problem being encountered before, so I am a bit confused why is happening. I do not get any error messages or anything that might point me to the cause of it or the right direction.
Note: I did managed to make it work using the same credentials trough JavaScript, but in this case it is not what I am looking for. I was able to retrieve data, display data in charts,etc using JS. I am new to making posts, so if anything is required from my part in order for you to have a better idea of what is going on, please do let me know.
I would greatly appreciate it I could get any indication to why that might be happening, or anything that would put me on the right path.
Codeigniter controller Class as follows
// Step 1 - Load PHP Client Libraries
require_once APPPATH.'libraries/Google/Client.php';
require_once APPPATH.'libraries/Google/Analytics.php';
class GoogleTest extends CI_Controller {
public function index(){
$this->load->helper(array('url','form'));
$this->load->model('googleapi_model'); //used to get the refresh token
// Step 2 - Start a session to persist credentials
session_start();
// Step 3 - Create and configure a new client object
$client = new Google_Client();
$client->setApplicationName("API Project");
// Insert client id, api key, client secret, project scope and redirect uri
$client->setDeveloperKey("***************");
$client->setClientId('********************');
$client->setClientSecret('******************');
$client->setRedirectUri('****************');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
// Check if refresh token exists, it is used to login users automatically & it is being generated only once when you login the first time from the created
// google analytics app, this will take precedence to Step 4 or 6 below ;
if(count($this->googleapi_model->getGoogleRefreshToken()) > 0){
$db_refresh_token = $this->googleapi_model->getGoogleRefreshToken();
$client->refreshToken($db_refresh_token[0]->refreshtoken);
$_SESSION['token'] = $client->getAccessToken();
}else{
if ($client->getAccessToken()) {
$token = $client->getAccessToken();
$authObj = json_decode($token);
$refreshToken = $authObj->refresh_token;
if(isset($refreshToken) && $refreshToken != null){
$this->googleapi_model->insertGoogleRefreshToken($refreshToken);
}
}
}
//Step 4 - Handle authorization flow from the server
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST']. $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 5 - Retrieve and use stored credentials
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Stept 6 - Either prompt the user to login or run the demo
if(!$client->getAccessToken()){
$authUrl = $client->createAuthUrl();
$this->data['auth'] = $authUrl;
}else{ //Create analytics service object
echo 'authenticated';
$analytics = new Google_Service_Analytics($client);
//TILL HERE MY CODE WORKS FINE, NO ERRORS, VIEW BEING RENDERED
$accounts = $analytics ->management_accountSummaries->listManagementAccountSummaries();
// $accounts = $analytics->management_accounts->listManagementAccounts();
echo '<pre>';
print_r($analytics);
echo '</pre>';
}
$this->data['content'] = '/public/dashboard/google_test';
$this->load->view('template/template', $this->data);
}
Make sure you're logged into the google account that API app is in.
And that you have clicked 'connect'.
Then run the script.
Also turn on error reporting (including notices)
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.
I want to write a PHP script that imports web stats data from GA. The script is accessible through a web front end (for triggering the import) and resides on a local server (127.0.0.1).
As I understood from the documentation is that there are two options for authenticating and using the core API:
API key - grants only access to statistics
OAuth2 - full authorization
If I understand the mechanics of OAuth2 correctly then this is not an option in my scenario because I cannot specify a callback URL. Hacky solutions come to my mind - like establishing a web profile authentication directly connecting to GA from the browser and then fetching the data by JavaScript and feeding it to the import script - but I would prefer to refrain from such solutions. Also because the browser interaction triggering the import process might be substituted with a cron job in the future.
The API key seems to be exactly what I want but the GET request from the browser fails.
GET request:
https://www.googleapis.com/analytics/v3/data/ga
?ids=ga:[profile ID]
&start-date=2013-01-01&end-date=2013-01-05
&metrics=ga:visits
&key=[the API key]
Response:
{
error: {
errors: [
{
domain: "global",
reason: "required",
message: "Login Required",
locationType: "header",
location: "Authorization"
}
],
code: 401,
message: "Login Required"
}
}
The URL though should be fine. Except for the key parameter it is the same as the one generated with http://ga-dev-tools.appspot.com/explorer/ which is also working (AOuth2 is used in that case). The API key is fresh.
Then again generating a new API key confronts me with the next inconveniency which is that apparently the key is only valid for a day.
So at the end of the day my question is this:
Is it possible to fetch data in the above described scenario without having to authenticate manually or generate API keys on a daily basis?
As already suggested, use this library: https://code.google.com/p/google-api-php-client/
but, instead of using oauth, create a service account from the api console (just select server application). This will provide you with a client id, an email that identify the service account, and *.p12 file holding the private key.
You then have to add the service account (the email) to your analytics as an admin user in order to get the data you need.
To use the service:
$client = new Google_Client();
$client->setApplicationName('test');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
EMAIL,
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents(PRIVATE_KEY_FILEPATH)
)
);
$client->setClientId(CLIENT_ID);
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
To get some data:
$analytics->data_ga->get(PROFILE_ID, $date_from, $date_to, $metrics, $optParams)
For the details check api docs. Also, be careful, there is a query cap (unless you pay)
I think to get this working, you need to use OAuth but with a slight modification to run it from server. Google calls this auth method "Using OAuth 2.0 for Web Server Applications"
As described on that page, you can use a PHP client library to get the authentication done. The client library is located here.
An example example on how to use this client library are on the same project's help pages. Note that you'll have to make some modifications to the code as the comments say to store the token in db and to refresh it regularly.
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.php';
// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcached.
session_start();
$client = new Google_Client();
$client->setApplicationName('Google+ PHP Starter Application');
// Visit https://code.google.com/apis/console?api=plus 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_simple_api_key');
$plus = new Google_PlusService($client);
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$activities = $plus->activities->listActivities('me', 'public');
print 'Your Activities: <pre>' . print_r($activities, true) . '</pre>';
// We're not done yet. Remember to update the cached access token.
// Remember to replace $_SESSION with a real database or memcached.
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a href='$authUrl'>Connect Me!</a>";
}
I have a similar setup. The thing that you don't realize is that you can specify a http://localhost or http://127.0.0.1 or anything else as an origin and callback URL. You need to setup some web interface on your local server that initiates an OAuth setup for the user with the GA access. Note that this is one time. The callback handler must be something like this:
Note: The libraries used here are the same as the previous answer, the detailed code is in the wrapper.
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . '/content/business-intelligence';
if (isset($_GET['code'])) {
require_once 'GAPI.php';
$client = GAPI::init(); //create client instance of Google_Client
$client->authenticate(); //convert auth code to access token
$token = $client->getAccessToken();
$retVal = CF_GAPI::persistToken($token); //save token
if($retVal)
$redirect .= "?new_token";
else
$redirect .= "?bad_token";
}
header('Location: ' . $redirect); //redirect to bi index
Once you have saved the token saved, you must set it in the client before making requests to GA to get your analytics data. Like:
try {
$token = GAPI::readToken(); //read from persistent storage
} catch (Exception $e) {
$token = FALSE;
}
if($token == FALSE) {
$logger->crit("Token not set before running cron!");
echo "Error: Token not set before running cron!";
exit;
}
$client = GAPI::init(); //instance of Google_Client
$client->setAccessToken($token);
The GAPI::init() is implemented as follows:
$client = new Google_Client();
$client->setApplicationName(self::APP_NAME);
$client->setClientId(self::CLIENT_ID);
$client->setClientSecret(self::CLIENT_SECRET);
$client->setRedirectUri(self::REDIRECT_URI);
$client->setDeveloperKey(self::DEVELOPER_KEY);
//to specify that the token is stored offline
$client->setAccessType('offline');
//all results will be objects
$client->setUseObjects(true);
//tell that this app will RO from Analytics
$client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
return $client;
My mysql table has columns like id, title, send_to_emails, frequency, dimensions, metrics, filters, profile_id which completely define each report to the generated from GA. You can play around with them using the documentation, list of metrics & dimensions and the sandbox tester that you already know about.
Using Facebook's PHP SDK, I was able to get Facebook login working pretty quickly on my website. They simply set a $user variable that can be accessed very easily.
I've had no such luck trying to get Twitter's OAuth login working... quite frankly, their github material is confusing and useless for someone that's relatively new to PHP and web design, not to mention that many of the unofficial examples I've tried working through are just as confusing or are outdated.
I really need some help getting Twitter login working--I mean just a basic example where I click the login button, I authorize my app, and it redirects to a page where it displays the name of the logged in user.
I really appreciate your help.
EDIT I'm aware of the existence of abraham's twitter oauth but it provides close to no instructions whatsoever to get his stuff working.
this one is the basic example of getting the url for authorization and then fetching the user basic info when once u get back from twitter
<?php
session_start();
//add autoload note:do check your file paths in autoload.php
require "ret/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
//this code will run when returned from twiter after authentication
if(isset($_SESSION['oauth_token'])){
$oauth_token=$_SESSION['oauth_token'];unset($_SESSION['oauth_token']);
$consumer_key = 'your consumer key';
$consumer_secret = 'your secret key';
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
//necessary to get access token other wise u will not have permision to get user info
$params=array("oauth_verifier" => $_GET['oauth_verifier'],"oauth_token"=>$_GET['oauth_token']);
$access_token = $connection->oauth("oauth/access_token", $params);
//now again create new instance using updated return oauth_token and oauth_token_secret because old one expired if u dont u this u will also get token expired error
$connection = new TwitterOAuth($consumer_key, $consumer_secret,
$access_token['oauth_token'],$access_token['oauth_token_secret']);
$content = $connection->get("account/verify_credentials");
print_r($content);
}
else{
// main startup code
$consumer_key = 'your consumer key';
$consumer_secret = 'your secret key';
//this code will return your valid url which u can use in iframe src to popup or can directly view the page as its happening in this example
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
$temporary_credentials = $connection->oauth('oauth/request_token', array("oauth_callback" =>'http://dev.crm.alifca.com/twitter/index.php'));
$_SESSION['oauth_token']=$temporary_credentials['oauth_token']; $_SESSION['oauth_token_secret']=$temporary_credentials['oauth_token_secret'];$url = $connection->url("oauth/authorize", array("oauth_token" => $temporary_credentials['oauth_token']));
// REDIRECTING TO THE URL
header('Location: ' . $url);
}
?>
I just tried abraham's twitteroauth from github and it seems to work fine for me. This is what I did
git clone https://github.com/abraham/twitteroauth.git
Upload this into your webhost with domain, say, www.example.com
Go to Twitter Apps and register your application. The changes that you need are (assuming that you will use abraham's twitteroauth example hosted at http://www.example.com/twitteroauth)
a) Application Website will be http://www.example.com/twitteroauth
b) Application type will be browser
c) Callback url is http://www.example.com/twitteroauth/callback.php (Callback.php is included in the git source)
Once you do this, you will get the CONSUMER_KEY and CONSUMER_SECRET which you can update in the config.php from the twitteroauth distribution. Also set the callback to be the same as http://www.example.com/twitteroauth/callback.php
Thats it. If you now navigate to http://www.example.com/twitteroauth, you will get a "Signin with Twitter", that will take you to Twitter , authorize the request and get you back to the index.php page.
EDIT:
Example will not work but do not worry. Follow the above steps and upload to server.
Make sure you rename the file from github repository i.e. config-sample.php->config.php
if you want to see a working sample, find it here
Here are some OAuth 1.0A PHP libraries with examples:
tmhOAuth
Oauth-php
Twitter async
Twitter async provides documentation on how to simply sign in a user as you asked for.
Here is the step by step guide to integrate Twitter OAuth API to Web-application using PHP. Please following tutorial.
http://www.smarttutorials.net/sign-in-with-twitter-oauth-api-using-php/
You need to create Twitter App First By going thorugh following URL
https://apps.twitter.com/
Then you need to provide necessary information for the twitter app. Once your provided all the information and then save it. You will get Twitter application Consumer Key and Consumer secret.
Please download the source file from above link, and just replace TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET and TWITTER_OAUTH_CALLBACK with your Consumer Key (API Key), Consumer Secret (API Secret) and callback URL. Then upload this to your server. Now it will work successfully.
Abraham's Twitteroauth has a working demo here:
https://github.com/abraham/twitteroauth-demo
Following the steps in the demo readme worked for me. In order to run composer on macOS I had to do this after installing it: mv composer.phar /usr/local/bin/composer
IMO the demo could be a lot simpler and should be included in the main twitteroauth repo.
I recently had to post new tweets to Twitter via PHP using V2 of their API but couldn’t find any decent examples online that didn’t use V1 or V1.1. I eventually figured it out using the great package TwitterOAuth.
Install this package via composer require abraham/twitteroauth first (or manually) and visit developer.twitter.com, create a new app to get the credentials needed to use the API (see below). Then you can post a tweet based on the code below.
use Abraham\TwitterOAuth\TwitterOAuth;
// Connect
$connection = new TwitterOAuth($twitterConsumerKey, // Your API key
$twitterConsumerSecret, // Your API secret key
$twitterOauthAccessToken, // From your app created at https://developer.twitter.com/
$twitterOauthAccessTokenSecret); // From your app created at https://developer.twitter.com/
// Set API version to 2
$connection->setApiVersion('2');
// POST the tweet; the third parameter must be set to true so it is sent as JSON
// See https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets for all options
$response = $connection->post('tweets', ['text' => 'Hello Twitter'], true);
if (isset($response['title']) && $response['title'] == 'Unauthorized') {
// Handle error
} else {
var_dump($response);
/*
object(stdClass)#404 (1) {
["data"]=>
object(stdClass)#397 (2) {
["id"]=>
string(19) "0123456789012345678"
["text"]=>
string(13) "Hello Twitter"
}
}
*/
}