Go语言版实现QQ扫码登陆
生活随笔
收集整理的這篇文章主要介紹了
Go语言版实现QQ扫码登陆
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
點擊查看 官方文檔
1. 申請appid和appkey
- appid:應用的唯一標識。在OAuth2.0認證過程中,appid的值即為oauth_consumer_key的值。
- appkey:appid對應的密鑰,訪問用戶資源時用來驗證應用的合法性。在OAuth2.0認證過程中,appkey的值即為oauth_consumer_secret的值。
申請地址
https://connect.qq.com/manage.html#/
2. 授權流程
QQ登錄和微信登陸一樣也是采用的OAuth2.0的方式,即先獲取一個授權的code然后拿著這個code去授權中心換取token,拿著這個token就可以訪問具體的API接口了。
3. 代碼詳解
3.1 獲取code
func GetAuthCode(w http.ResponseWriter, r *http.Request) {params := url.Values{}params.Add("response_type", "code")params.Add("client_id", AppId)params.Add("state", "test")str := fmt.Sprintf("%s&redirect_uri=%s", params.Encode(), redirectURI)loginURL := fmt.Sprintf("%s?%s", "https://graph.qq.com/oauth2.0/authorize", str)http.Redirect(w, r, loginURL, http.StatusFound) }它會自動打開一個網頁,我們可以點擊我們目前登陸的QQ號進行登陸,或掃碼登陸
3.2 獲取access_token
當我們點擊QQ登陸后,它會回調我們后臺的地址,回調地址的URL中會帶上授權碼code,我們根據這個code就可以獲取access_token了
func GetToken(w http.ResponseWriter, r *http.Request) {code := r.FormValue("code")params := url.Values{}params.Add("grant_type", "authorization_code")params.Add("client_id", AppId)params.Add("client_secret", AppKey)params.Add("code", code)str := fmt.Sprintf("%s&redirect_uri=%s", params.Encode(), redirectURI)loginURL := fmt.Sprintf("%s?%s", "https://graph.qq.com/oauth2.0/token", str)response, err := http.Get(loginURL)if err != nil {w.Write([]byte(err.Error()))}defer response.Body.Close()bs, _ := ioutil.ReadAll(response.Body)body := string(bs)resultMap := convertToMap(body)info := &PrivateInfo{}info.AccessToken = resultMap["access_token"]info.RefreshToken = resultMap["refresh_token"]info.ExpiresIn = resultMap["expires_in"]GetOpenId(info, w) }3.3 獲取OpenId
OpenId是每一個具體用戶在我們平臺下的唯一標識,后面的所有請求都會帶上這個OpenId
func GetOpenId(info *PrivateInfo, w http.ResponseWriter) {resp, err := http.Get(fmt.Sprintf("%s?access_token=%s", "https://graph.qq.com/oauth2.0/me", info.AccessToken))if err != nil {w.Write([]byte(err.Error()))}defer resp.Body.Close()bs, _ := ioutil.ReadAll(resp.Body)body := string(bs)info.OpenId = body[45:77]GetUserInfo(info, w) }3.4 獲取用戶信息
有了access_token和openId之后就可以去獲取用戶的信息了
func GetUserInfo(info *PrivateInfo, w http.ResponseWriter) {params := url.Values{}params.Add("access_token", info.AccessToken)params.Add("openid", info.OpenId)params.Add("oauth_consumer_key", AppId)uri := fmt.Sprintf("https://graph.qq.com/user/get_user_info?%s", params.Encode())resp, err := http.Get(uri)if err != nil {w.Write([]byte(err.Error()))}defer resp.Body.Close()bs, _ := ioutil.ReadAll(resp.Body)w.Write(bs) }3.5 全部代碼
更具體的代碼大家可以去我的GitHub上查看
https://github.com/pibigstar/go-demo/blob/master/sdk/qq/qq_pc_login.go
為了方便大家測試與使用,AppId 和 AppKey 我就暫時不刪了,大家可以直接用我申請的號進行測試
總結
以上是生活随笔為你收集整理的Go语言版实现QQ扫码登陆的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vpp之node节点分析二: qs类型
- 下一篇: 硬盘数据恢复