How to Get Channel id or url after Google Oauth PHP - php

i am trying to code an application system with youtube login. but i have an issue After i get required authorisation with oauth 2.0 i want to get choosen youtube channel id in a string but i could not do it can somebody please help me.
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setApplicationName("BYTNETWORK");
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/yt-analytics.readonly'
));
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
so after this i want a string like
$channelid = "xxxxx"; to use it in code below
$data = file_get_contents('http://gdata.youtube.com/feeds/api/users/$channelid?alt=json');
$data = json_decode($data, true);
$stats_data = $data['entry']['yt$statistics'];
$medya = $data['entry']['media$thumbnail'];
//yt$username kısmından kanal adı parse edilir
/**********************************************************/
echo "<img src='$medya[url]'></img><br>";
echo "Subscribers: $stats_data[subscriberCount]<br>";
echo "Views: $stats_data[totalUploadViews]<br>";

Using OAUTH 2, you can get a refresh_token and an access_token for the requested scope(s).
If you want to get the YouTube channel-id, for an authorized user, using his access_token, then you send the request:
https://www.googleapis.com/youtube/v3/channels?part=id&mine=true&access_token=HereYourAccessToken
In the request above you need to replace the string "HereYourAccessToken".
The respone is a JSON string. And the channel-id is in the field named: items['id'] (or items.id).
Note, that an access_token expires after 1 hour. If so, then use the refresh_token to obtain a new one,
The refresh_token is valid until revoked by the owner.

Related

Hello guys how can i scrap cookies after login gmail using oauth gmail doc?

i want to grab cookies after gmail oauth check login is true and i can login without password!
i use this script php to check (gmail) but now i want grab cookies after this
save cookie in file cookie.txt
`
<?php
require_once 'vendor/autoload.php';
//google-api-php-client--PHP5.6/
// init configuration
$clientID = 'clientID';
$clientSecret = 'clientSecret ';
$redirectUri = 'redirectUri ';
// create Client Re quest to access Google API
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
// authenticate code from Google OAuth Flow
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token['access_token']);
// get profile info
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
$email = $google_account_info->email;
$name = $google_account_info->name;
// now you can use this profile info to create account in your website and make user logged in.
} else {
echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
}
?>
`
Any idea?
i want scrape the cookies after request checker

how to get contact after google login

I am using google login and use this code for auth
$client = new Google_Client();
$client->setApplicationName("Google OAuth Login Example");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($simple_api_key);
$client->setAccessType('offline');
$client->setScopes(array('https://www.google.com/m8/feeds/',"https://www.googleapis.com/auth/userinfo.email"));
$objOAuthService = new Google_Service_Oauth2($client);
Now here get access token from client and use this access token from fetching user contacts
$accessToken = client->getAccessToken();
if ($client->getAccessToken()) {
$userData = $objOAuthService->userinfo->get();
$_SESSION['access_token'] = $client->getAccessToken();
}
Now i want to login user contact user this api and access token which i have got from during auth of google users
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results=' . $max_results . '&oauth_token=' . $accessToken;
$xmlresponse = curl_file_get_contents($url);
echo 'contact result='.$xmlresponse;
But i got 401 http status and not able to fetch user contact. Please help me how i got login user contact emails using access token which i got during auth .
The correct parameter name is access_token not oauth_token.
try this:
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results=' . $max_results . '&access_token=' . $accessToken;
$xmlresponse = curl_file_get_contents($url);
echo 'contact result='.$xmlresponse;
Note: the google contacts API is an old GData API you wont be able to use the Google php client library to access it. You should look into the Google People API I have found that the data returned is similar to that which is in Google contacts.

PHP - Google Sheets API OAuth2- can't get token

i am trying to create a token/refreshToken so my website will be able to submit data to Google Sheets without asking the end user for permissions and i am struggling with this for few hours now..
I tried many different codes i found on the web + Google's docs and i made some progress but i can't get it to work and i can't figure what i am missing..
At this point i get no error (neither in my logs) but also i don't get any redirect or new window for authorizing the app
<?php
session_start();
require_once('php-google-oauth/Google_Client.php');
include_once('lib/autoload.php');
include_once('php-google-oauth/auth/Google_OAuth2.php');
$CLIENT_ID = 'xxxxxxxxxxxx.apps.googleusercontent.com';
$SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$REDIRECT = 'http://mywebsite.com';
$APIKEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// $KEY = file_get_contents('php-google-oauth/client_secret.json');
$client = new Google_Client();
$client->setApplicationName("Contacts to Google Sheets");
$client->setClientId($CLIENT_ID);
$client->setClientSecret($SECRET);
$client->setRedirectUri($REDIRECT);
$client->setScopes(array('https://spreadsheets.google.com/feeds'));
$client->setAccessType('offline'); // Gets us our refresh token
// Step 1: The user has not authenticated so we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . filter_var($REDIRECT, FILTER_SANITIZE_URL));
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
$token = $client->getAccessToken();
}
echo '<script>console.log("TOKEN: '. $token .'");</script>';
?>
Thanks in advance!
I looked at my code and tried this-
// Step 1: The user has not authenticated so we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
echo 'Click here';
}
and now i do get a token back from Google

