wechat.go 1.9 KB

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