-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwecom.go
More file actions
422 lines (380 loc) · 12.5 KB
/
Copy pathwecom.go
File metadata and controls
422 lines (380 loc) · 12.5 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package wecom
import (
"context"
"errors"
"fmt"
"net/url"
"sync"
"github.com/shuaidd/wecom-core/config"
"github.com/shuaidd/wecom-core/internal/auth"
"github.com/shuaidd/wecom-core/internal/client"
"github.com/shuaidd/wecom-core/internal/retry"
"github.com/shuaidd/wecom-core/pkg/interceptor"
"github.com/shuaidd/wecom-core/services/agent"
"github.com/shuaidd/wecom-core/services/approval"
"github.com/shuaidd/wecom-core/services/calendar"
"github.com/shuaidd/wecom-core/services/checkin"
"github.com/shuaidd/wecom-core/services/contact"
"github.com/shuaidd/wecom-core/services/corpgroup"
"github.com/shuaidd/wecom-core/services/email"
"github.com/shuaidd/wecom-core/services/externalcontact"
"github.com/shuaidd/wecom-core/services/externalpay"
"github.com/shuaidd/wecom-core/services/hr"
"github.com/shuaidd/wecom-core/services/invoice"
"github.com/shuaidd/wecom-core/services/ip"
"github.com/shuaidd/wecom-core/services/journal"
"github.com/shuaidd/wecom-core/services/kf"
"github.com/shuaidd/wecom-core/services/media"
"github.com/shuaidd/wecom-core/services/meeting"
"github.com/shuaidd/wecom-core/services/meetingroom"
"github.com/shuaidd/wecom-core/services/message"
"github.com/shuaidd/wecom-core/services/miniapppay"
"github.com/shuaidd/wecom-core/services/oauth"
"github.com/shuaidd/wecom-core/services/qrcode"
"github.com/shuaidd/wecom-core/services/reserve_meeting"
"github.com/shuaidd/wecom-core/services/security"
"github.com/shuaidd/wecom-core/services/updown"
"github.com/shuaidd/wecom-core/services/webinar"
"github.com/shuaidd/wecom-core/services/wedoc"
"github.com/shuaidd/wecom-core/services/wedrive"
"github.com/shuaidd/wecom-core/types/common"
)
// 暴露给用户的类型别名,用于自定义 API 调用
// AgentConfig 应用配置(用于配置多应用)
type AgentConfig = config.AgentConfig
// Response 响应对象,包含原始响应数据
type Response = client.Response
// CommonResponse 企业微信API通用响应字段
// 用户自定义响应类型时应该嵌入此类型
type CommonResponse = common.Response
// RequestInterceptor 请求拦截器
type RequestInterceptor = interceptor.RequestInterceptor
// ResponseInterceptor 响应拦截器(解析前)
type ResponseInterceptor = interceptor.ResponseInterceptor
// AfterResponseInterceptor 响应后拦截器(解析后)
type AfterResponseInterceptor = interceptor.AfterResponseInterceptor
// InterceptorResponse 拦截器中使用的响应对象
type InterceptorResponse = interceptor.Response
// Client 企业微信SDK客户端
type Client struct {
// Agent 应用管理服务
Agent *agent.Service
// Calendar 日历服务
Calendar *calendar.Service
// Contact 通讯录服务
Contact *contact.Service
// IP IP相关服务
IP *ip.Service
// QRCode 企业二维码服务
QRCode *qrcode.Service
// OAuth 身份验证服务
OAuth *oauth.Service
// UpDown 上下游服务
UpDown *updown.Service
// CorpGroup 企业互联服务
CorpGroup *corpgroup.Service
// Security 安全管理服务
Security *security.Service
// Message 消息服务
Message *message.Service
// ExternalContact 外部联系人服务
ExternalContact *externalcontact.Service
// Media 素材管理服务
Media *media.Service
// Checkin 打卡服务
Checkin *checkin.Service
// Invoice 电子发票服务
Invoice *invoice.Service
// KF 微信客服服务
KF *kf.Service
// Email 邮件服务
Email *email.Service
// Wedoc 微文档服务
Wedoc *wedoc.Service
// Wedrive 微盘服务
Wedrive *wedrive.Service
// Meeting 会议服务
Meeting *meeting.Service
// MeetingRoom 会议室管理服务
MeetingRoom *meetingroom.Service
// ReserveMeeting 预约会议高级管理服务
ReserveMeeting *reserve_meeting.Service
// Webinar 网络研讨会服务
Webinar *webinar.Service
// Approval 审批服务
Approval *approval.Service
// ExternalPay 对外收款服务
ExternalPay *externalpay.Service
// HR 花名册服务
HR *hr.Service
// MiniAppPay 小程序支付服务
MiniAppPay *miniapppay.Service
// Journal 汇报服务
Journal *journal.Service
// 内部组件(不对外暴露)
config *config.Config
tokenManager *auth.TokenManager
httpClient *client.Client
}
// New 创建企业微信SDK客户端
func New(opts ...config.Option) (*Client, error) {
// 1. 创建配置
cfg := config.New(opts...)
// 2. 验证配置
if err := cfg.Validate(); err != nil {
return nil, err
}
// 3. 创建 Token 管理器
tokenManager := auth.NewTokenManager(
cfg.CorpID,
cfg.BaseURL,
cfg.Cache,
cfg.Logger,
)
// 4. 注册多应用配置到 TokenManager
if len(cfg.Agents) > 0 {
for key, agentCfg := range cfg.Agents {
corpId := agentCfg.CorpID
if corpId == "" {
corpId = cfg.CorpID
}
tokenManager.RegisterAgent(key, corpId, agentCfg.AgentID, agentCfg.Secret)
}
}
// 5. 创建重试策略
retryPolicy := retry.NewPolicy(
cfg.MaxRetries,
cfg.InitialBackoff,
cfg.MaxBackoff,
)
retryExecutor := retry.NewExecutor(retryPolicy, cfg.Logger)
// 6. 创建 HTTP 客户端
httpClient := client.New(
cfg.BaseURL,
cfg.Timeout,
cfg.Logger,
tokenManager,
retryExecutor,
)
if cfg.Debug {
httpClient.SetDebug(true)
}
// 设置自定义解码器(如果配置了)
if cfg.Decoder != nil {
httpClient.SetDecoder(cfg.Decoder)
}
httpClient.SetWithToken(cfg.WithToken)
// 7. 注册拦截器
for _, interceptor := range cfg.RequestInterceptors {
httpClient.AddRequestInterceptor(interceptor)
}
for _, interceptor := range cfg.ResponseInterceptors {
httpClient.AddResponseInterceptor(interceptor)
}
for _, interceptor := range cfg.AfterResponseInterceptors {
httpClient.AddAfterResponseInterceptor(interceptor)
}
// 8. 创建服务客户端
c := &Client{
config: cfg,
tokenManager: tokenManager,
httpClient: httpClient,
Agent: agent.NewService(httpClient),
Calendar: calendar.NewService(httpClient),
Contact: contact.NewService(httpClient),
IP: ip.NewService(httpClient),
QRCode: qrcode.NewService(httpClient),
OAuth: oauth.NewService(httpClient),
UpDown: updown.NewService(httpClient),
CorpGroup: corpgroup.NewService(httpClient),
Security: security.NewService(httpClient),
Message: message.NewService(httpClient),
ExternalContact: externalcontact.NewService(httpClient),
Media: media.NewService(httpClient),
Checkin: checkin.NewService(httpClient),
Invoice: invoice.NewService(httpClient),
KF: kf.NewService(httpClient),
Email: email.NewService(httpClient),
Wedoc: wedoc.New(httpClient),
Wedrive: wedrive.New(httpClient),
Meeting: meeting.NewService(httpClient),
MeetingRoom: meetingroom.NewService(httpClient),
ReserveMeeting: reserve_meeting.NewService(httpClient),
Webinar: webinar.NewService(httpClient),
Approval: approval.New(httpClient),
ExternalPay: externalpay.NewService(httpClient),
HR: hr.NewService(httpClient),
MiniAppPay: miniapppay.NewService(httpClient),
Journal: journal.NewService(httpClient),
}
return c, nil
}
// WithTraceID 将 TraceId 添加到 context
func WithTraceID(ctx context.Context, traceID string) context.Context {
return client.WithTraceID(ctx, traceID)
}
// WithAgentName 将应用名称添加到 context
// 使用此函数可以在调用API时指定使用哪个应用的凭证
func WithAgentName(ctx context.Context, agentName string) context.Context {
return client.WithAgentName(ctx, agentName)
}
// GetAgentName 从 context 获取应用名称
func GetAgentName(ctx context.Context) string {
return client.GetAgentName(ctx)
}
// WithAgentID 将应用ID添加到 context
// 使用此函数可以在调用API时指定使用哪个应用的凭证
func WithAgentID(ctx context.Context, agentID int64) context.Context {
return client.WithAgentID(ctx, agentID)
}
// CustomGet 发送自定义 GET 请求
// 自动处理 access_token 注入和重试逻辑
//
// 示例:
//
// resp, err := client.CustomGet(ctx, "/cgi-bin/custom/api", url.Values{"param": []string{"value"}})
// if err != nil {
// return err
// }
// // 手动解析响应
// var result YourCustomType
// if err := resp.Unmarshal(&result); err != nil {
// return err
// }
func (c *Client) CustomGet(ctx context.Context, path string, query map[string]string) (*client.Response, error) {
q := make(map[string][]string)
for k, v := range query {
q[k] = []string{v}
}
return c.httpClient.Get(ctx, path, q)
}
// CustomPost 发送自定义 POST 请求
// 自动处理 access_token 注入和重试逻辑
//
// 示例:
//
// req := YourCustomRequest{Field: "value"}
// resp, err := client.CustomPost(ctx, "/cgi-bin/custom/api", req)
// if err != nil {
// return err
// }
// // 手动解析响应
// var result YourCustomType
// if err := resp.Unmarshal(&result); err != nil {
// return err
// }
func (c *Client) CustomPost(ctx context.Context, path string, body any) (*client.Response, error) {
return c.httpClient.Post(ctx, path, body)
}
// CustomGetAndUnmarshal 发送自定义 GET 请求并自动解析响应
// 自动处理 access_token 注入、重试逻辑和响应解析
//
// 示例:
//
// type CustomRequest struct {
// Field string `json:"field"`
// }
// type CustomResponse struct {
// client.CommonResponse
// Result string `json:"result"`
// }
// req := CustomRequest{Field: "value"}
// result, err := client.CustomGetAndUnmarshal[CustomResponse](c, ctx, "/cgi-bin/custom/api", req)
// if err != nil {
// return err
// }
// fmt.Println(result.Data)
func CustomGetAndUnmarshal[T common.Errcode](c *Client, ctx context.Context, path string, query map[string]string) (*T, error) {
q := make(map[string][]string)
for k, v := range query {
q[k] = []string{v}
}
return client.GetAndUnmarshal[T](c.httpClient, ctx, path, q)
}
// CustomPostAndUnmarshal 发送自定义 POST 请求并自动解析响应
// 自动处理 access_token 注入、重试逻辑和响应解析
//
// 示例:
//
// type CustomRequest struct {
// Field string `json:"field"`
// }
// type CustomResponse struct {
// client.CommonResponse
// Result string `json:"result"`
// }
// req := CustomRequest{Field: "value"}
// result, err := client.CustomPostAndUnmarshal[CustomResponse](c, ctx, "/cgi-bin/custom/api", req)
// if err != nil {
// return err
// }
// fmt.Println(result.Result)
func CustomPostAndUnmarshal[T common.Errcode](c *Client, ctx context.Context, path string, body any, query url.Values) (*T, error) {
return client.PostAndUnmarshalWithQuery[T](c.httpClient, ctx, path, query, body)
}
// ---- 全局单例管理 ----
var (
// ErrAlreadyInitialized 当尝试重复初始化全局客户端时返回
ErrAlreadyInitialized = errors.New("wecom: already initialized")
// ErrNotInitialized 当全局客户端尚未初始化时返回
ErrNotInitialized = errors.New("wecom: not initialized")
defaultClientMu sync.RWMutex
defaultClient *Client
)
// Init 初始化全局单例客户端。首次调用会创建并设置默认客户端,重复调用会返回 ErrAlreadyInitialized。
// 参数与 wecom.New 一致。
func Init(opts ...config.Option) error {
c, err := New(opts...)
if err != nil {
return err
}
defaultClientMu.Lock()
defer defaultClientMu.Unlock()
if defaultClient != nil {
return ErrAlreadyInitialized
}
defaultClient = c
return nil
}
// MustInit 初始化全局单例客户端,初始化失败会 panic。
func MustInit(opts ...config.Option) {
if err := Init(opts...); err != nil {
panic(err)
}
}
// SetDefault 手动设置全局默认客户端(会覆盖已存在的默认客户端)。
func SetDefault(c *Client) {
defaultClientMu.Lock()
defaultClient = c
defaultClientMu.Unlock()
}
// Default 返回全局默认客户端,若尚未初始化则返回 ErrNotInitialized。
func Default() (*Client, error) {
defaultClientMu.RLock()
c := defaultClient
defaultClientMu.RUnlock()
if c == nil {
return nil, ErrNotInitialized
}
return c, nil
}
// MustDefault 返回全局默认客户端,若尚未初始化则 panic。
func MustDefault() *Client {
c, err := Default()
if err != nil {
panic(err)
}
return c
}
func (c *Client) GetAgentByID(ctx context.Context, agentID int64) (*AgentConfig, error) {
if a, ok := c.config.Agents[fmt.Sprintf("%d", agentID)]; ok {
return a, nil
}
return nil, fmt.Errorf("agent %d not found", agentID)
}
func (c *Client) GetAgentByName(ctx context.Context, agentName string) (*AgentConfig, error) {
if a, ok := c.config.Agents[agentName]; ok {
return a, nil
}
return nil, fmt.Errorf("agent %s not found", agentName)
}