I'm trying to insert card on my glass from an iOS app. In order to do this I've got an iOS app :
NSURL *url = [NSURL URLWithString:#"http://mydomain.com/server.php"];
Then, my server.php send the card to my Glass using the QuickStart project from Google. When I launch this script from my computer, I have to sign in and after it sends my card perfectly. However, when I try it from my iOS App, Google sends me it's Sign In page.
<?php
require_once 'config.php';
require_once 'mirror-client.php';
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_MirrorService.php';
require_once 'util.php';
$client = get_google_api_client();
if (!isset($_SESSION['userid']) || get_credentials($_SESSION['userid']) == null) {
header('Location: ' . $base_url . '/oauth2callback.php');
exit;
} else {
verify_credentials(get_credentials($_SESSION['userid']));
$client->setAccessToken(get_credentials($_SESSION['userid']));
}
$mirror_service = new Google_MirrorService($client);
$new_timeline_item = new Google_TimelineItem();
$new_timeline_item->setText("YoNewFromApp!");
$notification = new Google_NotificationConfig();
$notification->setLevel("DEFAULT");
$new_timeline_item->setNotification($notification);
insert_timeline_item($mirror_service, $new_timeline_item, null, null);
?>
I don't know if it's possible to authenticate my server directly by code to call my API from anywhere without signing in.
Anyone know how to do it ?
I'm totally new with Google Auth and I don't understand the doc. Thx in advance.
Related
I am authenticating via oAuth 2.0, using Google's API PHP Client library from App Engine, in order to retrieve the current user's list of layers in Maps Engine (now called My Maps).
I'm using the following code test.php:
<?php
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/MapsEngine.php';
$client_id = 'zzzzzzzzzzzzzzzzzzzzzzzzzzz';
$client_secret = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setAccessType('online');
$client->setApplicationName('myappname');
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey('rrrrrrrrrrrrrrrrrrrrrrrrrrrrr');
$client->setScopes("https://www.googleapis.com/auth/mapsengine");
$mymaps_service = new Google_Service_MapsEngine($client);
if (isset($_REQUEST['logout']))
{
unset($_SESSION['access_token']);
}
if (isset($_GET['code']))
{
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
echo "<html><body>";
if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
$client->setAccessToken($_SESSION['access_token']);
echo "<p>Access token set OK!</p>";
}
else
{
$authUrl = $client->createAuthUrl();
echo "<p>Could not authenticate.</p>";
echo "<p><a href='$authUrl' target=_blank>Try to authenticate by following this URL</a></p>";
}
if ($client->getAccessToken())
{
$_SESSION['access_token'] = $client->getAccessToken();
echo "<h1>Your Maps Engine Layer List:</h1>";
$layers = $mymaps_service->layers->listLayers(array());
var_dump($layers);
}
else
{
echo "<p>Could not get the Access Token.</p>";
}
echo "</body></html>";
?>
I have created my project, the client id, the secret, the developer key (simple api access key) for maps engine, the layers in maps engine (they are public), have also set up the IPs that can connect to my app in app engine, and the IP range that test.php can authenticate from.
When I deploy test.php, am logged out in the browser and load test.php I immediately get the message:
"Could not authenticate.
Try to authenticate by following this URL
Could not get the Access Token", that is, without the browser displaying Google's account select page.
Then I clic on the "Try to authenticate by following this URL" link and it opens up Google's account selection page. I provide my user and password for the account I know owns the layers in maps engine, and then I get the message:
"Access token set OK!
Your Map Engine Layer List:"
But no layer list appears... as if the $layers variable wouldn't get anything from the listLayers method.
When I try to get the list using the demo at developers.google.com I do get a list of layers OK.
What can I modify in my code in order to get the list of layers my user has access to in Maps Engine?
I am creating website page using Google drive API which do following stuff:--
provide user set of pdf file which is stored in my Google drive without any type of Login / authentication by any means and file are public.
who visit that page and if he/she want to download that file/pdf then he/she can do so just by clicking on it without any signup and login.
i have no idea how to getting started with it...is it necessary to use OAuth 2...
in simple word i want to use google drive as file hosting site to host my file and reach users through website.
please give me your valuable solution...
thanks
For php look here for a full example and video. You have to download the Google Drive API for the programming language you are using. Then use that API to help you auth and access files. Here is an example from Google developers page using PHP
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>
You will want to use the PHP client library located here: https://developers.google.com/api-client-library/php/
You will then want to authenticate against google using auth2.
Then you can make calls to the Drive API https://developers.google.com/drive/v2/reference/ using the PHP client library.
I can't get an offline access token with this code...
Why ?
$client = new Google_Client();
$client->setApplicationName('MyAppName');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$client->setClientId('MyCientID');
$client->setClientSecret('MyClientSecret');
$client->setRedirectUri('http://mydomain.com/googlecallback');
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
$client->setDeveloperKey('MyDeveloperKey');
$plus = new Google_Service_Plus($client);
header('Location: '.$client->createAuthUrl());
This is redirect to the google login page, which ask only for an 1hour access token...
I'm lost in the dark...
Thanks a lot!
EDIT :
here is my login page code :
$client = new Google_Client();
$client->setClientId('qvdsfvqdsf');
$client->setClientSecret('qsdfvqsdf');
$client->setRedirectUri('?a=callback');
$client->setDeveloperKey('qdcQSDCQSD');
$client->setApprovalPrompt('auto');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$plus = new Google_Service_Plus($client);
if($_GET['a'] == 'authorize'){
header('Location: '.$client->createAuthUrl());
}
elseif($_GET['a'] == 'callback' && isset($_GET['code']) && !isset($_GET['error'])){
$client->authenticate($_GET['code']);
if($client->getAccessToken()){
STORE ACCESS TOKEN
}
}
And my API usage :
$client = new Google_Client();
$client->setClientId('qsdfsqd');
$client->setClientSecret('qsdfqsd');
$client->setRedirectUri('qdfq');
$client->setDeveloperKey('sdfvsdf');
$client->setApprovalPrompt('auto');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$plus = new Google_Service_Plus($client);
$client->setAccessToken('STORED ACCESS TOKEN');
$activities = $plus->activities->listActivities('me', 'public', array('maxResults'=>10));
What I am doing wrong ?
You need to have the "http://mydomain.com/googlecallback" URL set as a redirect URI on the application settings page.
The $client->createAuthUrl() method creates the URL to the authentication page. After going to that page and authorizing the application, Google will redirect you back to /googlecallback with a query string param called 'code', which you should pass to the authenticate() method of the client. Only then you'll have access to the token.
Something like this (assuming this is on /googlecallback):
$client = new Google_Client();
$client->setApplicationName('MyAppName');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$client->setClientId('MyCientID');
$client->setClientSecret('MyClientSecret');
$client->setRedirectUri('http://mydomain.com/googlecallback');
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
$client->setDeveloperKey('MyDeveloperKey');
if (empty($_GET['code'])) {
header('Location: '.$client->createAuthUrl());
} else {
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
// save the token somewhere so you can use later
// without having to go to the auth page again
}
Finally got the answer :
Using $client->setApprovalPrompt('force'); was blocking the normal Google token refresh process, while $client->setApprovalPrompt('auto'); do it like a charm.
Thanks.
If a user has previously authenticated against the ClientID without requesting offline mode, and you then request offline mode, it wont give you the refresh token.
The user needs to de-authorize themselves from app and then re-authorize once the app will request offline mode.
I am attempting to retrieve the data from our content experiments from google analytics...
I am using the following code, my creds are good, and have been censored for this post...
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Hello Analytics API Sample');
// Visit https://cloud.google.com/console to generate your
// client id, client secret, and to register your redirect uri.
$client->setDeveloperKey('xxxxx');
$service = new Google_Service_Analytics($client);
try {
$results = $service->management_experiments->listManagementExperiments('xxxx', 'xxxx', 'xxxx');
} catch (apiServiceException $e) {
print 'There was an Analytics API service error ' . $e->getCode() . ':' . $e->getMessage();
} catch (apiException $e) {
print 'There was a general API error ' . $e->getCode() . ':' . $e->getMessage();
}
echo '<pre>';
print_r($results);
echo '</pre>';
I am using the following example ....
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#list
Any ideas on why I am getting a 401 unauthorized? That a login is required?
The problem is that you haven't Authorized access to your data yet. Since you say its only your own data you want to access i sugest you look into a service account. By setting up a service account in Google apis console it will allow you to access your own data with out needing to login and autenticate the code all the time.
Check the following link. Read though Before you begin make sure you do all that.
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#service
Register your application in the Google Developers Console
Authorize access to Google Analytics data.
Create an Analytics service object
You have skiped the first two steps and gone directly to step 3 creating the service object. Once you have done step 1 you can use the following code for step 2.
Here is an example of how to use a service account in php ServiceAccount
That sample project is for the PredictionService not the google analytics service. You need to edit it slightly.
require_once '../../src/Google/Client.php';
require_once '../../src/Google/Service/Analytics.php';
// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = 'INSERT_YOUR_CLIENT_ID';
const SERVICE_ACCOUNT_NAME = 'INSERT_YOUR_SERVICE_ACCOUNT_NAME';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = '/super/secret/path/to/key.p12';
$client = new Google_Client();
$client->setApplicationName("Google Analytics Sample");
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME(Email),
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents(KEY_FILE))
);
$client->setClientId(CLIENT_ID);
$service = new Google_Service_Analytics($client);
Now you have $service that you can use with the rest of your calls. Note: I didnt have time to test that code let me know if it doesnt work and i will give you a hand in fixing it.
I'm trying to get Youtube username via google plus api. I use php Services from Plus ang YT api and I'm using symfony 2. Obtaining access token works ok, and i'm not going to put it here.
There is also no problem with google plus service, after authorization i'm getting all the information that i need. In YT case, i'm getting error :
insufficientPermissions error
So i check my access token scope in here:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ACCESS_TOKEN
and scope of my Access token is only for Google Plus, i'm not able to force the google Api php clinet to make the YT scope aviable too.
Any ideas?
Here is my code :
require_once '../src/google_api_php_client/src/Google_Client.php';
require_once '../src/google_api_php_client/src/contrib/Google_PlusService.php';
require_once '../src/google_api_php_client/src/contrib/Google_YouTubeService.php';
$client = new Google_Client();
$client->setScopes('https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/plus');
$youtube = new Google_YouTubeService($client);
if(!empty($allR['code'])){
$client->setClientId('clientIDxxx');
$client->setClientSecret('SecretXXX');
$client->setRedirectUri('postmessage');
$client->authenticate($allR['code']);
$token = json_decode($client->getAccessToken());
}
First of all, make sure you enabled YouTube Data API v3 rom your devconsole.
Then instead of setting scopes, try setting client id and secret from devconsole.
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// YouTube object used to make all Data API requests.
$youtube = new Google_YoutubeService($client);
$plus = new $youtube = new Google_PlusService($client);