backend/pkg/wx/wx.go

68 lines
1.7 KiB
Go
Raw Normal View History

2022-01-14 04:10:34 +08:00
// 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
}