wechat.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package gowechat
  2. import (
  3. "net/http"
  4. "sync"
  5. "github.com/astaxie/beego/cache"
  6. "github.com/yaotian/gowechat/mch/pay"
  7. "github.com/yaotian/gowechat/server"
  8. "github.com/yaotian/gowechat/server/context"
  9. "github.com/yaotian/gowechat/util"
  10. )
  11. // Wechat struct
  12. type Wechat struct {
  13. Context *context.Context
  14. }
  15. // Config for user
  16. type Config struct {
  17. AppID string
  18. AppSecret string
  19. Token string
  20. EncodingAESKey string
  21. Cache cache.Cache
  22. //mch商户平台需要的变量
  23. //证书
  24. SslCertFilePath string //证书文件的路径
  25. SslKeyFilePath string
  26. SslCertContent string //证书的内容
  27. SslKeyContent string
  28. MchID string
  29. MchAPIKey string //商户平台设置的api key
  30. }
  31. // NewWechat init
  32. func NewWechat(cfg *Config) *Wechat {
  33. context := new(context.Context)
  34. initContext(cfg, context)
  35. return &Wechat{context}
  36. }
  37. func initContext(cfg *Config, context *context.Context) {
  38. context.AppID = cfg.AppID
  39. context.AppSecret = cfg.AppSecret
  40. context.Token = cfg.Token
  41. context.EncodingAESKey = cfg.EncodingAESKey
  42. if cfg.Cache == nil {
  43. cfg.Cache, _ = cache.NewCache("memory", `{"interval":60}`)
  44. }
  45. context.SetAccessTokenLock(new(sync.RWMutex))
  46. context.SetJsAPITicketLock(new(sync.RWMutex))
  47. //create http client
  48. if cfg.SslCertFilePath != "" && cfg.SslKeyFilePath != "" {
  49. if client, err := util.NewTLSHttpClient(cfg.SslCertFilePath, cfg.SslKeyFilePath); err == nil {
  50. context.SHTTPClient = client
  51. }
  52. }
  53. if cfg.SslCertContent != "" && cfg.SslKeyContent != "" {
  54. if client, err := util.NewTLSHttpClientFromContent(cfg.SslCertContent, cfg.SslKeyContent); err == nil {
  55. context.SHTTPClient = client
  56. }
  57. }
  58. context.MchAPIKey = cfg.MchAPIKey
  59. context.MchID = cfg.MchID
  60. }
  61. // GetServer 消息管理
  62. func (wc *Wechat) GetServer(req *http.Request, writer http.ResponseWriter) *server.Server {
  63. wc.Context.Request = req
  64. wc.Context.Writer = writer
  65. return server.NewServer(wc.Context)
  66. }
  67. //GetPay get pay
  68. func (wc *Wechat) GetPay() *pay.Pay {
  69. return pay.NewPay(wc.Context)
  70. }