Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YouTube API v3 and php returns "The request did not specify any referer"

I have this PHP code.

<?php 

require 'vendor/autoload.php';

$youtube_api_key = 'MY_KEY';

$playlist_id = 'PL3BE743993147F061';

$client = new \Google_Client();
$client->setDeveloperKey($youtube_api_key);
$youtube = new \Google_Service_YouTube($client);

try {
    $playlistResponse = $youtube->playlists->listPlaylists('snippet', array(
        'id' => $playlist_id
    ));
    echo '<pre>'.print_r($playlistResponse, true).'</pre>';
} catch (\Google_Service_Exception $e) {
    $gse_errors = $e->getErrors();
    echo '<h1>error!</h1>';
    echo '<pre>'.print_r($gse_errors, true).'</pre>';
}

If I did not enable Key restriction, this code works fine. But if I enable Key restriction it returns...

The request did not specify any referer. Please ensure that the client is sending referer or use the API Console to remove the referer restrictions.

How to enable Key restriction and make it work?


My 2nd test is...

<?php 

require 'vendor/autoload.php';

session_start();

$youtube_api_key = 'MY_KEY';
$oauth_client_id = 'MY_CLIENT_ID';
$oauth_client_secret = 'MY_CLIENT_SECRET';

$playlist_id = 'PL3BE743993147F061';

//$client = new \Google_Client();
//$client->setDeveloperKey($youtube_api_key);

$client = new Google_Client();
$client->setClientId($oauth_client_id);
$client->setClientSecret($oauth_client_secret);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

$youtube = new \Google_Service_YouTube($client);

$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION[$tokenSessionKey])) {
  $client->setAccessToken($_SESSION[$tokenSessionKey]);
}


try {
    if ($client->getAccessToken()) {
        $playlistResponse = $youtube->playlists->listPlaylists('snippet', array(
            'id' => $playlist_id
        ));
        echo '<pre>'.print_r($playlistResponse, true).'</pre>';
    } else {
        // If the user hasn't authorized the app, initiate the OAuth flow
        $state = mt_rand();
        $client->setState($state);
        $_SESSION['state'] = $state;

        $authUrl = $client->createAuthUrl();
        $htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;
        echo $htmlBody;
    }
} catch (\Google_Service_Exception $e) {
    $gse_errors = $e->getErrors();
    echo '<h1>error!</h1>';
    echo '<pre>'.print_r($gse_errors, true).'</pre>';
}

This code works fine with Key restriction but it required ALL users to authenticate using oAuth just to view the playlist and tracks info which is not good for any visitors at all.

The same question. How to enable Key restriction and make it work? (Without require any guest/user/visitor action.)


referrer:

  • https://developers.google.com/youtube/v3/code_samples/php#set_and_retrieve_localized_playlist_metadata
  • https://developers.google.com/youtube/v3/docs/
like image 844
vee Avatar asked Jan 30 '17 17:01

vee


1 Answers

This worked for me

$referrer = 'my.domain';
$api_key = 'apikey';
$client = new Google_Client();
$client->setDeveloperKey($api_key);

$headers = array('Referer' => $referrer);
$guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), 'headers' => $headers ));        
$client->setHttpClient($guzzleClient);

UPDATE ( to describe how I got to the code from above ):
I was receiving the same error response from the api request "The request did not specify any referrer". As the environment was local I've installed Charles Web Proxy ( as described in the repository instructions https://github.com/google/google-api-php-client/blob/master/README.md ) and have checked the request headers - then I've noticed that the referrer header was missing.
Then I looked for a way to pass that header to the request and noticed that the Guzzle HTTP Client Class had an option for that.
I'm not sure if that's the right way or if it's just a hack but it worked for me and hoped to be helpful for someone.

like image 76
Razvan Dvl Avatar answered Oct 23 '22 23:10

Razvan Dvl