400 (Bad Request) when requesting GA API

后端 未结 1 540
轻奢々
轻奢々 2020-12-22 11:04

I got a 400 Bad Request when trying to access Google Auth. I am using the demo code in this article: https://developers.google.com/analytics/solutions/articles/

相关标签:
1条回答
  • 2020-12-22 11:31

    There are several things wrong with your request. First the scope, second the respons_type. I'm not sure where on the page you linked that you found that example. You should really try and find a library for what ever language you are using it will make it easer. But if you want to know the exact URLs you should be posting they should look something like this.


    The initial URI to request that the user give you access to there account should look like this In this case the scope notice my scope is different then yours and I'm requesting a code:

    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
    

    Once they say yes you take the authentication Code you got from the above request and Post it back to request an access_token and a 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
    

    this is the response:

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

    The accesstoken you get from the above request is what you will be using to make requests to the service. After one hour your access token will have expired you will need to request a new access token you take the refreshtoken that you got above and post it to :

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

    This is the response:

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

    Hope this helps.

    0 讨论(0)
提交回复
热议问题