wx_app.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package services
  2. import (
  3. "fmt"
  4. wechat "github.com/silenceper/wechat/v2"
  5. "github.com/silenceper/wechat/v2/cache"
  6. "github.com/silenceper/wechat/v2/miniprogram"
  7. "github.com/silenceper/wechat/v2/miniprogram/auth"
  8. "github.com/silenceper/wechat/v2/miniprogram/config"
  9. "github.com/silenceper/wechat/v2/miniprogram/encryptor"
  10. "github.com/silenceper/wechat/v2/miniprogram/qrcode"
  11. "eta/eta_api/utils"
  12. )
  13. // 微信小程序配置信息
  14. var (
  15. WxId string //微信原始ID
  16. WxAppId string
  17. WxAppSecret string
  18. WxPlatform int //用户来源,需要入库,用来保存该用户来自哪个平台,默认是:1
  19. EnvVersion string // 小程序版本, release-正式版; trial-体验版; develop-开发版
  20. )
  21. func GetWxApp() (miniprogram *miniprogram.MiniProgram) {
  22. wc := wechat.NewWechat()
  23. memory := cache.NewMemory()
  24. //memory := cache.NewRedis(global.Redis)
  25. cfg := &config.Config{
  26. AppID: utils.WxYbAppId,
  27. AppSecret: utils.WxYbAppSecret,
  28. Cache: memory,
  29. }
  30. miniprogram = wc.GetMiniProgram(cfg)
  31. return
  32. }
  33. // GetSession 获取用户详情
  34. func GetSession(code string) (userInfo auth.ResCode2Session, err error) {
  35. wechatClient := GetWxApp()
  36. authClient := wechatClient.GetAuth()
  37. userInfo, err = authClient.Code2Session(code)
  38. return
  39. }
  40. // GetSession 获取用户详情
  41. func GetUserInfo(code string) (userInfo auth.ResCode2Session, err error) {
  42. wechatClient := GetWxApp()
  43. authClient := wechatClient.GetAuth()
  44. fmt.Println("code:", code)
  45. userInfo, err = authClient.Code2Session(code)
  46. return
  47. }
  48. // 获取解密信息 GetDecryptInfo
  49. func GetDecryptInfo(sessionKey, encryptedData, iv string) (decryptData *encryptor.PlainData, err error) {
  50. wechatClient := GetWxApp()
  51. encryptorClient := wechatClient.GetEncryptor()
  52. decryptData, err = encryptorClient.Decrypt(sessionKey, encryptedData, iv)
  53. return
  54. }
  55. // GetSunCode 获取太阳码
  56. func GetSunCode(page, scene string) (resp []byte, err error) {
  57. // 此处因初始化顺序问题不放在init中
  58. env := "trial"
  59. if utils.RunMode == "release" {
  60. env = "release"
  61. }
  62. codePars := qrcode.QRCoder{
  63. Page: page,
  64. Scene: scene,
  65. EnvVersion: env,
  66. }
  67. wechatClient := GetWxApp()
  68. qr := wechatClient.GetQRCode()
  69. return qr.GetWXACodeUnlimit(codePars)
  70. }