73 lines
1.6 KiB
Go
73 lines
1.6 KiB
Go
package service
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"yuleduiPay/repo"
|
|
"yuleduiPay/service/vo"
|
|
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
"github.com/gogf/gf/v2/net/ghttp"
|
|
)
|
|
|
|
type Wx struct {
|
|
payOrderRepo repo.PayOrder
|
|
shopRepo repo.Shop
|
|
}
|
|
|
|
// 微信用户登录
|
|
func (t *Wx) Login(r *ghttp.Request) {
|
|
req := vo.WxLoginReq{}
|
|
err := r.Parse(&req)
|
|
if err != nil {
|
|
r.SetError(err)
|
|
return
|
|
}
|
|
sessionResp, err := t.wxAuthorize(req.JsCode)
|
|
if err != nil {
|
|
r.SetError(err)
|
|
return
|
|
}
|
|
_ = sessionResp
|
|
//通过openId查询手机号
|
|
}
|
|
|
|
// 微信授权获取openId
|
|
func (t *Wx) wxAuthorize(jsCode string) (*vo.WxSessionResp, error) {
|
|
var urlResp *http.Response
|
|
var err error
|
|
appid := g.Cfg().MustGet(nil, "weixin.appId").String()
|
|
wxSecret := g.Cfg().MustGet(nil, "weixin.secret").String()
|
|
wx_url := "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
|
|
"&secret=" + wxSecret + "&js_code=" + jsCode + "&grant_type=authorization_code"
|
|
|
|
for i := 0; i < 2; i++ { // 失败一次,再次调用
|
|
urlResp, err = http.Get(wx_url)
|
|
if err == nil { // 成功的话,跳出
|
|
break
|
|
}
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
body, err := io.ReadAll(urlResp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
urlResp.Body.Close()
|
|
sessionResp := vo.WxSessionResp{} // 用户标志信息
|
|
err = json.Unmarshal(body, &sessionResp)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if sessionResp.ErrCode != 0 {
|
|
err = errors.New("errCode:" + strconv.Itoa(sessionResp.ErrCode) + " errMsg:" + sessionResp.ErrMsg)
|
|
return nil, err
|
|
}
|
|
//根据openId查询手机号
|
|
return &sessionResp, err
|
|
}
|