1. 程式人生 > 其它 >Golang語言呼叫百度帳號

Golang語言呼叫百度帳號

1:你要註冊一個開發者,建立應用,填寫完基本資訊之後就要填寫回調地址了

2:選擇右上角的管理控制檯---選擇左下角的 其他API -- 選擇安全設定--授權回撥頁

3:測試程式碼

如下:

package main

import (
    // 自己引包
)

type AccessToken struct {
    AccessToken string `json:"access_token"`
    ExpiresIn    int     `json:"expires_in"`
    SessionSecret        string    `json:"session_secret"`
    SessionKey    string    `json:"session_key"`
    Scope    string    `json:"scope"`
}

type UserInfo struct {
    UserId string `json:"userid"`
    UserName string `json:"username"`
}
 
func main() {
    r := mux.NewRouter()
    r.HandleFunc("/listview", listView)
    r.HandleFunc("/upload", upload)
    r.HandleFunc("/down", down)
    r.HandleFunc("/social/oauth/callback", index)
    http.Handle("/", r)
    err := http.ListenAndServe(":5555", nil)
    if err != nil {
        panic(err)
    }
}

type User struct {
    Name string
}

func listView(w http.ResponseWriter, r *http.Request) {
    if r.Method == "GET" {
        t, err := template.ParseFiles("./html/list.html")
        if err != nil {
            panic(err)
        }
        items := make([]*User, 0)
        u1 := &User{"u1"}
        u2 := &User{"u2"}
        items = append(items, u1)
        items = append(items, u2)        
        l := make(map[string]interface{})
        images := []string{}
        images = append(images, "A")
        images = append(images, "B")
        images = append(images, "C")
        l["images"] = items
        l["aaaa"] = images
        t.Execute(w, l)
    }
}

func index(w http.ResponseWriter, r *http.Request) {
    code := r.FormValue("code")
    item, err := getAccess_token(code, "自己的key", "自己的", "http://www.yingyutwo.com:5555/social/oauth/callback")
    if err != nil {
        fmt.Println("err="+err.Error())
        return
    }
    userinfo, err := getUserInfo(item.AccessToken)
    if err != nil {
        fmt.Println("err="+err.Error())
        return
    }
    fmt.Printf("item=%#vn", userinfo)
    fmt.Println("ok index")
}

//獲取access——token
func getAccess_token(code, client_id, client_secret, redirect_uri string) (*AccessToken, error) {
    url := "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code="+code+"&client_id="+client_id+"&client_secret="+client_secret+"&redirect_uri="+redirect_uri
    resp, err := http.Get(url)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }
    accesstoken := &AccessToken{}
    err = json.Unmarshal(body, accesstoken)
    return accesstoken, err
}


//獲取當前登入使用者資訊
func getUserInfo(access_token string) (*UserInfo, error)  {
    url := "https://openapi.baidu.com/rest/2.0/passport/users/getInfo?access_token="+access_token
    resp, err := http.Get(url)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }
    user := &UserInfo{}
    err = json.Unmarshal(body, user)
    return user, err
}
頁面list.html
<!doctype html>
<html>
<heade>
<meta character="utf-8">
<title>List</title>
</heade>

<body>
 
    <a id="login_baidu" stats="loginPage_baidu_link" href="https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=自己的&redirect_uri=http://www.yingyutwo.com:5555/social/oauth/callback">百度</a>
 
</body>
</html>