草庐IT

php - YouTube API v3 和 php 返回 "The request did not specify any referer"

coder 2024-01-04 原文

我有这个 PHP 代码。

<?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>';
}

如果我没有启用 key 限制,这段代码可以正常工作。但是,如果我启用 key 限制,它会返回...

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.

如何启用 key 限制并使其发挥作用?


我的第二个测试是...

<?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>';
}

此代码适用于 key 限制,但它要求所有 用户使用 oAuth 进行身份验证,只是为了查看播放列表和轨道信息,这对任何访问者都不利。

同样的问题。如何启用 key 限制并使其工作? (无需任何 guest /用户/访客操作。)


推荐人:

最佳答案

这对我有用

$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);

更新(描述我是如何从上面得到代码的):
我从 api 请求“请求未指定任何引用者”收到相同的错误响应。由于环境是本地的,所以我安装了 Charles Web Proxy(如存储库说明中所述 https://github.com/google/google-api-php-client/blob/master/README.md )并检查了请求 header - 然后我注意到引用 header 丢失了。
然后我寻找一种方法将该 header 传递给请求,并注意到 Guzzle HTTP 客户端类有一个选项。
我不确定这是正确的方法还是只是一种 hack,但它对我有用,希望对某人有所帮助。

关于php - YouTube API v3 和 php 返回 "The request did not specify any referer",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41941467/

有关php - YouTube API v3 和 php 返回 "The request did not specify any referer"的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  4. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  5. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  6. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  7. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  8. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  9. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  10. ruby - Ruby 中的隐式返回值是怎么回事? - 2

    所以我开始关注ruby​​,很多东西看起来不错,但我对隐式return语句很反感。我理解默认情况下让所有内容返回self或nil但不是语句的最后一个值。对我来说,它看起来非常脆弱(尤其是)如果你正在使用一个不打算返回某些东西的方法(尤其是一个改变状态/破坏性方法的函数!),其他人可能最终依赖于一个返回对方法的目的并不重要,并且有很大的改变机会。隐式返回有什么意义?有没有办法让事情变得更简单?总是有返回以防止隐含返回被认为是好的做法吗?我是不是太担心这个了?附言当人们想要从方法中返回特定的东西时,他们是否经常使用隐式返回,这不是让你组中的其他人更容易破坏彼此的代码吗?当然,记录一切并给出

随机推荐