发布时间:2022-08-19 12:27
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo</title>
</head>
<body>
<a href="https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=API_KEY&redirect_uri=http://localhost:8082/callBack&scope=basic">
百度授权页面
</a>
</body>
</html>
2)callback地址需要在OAuth中配置好
3)编写golang服务oauth.go文件,端口是8082;
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
)
// main
func main() {
http.HandleFunc("/", oauth)
err := http.ListenAndServe(":8082", nil)
if err != nil {
log.Fatal(err)
}
}
func oauth(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code") // 获取URL参数
var host = "https://openapi.baidu.com/oauth/2.0/token"
var param = map[string]string{
"grant_type": "authorization_code",
"redirect_uri": "http://localhost:8082/callBack",
"code": code,
"client_secret": "SECRET_KEY",
"client_id": "API_KEY",
}
uri, err := url.Parse(host)
if err != nil {
fmt.Println(err)
}
query := uri.Query()
for k, v := range param {
query.Set(k, v)
}
uri.RawQuery = query.Encode()
response, err := http.Get(uri.String())
if err != nil {
fmt.Println(err)
}
result, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(result))
w.Write([]byte(result))
}
4)执行oauth.go服务
go run oauth.go
点击html页面会跳转到授权,成功后会返回code值
进行授权
根据code可以获取access_token和refresh_token(用于刷新access_token)
3. 根据获取到的access_token就可以去获取用户的信息进行调试
注意:百度开发者平台填写callback后有一定的延时,需耐心等待。