package service import ( "encoding/json" "fmt" "os" "strconv" "github.com/silenceper/wechat/v2" "github.com/silenceper/wechat/v2/cache" "github.com/silenceper/wechat/v2/officialaccount" "github.com/silenceper/wechat/v2/officialaccount/config" "github.com/sirupsen/logrus" ) type ticketRequest struct { ExpireSeconds int `json:"expire_seconds"` ActionName string `json:"action_name"` ActionInfo struct { Scene struct { SceneStr string `json:"scene_str"` } `json:"scene"` } `json:"action_info"` } type ticketResponse struct { ErrCode int `json:"errcode"` ErrMsg string `json:"errmsg"` Ticket string `json:"ticket"` ExpireSeconds int `json:"expire_seconds"` Url string `json:"url"` } type WechatGetQrCodeResponse struct { Ticket string `json:"ticket"` ExpireSeconds string `json:"expire_seconds"` Url string `json:"url"` } var ( mp *officialaccount.OfficialAccount ) func init() { wx := wechat.NewWechat() wx.SetCache(cache.NewRedis(nil, &cache.RedisOpts{ Host: os.Getenv("REDIS_HOST"), Password: os.Getenv("REDIS_PWD"), Database: func() int { db := os.Getenv("REDIS_DB") n, err := strconv.Atoi(db) if err != nil { logrus.WithFields(logrus.Fields{ "func": "init", }).Warnf("strconv.Atoi failed: %v", err) n = 0 } return n }(), MaxIdle: 3, MaxActive: 300, IdleTimeout: 600, })) mp = wx.GetOfficialAccount(&config.Config{ AppID: os.Getenv("APPID"), AppSecret: os.Getenv("APPSECRET"), Token: os.Getenv("TOKEN"), EncodingAESKey: os.Getenv("EncodingAESKey"), Cache: nil, }) } // 通过ID获取临时二维码 func WechatQrGet(reqid *string) (any, error) { token, err := mp.GetAccessToken() if err != nil { logrus.WithFields(logrus.Fields{ "func": "WechatQrGet", }).Errorf("mp.GetAccessToken: %v", err) return nil, err } accurl := "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token data := ticketRequest{ ExpireSeconds: 180, ActionName: "QR_STR_SCENE", ActionInfo: struct { Scene struct { SceneStr string `json:"scene_str"` } `json:"scene"` }{ Scene: struct { SceneStr string `json:"scene_str"` }{ SceneStr: *reqid, }, }, } marshal, err := json.Marshal(&data) if err != nil { return nil, err } body, err := httpDO(accurl, "post", nil, marshal) if err != nil { return nil, err } var result *ticketResponse err = json.Unmarshal(body, &result) if err != nil { return nil, err } resp := &WechatGetQrCodeResponse{ Ticket: result.Ticket, ExpireSeconds: fmt.Sprintf("%d", result.ExpireSeconds), Url: result.Url, } return resp, nil } func WechatAuth(reqid, code *string) (any, error) { return nil, nil }