I have used oauth process to get the sitemap from google webmaster. and followed the steps to generate refresh token from developer key, but i am not getting the results.
Here is my code:-
$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->setAccessType("offline");
$client->setIncludeGrantedScopes(true);
$client->setApprovalPrompt('auto');
$client->addScope(Google_Service_Webmasters::WEBMASTERS);
$client->setRedirectUri('REDIERCT_URL');
$client->setDeveloperKey('MY-DEVELOPER-KEY');
$client->refreshToken('MYREFRESH-TOKEN');
$client->authenticate('MYREFRESH-TOKEN');
$newtoken = $client->getAccessToken();
$client->setAccessToken($newtoken['access_token']);
$service = new Google_Service_Webmasters($client);
// $search = new Google_Service_Webmasters_Resource_Sitemaps;
$results = $service->sitemaps->get('MYWEBSITE-URL', 'MYSITEMMAP-URL' , $resource = array());
// While printing $results i am getting blank array. Am i doing something wrong?
Please correct me i am missing anything. Thanks in advance.
Related
I am developing a patreon app which can get info from patreon and get tier spots_count and if spots_count is less than 4 than add more spots.
From the help of
API Docs
https://docs.patreon.com/
GitCode https://github.com/Patreon/patreon-php
I have prepared a code
<?php session_start();
require_once __DIR__.'/vendor/autoload.php';
use Patreon\API;
use Patreon\OAuth;
$access_token = $_SESSION['access_token'];
$refresh_token = $_SESSION['refresh_token'];
// Get your campaign data
// $campaign_response = $api_client->fetch_campaign();
// $campaign_id = $campaign_response->get('data.0.id');
// Make an OAuth client
$client_id = 'client_id';
$client_secret = 'client_secret';
$oauth_client = new Patreon\OAuth($client_id, $client_secret);
// Get a fresher access token
$tokens = $oauth_client->refresh_token($refresh_token, null);
print_r($tokens);
$_SESSION['access_token'] = $tokens['access_token'];
$_SESSION['refresh_token'] = $tokens['refresh_token'];
$access_token = $_SESSION['access_token']; // Your Creator Access Token
$refresh_token = $_SESSION['refresh_token'];
$api_client = new Patreon\API($access_token);
// $campaign_response = $api_client->fetch_campaign_details(7510630)['data']['relationships']['tiers']['data'][1];
$campaign_response = $api_client->fetch_campaign_details(campaign_id);
print_r($campaign_response);
I am able to get compaign info and tier_ids but i couldn't find any way to view tier_spots and any way to update that through API.
Please help me with that.
I am receiving an error message when trying to execute youtube analytics API.
A service error occurred: Error calling GET
https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DUCaayLD9i5x4MmIoVZxXSv_g&start-date=2016-08-01&end-date=2016-08-07&metrics=views&dimensions=7DayTotals:
(403) Forbidden
Here is my code:
require_once __DIR__.'\google-api-php-client-1-master\src\Google\autoload.php';
require_once __DIR__.'\google-api-php-client-1-master\src\Google\Client.php';
require_once __DIR__.'\google-api-php-client-1-master\src\Google\Service\YouTube.php';
session_start();
$key = file_get_contents('mykey.json');
$OAUTH2_CLIENT_ID = 'xx-xx-xx';
$OAUTH2_CLIENT_SECRET = 'xxx';
$scope = array("https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtubepartner-channel-audit", "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/yt-analytics.readonly", "https://www.googleapis.com/auth/yt-analytics-monetary.readonly","https://www.googleapis.com/auth/youtubepartner");
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setAccessType('offline');
$client->setAccessToken($key);
$client->setScopes($scope);
if ($client->getAccessToken()) {
//Check to see if our access token has expired. If so, get a new one and save it to file for future use.
if($client->isAccessTokenExpired()) {
//refresh your access token if it's expired
$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);
file_put_contents('mykey.json', $client->getAccessToken());
}
$analytics = new Google_Service_YouTubeAnalytics($client);
$channel_url = 'UCaayLD9i5x4MmIoVZxXSv_g';
$ids = 'channel==' . $channel_url . '';
$end_date = '2016-08-07';
$start_date = '2016-08-01';
$optparams = array(
'dimensions' => '7DayTotals',
);
$metric = 'views';
$api = $analytics->reports->query($ids, $start_date, $end_date, $metric, $optparams);
echo '<pre>';print_r($api);die;
}
I have already enable 'youtube analytic API' and I get the access_token from here
What is wrong with my code ,Or do we need to do some more stuff to get rid from this?
Looking at your code, it seems that you are generating a new access token at the point you save it to file (invalidating the first one).
Try :
if($client->isAccessTokenExpired()) {
//refresh your access token if it's expired
$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);
file_put_contents('mykey.json', $newToken);
}
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.
I'm trying to access the YouTube Analytics API in PHP using OAUTH2. In my scenario, I first retrieve the channel data, which works fine (even with authenticated segments). Then I parse the channel-id in my Analytics-call. The YouTube Analytics API is activated in my Google Developer Console. I end up with the following error:
An client error occurred: Error calling GET https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3D##MY_CHANNEL_ID##&start-date=2014-01-01&end-date=2014-01-25&metrics=views&dimensions=7DayTotals&sort=day: (403) Insufficient Permission
Here's my code. Please note that I added my channel-id manually to make sure it's absolutely correct. As I said: the authentication works for the YouTube Data API, but it fails to connect to the Analytics-API.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$OAUTH2_CLIENT_ID = '##MY_CLIENT_ID##';
$OAUTH2_CLIENT_SECRET = '##MY_SECRET##';
set_include_path('##PATH_TO_CLIENT_LIBRARY##');
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
require_once 'Google/Service/YouTubeAnalytics.php';
session_start();
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$youtube = new Google_Service_YouTube($client);
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$analytics = new Google_Service_YouTubeAnalytics($client);
$id = 'channel==##MY_CHANNEL_ID##';
$start_date = '2014-01-01';
$end_date = '2014-01-20';
$optparams = array(
'dimensions' => '7DayTotals',
'sort' => 'day',
);
$metrics = array(
'views',
'estimatedMinutesWatched',
'averageViewDuration',
'comments',
'favoritesAdded',
'favoritesRemoved',
'likes',
'dislikes',
'shares',
'subscribersGained',
'subscribersLost'
);
$api_response = $metrics;
foreach ($metrics as $metric)
{
$api = $analytics->reports->query($id, $start_date, $end_date, $metric, $optparams);
if (isset($api['rows'])) $api_response[$metric] = $api['rows'][0][0];
}
}
?>
By the way, if anyone has examples of working PHP-scripts using the YouTube Analytics API, I would be very happy if you could share them. I haven't seen a single working example on the entire WWW yet.
I already found the answer myself. The problem was in the line
$client->setScopes('https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly');
Changing this to the line below made the script work:
$client->setScopes(array('https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly'));
I am trying to learn a simple web app (PHP) using Google drive API.
Display list of files in the drive.
Add a new file to the drive.
Code as follows:
<?php
session_start();
$url_array = explode('?', 'http://'.$_SERVER ['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$url = $url_array[0];
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();
$client->setClientId(''); // Kept my id
$client->setClientSecret(''); //kept my key
$client->setRedirectUri($url);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
if (isset($_GET['code'])) {
$_SESSION['accessToken'] = $client->authenticate($_GET['code']);
header('location:'.$url);exit;
} elseif (!isset($_SESSION['accessToken'])) {
$client->authenticate();
}
It works fine till here. The app gets authenticated and redirects back to my app.
Now, I try displaying list of files.
Problem code:
$service = new Google_DriveService($client);
$result = array();
$files = $service->files->listFiles();
$result = array_merge($result, $files->getItems());
print_r($result);
I get this error:
Error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET https://www.googleapis.com/drive/v2/files: (401) Login Required' in C:\wamp\www\Sample\google-api-php-client\src\io\Google_REST.php
Can someone please help in correcting me and also I would be thankful in sharing simple code how to insert a doc.
Add this line after $client->authenticate();:
$client->setAccessToken($accessToken);