creatorshub / oauth2-youtube
YouTube OAuth 2.0 Client Provider for The PHP League OAuth2-Client
Requires
- league/oauth2-client: ^2.0
Requires (Dev)
- eloquent/phony: ^0.14.6
- phpunit/phpunit: ^5.7
- satooshi/php-coveralls: dev-master as 2.0.0
- squizlabs/php_codesniffer: ^2.0
This package is auto-updated.
Last update: 2024-10-29 05:10:34 UTC
README
This package provides YouTube OAuth 2.0 support for the PHP League's OAuth 2.0 Client.
This package is compliant with PSR-1, PSR-2 and PSR-4. If you notice compliance oversights, please send a patch via pull request.
Requirements
The following versions of PHP are supported.
- PHP 5.6
- PHP 7.0
- PHP 7.1
- HHVM
Installation
To install, use composer:
composer require creatorshub/oauth2-youtube
Usage
Authorization Code Flow
$provider = new CreatorsHub\OAuth2\Client\Provider\YouTube([
'clientId' => '{google-client-id}',
'clientSecret' => '{google-client-secret}',
'redirectUri' => 'https://example.com/callback-url'
]);
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
// Fetch the authorization URL from the provider; this returns the
// urlAuthorize option and generates and applies any necessary parameters
// (e.g. state).
$authorizationUrl = $provider->getAuthorizationUrl();
// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) {
if (isset($_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
}
exit('Invalid state');
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// We have an access token, which we may use in authenticated
// requests against the service provider's API.
echo 'Access Token: ' . $accessToken->getToken() . "<br>";
echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";
// Using the access token, we may look up details about the
// resource owner.
$resourceOwner = $provider->getResourceOwner($accessToken);
var_export($resourceOwner->toArray());
// You can also use these functions:
$channelId = $resourceOwner->getId();
$channelName = $resourceOwner->getName(); // or $resourceOwner->getTitle();
$channelAvatar = $resourceOwner->getAvatarUrl($size = 'default');
$channelDescription = $resourceOwner->getDescription();
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
// Failed to get the access token or user details.
exit($e->getMessage());
}
}
Refreshing a Token
Refresh tokens are only provided to applications which request offline access. You can specify offline access by setting the accessType
option in your provider:
$provider = new CreatorsHub\OAuth2\Client\Provider\YouTube([
'clientId' => '{google-client-id}',
'clientSecret' => '{google-client-secret}',
'redirectUri' => 'https://example.com/callback-url',
'accessType' => 'offline',
]);
It is important to note that the refresh token is only returned on the first request after this it will be null
. You should securely store the refresh token when it is returned:
$token = $provider->getAccessToken('authorization_code', [
'code' => $code
]);
// persist the token in a database
$refreshToken = $token->getRefreshToken();
If you ever need to get a new refresh token you can request one by forcing the approval prompt:
$authUrl = $provider->getAuthorizationUrl(['approval_prompt' => 'force']);
Now you have everything you need to refresh an access token using a refresh token:
$provider = new CreatorsHub\OAuth2\Client\Provider\YouTube([
'clientId' => '{google-app-id}',
'clientSecret' => '{google-app-secret}',
'redirectUri' => 'https://example.com/callback-url',
]);
$grant = new League\OAuth2\Client\Grant\RefreshToken();
$token = $provider->getAccessToken($grant, ['refresh_token' => $refreshToken]);
Scopes
If needed, you can include an array of scopes when getting the authorization url. Example:
$authorizationUrl = $provider->getAuthorizationUrl([
'scope' => [
'https://www.googleapis.com/auth/youtube', // Manage your YouTube account
'https://www.googleapis.com/auth/youtube.force-ssl', // Manage your YouTube account
'https://www.googleapis.com/auth/youtube.readonly', // iew your YouTube account
'https://www.googleapis.com/auth/youtube.upload', // Manage your YouTube videos
'https://www.googleapis.com/auth/youtubepartner', // View and manage your assets and associated content on YouTube
'https://www.googleapis.com/auth/youtubepartner-channel-audit', // View private information of your YouTube channel relevant during the audit process with a YouTube partner
]
]);
header('Location: ' . $authorizationUrl);
exit;
Testing
$ ./vendor/bin/phpunit
Contributing
Please see CONTRIBUTING for details.
Credits
- Pascal Schwientek
- Woody Gilk (Providing a good starting point with his unit tests)
- All Contributors
License
The MIT License (MIT). Please see License File for more information.