Google OAuth 2.0 for Server to Server PHP return 403 Forbidden

557 Views Asked by At

I tried to update title and description of video on YouTube directly from my PHP application with hardcoded credentials (user shouldn't see anything related with Google service). I created Service account in my project in Developer Console with enabled YouTube Data API v3.

I always get 403 Forbidden without any extra information.

Any idea?

require_once 'google-api-php-client-master/src/Google/autoload.php';

$client_email = '[email protected]';
$private_key = file_get_contents('/key.p12');
$scopes = array('https://www.googleapis.com/auth/youtube');
$credentials = new Google_Auth_AssertionCredentials(
    $client_email,
    $scopes,
    $private_key
);

$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion();
}

$youtube = new Google_Service_YouTube($client);

try {
    $videoId = MY_VIDEO_ID;

    $listResponse = $youtube->videos->listVideos("snippet",
        array('id' => $videoId));

    if (empty($listResponse)) {
        throw new Exception('Can\'t find a video with video id: ' . $videoId);
    } else {
        $video = $listResponse[0];
        $videoSnippet = $video['snippet'];

        $videoSnippet['title'] = NEW_TITLE;
        $videoSnippet['description'] = NEW_DESCRIPTION;

        $updateResponse = $youtube->videos->update("snippet", $video);
    }
}
catch (Exception $e) {
    ...
}

Thanks for your time.

UPDATE - SOLVED

I changed my code to this version (change Authentication type in Google Console Developer to Web Application) and used OAuth 2.0 Playground to Authorize project (set project API client id and client secret in OAuth 2.0 Playground and generate refresh token).

require_once 'google-api-php-client-master/src/Google/autoload.php';

$client = new Google_Client();
$client->setClientId('...');
$client->setClientSecret('...');
$client->setScopes('https://www.googleapis.com/auth/youtube');
$client->refreshToken('...');

$youtube = new Google_Service_YouTube($client);

try {
    $videoId = MY_VIDEO_ID;

    $listResponse = $youtube->videos->listVideos("snippet",
        array('id' => $videoId));

    if (empty($listResponse)) {
        throw new Exception('Can\'t find a video with video id: ' . $videoId);
    } else {
        $video = $listResponse[0];
        $videoSnippet = $video['snippet'];

        $videoSnippet['title'] = NEW_TITLE;
        $videoSnippet['description'] = NEW_DESCRIPTION;

        $updateResponse = $youtube->videos->update("snippet", $video);
    }
}
catch (Exception $e) {
    ...
}
0

There are 0 best solutions below