Good afternoon everyone! I need to get the estimatedMinutesWatched
parameter from YouTube's Analytics API. I found some examples on the internet, for example this one, and they all used the method:
$api = $analytics->reports->query($id, $start_date, $end_date, $metric, $optparams);
but now you need to pass a single array to the method, which is why I get errors.
I can't figure out which array should be passed to query()
. This is my code:
$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);
$start_date = '2000-01-01';
$end_date = '2021-01-01';
$metrics = 'estimatedMinutesWatched';
$channel_url='https://www.youtube.com/channel/UCqRTXU9O7v3KeJcQuxmEhaA';
$ids = 'channel==' . $channel_url . '';
$analytics = new Google_Service_YouTubeAnalytics($client);
$optparams = array(
'dimensions' => '7DayTotals',
'sort' => 'day',
'ids' => $ids,
'start_date' => $start_date,
'end_date' => $end_date,
'metric'=>$metrics
);
$api = $analytics->reports->query($optparams);
var_dump($api);
die();
The exeption I've got is:
(query) unknown parameter: 'start_date'
I understand that I need to rewrite the query, but really don't know how to do that.
According to the official doc of YouTube Analytics' Reports Query, the name of the date parameters are: startDate
and endDate
(notice the camel case).
Thus your API call should look like:
$analytics = new Google_Service_YouTubeAnalytics($client);
$optparams = array(
'dimensions' => '7DayTotals',
'sort' => 'day',
'ids' => $ids,
'startDate' => $start_date,
'endDate' => $end_date,
'metrics' => $metrics
);
$api = $analytics->reports->query($optparams);
I also corrected the metric
parameter to metrics
.
Do note also that the ids
parameter should contain a specification of form channel == CHANNEL_ID
, but yours is channel == CHANNEL_URL
. Just replace that with:
channel == UCqRTXU9O7v3KeJcQuxmEhaA
or channel == MINE
.
As per the official doc, it is presumed that UCqRTXU9O7v3KeJcQuxmEhaA
is the ID of the channel corresponding to the user that authorized your app during the OAuth 2.0 authentication/authorization flow.