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