微信小程序服务端SDK,实现了小程序的登录、数据解密、客服消息、订阅消息、生成小程序码、生成小程序shortLink、生成页面Scheme码、生成小程序URL Link等功能。
go get gitee.com/haming123/wxapp4go
var WxApp *wxapp.WeixinApp
func main() {
WxApp = wxapp.NewWeixinApp("appID_string", "app_Secret", wxapp.GetAccessToken)
//其他业务逻辑
}
func HandlerWxLogin(w http.ResponseWriter, r *http.Request) {
code := r.FormValue("code")
//获取openid以及Sessionkey
wxtoken, err := WxApp.GetOpenIdByCode(code)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
w.Write([]byte(wxtoken.OpenId))
}
func HandlerWxPhone(w http.ResponseWriter, r *http.Request) {
data := r.FormValue("data")
iv := r.FormValue("iv")
ret, err := WxApp.DecodePhoneNumber(data, "填入微信登录时获取的session_key", iv)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
fmt.Fprintf(w, ret.PhoneNumber)
}
func HandlerGenQrcode(w http.ResponseWriter, r *http.Request) {
var param wxapp.ACodeParam
page := r.FormValue("page");
scene := r.FormValue("scene");
param.Path = page
param.Scene = scene
param.Width = 430
raw, err := WxApp.CreateACode(param)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type","image/gif")
io.WriteString(w, string(raw))
}
建议开发者使用中控服务器统一获取和刷新access_token,服务器所使用的access_token均来自于该中控服务器,不应该各自去刷新,否则容易造成冲突,导致access_token覆盖而影响业务。
package main
import (
wxapp "gitee.com/haming123/wxapp4go"
"net/http"
)
func HandlerGetAccessToken(w http.ResponseWriter, r *http.Request) {
app_id := r.FormValue("app_id")
app_secret := r.FormValue("app_secret")
token, err := wxapp.GetAccessToken(app_id, app_secret)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
w.Write([]byte(token))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/access_token", HandlerGetAccessToken)
http.ListenAndServe(":8091", mux)
}
var WxApp *wxapp.WeixinApp
func InitWxApp() {
WxApp = wxapp.NewWeixinApp("appID_string", "app_Secret", getAccessToken)
}
func getAccessToken(appid string, secret string) (string, error) {
addr := "http://127.0.0.1:8091/access_token"
addr = fmt.Sprintf("%s?app_id=%s&app_secret=%s", addr, appid, secret)
res, err := http.Get(addr)
if err != nil {
return "", err
}
raw, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return "", err
}
return string(raw), nil
}
func main() {
//初始化微信小程序
InitWxApp()
//其他业务逻辑
}