3

I m trying to fetch share count of youtube video using YouTube Analytics API v3. I am using google php client library to upload videos. I am able to find count of likes, dislikes, etc using this url:

https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Nyk_ltlr6pc&key={APP_KEY}

But not able to find any such resource to fetch count of share.

I have seen this post: How to get share count of a youtube video using youtube api?

But I am unable to get anything from this post, as this post is old and it is using YouTube Analytics API v1 compare to current YouTube Analytics API v3.

Kindly guide me. Thank you.

Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
Tony Montana
  • 921
  • 18
  • 46
  • YouTube Analytics API is completely different than YouTube Data API you're using. Share metric is not available publicly, only video's owner may access it. The docs: https://developers.google.com/youtube/analytics/v1/#Parameters – jkondratowicz Apr 27 '16 at 07:38
  • Thanks for reply, I want to fetch share count of videos which are uploaded by me. – Tony Montana Apr 27 '16 at 07:41
  • Then you should familiarize yourself with YT Analytics API and OAuth2 flows. What you're looking for is `shares` metric with `video` filter. – jkondratowicz Apr 27 '16 at 07:43
  • Hey @jkondratowicz, thanks once again. I am trying to fetch count using Google's API explorer, In request I get this `GET https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DUCuF1DUcfn26yoSYlsQ6hfoA&start-date=2016-04-25&end-date=2016-04-27&metrics=shares&key={YOUR_API_KEY}` and in response I got this ` { "kind": "youtubeAnalytics#resultTable", "columnHeaders": [ { "name": "shares", "columnType": "METRIC", "dataType": "INTEGER" } ] }`, but it is not showing any count. – Tony Montana Apr 27 '16 at 08:47
  • This means there is no data to show - for the selected date period, for this channel there were no shares recorded. Note that data in YTA usually appears with 2 day delay. – jkondratowicz Apr 27 '16 at 09:21
  • Ok, for testing purpose I have shared my video today, so in YTA, count of that share will come 2 days later. Am I right? – Tony Montana Apr 27 '16 at 09:34
  • It should. For reference you can always look in the YouTube Analytics app: http://youtube.com/analytics – jkondratowicz Apr 27 '16 at 09:40
  • Hey @jkondratowicz, yeah you were right. I have checked now and now it is showing me share count in API explorer. But according to this link [link](https://developers.google.com/youtube/analytics/v1/#examples), example script to fetch count of shares is not available for PHP language. Do you happen to know, any resource or examples which I can refer? – Tony Montana Apr 28 '16 at 12:56
  • There are numerous resources available on the Internet, you just need to look around. I recommend official Google API PHP client: https://github.com/google/google-api-php-client. – jkondratowicz Apr 28 '16 at 14:26

1 Answers1

2

I know it's late, but still I think I should share the code, so if any need person looking for such functionality similar to this, it would help him.

set_include_path($_SERVER['DOCUMENT_ROOT'] . '/library/Youtube/src/');

require_once 'Google/autoload.php';
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';

session_start();

$startdate = <DATE_WHEN_YOUR_GET_UPLOADED>;
$video_id = <YOUR_VIDEO_ID>;
$video_id = "video==" .$video_id;

$key = file_get_contents('the_key.txt'); //YOUR_ACCESS_TOKEN

$OAUTH2_CLIENT_ID = <YOUR_OAUTH2_CLIENT_ID>;
$OAUTH2_CLIENT_SECRET = <YOUR_OAUTH2_CLIENT_SECRET>;

$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");

try{
    // Client init
    $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('the_key.txt', $client->getAccessToken());
        }

        $analytics = new Google_Service_YouTubeAnalytics($client);

        $channel_id = <YOUR_CHANNEL_ID>;
        $ids = 'channel=='.$channel_id;
        $end_date = date("Y-m-d"); //current date 
        $start_date = startdate; //date when you uploaded your video
        $optparams = array(
            'filters' => $video_id,
        );

        $metric = 'likes,shares'; //what you want to fetch

        $api = $analytics->reports->query($ids, $start_date, $end_date, $metric, $optparams);
        print_r(json_encode($api->rows[0]));

    } else{
        // @TODO Log error
        echo 'Problems creating the client';
    }
}catch (Google_Service_Exception $e) {
    echo sprintf('<p>A service error occurred: <code>%s</code></p>',htmlspecialchars($e->getMessage()));
}

Kindly feel free to review my code and suggest any suitable changes.

Tony Montana
  • 921
  • 18
  • 46
  • Where can I get this access token? which is in the file 'the_key.txt' – Rahul Sep 14 '16 at 11:46
  • @Rahul, check this [link](https://www.domsammut.com/code/php-server-side-youtube-v3-oauth-api-video-upload-guide) for complete tutorial.... – Tony Montana Sep 15 '16 at 11:18
  • I'm already working like same. I already posted a new question in stackoverflow [here](http://stackoverflow.com/questions/39505288/getting-forbidden-error-when-tying-to-excute-youtube-analytic-api) Can you please reply on same. – Rahul Sep 15 '16 at 11:36
  • Also,I think the main problem is with token and API keys,Can you please tell me how to generate refresh token,I don't want login popup(authentication) for my users. – Rahul Sep 15 '16 at 11:38
  • You will have to login only one time, then after that you'll see json output on your screen, copy & paste it into `the_key.txt`file, and then you script will use this file and if required it will replace `access_token` in this file. You have to do it one time only. Let me know, if it works. Kindly go through the link thoroughly. – Tony Montana Sep 15 '16 at 11:47
  • I followed the step in the tutorial above.I got the json output on my screen,but when I tried to use that token in key.txt it gave me same error. [here](http://stackoverflow.com/questions/39505288/getting-forbidden-error-when-tying-to-excute-youtube-analytic-api) – Rahul Sep 15 '16 at 12:26
  • On more thing,It is working fine if I am going to use same snippet of code mentioned in above tutorial for video upload.But I want to fetch last 30 day/7 days channel view etc – Rahul Sep 15 '16 at 12:43
  • @Rahul for video upload, you need to use different script. This script is for fetching youtube analytics. Have you read that post thoroughly? – Tony Montana Sep 15 '16 at 13:25
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/123442/discussion-between-tony-montana-and-rahul). – Tony Montana Sep 15 '16 at 13:33
  • can you please reply me on chat. – Rahul Sep 15 '16 at 14:21