设置网站限制时出现YouTube API 403错误

时间:2020-07-31 作者:AncientRo

我正在使用YouTube API将最新视频从YouTube频道加载到WordPress:

function load_feed() {
    $url = add_query_arg(
        array(
            \'part\' => \'snippet\',
            \'channelId\' => \'[YouTube channel ID]\',
            \'maxResults\' => 3,
            \'order\' => \'date\',
            \'type\' => \'video\',
            \'key\' => \'[YouTube API key]\'
        ),
        \'https://www.googleapis.com/youtube/v3/search\'
    );

    $response = wp_remote_get(esc_url_raw($url));

    return json_decode(wp_remote_retrieve_body($response), true);
}
在Google开发者的API设置中,一切都很好:

Application restrictions: None
但当我设定时:

Application restrictions: HTTP referrers (web sites)

Website restrictions: www.mysite.com/*
我从API得到以下响应:

{
    "error": {
        "code": 403,
        "message": "Requests from referer https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=[Channel ID]&maxResults=3&order=date&type=video&key=[API key] are blocked.",
        "errors": [
            {
                "message": "Requests from referer https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=[Channel ID]&maxResults=3&order=date&type=video&key=[API key] are blocked.",
                "domain": "global",
                "reason": "forbidden"
            }
        ],
        "status": "PERMISSION_DENIED"
    }
}
API似乎检测到请求来自googleapis.com 而不是来自mysite.com, 在这里,我安装了WP,正在运行上述代码。

为什么会发生此错误,我可以做些什么来修复它?

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

如果通过HTTP引用程序限制应用程序(或API密钥),则远程HTTP请求应包含有效的HTTP_REFERER 标题,其中wp_remote_get() 默认情况下不设置。您可以使用headers 类似于so的参数,其中数组键为referer (请注意,它不是“referer”中的“r”的两倍):

$response = wp_remote_get( esc_url_raw( $url ), array(
    \'headers\' => [ \'referer\' => home_url() ],
) );