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_tokenopenId之後就可以去獲取用戶的信息了

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

爲了方便大家測試與使用,AppIdAppKey 我就暫時不刪了,大家可以直接用我申請的號進行測試

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章