wx_app.go 1.9 KB

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