在开发微信小程序的过程当中,小程序能够经过微信官方提供的登陆能力方便地获取微信提供的用户身份标识,快速创建小程序内的用户体系。那么这个用户身份标识就是 openid。html
那么小程序获取 openid 的流程具体以下,这里我简化了一下,由于咱们只须要获取到 openid 便可,具体能够参考这里 json
咱们须要在小程序中调用 wx.login() 获取 code 码,而后将这个 code 码发送给后端,后端带着这个 code 码和 appid,appsecret 向微信接口发起 http 请求获取 openid。小程序
在开发的小程序中的 AppID 必定要和后端使用的 AppID 保持一致,不然会获取 openid 失败 后端
咱们请求的微信 API 为 auth.code2Session,微信小程序
请求地址为:api
GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
复制代码
所需的四个参数为:bash
属性 | 类型 | 默认值 | 必填 | 说明 |
---|---|---|---|---|
appid | string | 是 | 小程序 appId | |
secret | string | 是 | 小程序 appSecret | |
js_code | string | 是 | 登陆时获取的 code | |
grant_type | string | 是 | 受权类型,此处只需填写 authorization_code |
js_code 就是咱们经过 wx.login 获得的 code,grant_type 为 authorization_code,只剩下 appid 和 secret 须要咱们登陆微信公总平台里面找 微信
为了方便操做,咱们在 index 页面编写了一个 button,经过 button 触发事件session
<!--index.wxml-->
<view class="container">
<button bindtap="onGetOpenId">点击获取openid</button>
</view>
复制代码
而后编写事件函数:app
//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);
}
});
}
}
});
}
});
复制代码
那么,在小程序中发送 http 请求强制要求地址必须为 https,因为咱们在开发中,咱们能够把强制 https 的设置关闭
小程序发过来的数据和去微信 API 获取的数据都是放在 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
}
复制代码
运行代码,在小程序中点击: