wechat.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. //Package gowechat 一个简单易用的wechat封装.
  2. package gowechat
  3. import (
  4. "fmt"
  5. "sync"
  6. "github.com/astaxie/beego/cache"
  7. "github.com/yaotian/gowechat/wxcontext"
  8. )
  9. //memCache if wxcontext.Config no cache, this will give a default memory cache.
  10. var memCache cache.Cache
  11. // Wechat struct
  12. type Wechat struct {
  13. Context *wxcontext.Context
  14. }
  15. // NewWechat init
  16. func NewWechat(cfg wxcontext.Config) *Wechat {
  17. context := new(wxcontext.Context)
  18. initContext(&cfg, context)
  19. return &Wechat{context}
  20. }
  21. func initContext(cfg *wxcontext.Config, context *wxcontext.Context) {
  22. if cfg.Cache == nil {
  23. if memCache == nil {
  24. memCache, _ = cache.NewCache("memory", `{"interval":60}`)
  25. }
  26. cfg.Cache = memCache
  27. }
  28. context.Config = cfg
  29. context.SetAccessTokenLock(new(sync.RWMutex))
  30. context.SetJsAPITicketLock(new(sync.RWMutex))
  31. }
  32. //MchMgr 商户平台
  33. func (wc *Wechat) MchMgr() (mch *MchMgr, err error) {
  34. err = wc.checkCfgMch()
  35. if err != nil {
  36. return
  37. }
  38. mch = new(MchMgr)
  39. mch.Wechat = wc
  40. return
  41. }
  42. //MpMgr 公众平台
  43. func (wc *Wechat) MpMgr() (mp *MpMgr, err error) {
  44. err = wc.checkCfgBase()
  45. if err != nil {
  46. return
  47. }
  48. mp = new(MpMgr)
  49. mp.Wechat = wc
  50. return
  51. }
  52. //checkCfgBase 检查配置基本信息
  53. func (wc *Wechat) checkCfgBase() (err error) {
  54. if wc.Context.AppID == "" {
  55. return fmt.Errorf("%s", "配置中没有AppID")
  56. }
  57. if wc.Context.AppSecret == "" {
  58. return fmt.Errorf("%s", "配置中没有AppSecret")
  59. }
  60. if wc.Context.Token == "" {
  61. return fmt.Errorf("%s", "配置中没有Token")
  62. }
  63. return
  64. }
  65. func (wc *Wechat) checkCfgMch() (err error) {
  66. err = wc.checkCfgBase()
  67. if err != nil {
  68. return
  69. }
  70. if wc.Context.MchID == "" {
  71. return fmt.Errorf("%s", "配置中没有MchID")
  72. }
  73. if wc.Context.MchAPIKey == "" {
  74. return fmt.Errorf("%s", "配置中没有MchAPIKey")
  75. }
  76. if wc.Context.SslCertFilePath == "" && wc.Context.SslCertContent == "" {
  77. return fmt.Errorf("%s", "配置中没有SslCert")
  78. }
  79. if wc.Context.SslKeyFilePath == "" && wc.Context.SslKeyContent == "" {
  80. return fmt.Errorf("%s", "配置中没有SslKey")
  81. }
  82. //初始化 http client, 有错误会出错误
  83. err = wc.Context.InitHTTPClients()
  84. return
  85. }