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
Related
I am trying to get facebook page contents using graph api in codeigniter. when I use access token in controller with a get function, I get the contents. But when I try to use graph url in view file, It's showing an error -- " Invalid OAuth access token"
In my controller, I tried this--
$response2 = $this->get('/me?fields=id,name,posts{actions,comments,message}',$accessToken);
echo "<pre>";
print_r($response2);
the get function is--
public function get($params, $accessToken){
try {
$response = $this->fb->get($params, $accessToken);
return json_decode($response->getBody());
} catch(Facebook\Exceptions\FacebookResponseException $e) {
return $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
return $e->getMessage();
}
}
Here I got the result .
but If I try to use it another view file--
<?php
foreach ($h->result() as $row) {
if ($row->social_network == 'facebook') {
$token = $row->token;
$id = $row->pid;
print_r($id);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v15.0/$id?fields=posts%7Bmessage%2Ccomments%2Cactions%7D&access_token=$token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
$result = json_decode($result);
print_r($result);
}
}
?>
Here I am getting the access token from database that I previously stored. Here It shows me an error--
Invalid OAuth access token - Cannot parse access token
How do I make It work?
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
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
I m trying to get access to the linkedin api but like a lot of people, fail everytime and have this following message of error :
missing required parameters, includes an invalid parameter value, parameter more then once. : Unable to retrieve access token : appId or redirect uri does not match authorization code or authorization code expired
I've cheked the hosting server's timestamp and i revoke and create the token on the app admin before i launch the code (the faster i can due to the short life time of the authorization code given).
Here's my index file and just after the functions i use :
<?php
// VARS
define('API_KEY', 'xxxxxxxxxx');
define('API_SECRET', 'xxxxxxxxxx');
define('REDIRECT_URI', 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']);
define('SCOPE', 'r_basicprofile');
session_name('linkedin');
session_start();
include('lib/functions.php');
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
// LinkedIn returned an error
print $_GET['error'] . ': ' . $_GET['error_description'];
exit;
}
elseif (isset($_GET['code'])) {
// User authorized your application
getAccessToken();
}
else {
if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
// Token has expired, clear the state
$_SESSION = array();
}
if (empty($_SESSION['access_token'])) {
// Start authorization process
getAuthorizationCode();
}
}
// Congratulations! You have a valid token. Now fetch your profile
$user = fetch('GET', '/v1/people/~:(firstName,lastName)');
print "Hello $user->firstName $user->lastName.";
?>
And the functions :
<?php
function getAuthorizationCode() {
$params = array('response_type' => 'code',
'client_id' => API_KEY,
'scope' => SCOPE,
'state' => uniqid('', true), // unique long string
'redirect_uri' => REDIRECT_URI
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?'.http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['state'] = $params['state'];
// Redirect user to authenticate
header("Location: $url");
exit;
}
function getAccessToken() {
$params = array('grant_type' => 'authorization_code',
'client_id' => API_KEY,
'client_secret' => API_SECRET,
'code' => $_GET['code'],
'redirect_uri' => REDIRECT_URI
);
var_dump($params);
// Access Token request
//$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
$url = 'https://www.linkedin.com/uas/oauth2/accessToken';
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_POST,true);
curl_setopt($c, CURLOPT_POSTFIELDS, http_build_query($params));
$response = curl_exec($c); // on execute la requete
curl_close($c);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
// DEBUG //
echo 'Retour get access token : </br>';
var_dump($token);
echo '</br>--------------------------</br></br>';
// ! DEBUG //
return true;
}
function fetch($method, $resource, $body = '') {
$params = array('oauth2_access_token' => $_SESSION['access_token'], 'format' => 'json');
// Need to use HTTPS
//$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
// Tell streams to make a (GET, POST, PUT, or DELETE) request
$url = 'https://api.linkedin.com' . $resource;
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_POSTFIELDS,http_build_query($params));
$response = curl_exec($c);
curl_close($c);
// DEBUG //
echo 'Retour fetch : </br>';
var_dump($response);
echo '</br>--------------------------</br></br>';
// ! DEBUG //
// Native PHP object, please
return json_decode($response);
}
?>
I tried many things but it never works. If someone see the issue tnaks a lot in advance.
Thanks
I have faced the same problem and my issue was caused by http_build_query() function, http://www.php.net/manual/en/function.http-build-query.php
for some reason it tries to encode the parameters to build a query string that will be used by the Linkedin services, if you try to construct the string manually it will pass and it will work.
and actually I reached this page while searching to figure out if its a PHP version issue or maybe the function http_build_query() take in account some environment variables like encoding and locale settings.
not sure but this fixed my issue.
Hi i am using a different account for google analytics and is returning an error:
GDataauthErrorAuthorizationInvalid Credentials
Though for my previous account is working fine. it could be because i missed some things in the registration process, could anyone give me a detailed steps for the registration to work for oauth 2.0 using api_key for google analytics v2.4
thank you
//returns session token for multiple calls to API
function get_session_token($onetimetoken) {
$output = call_api($onetimetoken, "https://www.google.com/accounts/AuthSubSessionToken");
if(preg_match("/Token=(.*)/", $output, $matches)) {
$sessionToken = $matches[1];
} else {
echo "Error authenticating with Google.";
exit;
}
return $sessionToken;
}
//gets the data
function call_api($sessionToken,$url){
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
if ($_SESSION['authSub']==true){
$curlheader[0] = sprintf("Authorization: AuthSub token=\"%s\"/n", $sessionToken);
} else {
$curlheader[0] = "Authorization: GoogleLogin auth=" . $sessionToken;
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlheader);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
$requrlvisits = sprintf("https://www.googleapis.com/analytics/v2.4/data?ids=ga:%s&dimensions=ga:date&metrics=ga:visits,ga:pageviews,ga:bounces,ga:timeOnSite&start-date=%s&end-date=%s&sort=ga:date&key=%s",$get_profid[9],$date1,$date2,$api_key);
// echo $requrlvisits;
$visitsxml = call_api($_SESSION['sessionToken'],$requrlvisits);
$visits = parse_data($visitsxml);
print_r($visitsxml);