我试图获取 ebay 用户 token 。 我已经在 ebay 上获得了授权码,但无法获得带有授权码的用户 token 。 代码如下:
status := ctx.UserValue("status").(string)
applicationToken := string(ctx.QueryArgs().Peek("code"))
log.Println("ApplicationToken: ", applicationToken)
log.Println("Status: ", status)
if status == "declined" {
fmt.Printf("User doesn't give permission. Go back to your dashboard.")
ctx.Redirect("/dashboard", fasthttp.StatusSeeOther)
}
//var appConfig = config.Config()
client := &http.Client{}
applicationTokenURLEncoded, _ := url.Parse(applicationToken)
body := url.Values{
"grant_type": {"authorization_code"},
"code": {applicationTokenURLEncoded.String()},
"redirect_uri": {Runame},
}
reqBody := bytes.NewBufferString(body.Encode())
log.Println("Reqbody: ", reqBody)
req, _ := http.NewRequest("POST", "https://api.sandbox.ebay.com/identity/v1/oauth2/token", reqBody)
authorization := “AppID” + ":" + “CertID”
authorizationBase64 := base64.StdEncoding.EncodeToString([]byte(authorization))
req.Header.Add("Authorization", "Basic "+authorizationBase64)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
log.Println("Body: ", req)
resp, _ := client.Do(req)
log.Println("resp: ", resp)
log.Println("ResBody: ", resp.Body)
错误是这样的:
Bad Request 400
最佳答案
我看起来消息的格式不正确(这就是服务器返回 400
的原因)。
当你设置你的标题时,你写:
req.Header.Add("Authorization", "Basic "+authorizationBase64)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
Golang 有一个很好的内置方法可以将授权添加到 header :SetBasicAuth
,这是http.Request
的一个方法。
func (r *Request) SetBasicAuth(username, password string)
SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.
With HTTP Basic Authentication the provided username and password are not encrypted.
因此,您可以尝试以下操作,而不是手动设置授权 header :
req.SetBasicAuth("AppID”, “CertID”)
您使用的是 CertID,但我认为您指的是 ClientId 和 ClientSecret - 分别是用户和密码
我不知道这是否是您问题的原因:)。一种帮助找出答案的方法是一致的错误检查,请参阅您的行:
applicationTokenURLEncoded, _ := url.Parse(applicationToken)
关于api - 在 golang 中获取 oauth 用户 token 时出现 400 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43720183/