Automatically refresh token using google drive api with php script

I followed again THIS TUTORIAL to upload a file on Google Drive with php, directly from my REMOTE SERVER: so I have created new API Project from Google API Console, enabled Drive API service, requested OAuth Client ID and Client Secret, wrote them in a script, then upload it together with Google APIs Client Library for PHP folder to this http://www.MYSERVER.com/script1.php, to retrieve Auth code:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('XXX'); // HERE I WRITE MY Client ID
$drive->setClientSecret('XXX'); // HERE I WRITE MY Client Secret
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$url = $drive->createAuthUrl();
$authorizationCode = trim(fgets(STDIN));
$token = $drive->authenticate($authorizationCode);
?>
When I visit http://www.MYSERVER.com/script1.php I allow authorization and get the Auth code that I can write in a second script. Then I upload it to http://www.MYSERVER.com/script2.php, who looks like:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('X'); // HERE I WRITE MY Client ID
$drive->setClientSecret('X'); // HERE I WRITE MY Client Secret
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$_GET['code']= 'X/XXX'; // HERE I WRITE AUTH CODE RETRIEVED AFTER RUNNING REMOTE script.php
file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$doc = new Google_DriveFile();
$doc->setTitle('Test Drive');
$doc->setDescription('Document');
$doc->setMimeType('text/plain');
$content = file_get_contents('drive.txt');
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
?>
Well, now the file drive.txt is uploaded on my Google Drive and structure of token.json file is a sort of:
{"access_token":"XXX","token_type":"Bearer","expires_in":3600,"refresh_token":"YYY","created":1365505148}
Now, as you can imagine I can call script2.php and upload file until a certain time. Finally, the point is: I don't want the token to expire, I don't want to allow authorization each time it expire (recalling script1.php): I need to call the script2.php periodically during the day, to upload my file automatically, without user interaction. So, what's the best way to automatically refresh the token forever in this context? Do I need another script? Can I add some code to script2.php? or modify the token.json file? And where can I read the time remaining before the token expire? Thanks!
You don't have to periodically ask for an access token. If you have a refresh_token, PHP client will automatically acquire a new access token for you.
In order to retrieve an refresh_token, you need to set access_type to "offline" and ask for offline access permissions:
$drive->setAccessType('offline');
Once you get a code,
$_GET['code']= 'X/XXX';
$drive->authenticate();
// persist refresh token encrypted
$refreshToken = $drive->getAccessToken()["refreshToken"];
For future requests, make sure that refreshed token is always set:
$tokens = $drive->getAccessToken();
$tokens["refreshToken"] = $refreshToken;
$drive->setAccessToken(tokens);
If you want a force access token refresh, you can do it by calling refreshToken:
$drive->refreshToken($refreshToken);
Beware, refresh_token will be returned only on the first $drive->authenticate(), you need to permanently store it. In order to get a new refresh_token, you need to revoke your existing token and start auth process again.
Offline access is explained in detail on Google's OAuth 2.0 documentation.
After messing a lot I got this to work. I am using one file/script to get the offline token and then a class to do stuff with the api:
require_once 'src/Google/autoload.php'; // load library
session_start();
$client = new Google_Client();
// Get your credentials from the console
$client->setApplicationName("Get Token");
$client->setClientId('...');
$client->setClientSecret('...');
$client->setRedirectUri('...'); // self redirect
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
$client->setAccessType("offline");
$client->setApprovalPrompt('force');
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$client->getAccessToken(["refreshToken"]);
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
return;
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
?>
<!doctype html>
<html>
<head><meta charset="utf-8"></head>
<body>
<header><h1>Get Token</h1></header>
<?php
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
$token = json_decode($_SESSION['token']);
echo "Access Token = " . $token->access_token . '<br/>';
echo "Refresh Token = " . $token->refresh_token . '<br/>';
echo "Token type = " . $token->token_type . '<br/>';
echo "Expires in = " . $token->expires_in . '<br/>';
echo "Created = " . $token->created . '<br/>';
echo "<a class='logout' href='?logout'>Logout</a>";
file_put_contents("token.txt",$token->refresh_token); // saving access token to file for future use
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
</body>
</html>
You can load refresh token from file and use it as necessary for offline access:
class gdrive{
function __construct(){
require_once 'src/Google/autoload.php';
$this->client = new Google_Client();
}
function initialize(){
echo "initializing class\n";
$client = $this->client;
// credentials from google console
$client->setClientId('...');
$client->setClientSecret('...');
$client->setRedirectUri('...');
$refreshToken = file_get_contents(__DIR__ . "/token.txt"); // load previously saved token
$client->refreshToken($refreshToken);
$tokens = $client->getAccessToken();
$client->setAccessToken($tokens);
$this->doSomething(); // go do something with the api
}
}
More here: https://github.com/yannisg/Google-Drive-Uploader-PHP

