在開(kāi)發(fā)微信小程序的過(guò)程中,小程序可以通過(guò)微信官方提供的登錄能力方便地獲取微信提供的用戶身份標(biāo)識(shí),快速建立小程序內(nèi)的用戶體系。那么這個(gè)用戶身份標(biāo)識(shí)就是 openid。
那么小程序獲取 openid 的流程具體如下,這里我簡(jiǎn)化了一下,因?yàn)槲覀冎恍枰@取到 openid 即可,具體可以參考 這里
我們需要在小程序中調(diào)用 wx.login() 獲取 code 碼,然后將這個(gè) code 碼發(fā)送給后端,后端帶著這個(gè) code 碼和 appid,appsecret 向微信接口發(fā)起 http 請(qǐng)求獲取 openid。
在開(kāi)發(fā)的小程序中的 AppID 一定要和后端使用的 AppID 保持一致,否則會(huì)獲取 openid 失敗
我們請(qǐng)求的微信 API 為 auth.code2Session ,
請(qǐng)求地址為:
GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
所需的四個(gè)參數(shù)為:
| 屬性 | 類型 | 默認(rèn)值 | 必填 | 說(shuō)明 |
|---|---|---|---|---|
| appid | string | 是 | 小程序 appId | |
| secret | string | 是 | 小程序 appSecret | |
| js_code | string | 是 | 登錄時(shí)獲取的 code | |
| grant_type | string | 是 | 授權(quán)類型,此處只需填寫 authorization_code |
js_code 就是我們通過(guò) wx.login 得到的 code,grant_type 為 authorization_code,只剩下 appid 和 secret 需要我們登錄 微信公總平臺(tái) 里面找
為了方便操作,我們?cè)?index 頁(yè)面編寫了一個(gè) button,通過(guò) button 觸發(fā)事件
<!--index.wxml--> <view class="container"> <button bindtap="onGetOpenId">點(diǎn)擊獲取openid</button> </view>
然后編寫事件函數(shù):
//index.js
Page({
onGetOpenId() {
wx.login({
success: res => {
if (res.code) {
wx.request({
url: "http://localhost:2020/openid",
method: "POST",
data: {
code: res.code
},
success: res => {
console.log(res);
}
});
}
}
});
}
});
那么,在小程序中發(fā)送 http 請(qǐng)求強(qiáng)制要求地址必須為 https,由于我們?cè)陂_(kāi)發(fā)中,我們可以把強(qiáng)制 https 的設(shè)置關(guān)閉
小程序發(fā)過(guò)來(lái)的數(shù)據(jù)和去微信 API 獲取的數(shù)據(jù)都是放在 http body 里,所以我們要從 body 獲取
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/openid", getOpenID)
http.ListenAndServe(":2020", nil)
}
func getOpenID(writer http.ResponseWriter, request *http.Request) {
if request.Method != http.MethodPost {
return
}
var codeMap map[string]string
err := json.NewDecoder(request.Body).Decode(&codeMap)
if err != nil {
return
}
defer request.Body.Close()
code := codeMap["code"]
openid, err := sendWxAuthAPI(code)
if err != nil {
return
}
fmt.Println("my openid", openid)
}
const (
code2sessionURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
appID = "你的AppID"
appSecret = "你的AppSecret"
)
func sendWxAuthAPI(code string) (string, error) {
url := fmt.Sprintf(code2sessionURL, appID, appSecret, code)
resp, err := http.DefaultClient.Get(url)
if err != nil {
return "", err
}
var wxMap map[string]string
err = json.NewDecoder(resp.Body).Decode(&wxMap)
if err != nil {
return "", err
}
defer resp.Body.Close()
return wxMap["openid"], nil
}
運(yùn)行代碼,在小程序中點(diǎn)擊:
結(jié)果: