← Other topics

Google API OAuth - Local URLs for authorized redirect

Video Notes

I was recently building a project that interacts with Google’s YouTube API. When configuring OAuth for the API, you have to indicate a redirect URL that Google will redirect the user after processing an authorization request.

The issue I faced was that it would only allow public top-level domains (TLDs) such as .com, .org, .me, etc. This was not a problem for my application when running in production but in my local development environment, I was running my application with a .test domain extension, which Google would not accept.

To work around this, I used https://redirectmeto.com to create a redirect link: https://redirectmeto.com/https://demo.test.

Redirect locations

Here are the places within the Google Cloud console where you need to specify your doman:

Code example

Here’s my test code using the Google API PHP client:

<?php

session_start();

define('DOC_ROOT', dirname(__FILE__) . '/..');

require_once DOC_ROOT . '/vendor/autoload.php';

$redirectUrl = 'https://redirectmeto.com/https://demo.test';


if(isset($_GET['disconnect'])) {
    $_SESSION['youTubeToken'] = null;
    $_SESSION['code_verifier'] = null;
}

$client = new Google\Client();

# Initialize
$client->setAuthConfig(DOC_ROOT . '/youtube.json');
$client->setRedirectUri($redirectUrl);
$client->addScope("https://www.googleapis.com/auth/youtube");

# If we have a code, handle callback from YouTube
if (isset($_GET['code'])) {
    # Exchange the authorization code for an access token
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code'], $_SESSION['code_verifier']);
    $client->setAccessToken($token);
    $_SESSION['youTubeToken'] = $token;
    header('Location: ' . $redirectUrl);
}

# Check authorization
if (!empty($_SESSION['youTubeToken'])) {
    $client->setAccessToken($_SESSION['youTubeToken']);
    $connected = true;
    if ($client->isAccessTokenExpired()) {
        $_SESSION['youTubeToken'] = null;
        $connected = false;
    }
} else {
    $connected = false;
    $_SESSION['code_verifier'] = $client->getOAuth2Service()->generateCodeVerifier();
    $authUrl = $client->createAuthUrl();
}
?>

<p>
<strong>Status:</strong>
<?php if($connected): ?>
    Authorized. <a href='?disconnect'>Disconnect</a>
<?php else: ?>
    Not authorized.
<?php endif; ?>
</p>

<p>
<?php if(isset($authUrl)): ?>
    <a href='<?php echo $authUrl; ?>'>Authorize with YouTube...</a>
<?php endif; ?>
</p>
If this info helped you out, you can send a tip via PayPal. Thanks for your support!
← Other topics