Using Google+ API for PHP -- Need to get the users email

I'm using the Google PHP API. The documentation is rather lackluster... I want to allow users to connect their Google+ information and also use it to sign the users up in my database. In order to do that I need to get the email they use for their google account. I can't seem to figure out how to. It's easy enough in Facebook by forcing the permission when the users connect to my app. Anyone have any idea? This is the code I'm using to grab the users google+ profile and it works fine, except users may not have their email listed there.
include_once("$DOCUMENT_ROOT/../qwiku_src/php/google/initialize.php");
$plus = new apiPlusService($client);
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$me = $plus->people->get('me');
print "Your Profile: <pre>" . print_r($me, true) . "</pre>";
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
Without the users email address, it sort of defeats the purpose of allowing users to signup with Google+ Anyone more familiar with the Google API know how I can get it?
The UserInfo API is now supported by the Google API PHP Client.
Here's a small sample application:
http://code.google.com/p/google-api-php-client/source/browse/trunk/examples/userinfo/index.php
The important bit of the sample is here:
$client = new apiClient();
$client->setApplicationName(APP_NAME);
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setDeveloperKey(DEVELOPER_KEY);
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/plus.me')); // Important!
$oauth2 = new apiOauth2Service($client);
// Authenticate the user, $_GET['code'] is used internally:
$client->authenticate();
// Will get id (number), email (string) and verified_email (boolean):
$user = $oauth2->userinfo->get();
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
print $email;
I'm assuming this snippet was called with a GET request including the authorization code. Remember to include or require apiOauth2Service.php in order for this to work. In my case is something like this:
require_once 'google-api-php-client/apiClient.php';
require_once 'google-api-php-client/contrib/apiOauth2Service.php';
Good luck.
Updated with today's API:
$googlePlus = new Google_Service_Plus($client);
$userProfile = $googlePlus->people->get('me');
$emails = $userProfile->getEmails();
This assumes the following:
You've authenticated the current user with the proper scopes.
You've set up $client with your client_id and client_secret.
Forgive me if I'm missing something, but how do you know what Google account to link them with if you don't have their email address? Usually, you'd prompt the user to enter their Google Account's email in order to find their profile in the first place.
Using OAuth2, you can request permissions through the scope parameter. (Documentation.) I imagine the scopes you want are https://www.googleapis.com/auth/userinfo.email and https://www.googleapis.com/auth/userinfo.profile.
Then, it's a simple matter to get the profile info once you've obtained your access token. (I assume you've been able to redeem the returned authorization code for an access token?) Just make a get request to https://www.googleapis.com/oauth2/v1/userinfo?access_token={accessToken}, which returns a JSON array of profile data, including email:
{
"id": "00000000000000",
"email": "fred.example#gmail.com",
"verified_email": true,
"name": "Fred Example",
"given_name": "Fred",
"family_name": "Example",
"picture": "https://lh5.googleusercontent.com/-2Sv-4bBMLLA/AAAAAAAAAAI/AAAAAAAAABo/bEG4kI2mG0I/photo.jpg",
"gender": "male",
"locale": "en-US"
}
There's got to be a method in the PHP library to make that request, but I can't find it. No guarantees, but try this:
$url = "https://www.googleapis.com/oauth2/v1/userinfo";
$request = apiClient::$io->makeRequest($client->sign(new apiHttpRequest($url, 'GET')));
if ((int)$request->getResponseHttpCode() == 200) {
$response = $request->getResponseBody();
$decodedResponse = json_decode($response, true);
//process user info
} else {
$response = $request->getResponseBody();
$decodedResponse = json_decode($response, true);
if ($decodedResponse != $response && $decodedResponse != null && $decodedResponse['error']) {
$response = $decodedResponse['error'];
}
}
}
Anyway, in the code you posted, just pass the desired scope to createAuthUrl():
else {
$authUrl = $client->createAuthUrl("https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile");
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}

Categories