client.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package wechat
  2. import (
  3. "dashoo.cn/opms_libary/plugin/wechat/context"
  4. "fmt"
  5. "github.com/gogf/gf/os/gcache"
  6. "sync"
  7. )
  8. var Client *ClientImpl
  9. var memCache *gcache.Cache
  10. // ClientImpl struct
  11. type ClientImpl struct {
  12. Context *context.Context
  13. }
  14. func init() {
  15. Client = NewClient()
  16. }
  17. // NewClient init
  18. func NewClient() *ClientImpl {
  19. var config = context.Config{
  20. //微信公众平台,需要填写的信息
  21. AppID: "wx7a7372d6b94c0ee9", //g.Config().GetString("wechat.app-id"), //"your app id",
  22. AppSecret: "5733eee31e2625dd2ebf18e2d4cd3cbc", //g.Config().GetString("wechat.app-secret"), //"your app secret",
  23. Token: "WEIXIN_dashoo_labsop_171210", //g.Config().GetString("wechat.token"), //"your token",
  24. EncodingAESKey: "9b2TW1dend4Vsu4prELD7Wfg0WHpHf48i6OtViYimfZ", //g.Config().GetString("wechat.aes-key"), //"your encoding aes key",
  25. }
  26. return newClient(config)
  27. }
  28. func newClient(cfg context.Config) *ClientImpl {
  29. context := new(context.Context)
  30. initContext(&cfg, context)
  31. return &ClientImpl{context}
  32. }
  33. func initContext(cfg *context.Config, context *context.Context) {
  34. if cfg.Cache == nil {
  35. if memCache == nil {
  36. memCache = gcache.New()
  37. }
  38. cfg.Cache = memCache
  39. }
  40. context.Config = cfg
  41. context.SetAccessTokenLock(new(sync.RWMutex))
  42. context.SetJsAPITicketLock(new(sync.RWMutex))
  43. }
  44. //MpClient 公众平台
  45. func (wc *ClientImpl) MpClient() (media *Media, err error) {
  46. err = wc.checkCfgBase()
  47. if err != nil {
  48. return
  49. }
  50. media = NewMedia()
  51. media.ClientImpl = wc
  52. return
  53. }
  54. //MiniClient 公众平台
  55. func (wc *ClientImpl) MiniClient() (media *Mini, err error) {
  56. err = wc.checkCfgBase()
  57. if err != nil {
  58. return
  59. }
  60. media = NewMini()
  61. media.ClientImpl = wc
  62. return
  63. }
  64. //checkCfgBase 检查配置基本信息
  65. func (wc *ClientImpl) checkCfgBase() (err error) {
  66. if wc.Context.AppID == "" {
  67. return fmt.Errorf("%s", "配置中没有AppID")
  68. }
  69. if wc.Context.AppSecret == "" {
  70. return fmt.Errorf("%s", "配置中没有AppSecret")
  71. }
  72. if wc.Context.Token == "" {
  73. return fmt.Errorf("%s", "配置中没有Token")
  74. }
  75. return
  76. }