| 属性 | 类型 | 默认值 | 必填 | 说明 |
|---|---|---|---|---|
| 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 触发事件
!--index.wxml--> view class="container"> button bindtap="onGetOpenId">点击获取openid/button> /view>
然后编写事件函数:
//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 的设置关闭
Go 语言后端代码演示
小程序发过来的数据和去微信 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=%ssecret=%sjs_code=%sgrant_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
}
运行结果
运行代码,在小程序中点击:

结果:

到此这篇关于Golang通过小程序获取微信openid的方法示例的文章就介绍到这了,更多相关Golang获取openid内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
标签:调研邀请 太原 贵阳 阿克苏 广西 西双版纳 庆阳 德州
巨人网络通讯声明:本文标题《Golang通过小程序获取微信openid的方法示例》,本文关键词 Golang,通,过小,程序,获取,;如发现本文内容存在版权问题,烦请提供相关信息告之我们,我们将及时沟通与处理。本站内容系统采集于网络,涉及言论、版权与本站无关。