403- request has insufficient authentication scopes - php

I want to link and view the analytics account linked with Google Adwords.
Procedure used:
Authenticating google account with scopes "Ananlytics and Adwords" with following url
https://www.googleapis.com/auth/adwords
https://www.googleapis.com/auth/analytics
After getting the authentication response creating Google analytics service object.
Google ads link API throwing error "Insufficient Premissions" screenshot attached
Script :
<?php
//function to authenticate google account and create analytics service object
function googleAuth(){
if (!empty($code)) {
$postFields = 'client_id=' . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . '&client_secret=' . Configure::read('GOOGLE_OAUTH_CLIENT_SECRET') . '&code=' . $code . '&grant_type=authorization_code&redirect_uri=' . Configure::read('GOOGLE_OAUTH_REDIRECT_URI');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$Rec_Data = curl_exec($ch);
if (curl_exec($ch) === false) {
return $Rec_Data;
}
$Rec_Data = json_decode($Rec_Data, true);
if (isset($Rec_Data['refresh_token'])) {
try {
$credentials = array('client_id' => Configure::read('GOOGLE_OAUTH_CLIENT_ID'), 'client_secret' => Configure::read('GOOGLE_OAUTH_CLIENT_SECRET'), 'redirect_uris' => array(Configure::read('GOOGLE_OAUTH_REDIRECT_URI')));
$client = new \Google_Client($credentials);
$client->addScope(\Google_Service_Analytics::ANALYTICS_READONLY);
$client->setAccessToken($Rec_Data['access_token']);
// Create an authorized analytics service object.
$analytics = new \Google_Service_Analytics($client);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
die();
}
}
} else {
if (!empty($id)) {
header("Location:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=" . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . "&redirect_uri=" . Configure::read('GOOGLE_OAUTH_REDIRECT_URI') . "&access_type=offline&approval_prompt=force&state=" . $id . "&scope=https://www.googleapis.com/auth/adwords https://www.googleapis.com/auth/analytics");
exit;
}
}
}
//function to fetch linked account list
function adwordsLinkAnalytics($analyticsAuth) {
$this->autoRender = false;
try {
$adWordsLinks = $analyticsAuth->management_webPropertyAdWordsLinks
->listManagementwebPropertyAdWordsLinks('123456', 'UA-123456-1');
} catch (apiServiceException $e) {
print 'There was an Analytics API service error '
. $e->getCode() . ':+' . $e->getMessage();
exit;
} catch (apiException $e) {
print 'There was a general API error '
. $e->getCode() . ':-' . $e->getMessage();
exit;
}
pr($adWordsLinks);
exit;
}
Required result: List of the analytics account linked with adwords account.

You are missing scope to management entities in Google Analytics, please look at this https://developers.google.com/identity/protocols/oauth2/scopes#analytics
Please update your scope with "https://www.googleapis.com/auth/analytics.edit"
My suggested Updates:
function googleAuth(){
if (!empty($code)) {
--------------
---- Your existing script ----
--------------
} else {
if (!empty($id)) {
header("Location:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=" . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . "&redirect_uri=" . Configure::read('GOOGLE_OAUTH_REDIRECT_URI') . "&access_type=offline&approval_prompt=force&state=" . $id . "&scope=https://www.googleapis.com/auth/adwords%20https://www.googleapis.com/auth/analytics%20https://www.googleapis.com/auth/analytics.edit");
exit;
}
}
}
Reference Url: https://developers.google.com/identity/protocols/oauth2/scopes#analytics

Related

Logging in with Google Oauth in PHP without authenticate permission

Am using https://github.com/googleapis/google-api-php-client/releases
Source File :https://github.com/googleapis/google-api-php-client/archive/v2.4.0.zip
to get User details like Username, email, profile picture, user ID, access token, refresh token so on and i was able to get all details with user authenticate permission and saved it to my database.
Google_config.php
require_once 'Google/autoload.php';
//require_once 'client.json';
session_start();
$client = new Google_Client();
$client->setApplicationName("Login with Google Account");
$client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://localhost:8000/ads/login/redirect.php');
//$client->setAuthConfig("client.json");
$client->addScope([
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile"
]);
$client->setAccessType('offline');
$client->setApprovalPrompt ("force");
Redirect.php
if (isset($_SESSION['accessToken'])) {
$client->setAccessToken($_SESSION['accessToken']);
} else if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
$_SESSION['accessToken'] = $access_token;
} else {
header('location : index.php');
}
$oauth = new Google_Service_Oauth2($client);
if ($client->getAccessToken()) {
// Get user profile data from google
$gpUserProfile = $oauth->userinfo->get();
// Initialize User class
$user = new User();
// Getting user profile info
$gpUserData = array();
$gpUserData['oauth_uid'] = !empty($gpUserProfile['id']) ? $gpUserProfile['id'] : '';
$gpUserData['first_name'] = !empty($gpUserProfile['given_name']) ? $gpUserProfile['given_name'] : '';
$gpUserData['last_name'] = !empty($gpUserProfile['family_name']) ? $gpUserProfile['family_name'] : '';
$gpUserData['email'] = !empty($gpUserProfile['email']) ? $gpUserProfile['email'] : '';
$gpUserData['gender'] = !empty($gpUserProfile['gender']) ? $gpUserProfile['gender'] : '';
$gpUserData['locale'] = !empty($gpUserProfile['locale']) ? $gpUserProfile['locale'] : '';
$gpUserData['picture'] = !empty($gpUserProfile['picture']) ? $gpUserProfile['picture'] : '';
$gpUserData['link'] = !empty($gpUserProfile['link']) ? $gpUserProfile['link'] : '';
// Insert or update user data to the database
$gpUserData['oauth_provider'] = 'google';
$userData = $user->checkUser($gpUserData);
// Storing user data in the session
$_SESSION['userData'] = $userData;
// Render user profile data
if (!empty($userData)) {
$output = '<h2>Google Account Details</h2>';
$output .= '<div class="ac-data">';
$output .= '<img src="' . $userData['picture'] . '">';
$output .= '<p><b>Google ID:</b> ' . $userData['picture'] . '</p>';
$output .= '<p><b>Google ID:</b> ' . $userData['oauth_uid'] . '</p>';
$output .= '<p><b>Name:</b> ' . $userData['first_name'] . ' ' . $userData['last_name'] . '</p>';
$output .= '<p><b>Email:</b> ' . $userData['email'] . '</p>';
$output .= '<p><b>Gender:</b> ' . $userData['gender'] . '</p>';
$output .= '<p><b>Locale:</b> ' . $userData['locale'] . '</p>';
$output .= '<p><b>access token:</b> ' . $client->getAccessToken() . '</p>';
$output .= '<p>Click to visit Google+</p>';
$output .= '<p>Logout from Google</p>';
$output .= '</div>';
} else {
$output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
}
} else {
// Get login url
$authUrl = $client->createAuthUrl();
// Render google login button
$output = '<img src="images/google-sign-in-btn.png" alt=""/>';
}
?>
<div class="container">
<!-- Display login button / Google profile information -->
<?php echo $output; ?>
</div>
Now my problem is HOW DOES GOOGLE LOGIN WORKS Because when i use above method it get user authentication and then give back user info.
Where here in https://stackoverflow.com/ when i try to log-in i was able to login with google account with some redirect.
How do i do a login, tried many online solution and google document too.
Any solution would be helpfull.
finally a simple solution here:
if (isset($_GET['code'])) {
try {
$gapi = new GoogleLoginApi();
// Get the access token
$data = $gapi->GetAccessToken(CLIENT_ID, CLIENT_REDIRECT_URL, CLIENT_SECRET, $_GET['code']);
// Get user information
$user_info = $gapi->GetUserProfileInfo($data['access_token']);
} catch (Exception $e) {
echo $e->getMessage();
exit();
}
}
class GoogleLoginApi {
public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {
$url = 'https://www.googleapis.com/oauth2/v4/token';
$curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code=' . $code . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code != 200) {
throw new Exception('Error : Failed to receieve access token');
}
return $data;
}
public function GetUserProfileInfo($access_token) {
$url = 'https://www.googleapis.com/oauth2/v2/userinfo?fields=name,email,gender,id,picture,verified_email';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $access_token));
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code != 200) {
throw new Exception('Error : Failed to get user information');
}
return $data;
}
}

integrating seat seller api using codeigniter .Error: ExceptionRequest failed with code 401: Error: OAUTH verification failed

I have successfully done oauth1.0 authentication for the get methods provided in the api document
http://api.seatseller.travel/docs/interface.html
But I am getting issue in blockticket url in the above document URL : http://api.seatseller.travel/blockTicket. I need to post the parameters along .I have used Oauth1.0 2Leg library in codeigniter.But its giving me the error as :
ExceptionRequest failed with code 401: Error: OAUTH verification
failed.
Take reference of this url for Oauth library. https://github.com/jesstelford/OAuth-PHP
In codeigniter/application/helpers I have created a helper in that I coded
include_once APPPATH . 'libraries/OAuth/OAuthStore.php';
include_once APPPATH . 'libraries/OAuth/OAuthRequester.php';
function getbusUrlPost($url,$data) {
$key = 'key';
$secret = 'secret';
$options = array('consumer_key' => $key, 'consumer_secret' => $secret);
OAuthStore::instance("2Leg", $options);
$method = "POST";
$params =$data;
//var_dump($params);
try
{
// Obtain a request object for the request we want to make
$request = new OAuthRequester($url, $method,$params);
$result = $request->doRequest(0);
// Sign the request, perform a curl request and return the results,
// throws OAuthException2 exception on an error
// $result is an array of the form: array ('code'=>int,
'headers'=>array(), 'body'=>string)
$result = $request->doRequest();
$response = $result['body'];
if ($response !=
'oauth_token=requestkey&oauth_token_secret=requestsecret')
{
echo $response;
}
else
{
ECHO '------';
}
}
catch(OAuthException2 $e)
{
echo "Exception" . $e->getMessage();
}
}
in controller:
<?php
include_once APPPATH . 'libraries/REST_Controller.php';
class BusBooking extends Rest_Controller {
public function get_bus_blockTicket_post() {
if(isset($_REQUEST['availableTripID']) &&
isset($_REQUEST['seatname'])
&& isset($_REQUEST['fare']) &&
isset($_REQUEST['ladiesSeat'])
&& isset($_REQUEST['name']) && isset($_REQUEST['mobile'])
&& isset($_REQUEST['title'])
&& isset($_REQUEST['email']) && isset($_REQUEST['age']) &&
isset($_REQUEST['gender'])){
$url="http://api.seatseller.travel/blockTicket";
$data=array(
'availableTripID'=>$_REQUEST['availableTripID'],
'seatname'=>$_REQUEST['seatname'],
'fare'=>$_REQUEST['fare'],
'ladiesSeat'=>$_REQUEST['ladiesSeat'],
'name'=>$_REQUEST['name'],
'mobile'=>$_REQUEST['mobile'],
'title'=>$_REQUEST['title'],
'email'=>$_REQUEST['email'],
'age'=>$_REQUEST['age'],
'gender'=>$_REQUEST['gender']
);
$sources= getbusUrlPost($url, $data);
}
}
I have also tried with curl. But getting same error.Check the following code with curl.
function getBusblock($data) {
$url="http://api.seatseller.travel/blockTicket";
$header[]= 'Content-Type: application/x-www-form-urlencoded';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('oauth_consumer_key'=>"key",'oauth_signature_method'=>"HMAC-
SHA1",'oauth_timestamp'=>'1557752217','oauth_nonce'=>'5cd969995be23','oauth_version'=>'1.0','oauth_signature'=>'DsMdvOOUI57VTkx5VQokUmi9rvw%3D&'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if(curl_error($ch))
{
echo 'error:' . curl_error($ch);
}
echo "<pre>";
echo json_encode($result);
echo "</pre>";
exit;
}
Please help me.I have tried much but I am getting Oauth verification failed issue.
I am expecting response in json format with all the ticket details .But getting this output :
ExceptionRequest failed with code 401: Error: OAUTH verification failed.
when hitted webservice with postman.
Use
CURLOPT_HTTPHEADER
instead of
CURLOPT_POSTFIELDS

Cant receive an access token in Stripe

I'm new at Stripe integration. I've read the API documentation for Stripe and here is the OAuth flow. But I still don't receive any OAuth access token. Can someone explain how can I receive an access token? Thanks!
if (isset($_GET['code'])) { // Redirect w/ code
$code = $_GET['code'];
$token_request_body = array(
'grant_type' => 'authorization_code',
'client_id' => 'ca_32D88BD1qLklliziD7gYQvctJIhWBSQ7',
'code' => $code,
'client_secret' => ''
);
$req = curl_init(TOKEN_URI);
curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
curl_setopt($req, CURLOPT_POST, true );
curl_setopt($req, CURLOPT_POSTFIELDS, http_build_query($token_request_body));
// TODO: Additional error handling
$respCode = curl_getinfo($req, CURLINFO_HTTP_CODE);
$resp = json_decode(curl_exec($req), true);
curl_close($req);
echo $resp['access_token'];
} else if (isset($_GET['error'])) { // Error
echo $_GET['error_description'];
} else { // Show OAuth link
$authorize_request_body = array(
'response_type' => 'code',
'scope' => 'read_write',
'client_id' => 'ca_32D88BD1qLklliziD7gYQvctJIhWBSQ7'
);
$url = AUTHORIZE_URI . '?' . http_build_query($authorize_request_body);
echo "<a href='$url'>Connect with Stripe</a>";
}
You should use an OAuth 2.0 client library for this instead of attempting to roll this yourself as suggested by Stripe:
https://stripe.com/docs/connect/standalone-accounts#sample-code
There are many of these, but this is a pretty good option:
https://github.com/thephpleague/oauth2-client
You could modify this example and retrieve the account ID like so:
$provider->getResourceOwner($accessToken)->getId();
Once you retrieve the account ID, you'd store and use this to authenticate as the connected account as suggested by Stripe:
https://stripe.com/docs/connect/authentication#authentication-via-the-stripe-account-header
they actually have, what seems like, an official github library
and they have an example for the oauth thing
just missing in the docs for whatever reason...
https://github.com/stripe/stripe-php/blob/master/examples/oauth.php
in case they delete it, i include the file here, note: they make use of their library, so you have to install it prior to this to work
<?php
require('../init.php');
\Stripe\Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
\Stripe\Stripe::setClientId(getenv('STRIPE_CLIENT_ID'));
if (isset($_GET['code'])) {
// The user was redirected back from the OAuth form with an authorization code.
$code = $_GET['code'];
try {
$resp = \Stripe\OAuth::token([
'grant_type' => 'authorization_code',
'code' => $code,
]);
} catch (\Stripe\Error\OAuth\OAuthBase $e) {
exit("Error: " . $e->getMessage());
}
$accountId = $resp->stripe_user_id;
echo "<p>Success! Account <code>$accountId</code> is connected.</p>\n";
echo "<p>Click here to disconnect the account.</p>\n";
} elseif (isset($_GET['error'])) {
// The user was redirect back from the OAuth form with an error.
$error = $_GET['error'];
$error_description = $_GET['error_description'];
echo "<p>Error: code=" . htmlspecialchars($error, ENT_QUOTES) . ", description=" . htmlspecialchars($error_description, ENT_QUOTES) . "</p>\n";
echo "<p>Click here to restart the OAuth flow.</p>\n";
} elseif (isset($_GET['deauth'])) {
// Deauthorization request
$accountId = $_GET['deauth'];
try {
\Stripe\OAuth::deauthorize([
'stripe_user_id' => $accountId,
]);
} catch (\Stripe\Error\OAuth\OAuthBase $e) {
exit("Error: " . $e->getMessage());
}
echo "<p>Success! Account <code>" . htmlspecialchars($accountId, ENT_QUOTES) . "</code> is disconnected.</p>\n";
echo "<p>Click here to restart the OAuth flow.</p>\n";
} else {
$url = \Stripe\OAuth::authorizeUrl([
'scope' => 'read_only',
]);
echo "Connect with Stripe\n";
}

Google Calendar API using refresh token

I have a php app on my site that allows my users to schedule/reschedule calendar events using one of my google calendars, so I don't need the users to authenticate themselves with google. I have worked through getting a token and stored a refresh token but now when I try to access calendar I get an error that says my token has expired. The output is
creating a client
found access token = { "access_token" : "long...token...string", "token_type" : "Bearer", "expires_in" : 3600 }
An error occurred: (0) The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.
Not sure why I'm getting this error.
function getAccessToken(){
$tokenURL = 'https://accounts.google.com/o/oauth2/token';
$postData = array(
'client_secret'=>'My-Secret',
'grant_type'=>'refresh_token',
'approval_promt'=> 'force',
'refresh_token'=>'My-Refresh-Token',
'client_id'=>'My-Client-ID'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$tokenReturn = curl_exec($ch);
return $tokenReturn;
}
function outputCalendarByDateRange($client, $startDate='2007-05-01', $endDate='2007-08-01'){
date_default_timezone_set("America/Chicago");
$client->addScope('https://www.googleapis.com/auth/calendar');
try {
$service = new Google_Service_Calendar($client);
}catch(Google_ServiceException $e){
print "Error code :" . $e->getCode() . "\n";
print "Error message: " . $e->getMessage() . "\n";
} catch (Google_Exception $e) {
print "An error occurred: (" . $e->getCode() . ") " . $e->getMessage() . "\n";
}
$optParams = array(
'orderBy'=>'starttime',
'singleEvents'=>False,
'timeMax'=>$endDate,
'timeMin'=>$startDate,
'timeZone'=>'America/Chicago',
'maxResults'=>1000
);
try{
$events = $service->events->listEvents('primary',$optParams);
} catch (Google_ServiceException $e) {
print "Error code :" . $e->getCode() . "\n";
print "Error message: " . $e->getMessage() . "\n";
} catch (Google_Exception $e) {
print "An error occurred: (" . $e->getCode() . ") " . $e->getMessage() . "\n";
}
foreach ($events->getItems() as $event) {
echo $event->getSummary();
}
}
echo "creating a client<br>";
$client = new Google_Client();
$accessToken = getAccessToken();
echo "found access token = ".$accessToken."<br>";
try{
$client->setAccessToken($accessToken);
}
catch (Google_ServiceException $e) {
print "Error code :" . $e->getCode() . "\n";
print "Error message: " . $e->getMessage() . "\n";
} catch (Google_Exception $e) {
print "An error occurred: (" . $e->getCode() . ") " . $e->getMessage() . "\n";
}
outputCalendarByDateRange($client, $today, $tomorrow);
You should consider doing this with a service account. A service account will allow your application to access your Google Calendar data without prompting a user for access.
When you create the service account take the email address it gives you and add it like you would any other user to your Google Calendar. The script will then have access to it.
<?php
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com';
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/calendar.readonly";
$cred = new Google_Auth_AssertionCredentials(
$Email_address,
array($scopes),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Calendar($client);
?>
<html><body>
<?php
$calendarList = $service->calendarList->listCalendarList();
print_r($calendarList);
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo "<a href='Oauth2.php?type=event&id=".$calendarListEntry->id." '>".$calendarListEntry->getSummary()."</a><br>\n";
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
?>
</html>
Code ripped from tutorial Google Calendar API with PHP – Service Account

message and video sharing youtube php

i want to get user's inbox of youtube and send a video messsage. below is the code i am using to retrieve inbox. inbox comes shows that inbox of user XXXX but inbox is empty, no messages comes. while i have four video messages in my inbox.
$developer_key='REPLACE_ME';
$client_id= 'REPLACE_ME';
$client_secret='REPLACE_ME';
// error checking; user might have denied access
if (isset($_GET['error'])) {
if ($_GET['error'] == 'access_denied') {
echo('You have denied access. Click here to retry…');
} else {
echo("An error has occurred: ". $_GET['error']);
}
exit;
}
// Step 1: redirect to google account login if necessary
if(!isset($_GET['code']) || $_GET['code'] === '') {
Header('Location: https://accounts.google.com/o/oauth2/auth?client_id='. $client_id .
'&redirect_uri=http://localhost:8080/Test/sendMessage.php' .
'&scope=https://gdata.youtube.com&response_type=code&access_type=offline',
true, 307);
exit;
}
$authorization_code= $_GET['code'];
// Step 2: use authorization code to get access token
$url = "https://accounts.google.com/o/oauth2/token";
$message_post= 'code='. $authorization_code .
'&client_id='. $client_id .
'&client_secret='. $client_secret .
'&redirect_uri=http://localhost:8080/Test/sendMessage.php' .
'&grant_type=authorization_code';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
echo "<pre>";
echo "<br><br> message_post : ";
print_r($result);
if ($cur_error= curl_error($ch)) {
echo($cur_error);
curl_close($ch);
exit;
}
curl_close($ch);
$jsonArray= json_decode($result, true);
if ($jsonArray === null) {
echo("Could not decode JSON.");
exit;
}
if (isset($jsonArray['error'])) {
echo("An error has occurred: ". $jsonArray['error']);
exit;
}
if (!isset($jsonArray['access_token'])) {
echo("Access token not found.");
exit;
}
//The user's authentication token
$access_token= $jsonArray['access_token'];
$title ='krishna'; //The title of the caption track
$lang = 'en'; //The languageof the caption track
//$transcript = $_REQUEST['transcript']; //The caption file data
$inboxUrl ='https://gdata.youtube.com/feeds/api/users/default/inbox?alt=json&&key=AIzaSyBeh0Aevex7q3iRIY5bV3N9gx0WAkNBMi4&access_token=' . $access_token;
echo $inboxUrl . "<br />";
$homepage = file_get_contents($inboxUrl);
echo "file content : <pre>";
print_r($homepage);
YouTube's video responses feature has been retired as explained in
this announcement. While existing video responses are still available,
YouTube no longer supports the ability to retrieve a list of video
responses for a video, to upload new video responses, or to delete
video responses, though you can delete the video that was used in a
video response. Consequently, these functions are also no longer
supported in the API.
https://developers.google.com/youtube/2.0/developers_guide_protocol_video_responses

Categories