← Other topics

YouTube API & PHP - OAuth Connection (google-api-php-client)

Video Notes

Click here to go directly to the code...

Guides in this series:

Intro

In the previous parts of this series, we saw examples of interacting with the YouTube API using PHP and the google-api-php-client package. In all of these examples, we only ever retrieved data from the API using an API key.

In this guide, we’re going to dig deeper and set up an OAuth connection with the Google servers so that we can get write access to the YouTube API.

To supplement everything you’re learning in this guide, be sure to also read through the YouTube API developer’s guide to OAuth 2.0 Authorization.

To begin, in the Google Cloud console under APIs & Services, find the OAuth consent screen section.

The first question it will ask you is whether you want to configure your app as Internal or External. For this example, I will choose External.

Choosing Internal or External when setting up OAuth consent screen in the Google Cloud Console

On the page that follows, fill out your app information as prompted.

Under the section Authorized domains I will enter the domain redirectmeto.com because in a later step, I will set my Redirect URI to https://redirectmeto.com/https://demo.test. In my example, using the redirectmeto.com service is necessary because Google will not accept my local testing domain of demo.test. If I were configuring an in-production application with a real world domain (e.g. demo.com), I would enter that instead.

Entering redirectmeto.com as my Authorized Domain in the Google OAuth Consent screen

Scopes

After saving the details of your OAuth Consent Screen, you’ll be asked to specify what Scopes (aka permissions) this OAuth connection will grant.

Click ADD OR REMOVE SCOPES and on the screen that follows filter the results by YouTube and select the scope(s) that correlate with the actions your application will perform.

Setting the scope for you Google OAuth consent screen

If you’re just joining us in this series and have not yet enabled the YouTube Data API service in your account, searching for “YouTube” in Scopes will not yield any results. To address this, locate the YouTube Data API service within the Google cloud console and enable it.

Check off and add the scopes relevant to the actions you will perform with this OAuth connection. Options will include:

  • /auth/youtube Manage your YouTube account
  • /auth/youtube.channel-memberships.creator See a list of your current active channel members, their current level, and when they became a member
  • /auth/youtube.force-ssl See, edit, and permanently delete your YouTube videos, ratings, comments and captions
  • /auth/youtube.readonly View your YouTube account
  • /auth/youtube.upload Manage your YouTube videos
  • /auth/youtubepartner View and manage your assets and associated content on YouTube
  • /auth/youtubepartner-channel-audit View private information of your YouTube channel relevant during the audit process with a YouTube partner

In the upcoming example, we will see how to edit our YouTube videos (title, description, etc.), so I’ll choose the scope /auth/youtube Manage your YouTube account

Test users

After the Scopes screen, you can specify the email addresses of Test users. These users will be able to authenticate your app, so be sure to add your own email for testing purposes.

After saving your Test users, you are finished with setting up your OAuth consent screen. The next step is to generate your OAuth Client credentials...

Create OAuth Client ID

In the Google Cloud console under APIs & Services, find the Credentials section.

Click the + CREATE CREDENTIALS button up top and choose OAuth Client ID.

Set Application Type to Web application.

Give your application a name; I‘ll call mine Demo.

Don’t fill anything in for Authorized JavaScript origins.

Results of completing the above steps:

Create OAuth credentials in Google Cloud console

For Authorized redirect URIs you need to specify the URL that will handle the OAuth response from Google.

In my case, I am running my test code/application from the URL https://demo.test. However, because .test is not a real world domain extension, it won’t let me use this URL:

Google Cloud console only allows TLD (Top Level Domains) for Authorized redirect URIs

To get around this when in development, you can prepend your URL with https://redirectmeto.com like so:

Using RedirectMeTo.com as the Authorized Redirect URI in Google Cloud console

This satisfies the TLD requirement while still being able to use a testing/development URL.

If I was setting this up for a real-world and “in production” application, I would use my actual URL with proper TLD at this step.

With all the detailed filled in click CREATE and your OAuth client will be generated. On the screen that pops up, choose DOWNLOAD JSON.

Rename the resulting file youtube.json and place it somewhere accessible to your website. In my example, I’ll just place it in the root of my application’s directory.

The code

Below is the code from the authentication flow demonstrated in the video:

<?php

session_start();

require_once 'vendor/autoload.php';

use Google\Client;

# Determines where the API server redirects the user after the user completes the authorization flow
# This value must exactly match one of the authorized redirect URIs for the OAuth 2.0 client, which you configured in your client’s API Console Credentials page.
$redirectUrl = 'https://redirectmeto.com/https://demo.test';

# Create an configure client
$client = new Client();
$client->setAuthConfig('youtube.json');
$client->setRedirectUri($redirectUrl);
$client->addScope('https://www.googleapis.com/auth/youtube');


# === SCENARIO 1: PREPARE FOR AUTHORIZATION ===
if(!isset($_GET['code']) && empty($_SESSION['google_oauth_token'])) {
    $_SESSION['code_verifier'] = $client->getOAuth2Service()->generateCodeVerifier();

    # Get the URL to Google’s OAuth server to initiate the authentication and authorization process
    $authUrl = $client->createAuthUrl();

    $connected = false;
}


# === SCENARIO 2: COMPLETE AUTHORIZATION ===
# If we have an authorization code, handle callback from Google to get and store access token
if (isset($_GET['code'])) {
    # Exchange the authorization code for an access token
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code'], $_SESSION['code_verifier']);
    $client->setAccessToken($token);
    $_SESSION['google_oauth_token'] = $token;
    header('Location: ' . $redirectUrl);
}


# === SCENARIO 3: ALREADY AUTHORIZED ===
# If we’ve previously been authorized, we’ll have an access token in the session
if (!empty($_SESSION['google_oauth_token'])) {
    $client->setAccessToken($_SESSION['google_oauth_token']);
    if ($client->isAccessTokenExpired()) {
        $_SESSION['google_oauth_token'] = null;
        $connected = false;
    }
    $connected = true;
}

# === SCENARIO 4: TERMINATE AUTHORIZATION ===
if(isset($_GET['disconnect'])) {
    $_SESSION['google_oauth_token'] = null;
    $_SESSION['code_verifier'] = null;
    header('Location: ' . $redirectUrl);
}
?>

<h1>Demo</h1>
<p>
    <strong>Status:</strong>
    <?php if($connected): ?>
        Authorized. <a href='?disconnect'>Disconnect</a>
    <?php else: ?>
        Not authorized. 
        <a href='<?php echo $authUrl; ?>'>Authorize with YouTube...</a>
    <?php endif; ?>
</p>

What next?

Now that you’ve established an OAuth connection, you’ll be able to alter YouTube data using the API. In the next part of this series we’ll see an example of editing the basic details of a video (title, description, etc.)

If this info helped you out you can say thanks and support future content by clicking my Amazon affiliate link: https://amzn.to/3UtgnYk. If you make a purchase on Amazon within 24 hours of clicking the link I may receive a micro-commission and it costs you nothing extra. Any income from these sales goes directly to supporting me in making new videos and guides. Thank you for your support!

← Other topics