package utils import ( "Lee-WineList/config" "Lee-WineList/model/param" "git.echol.cn/loser/logger/log" "github.com/medivhzhan/weapp/v3" "github.com/medivhzhan/weapp/v3/auth" "github.com/medivhzhan/weapp/v3/phonenumber" ) type wechat struct{} func WeChatUtils() *wechat { return &wechat{} } // GetWechatUnionId 获取微信用户基础信息 func (w wechat) GetWechatUnionId(code string) (unionId, openId, sessionKey string, err error) { sdk := weapp.NewClient(config.Scd.Tencent.MiniApp.AppId, config.Scd.Tencent.MiniApp.AppSecret, weapp.WithLogger(nil)) cli := sdk.NewAuth() p := auth.Code2SessionRequest{ Appid: config.Scd.Tencent.MiniApp.AppId, Secret: config.Scd.Tencent.MiniApp.AppSecret, JsCode: code, GrantType: "authorization_code", } session, err := cli.Code2Session(&p) if err != nil { return } if session.GetResponseError() != nil { log.Errorf("Code解析失败: %v", session.GetResponseError()) err = session.GetResponseError() return } // 设置UnionId值 unionId = session.Unionid openId = session.Openid sessionKey = session.SessionKey return } // GetWechatPhone 根据Code获取小程序用户手机号 // return 不带区号的手机号 func (w wechat) GetWechatPhone(param param.DecryptMobile) (string, error) { sdk := weapp.NewClient(config.Scd.Tencent.MiniApp.AppId, config.Scd.Tencent.MiniApp.AppSecret) mobile, err := sdk.DecryptMobile(param.SessionKey, param.EncryptedData, param.Iv) if err != nil { log.Errorf("解密手机号失败: %v", err) return "", err } log.Debugf("解密后的手机号: %+v", mobile) return mobile.PurePhoneNumber, nil } // GetPhoneNumber 获取手机号 func (w wechat) GetPhoneNumber(code string) (phone string, err error) { sdk := weapp.NewClient(config.Scd.Tencent.MiniApp.AppId, config.Scd.Tencent.MiniApp.AppSecret) resp, err := sdk.NewPhonenumber().GetPhoneNumber(&phonenumber.GetPhoneNumberRequest{Code: code}) if err != nil { log.Errorf("获取手机号失败: %v", err) return } // 获取手机号 phone = resp.Data.PurePhoneNumber return }