wechat.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package gowechat
  2. import (
  3. "net/http"
  4. "sync"
  5. "github.com/yaotian/gowechat/mp/jssdk"
  6. "github.com/yaotian/gowechat/mp/material"
  7. "github.com/yaotian/gowechat/mp/menu"
  8. "github.com/yaotian/gowechat/mp/template"
  9. "github.com/yaotian/gowechat/mp/user"
  10. "github.com/yaotian/gowechat/server/context"
  11. "github.com/yaotian/gowechat/server/oauth"
  12. "github.com/astaxie/beego/cache"
  13. "github.com/yaotian/gowechat/server"
  14. )
  15. // Wechat struct
  16. type Wechat struct {
  17. Context *context.Context
  18. }
  19. // Config for user
  20. type Config struct {
  21. AppID string
  22. AppSecret string
  23. Token string
  24. EncodingAESKey string
  25. Cache cache.Cache
  26. }
  27. // NewWechat init
  28. func NewWechat(cfg *Config) *Wechat {
  29. context := new(context.Context)
  30. copyConfigToContext(cfg, context)
  31. return &Wechat{context}
  32. }
  33. func copyConfigToContext(cfg *Config, context *context.Context) {
  34. context.AppID = cfg.AppID
  35. context.AppSecret = cfg.AppSecret
  36. context.Token = cfg.Token
  37. context.EncodingAESKey = cfg.EncodingAESKey
  38. context.Cache = cfg.Cache
  39. context.SetAccessTokenLock(new(sync.RWMutex))
  40. context.SetJsAPITicketLock(new(sync.RWMutex))
  41. }
  42. // GetServer 消息管理
  43. func (wc *Wechat) GetServer(req *http.Request, writer http.ResponseWriter) *server.Server {
  44. wc.Context.Request = req
  45. wc.Context.Writer = writer
  46. return server.NewServer(wc.Context)
  47. }
  48. //GetAccessToken 获取access_token
  49. func (wc *Wechat) GetAccessToken() (string, error) {
  50. return wc.Context.GetAccessToken()
  51. }
  52. // GetOauth oauth2网页授权
  53. func (wc *Wechat) GetOauth() *oauth.Oauth {
  54. return oauth.NewOauth(wc.Context)
  55. }
  56. // GetMaterial 素材管理
  57. func (wc *Wechat) GetMaterial() *material.Material {
  58. return material.NewMaterial(wc.Context)
  59. }
  60. // GetJs js-sdk配置
  61. func (wc *Wechat) GetJs() *jssdk.Js {
  62. return jssdk.NewJs(wc.Context)
  63. }
  64. // GetMenu 菜单管理接口
  65. func (wc *Wechat) GetMenu() *menu.Menu {
  66. return menu.NewMenu(wc.Context)
  67. }
  68. // GetUser 用户管理接口
  69. func (wc *Wechat) GetUser() *user.User {
  70. return user.NewUser(wc.Context)
  71. }
  72. // GetTemplate 模板消息接口
  73. func (wc *Wechat) GetTemplate() *template.Template {
  74. return template.NewTemplate(wc.Context)
  75. }