From 5c6575728cbc227a12365ab4f35d42853b74dc7d Mon Sep 17 00:00:00 2001 From: liuhaotian Date: Fri, 14 Jan 2022 04:10:34 +0800 Subject: [PATCH] =?UTF-8?q?feat=20:=20wx=20=E8=AE=BF=E9=97=AE=20Code2Sessi?= =?UTF-8?q?on=20APi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/wx/wx.go | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 pkg/wx/wx.go diff --git a/pkg/wx/wx.go b/pkg/wx/wx.go new file mode 100644 index 0000000..2f42dc1 --- /dev/null +++ b/pkg/wx/wx.go @@ -0,0 +1,67 @@ +// Package wx 与Wechat Http Api交互 +package wx + +import ( + "encoding/json" + "fmt" + "git.icechen.cn/monorepo/backend/pkg/api" + "github.com/gofiber/fiber/v2" + "io/ioutil" + "net/http" + "strings" +) + +type code2SessionApiUrlResp struct { + ErrCode int `json:"errcode"` + ErrMsg string `json:"errmsg"` + OpenId string `json:"openid"` + UnionId string `json:"unionid"` +} + +// Code2Session 登录凭证 code 后传到开发者服务器调用此接口完成登录流程 +func Code2Session(appId, secret, jsCode string) (*code2SessionApiUrlResp, error) { + // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html ->> wx.login + const code2SessionApiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code" + + p := map[string]string{ + "appid": appId, + "secret": secret, + "js_code": jsCode, + } + + paramValueReplace := func() string { + url := code2SessionApiUrl + for k, v := range p { + url = strings.ReplaceAll(url, k, v) + } + return url + } + + get, err := http.Get(paramValueReplace()) + defer get.Body.Close() + + if err != nil { + return nil, api.NewFError(err.Error()) + } + + resp, err := ioutil.ReadAll(get.Body) + if err != nil { + return nil, api.NewFError(err.Error()) + } + + if get.StatusCode != fiber.StatusOK { + return nil, api.NewFError(fmt.Sprintf("jscode2session statusCode:%v,resp:%v", get.StatusCode, string(resp))) + } + + c := new(code2SessionApiUrlResp) + if err := json.Unmarshal(resp, c); err != nil { + return nil, api.NewFError(err.Error()) + } + + if c.ErrCode != 0 && c.ErrMsg != "" { + return nil, api.NewFError(fmt.Sprintf("jscode2session errCode:%v,errMsg:%v", c.ErrCode, c.ErrMsg)) + } + + return c, nil + +}