首页 > 解决方案 > 带有 CURL OAuth 的 Google Search Console API

问题描述

我想使用 CURL 使用 Google Search Console API 获取我们网站页面的月度数据 - 使用的关键字、页面展示次数等。我有一个经过域验证的 Google 帐户。我有一个可以访问 API 的项目和一个 API 密钥。

我已经搜索和测试了几个小时

谷歌文档说我可以使用 API 密钥并将其附加到 URL 的末尾:

https://www.googleapis.com/webmasters/v3/sites/https%3A%2F%2Fwww.example.com%2F/searchAnalytics/query?key={my API key}

我发布到 API 的 JSON 是:

{
"startDate": "2021-04-01",
"endDate\": \"2021-04-30",
"dimensions": ["PAGE","QUERY"]
}

我总是收到一个身份验证错误:“请求缺少所需的身份验证凭据”。

试图了解 OAuth。我只是无法理解它,也无法通过各种“帮助”文章准确解释我所做的事情。我无法确定是否需要以及如何获得教程中提到的授权令牌以便随后请求数据。我迷茫和困惑。

任何人都可以解释如何使用 CURL 来验证对 Google Search Console API 的请求,使用 OAuth 或 API 密钥。

标签: curlgoogle-apigoogle-oauthgoogle-search-console

解决方案


Api 密钥仅用于访问公共数据,您要访问的数据是私有数据。

要访问私有数据,您需要使用 oauth2 来获取访问令牌

# Tutorial https://www.daimto.com/how-to-get-a-google-access-token-with-curl/
# YouTube video https://youtu.be/hBC_tVJIx5w
# Client id from Google Developer console
# Client Secret from Google Developer console
# Scope this is a space seprated list of the scopes of access you are requesting.

# Authorization link.  Place this in a browser and copy the code that is returned after you accept the scopes.
https://accounts.google.com/o/oauth2/auth?client_id=[Application Client Id]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=[Scopes]&response_type=code

# Exchange Authorization code for an access token and a refresh token.

curl \
--request POST \
--data "code=[Authentcation code from authorization link]&client_id=[Application Client Id]&client_secret=[Application Client Secret]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code" \
https://accounts.google.com/o/oauth2/token

# Exchange a refresh token for a new access token.
curl \
--request POST \
--data 'client_id=[Application Client Id]&client_secret=[Application Client Secret]&refresh_token=[Refresh token granted by second step]&grant_type=refresh_token' \
https://accounts.google.com/o/oauth2/token

本视频将引导您了解使用 curl 的 Google OAuth 2.0


推荐阅读