请求GA API时400(错误请求)

时间:2014-02-26 05:19:56

标签: google-analytics google-api

我在尝试访问Google Auth时获得了400 Bad Request。我正在使用本文中的演示代码: https://developers.google.com/analytics/solutions/articles/hello-analytics-api

我要求的地址是: https://accounts.google.com/o/oauth2/auth?client_id=875938******.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.readonly&immediate=true&include_granted_scopes=true&proxy=oauth2relay452650337&redirect_uri=postmessage&origin=http%3A%2F%2Flocalhost%3A8080&response_type=token&state=895891795%7C0.1215960807&authuser=0

我已经成功创建了自己的ClientId和Keys。

我需要照顾什么吗?

谢谢,

1 个答案:

答案 0 :(得分:1)

您的请求有几个问题。首先是范围,第二个是respons_type。我不确定您在链接的页面上找到了哪个示例。您应该尝试找到一个库,以便您使用它的语言将使其更容易。但是如果你想知道你应该发布的确切网址,他们应该看起来像这样。


请求用户允许您访问该帐户的初始URI应如下所示在这种情况下,范围通知我的范围与您的范围不同,我正在请求代码:

https://accounts.google.com/o/oauth2/auth?client_id={clientid}.apps.googleusercontent.com&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code

一旦他们说是,你就可以从上面的请求中获取认证码并将其发回去请求access_token和refresh_token

https://accounts.google.com/o/oauth2/token
code=4/X9lG6uWd8-MMJPElWggHZRzyFKtp.QubAT_P-GEwePvB8fYmgkJzntDnaiAI&client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code

这是回复:

{
  "access_token" : "ya29.1.AADtN_VSBMC2Ga2lhxsTKjVQ_ROco8VbD6h01aj4PcKHLm6qvHbNtn-_BIzXMw",
  "token_type" : "Bearer",
  "expires_in" : 3600,
  "refresh_token" : "1/J-3zPA8XR1o_cXebV9sDKn_f5MTqaFhKFxH-3PUPiJ4"
}

您从上述请求获得的accessstoken是您将用于向服务发出请求的内容。一小时后,您的访问令牌将过期,您将需要请求一个新的访问令牌,您可以使用上面提到的refreshtoken并将其发布到:

https://accounts.google.com/o/oauth2/token
client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&refresh_token=1/ffYmfI0sjR54Ft9oupubLzrJhD1hZS5tWQcyAvNECCA&grant_type=refresh_token

这是回复:

{
  "access_token" : "ya29.1.AADtN_XK16As2ZHlScqOxGtntIlevNcasMSPwGiE3pe5ANZfrmJTcsI3ZtAjv4sDrPDRnQ",
  "token_type" : "Bearer",
  "expires_in" : 3600
}

希望这会有所帮助。

相关问题