John Davidson

php - Accessing YouTube account for stats from Google Cloud via API


I have a YouTube channel with [email protected] as the manager.
I have set up a Google Cloud account for my domain (Free trial).
I have written OAuth code to access the YT API and activated YT APIs.
I run the code and authenticate as [email protected].
I called:

$youtube = new Google_Service_YouTube($client);
try {
$channel = $youtube->channels->listChannels('snippet', ['mine' => TRUE]);...

and got the exception message: "Unauthorized", "errors": [ { "message": "Unauthorized", "domain": "youtube.header", "reason": "youtubeSignupRequired", "location": "Authorization", "locationType": "header" }

I added [email protected] as a manager on the YT account and clicked the link in the ‘Invitation to access xxx’ email.
This was ok but then gave error referring to which is about G Suite trials.

What is best way to link GC with my YT account?

My Answer:
protected] and I want to access the statistics of my channel using the YouTube Data API from Google Cloud. Here's how you can do it:

1. Create a project on Google Cloud Platform:
- Go to the Google Cloud Console (
- Create a new project and enable the YouTube Data API for that project

2. Generate API key:
- Go to the API & Services > Credentials section in your project
- Create a new API key and copy the key

3. Install the Google API client library for PHP:
- You can install the library using Composer by running the following command:

composer require google/apiclient:^2.0

4. Write PHP code to access YouTube statistics:
- Use the following code snippet to access the statistics of your YouTube channel:

require_once 'vendor/autoload.php';

$client = new Google_Client();

$youtube = new Google_Service_YouTube($client);

$channelId = 'YOUR_CHANNEL_ID';
$response = $youtube->channels->listChannels('statistics', array('id' => $channelId));

$stats = $response->getItems()[0]->getStatistics();

echo 'Total views: ' . $stats->getViewCount() . PHP_EOL;
echo 'Total subscribers: ' . $stats->getSubscriberCount() . PHP_EOL;


5. Replace 'YOUR_API_KEY' with the API key you generated in step 2 and 'YOUR_CHANNEL_ID' with the ID of your YouTube channel.

6. Run the PHP script:
- Save the PHP script in a file and run it using a web server or the PHP command line interface.

By following these steps, you should be able to access the statistics of your YouTube channel using the YouTube Data API from Google Cloud.

Rate this post

3 of 5 based on 3211 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us