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 + +}