1
0
mirror of https://github.com/silenceper/wechat.git synced 2026-02-04 21:02:25 +08:00

Compare commits

..

58 Commits

Author SHA1 Message Date
ourines
45ad2ab8ca 调整结构体中CreateTime (#691)
* fix: 修改FollowInfo结构体中的tag标签为createtime

* fix: 统一CreateTime为int64

* chore: format

* chore: format
2023-06-30 09:54:12 +08:00
txws
5d0e32e2ea 微信开放平台 消息与事件url 添加result_info (#696)
* add result_info

* edit result_info

* edit-01 result_info

* 开放平台message添加小程序名称审核字段
2023-06-30 09:53:01 +08:00
markwang
822cfaa6c8 feat:企业微信-身份验证-获取用户身份及敏感信息 (#692)
Co-authored-by: markwang <www.wang61@qq.com>
2023-06-30 09:52:44 +08:00
markwang
acaab64fe7 feat:企业微信-客户联系-规则组/规则组标签 (#697)
Co-authored-by: markwang <www.wang61@qq.com>
2023-06-30 09:51:36 +08:00
markwang
b12825f83b feat:企业微信-电子发票 (#695)
Co-authored-by: markwang <www.wang61@qq.com>
2023-06-21 17:31:08 +08:00
okhowang
86cbd8c0b2 feat: 微信回调消息增加菜单ID字段 (#694)
close #693
2023-06-16 18:07:15 +08:00
markwang
46c3722308 feat:企业微信-通讯录管理-互联企业 (#688) 2023-06-12 13:34:56 +08:00
houseme
7d11af713b feat: improve workflows config and upgrade action version (#690) 2023-06-11 12:08:38 +08:00
silenceper
fafb1784da Update go.yml: 指定golangci-lint 版本为v1.52.2 (#689) 2023-06-09 20:35:49 +08:00
sam
31f8e24994 feat: 小程序/公众号增加 openApi 管理。 (#685)
* feat: 小程序/公众号增加 openApi 管理。

* update: 修改字段名大小写。

* update: 修改字段名大小写。

* style: import 换行。

* update: openApi 管理放到内部包中。
2023-06-04 21:57:15 +08:00
sam
ae1b056515 feat: 公众号: 批量获取用户信息。 (#686)
* feat: 公众号: 批量获取用户信息。

* update: 公众号: 调整批量获取用户方法的输入参数。

* update: 公众号: 调整批量获取用户方法的输入参数。
2023-05-31 21:55:21 +08:00
jingyuexing
8bae546b77 Improve developer experience (#681)
* feat: 添加query 以及query单元测试
feat: 添加模板字符串解析以及模板字符串单元测试

* improve: 序列化请求参数,使得参数更易读

* delete: delete useless module

* format: format code

* docs: add function comment

* docs: comment method

* fix: fixed type convert error

* feat: support any type

* feat: support other type

* format: format code

* test: check logger

* format: format code

* test: udpate testing case

* del: remove useless code

* del: remove useless module

* test: update testing case

*  feat: support for unsigned integers

*  feat: template string support any type
2023-05-31 17:26:43 +08:00
markwang
9df943df69 企业微信userid与openid互换 (#676)
* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* debug

* rollback

* debug

* debug

* 获取用户信息

* token

* json.Marshal错误输出

* debug

* bugfix

* 企业微信-通讯录管理相关接口

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-[联系我]方式新增和查询

* 企业微信-[联系我]方式新增和获取

* 企业微信-[联系我]方式更新

* 企业微信-[联系我]方式列表、删除

* json.Marshal错误输出

* 已实现接口bug修改

* 历史接口bugfix

* 历史接口bugfix

* comment

* 企业微信:客户联系-消息推送;素材管理-上传图片

* fix

* 企业微信-获取群发记录列表

* 历史接口bugfix

* 1.企业微信-客户联系-消息推送-入群欢迎语素材管理
2.企业微信-通讯录管理-成员管理-获取成员ID列表

* golangci-lint

* gofmt

* 方法访问命名

* 企业微信-批量获取客户详情入参优化

* 企业微信-通讯录管理-标签管理-创建/更新/删除标签

* 请求地址常量无需导出

* 企业微信保持代码风格统一,接口URL不导出

* 企业微信-通讯录管理-标签管理-获取/增加/删除标签成员、获取标签列表

* feat:企业微信userid与openid互换

---------

Co-authored-by: wang.yu <wangyu@uniondrug.com>
Co-authored-by: markwang <www.wang61@qq.com>
2023-05-16 19:22:56 +08:00
just5325
0a37184c2f 新增应用推送消息模块,实现部分常用消息推送:SendText 发送文本消息、SendImage 发送图片消息、SendVoice 发送语音消息 企业微信应用推送消息接口:https://qyapi.weixin.qq.com/cgi-bin/appchat/send (#678)
* 修正work.GetMessage()方法的注释信息

(cherry picked from commit 3dfaf9222910ae4ad977e2852908692d04118abc)

* 新增应用推送消息模块,实现部分常用消息推送:SendText 发送文本消息、SendImage 发送图片消息、SendVoice 发送语音消息
企业微信应用推送消息接口:https://qyapi.weixin.qq.com/cgi-bin/appchat/send

(cherry picked from commit 654ea158d6590a006a8c78ac3c38eafe361fe303)
2023-05-16 19:22:18 +08:00
Sunny
b4f243ab13 Fix:err != nil return nil (#680) 2023-05-16 19:20:40 +08:00
markwang
d92cd35533 企业微信-通讯录管理-标签管理-获取/增加/删除标签成员、获取标签列表 (#674)
* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* debug

* rollback

* debug

* debug

* 获取用户信息

* token

* json.Marshal错误输出

* debug

* bugfix

* 企业微信-通讯录管理相关接口

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-[联系我]方式新增和查询

* 企业微信-[联系我]方式新增和获取

* 企业微信-[联系我]方式更新

* 企业微信-[联系我]方式列表、删除

* json.Marshal错误输出

* 已实现接口bug修改

* 历史接口bugfix

* 历史接口bugfix

* comment

* 企业微信:客户联系-消息推送;素材管理-上传图片

* fix

* 企业微信-获取群发记录列表

* 历史接口bugfix

* 1.企业微信-客户联系-消息推送-入群欢迎语素材管理
2.企业微信-通讯录管理-成员管理-获取成员ID列表

* golangci-lint

* gofmt

* 方法访问命名

* 企业微信-批量获取客户详情入参优化

* 企业微信-通讯录管理-标签管理-创建/更新/删除标签

* 请求地址常量无需导出

* 企业微信保持代码风格统一,接口URL不导出

* 企业微信-通讯录管理-标签管理-获取/增加/删除标签成员、获取标签列表

---------

Co-authored-by: wang.yu <wangyu@uniondrug.com>
Co-authored-by: markwang <www.wang61@qq.com>
2023-05-08 11:56:48 +08:00
Mark
58621cd79d fix CallbackMessage open_kfid and SyncMsg error (#672)
* 企业微信微信客服字段同步

* fix ci lint

* fix open_kfid xml Unmarshal error and  'syncMsg: field `open_kfid` unexpected empty string. invalid Request Parameter'

* add struct CallbackMessage xml tag

---------

Co-authored-by: liuyuezhong <liuyuezhong@inke.cn>
2023-04-19 16:21:04 +08:00
welllog
8821a3856d feat: 获取稳定版接口调用凭据 (#669)
* feat: 获取稳定版接口调用凭据

* Update default_access_token.go

* fix: format code

---------

Co-authored-by: ctr <orinfy@foxmail.com>
Co-authored-by: houseme <housemecn@gmail.com>
2023-04-18 11:54:34 +08:00
Mark
4094adc5b4 企业微信微信客服字段同步 (#670)
* 企业微信微信客服字段同步

* fix ci lint

---------

Co-authored-by: liuyuezhong <liuyuezhong@inke.cn>
2023-04-18 11:07:06 +08:00
misu
cb0928a03c 获取企业微信实例,设置全局Cache (#671)
Co-authored-by: masong <misu99@github.com>
2023-04-18 11:06:39 +08:00
牛强
d6371c7289 chore: 移除 panic,转移 cache 初始化到 Wechat 结构体方法下;在使用时可以只设置一次 cache 同时避免 panic 出现 (#668) 2023-04-13 14:23:46 +08:00
okhowang
07b7dc40fc cache增加带Context版本,开放平台相关接口支持Context版本 (#653) 2023-04-03 20:32:44 +08:00
Ace
01784c2a4a fix:修复互通红包和视频号消息部分字段错误的数据类型声明 (#663)
* fix:修复消息存档内红包祝福语和视频号部分字段数据类型声明错误的问题

* docs:更新注释说明

* fix:校正互通红包内的数据结构声明类型
2023-04-03 20:31:58 +08:00
Guo yongrong
8bc1474777 增加发送图文消息(点击跳转到图文消息页面)使用通过 “发布” 系列接口得到的 article_id (#664)
Co-authored-by: handson@intonead.com <gyr@3332502!>
2023-04-03 18:13:25 +08:00
markwang
ca0b74e082 企业微信保持代码风格统一,接口URL不导出 (#660)
* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* debug

* rollback

* debug

* debug

* 获取用户信息

* token

* json.Marshal错误输出

* debug

* bugfix

* 企业微信-通讯录管理相关接口

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-[联系我]方式新增和查询

* 企业微信-[联系我]方式新增和获取

* 企业微信-[联系我]方式更新

* 企业微信-[联系我]方式列表、删除

* json.Marshal错误输出

* 已实现接口bug修改

* 历史接口bugfix

* 历史接口bugfix

* comment

* 企业微信:客户联系-消息推送;素材管理-上传图片

* fix

* 企业微信-获取群发记录列表

* 历史接口bugfix

* 1.企业微信-客户联系-消息推送-入群欢迎语素材管理
2.企业微信-通讯录管理-成员管理-获取成员ID列表

* golangci-lint

* gofmt

* 方法访问命名

* 企业微信-批量获取客户详情入参优化

* 企业微信-通讯录管理-标签管理-创建/更新/删除标签

* 请求地址常量无需导出

* 企业微信保持代码风格统一,接口URL不导出

---------

Co-authored-by: wang.yu <wangyu@uniondrug.com>
Co-authored-by: markwang <www.wang61@qq.com>
2023-04-03 17:06:07 +08:00
markwang
fbda048f62 企业微信-通讯录管理-标签管理-创建/更新/删除标签 (#659) 2023-03-21 23:58:37 +08:00
markwang
494082ff4f 企业微信-批量获取客户详情入参优化 (#657)
* 企业微信-批量获取客户详情入参优化

---------

Co-authored-by: wang.yu <wangyu@uniondrug.com>
Co-authored-by: markwang <www.wang61@qq.com>
2023-03-14 19:18:20 +08:00
johnpoint
9c0189340b pref: 变量命名 & url (#650) 2023-02-14 12:04:44 +08:00
realpg
d39615f2fa 补全模板消息API中遗漏的 ‘防重入ID’ 参数 (#651)
client_msg_id:
防重入id。
对于同一个openid + client_msg_id, 只发送一条消息,10分钟有效,超过10分钟不保证效果。若无防重入需求,可不填
2023-02-11 23:50:33 +08:00
just5325
429219b53f 新增消息推送模块,实现部分常用消息推送:SendText 发送文本消息、SendImage 发送图片消息、SendVoice 发送语音消息 (#649)
企业微信消息推送接口:https://qyapi.weixin.qq.com/cgi-bin/message/send
2023-02-10 17:11:02 +08:00
johnpoint
6e80b71cb2 避免无效的access_token留在cache (#645) 2023-02-08 21:19:37 +08:00
Lien Li
ab354c4d03 feat: 支持企业微信上传临时素材 (#644) 2023-02-06 08:43:41 +08:00
daguang
d1d034eb95 oauth add snapshot user mark field (#643) 2023-01-29 11:58:00 +08:00
Lien Li
1a9dbc493b feat:支持客户联系的服务端事件 (#639)
https://developer.work.weixin.qq.com/document/path/92130
2023-01-04 10:26:16 +08:00
Lien Li
04559ed4bb fix:避免游标拼接异常导致取不到数据 (#638) 2023-01-03 10:07:45 +08:00
silenceper
abd583df01 fix #636 生成短链方法报commonError is invalid or not struct (#637) 2023-01-01 23:54:58 +08:00
xuannanxan
3cb741ae1a 企业微信客户群进群方式配置(#631) (#632) 2022-11-17 09:28:42 +08:00
markwang
da3859261b 企业微信-欢迎语素材管理,企业微信-获取成员ID列表 (#629)
* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* debug

* rollback

* debug

* debug

* 获取用户信息

* token

* json.Marshal错误输出

* debug

* bugfix

* 企业微信-通讯录管理相关接口

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-[联系我]方式新增和查询

* 企业微信-[联系我]方式新增和获取

* 企业微信-[联系我]方式更新

* 企业微信-[联系我]方式列表、删除

* json.Marshal错误输出

* 已实现接口bug修改

* 历史接口bugfix

* 历史接口bugfix

* comment

* 企业微信:客户联系-消息推送;素材管理-上传图片

* fix

* 企业微信-获取群发记录列表

* 历史接口bugfix

* 1.企业微信-客户联系-消息推送-入群欢迎语素材管理
2.企业微信-通讯录管理-成员管理-获取成员ID列表

* golangci-lint

* gofmt

* 方法访问命名

Co-authored-by: wang.yu <wangyu@uniondrug.com>
2022-10-20 14:34:51 +08:00
Mr. Yang
86ceb6af2f 增加小程序审核结果回调通知 (#630)
Co-authored-by: yanglaosan <yang88can@163.com>
2022-10-17 16:52:19 +08:00
markwang
243f8198ae 企业微信-客户联系-获取群发记录列表 (#627)
* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* debug

* rollback

* debug

* debug

* 获取用户信息

* token

* json.Marshal错误输出

* debug

* bugfix

* 企业微信-通讯录管理相关接口

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-[联系我]方式新增和查询

* 企业微信-[联系我]方式新增和获取

* 企业微信-[联系我]方式更新

* 企业微信-[联系我]方式列表、删除

* json.Marshal错误输出

* 已实现接口bug修改

* 历史接口bugfix

* 历史接口bugfix

* comment

* 企业微信:客户联系-消息推送;素材管理-上传图片

* fix

* 企业微信-获取群发记录列表

* 历史接口bugfix

Co-authored-by: wang.yu <wangyu@uniondrug.com>
2022-10-12 10:03:08 +08:00
Mr. Yang
2bc0536c02 mini 开发平台代小程序实现业务逻辑完善 (#623)
* mini 代小程序实现业务逻辑完善

* mini fix ci

* fix ci1

Co-authored-by: yanglaosan <yang88can@163.com>
2022-10-10 10:08:53 +08:00
markwang
bbbada1b44 企业微信-获取群发记录列表 (#621)
* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* debug

* rollback

* debug

* debug

* 获取用户信息

* token

* json.Marshal错误输出

* debug

* bugfix

* 企业微信-通讯录管理相关接口

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-[联系我]方式新增和查询

* 企业微信-[联系我]方式新增和获取

* 企业微信-[联系我]方式更新

* 企业微信-[联系我]方式列表、删除

* json.Marshal错误输出

* 已实现接口bug修改

* 历史接口bugfix

* 历史接口bugfix

* comment

* 企业微信:客户联系-消息推送;素材管理-上传图片

* fix

* 企业微信-获取群发记录列表

Co-authored-by: wang.yu <wangyu@uniondrug.com>
2022-10-10 10:07:15 +08:00
okhowang
5380d5bee7 GetAccessToken支持Context (#618) 2022-09-29 14:33:53 +08:00
markwang
a03f3f9f32 企业微信新增接口:素材管理、企业群发 (#620)
* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* debug

* rollback

* debug

* debug

* 获取用户信息

* token

* json.Marshal错误输出

* debug

* bugfix

* 企业微信-通讯录管理相关接口

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-[联系我]方式新增和查询

* 企业微信-[联系我]方式新增和获取

* 企业微信-[联系我]方式更新

* 企业微信-[联系我]方式列表、删除

* json.Marshal错误输出

* 已实现接口bug修改

* 历史接口bugfix

* 历史接口bugfix

* comment

* 企业微信:客户联系-消息推送;素材管理-上传图片

* fix

Co-authored-by: wang.yu <wangyu@uniondrug.com>
2022-09-29 14:31:52 +08:00
markwang
9d8b803b33 企业微信历史接口bugfix (#619)
* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* debug

* rollback

* debug

* debug

* 获取用户信息

* token

* json.Marshal错误输出

* debug

* bugfix

* 企业微信-通讯录管理相关接口

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-[联系我]方式新增和查询

* 企业微信-[联系我]方式新增和获取

* 企业微信-[联系我]方式更新

* 企业微信-[联系我]方式列表、删除

* json.Marshal错误输出

* 已实现接口bug修改

* 历史接口bugfix

* 历史接口bugfix

* comment

Co-authored-by: wang.yu <wangyu@uniondrug.com>
2022-09-27 09:59:56 +08:00
chcthink
5e0c31bfa9 feat(work): 企业微信接口增加 (#617)
* feat(work): 企业微信接口增加

群机器人 查询成员信息

* 变更

* fix(fix): 修复lint 报错

* fix: 删除注释多余字符
2022-09-23 09:14:54 +08:00
markwang
9ad8981ff0 历史接口bugfix (#614)
* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* debug

* rollback

* debug

* debug

* 获取用户信息

* token

* json.Marshal错误输出

* debug

* bugfix

* 企业微信-通讯录管理相关接口

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-[联系我]方式新增和查询

* 企业微信-[联系我]方式新增和获取

* 企业微信-[联系我]方式更新

* 企业微信-[联系我]方式列表、删除

* json.Marshal错误输出

* 已实现接口bug修改

* 历史接口bugfix

Co-authored-by: wang.yu <wangyu@uniondrug.com>
2022-09-21 14:36:48 +08:00
Feng
57fd96454c fix: UniformMessage form field name (#611) 2022-09-13 12:35:20 +08:00
markwang
d09d706946 历史接口bugfix (#612) 2022-09-13 12:20:34 +08:00
gzylg
88fc6465bb 公众号用户黑名单管理 (#609) 2022-08-31 22:50:51 +08:00
markwang
b3cb101899 企业微信-客户联系实现以及json.Marshal错误输出 (#608)
* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* debug

* rollback

* debug

* debug

* 获取用户信息

* token

* json.Marshal错误输出

* debug

* bugfix

* 企业微信-通讯录管理相关接口

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-[联系我]方式新增和查询

* 企业微信-[联系我]方式新增和获取

* 企业微信-[联系我]方式更新

* 企业微信-[联系我]方式列表、删除

* json.Marshal错误输出

Co-authored-by: wang.yu <wangyu@uniondrug.com>
2022-08-25 10:03:40 +08:00
markwang
86e036a55b 企业微信-[联系我]方式列表、删除 (#606) 2022-08-23 22:07:48 +08:00
houseme
a8f7a24ff6 feat: improve comment and upgrade golang version 1.16 (#604)
* feat: improve action config and code comment

* feat: improve comment and upgrade golang version 1.16

* feat: improve import
2022-08-23 10:13:24 +08:00
markwang
df62164811 企业微信-[联系我]方式更新 (#605)
* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* 企业微信-客户联系-统计管理

* debug

* rollback

* json.Marshal错误输出

* 企业微信-通讯录管理相关接口

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-通讯录管理

* 企业微信-[联系我]方式新增和查询

* 企业微信-[联系我]方式新增和获取

* 企业微信-[联系我]方式更新

Co-authored-by: wang.yu <wangyu@uniondrug.com>
2022-08-22 14:28:52 +08:00
markwang
0160f99045 企业微信-[联系我]方式新增和获取 (#603) 2022-08-19 21:45:11 +08:00
yechuzheng
430c60a36e fix: 将小程序数据统计UserPortraitItem结构体的access_source_visit_uv改为value (#602)
Co-authored-by: Yechuzheng <yechuzheng@uino.com>
2022-08-15 19:13:05 +08:00
markwang
cac3072199 企业微信-通讯录管理 (#601) 2022-08-14 19:54:33 +08:00
Wangrong
37f9e981d6 客服管理功能添加 (#600) 2022-08-13 12:24:12 +08:00
76 changed files with 4607 additions and 338 deletions

View File

@@ -10,17 +10,21 @@ jobs:
golangci:
strategy:
matrix:
go-version: [1.15.x,1.16.x,1.17.x]
go-version: [ '1.16','1.17','1.18','1.19','1.20' ]
name: golangci-lint
runs-on: ubuntu-latest
steps:
- uses: actions/setup-go@v2
- uses: actions/checkout@v2
- name: Setup Golang ${{ matrix.go-version }}
uses: actions/setup-go@v4
with:
go-version: ${{ matrix.go-version }}
- name: Checkout
uses: actions/checkout@v3
- name: golangci-lint
uses: golangci/golangci-lint-action@v3.1.0
uses: golangci/golangci-lint-action@v3
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.31
version: v1.52.2
build:
name: Test
runs-on: ubuntu-latest
@@ -28,7 +32,7 @@ jobs:
redis:
image: redis
ports:
- 6379:6379
- 6379:6379
options: --entrypoint redis-server
memcached:
image: memcached
@@ -38,14 +42,14 @@ jobs:
# strategy set
strategy:
matrix:
go: ["1.15", "1.16", "1.17", "1.18"]
go: [ '1.16','1.17','1.18','1.19','1.20' ]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Set up Go 1.x
uses: actions/setup-go@v2
uses: actions/setup-go@v4
with:
go-version: ${{ matrix.go }}
id: go
- name: Test
run: go test -v -race ./...
run: go test -v -race ./...

View File

@@ -11,17 +11,17 @@ jobs:
steps:
-
name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
with:
fetch-depth: 0
-
name: Set up Go
uses: actions/setup-go@v2
uses: actions/setup-go@v4
with:
go-version: 1.15
go-version: 1.16
-
name: Run GoReleaser
uses: goreleaser/goreleaser-action@v2
uses: goreleaser/goreleaser-action@v4
with:
version: latest
args: release --rm-dist

46
cache/cache.go vendored
View File

@@ -1,6 +1,9 @@
package cache
import "time"
import (
"context"
"time"
)
// Cache interface
type Cache interface {
@@ -9,3 +12,44 @@ type Cache interface {
IsExist(key string) bool
Delete(key string) error
}
// ContextCache interface
type ContextCache interface {
Cache
GetContext(ctx context.Context, key string) interface{}
SetContext(ctx context.Context, key string, val interface{}, timeout time.Duration) error
IsExistContext(ctx context.Context, key string) bool
DeleteContext(ctx context.Context, key string) error
}
// GetContext get value from cache
func GetContext(ctx context.Context, cache Cache, key string) interface{} {
if cache, ok := cache.(ContextCache); ok {
return cache.GetContext(ctx, key)
}
return cache.Get(key)
}
// SetContext set value to cache
func SetContext(ctx context.Context, cache Cache, key string, val interface{}, timeout time.Duration) error {
if cache, ok := cache.(ContextCache); ok {
return cache.SetContext(ctx, key, val, timeout)
}
return cache.Set(key, val, timeout)
}
// IsExistContext check value exists in cache.
func IsExistContext(ctx context.Context, cache Cache, key string) bool {
if cache, ok := cache.(ContextCache); ok {
return cache.IsExistContext(ctx, key)
}
return cache.IsExist(key)
}
// DeleteContext delete value in cache.
func DeleteContext(ctx context.Context, cache Cache, key string) error {
if cache, ok := cache.(ContextCache); ok {
return cache.DeleteContext(ctx, key)
}
return cache.Delete(key)
}

28
cache/redis.go vendored
View File

@@ -47,7 +47,12 @@ func (r *Redis) SetRedisCtx(ctx context.Context) {
// Get 获取一个值
func (r *Redis) Get(key string) interface{} {
result, err := r.conn.Do(r.ctx, "GET", key).Result()
return r.GetContext(r.ctx, key)
}
// GetContext 获取一个值
func (r *Redis) GetContext(ctx context.Context, key string) interface{} {
result, err := r.conn.Do(ctx, "GET", key).Result()
if err != nil {
return nil
}
@@ -56,17 +61,32 @@ func (r *Redis) Get(key string) interface{} {
// Set 设置一个值
func (r *Redis) Set(key string, val interface{}, timeout time.Duration) error {
return r.conn.SetEX(r.ctx, key, val, timeout).Err()
return r.SetContext(r.ctx, key, val, timeout)
}
// SetContext 设置一个值
func (r *Redis) SetContext(ctx context.Context, key string, val interface{}, timeout time.Duration) error {
return r.conn.SetEX(ctx, key, val, timeout).Err()
}
// IsExist 判断key是否存在
func (r *Redis) IsExist(key string) bool {
result, _ := r.conn.Exists(r.ctx, key).Result()
return r.IsExistContext(r.ctx, key)
}
// IsExistContext 判断key是否存在
func (r *Redis) IsExistContext(ctx context.Context, key string) bool {
result, _ := r.conn.Exists(ctx, key).Result()
return result > 0
}
// Delete 删除
func (r *Redis) Delete(key string) error {
return r.conn.Del(r.ctx, key).Err()
return r.DeleteContext(r.ctx, key)
}
// DeleteContext 删除
func (r *Redis) DeleteContext(ctx context.Context, key string) error {
return r.conn.Del(ctx, key).Err()
}

10
cache/redis_test.go vendored
View File

@@ -4,17 +4,23 @@ import (
"context"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
)
func TestRedis(t *testing.T) {
server, err := miniredis.Run()
if err != nil {
t.Error("miniredis.Run Error", err)
}
t.Cleanup(server.Close)
var (
timeoutDuration = time.Second
ctx = context.Background()
opts = &RedisOpts{
Host: "127.0.0.1:6379",
Host: server.Addr(),
}
redis = NewRedis(ctx, opts)
err error
val = "silenceper"
key = "username"
)

View File

@@ -1,6 +1,14 @@
package credential
import "context"
// AccessTokenHandle AccessToken 接口
type AccessTokenHandle interface {
GetAccessToken() (accessToken string, err error)
}
// AccessTokenContextHandle AccessToken 接口
type AccessTokenContextHandle interface {
AccessTokenHandle
GetAccessTokenContext(ctx context.Context) (accessToken string, err error)
}

View File

@@ -1,6 +1,7 @@
package credential
import (
"context"
"encoding/json"
"fmt"
"sync"
@@ -11,9 +12,11 @@ import (
)
const (
// AccessTokenURL 获取access_token的接口
// accessTokenURL 获取access_token的接口
accessTokenURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"
// AccessTokenURL 企业微信获取access_token的接口
// stableAccessTokenURL 获取稳定版access_token的接口
stableAccessTokenURL = "https://api.weixin.qq.com/cgi-bin/stable_token"
// workAccessTokenURL 企业微信获取access_token的接口
workAccessTokenURL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s"
// CacheKeyOfficialAccountPrefix 微信公众号cache key前缀
CacheKeyOfficialAccountPrefix = "gowechat_officialaccount_"
@@ -33,7 +36,7 @@ type DefaultAccessToken struct {
}
// NewDefaultAccessToken new DefaultAccessToken
func NewDefaultAccessToken(appID, appSecret, cacheKeyPrefix string, cache cache.Cache) AccessTokenHandle {
func NewDefaultAccessToken(appID, appSecret, cacheKeyPrefix string, cache cache.Cache) AccessTokenContextHandle {
if cache == nil {
panic("cache is ineed")
}
@@ -56,6 +59,11 @@ type ResAccessToken struct {
// GetAccessToken 获取access_token,先从cache中获取没有则从服务端获取
func (ak *DefaultAccessToken) GetAccessToken() (accessToken string, err error) {
return ak.GetAccessTokenContext(context.Background())
}
// GetAccessTokenContext 获取access_token,先从cache中获取没有则从服务端获取
func (ak *DefaultAccessToken) GetAccessTokenContext(ctx context.Context) (accessToken string, err error) {
// 先从cache中取
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.appID)
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
@@ -73,17 +81,87 @@ func (ak *DefaultAccessToken) GetAccessToken() (accessToken string, err error) {
// cache失效从微信服务器获取
var resAccessToken ResAccessToken
resAccessToken, err = GetTokenFromServer(fmt.Sprintf(accessTokenURL, ak.appID, ak.appSecret))
if resAccessToken, err = GetTokenFromServerContext(ctx, fmt.Sprintf(accessTokenURL, ak.appID, ak.appSecret)); err != nil {
return
}
if err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(resAccessToken.ExpiresIn-1500)*time.Second); err != nil {
return
}
accessToken = resAccessToken.AccessToken
return
}
// StableAccessToken 获取稳定版接口调用凭据(与getAccessToken获取的调用凭证完全隔离互不影响)
// 不强制更新access_token,可用于不同环境不同服务而不需要分布式锁以及公用缓存避免access_token争抢
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html
type StableAccessToken struct {
appID string
appSecret string
cacheKeyPrefix string
cache cache.Cache
}
// NewStableAccessToken new StableAccessToken
func NewStableAccessToken(appID, appSecret, cacheKeyPrefix string, cache cache.Cache) AccessTokenContextHandle {
if cache == nil {
panic("cache is need")
}
return &StableAccessToken{
appID: appID,
appSecret: appSecret,
cache: cache,
cacheKeyPrefix: cacheKeyPrefix,
}
}
// GetAccessToken 获取access_token,先从cache中获取没有则从服务端获取
func (ak *StableAccessToken) GetAccessToken() (accessToken string, err error) {
return ak.GetAccessTokenContext(context.Background())
}
// GetAccessTokenContext 获取access_token,先从cache中获取没有则从服务端获取
func (ak *StableAccessToken) GetAccessTokenContext(ctx context.Context) (accessToken string, err error) {
// 先从cache中取
accessTokenCacheKey := fmt.Sprintf("%s_stable_access_token_%s", ak.cacheKeyPrefix, ak.appID)
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
return val.(string), nil
}
// cache失效从微信服务器获取
var resAccessToken ResAccessToken
resAccessToken, err = ak.GetAccessTokenDirectly(ctx, false)
if err != nil {
return
}
expires := resAccessToken.ExpiresIn - 1500
err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
expires := resAccessToken.ExpiresIn - 300
_ = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
accessToken = resAccessToken.AccessToken
return
}
// GetAccessTokenDirectly 从微信获取access_token
func (ak *StableAccessToken) GetAccessTokenDirectly(ctx context.Context, forceRefresh bool) (resAccessToken ResAccessToken, err error) {
b, err := util.PostJSONContext(ctx, stableAccessTokenURL, map[string]interface{}{
"grant_type": "client_credential",
"appid": ak.appID,
"secret": ak.appSecret,
"force_refresh": forceRefresh,
})
if err != nil {
return
}
accessToken = resAccessToken.AccessToken
if err = json.Unmarshal(b, &resAccessToken); err != nil {
return
}
if resAccessToken.ErrCode != 0 {
err = fmt.Errorf("get stable access_token error : errcode=%v , errormsg=%v", resAccessToken.ErrCode, resAccessToken.ErrMsg)
return
}
return
}
@@ -97,7 +175,7 @@ type WorkAccessToken struct {
}
// NewWorkAccessToken new WorkAccessToken
func NewWorkAccessToken(corpID, corpSecret, cacheKeyPrefix string, cache cache.Cache) AccessTokenHandle {
func NewWorkAccessToken(corpID, corpSecret, cacheKeyPrefix string, cache cache.Cache) AccessTokenContextHandle {
if cache == nil {
panic("cache the not exist")
}
@@ -112,6 +190,11 @@ func NewWorkAccessToken(corpID, corpSecret, cacheKeyPrefix string, cache cache.C
// GetAccessToken 企业微信获取access_token,先从cache中获取没有则从服务端获取
func (ak *WorkAccessToken) GetAccessToken() (accessToken string, err error) {
return ak.GetAccessTokenContext(context.Background())
}
// GetAccessTokenContext 企业微信获取access_token,先从cache中获取没有则从服务端获取
func (ak *WorkAccessToken) GetAccessTokenContext(ctx context.Context) (accessToken string, err error) {
// 加上lock是为了防止在并发获取token时cache刚好失效导致从微信服务器上获取到不同token
ak.accessTokenLock.Lock()
defer ak.accessTokenLock.Unlock()
@@ -124,7 +207,7 @@ func (ak *WorkAccessToken) GetAccessToken() (accessToken string, err error) {
// cache失效从微信服务器获取
var resAccessToken ResAccessToken
resAccessToken, err = GetTokenFromServer(fmt.Sprintf(workAccessTokenURL, ak.CorpID, ak.CorpSecret))
resAccessToken, err = GetTokenFromServerContext(ctx, fmt.Sprintf(workAccessTokenURL, ak.CorpID, ak.CorpSecret))
if err != nil {
return
}
@@ -140,8 +223,13 @@ func (ak *WorkAccessToken) GetAccessToken() (accessToken string, err error) {
// GetTokenFromServer 强制从微信服务器获取token
func GetTokenFromServer(url string) (resAccessToken ResAccessToken, err error) {
return GetTokenFromServerContext(context.Background(), url)
}
// GetTokenFromServerContext 强制从微信服务器获取token
func GetTokenFromServerContext(ctx context.Context, url string) (resAccessToken ResAccessToken, err error) {
var body []byte
body, err = util.HTTPGet(url)
body, err = util.HTTPGetContext(ctx, url)
if err != nil {
return
}

2
doc.go
View File

@@ -7,4 +7,6 @@ Package wechat provide wechat sdk for go
更多信息https://github.com/silenceper/wechat
*/
// Package wechat provide wechat sdk for go
package wechat

View File

@@ -1,29 +1,29 @@
# 微信公众号API列表
# 微信公众号 API 列表
## 基础接口
[官方文档](https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html)
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| :---------------------: | -------- | :------------------------- | ---------- | -------- |
| 获取Access token | GET | /cgi-bin/token | YES | |
| 获取微信服务器IP地址 | GET | /cgi-bin/get_api_domain_ip | YES | |
| 获取微信callback IP地址 | GET | /cgi-bin/getcallbackip | YES | |
| 清理接口调用次数 | POST | /cgi-bin/clear_quota | YES | |
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| :-----------------------: | -------- | :------------------------- | ---------- | -------- |
| 获取 Access token | GET | /cgi-bin/token | YES | |
| 获取微信服务器 IP 地址 | GET | /cgi-bin/get_api_domain_ip | YES | |
| 获取微信 callback IP 地址 | GET | /cgi-bin/getcallbackip | YES | |
| 清理接口调用次数 | POST | /cgi-bin/clear_quota | YES | |
## 订阅通知
[官方文档](https://developers.weixin.qq.com/doc/offiaccount/Subscription_Messages/api.html)
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| -------------------- | -------- | -------------------------------------- | ---------- | ----------------------- |
| 选用模板 | POST | /wxaapi/newtmpl/addtemplate | YES | (tpl *Subscribe) Add |
| 删除模板 | POST | /wxaapi/newtmpl/deltemplate | YES | (tpl *Subscribe) Delete |
| 获取公众号类目 | GET | /wxaapi/newtmpl/getcategory | YES | (tpl *Subscribe) GetCategory |
| 获取模板中的关键词 | GET | /wxaapi/newtmpl/getpubtemplatekeywords | YES | (tpl *Subscribe) GetPubTplKeyWordsByID |
| 获取类目下的公共模板 | GET | /wxaapi/newtmpl/getpubtemplatetitles | YES | (tpl *Subscribe) GetPublicTemplateTitleList |
| 获取私有模板列表 | GET | /wxaapi/newtmpl/gettemplate | YES | (tpl *Subscribe) List() |
| 发送订阅通知 | POST | /cgi-bin/message/subscribe/bizsend | YES | (tpl *Subscribe) Send |
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| -------------------- | -------- | -------------------------------------- | ---------- | -------------------------------------------- |
| 选用模板 | POST | /wxaapi/newtmpl/addtemplate | YES | (tpl \*Subscribe) Add |
| 删除模板 | POST | /wxaapi/newtmpl/deltemplate | YES | (tpl \*Subscribe) Delete |
| 获取公众号类目 | GET | /wxaapi/newtmpl/getcategory | YES | (tpl \*Subscribe) GetCategory |
| 获取模板中的关键词 | GET | /wxaapi/newtmpl/getpubtemplatekeywords | YES | (tpl \*Subscribe) GetPubTplKeyWordsByID |
| 获取类目下的公共模板 | GET | /wxaapi/newtmpl/getpubtemplatetitles | YES | (tpl \*Subscribe) GetPublicTemplateTitleList |
| 获取私有模板列表 | GET | /wxaapi/newtmpl/gettemplate | YES | (tpl \*Subscribe) List() |
| 发送订阅通知 | POST | /cgi-bin/message/subscribe/bizsend | YES | (tpl \*Subscribe) Send |
## 客服消息
@@ -33,14 +33,16 @@
[官方文档](https://developers.weixin.qq.com/doc/offiaccount/Customer_Service/Customer_Service_Management.html)
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| ---------------- | --------- | -------------------------------------- | ---------- | -------- |
| 获取客服基本信息 | GET | /cgi-bin/customservice/getkflist | NO | |
| 添加客服帐号 | POST | /customservice/kfaccount/add | NO | |
| 邀请绑定客服帐号 | POST | /customservice/kfaccount/inviteworker | NO | |
| 设置客服信息 | POST | /customservice/kfaccount/update | NO | |
| 上传客服头像 | POST/FORM | /customservice/kfaccount/uploadheadimg | NO | |
| 删除客服帐号 | GET | /customservice/kfaccount/del | NO | |
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| ---------------- | --------- | -------------------------------------- | ---------- | -------------------------------- |
| 获取客服基本信息 | GET | /cgi-bin/customservice/getkflist | YES | (csm \*Manager) List |
| 添加客服帐号 | POST | /customservice/kfaccount/add | YES | (csm \*Manager) Add |
| 邀请绑定客服帐号 | POST | /customservice/kfaccount/inviteworker | YES | (csm \*Manager) InviteBind |
| 设置客服信息 | POST | /customservice/kfaccount/update | YES | (csm \*Manager) Update |
| 上传客服头像 | POST/FORM | /customservice/kfaccount/uploadheadimg | YES | (csm \*Manager) UploadHeadImg |
| 删除客服帐号 | POST | /customservice/kfaccount/del | YES | (csm \*Manager) Delete |
| 获取在线客服 | POST | /cgi-bin/customservice/getonlinekflist | YES | (csm \*Manager) OnlineList |
| 下发客服输入状态 | POST | /cgi-bin/message/custom/typing | YES | (csm \*Manager) SendTypingStatus |
#### 会话控制
@@ -146,15 +148,15 @@
[官方文档](https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html)
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| ------------------------------------------------------------ | -------- | --------------------------------------------------- | ---------- | ----------------------------------- |
| 获取跳转的url地址 | GET | https://open.weixin.qq.com/connect/oauth2/authorize | YES | (oauth *Oauth) GetRedirectURL |
| 获取网页应用跳转的url地址 | GET | https://open.weixin.qq.com/connect/qrconnect | YES | (oauth *Oauth) GetWebAppRedirectURL |
| 通过网页授权的code 换取access_token(区别于context中的access_token) | GET | /sns/oauth2/access_token | YES | (oauth *Oauth) GetUserAccessToken |
| 刷新access_token | GET | /sns/oauth2/refresh_token? | YES | (oauth *Oauth) RefreshAccessToken |
| 检验access_token是否有效 | GET | /sns/auth | YES | (oauth *Oauth) CheckAccessToken( |
| 拉取用户信息(需scope为 snsapi_userinfo) | GET | /sns/userinfo | YES | (oauth *Oauth) GetUserInfo |
| 获取jssdk需要的配置参数 | GET | /cgi-bin/ticket/getticket | YES | (js *Js) GetConfig |
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| ----------------------------------------------------------------------- | -------- | --------------------------------------------------- | ---------- | ------------------------------------ |
| 获取跳转的 url 地址 | GET | https://open.weixin.qq.com/connect/oauth2/authorize | YES | (oauth \*Oauth) GetRedirectURL |
| 获取网页应用跳转的 url 地址 | GET | https://open.weixin.qq.com/connect/qrconnect | YES | (oauth \*Oauth) GetWebAppRedirectURL |
| 通过网页授权的 code 换取 access_token(区别于 context 中的 access_token) | GET | /sns/oauth2/access_token | YES | (oauth \*Oauth) GetUserAccessToken |
| 刷新 access_token | GET | /sns/oauth2/refresh_token? | YES | (oauth \*Oauth) RefreshAccessToken |
| 检验 access_token 是否有效 | GET | /sns/auth | YES | (oauth \*Oauth) CheckAccessToken( |
| 拉取用户信息(需 scope 为 snsapi_userinfo) | GET | /sns/userinfo | YES | (oauth \*Oauth) GetUserInfo |
| 获取 jssdk 需要的配置参数 | GET | /cgi-bin/ticket/getticket | YES | (js \*Js) GetConfig |
## 素材管理
@@ -162,17 +164,15 @@
[官方文档](https://developers.weixin.qq.com/doc/offiaccount/Draft_Box/Add_draft.html)
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| -------------------------- | -------- | ------------------------------------------------------------ | ---------- | ---------------------------- |
| 新建草稿 | POST | /cgi-bin/draft/add | YES | (draft *Draft) AddDraft |
| 获取草稿 | POST | /cgi-bin/draft/get | YES | (draft *Draft) GetDraft |
| 删除草稿 | POST | /cgi-bin/draft/delete | YES | (draft *Draft) DeleteDraft |
| 修改草稿 | POST | /cgi-bin/draft/update | YES | (draft *Draft) UpdateDraft |
| 获取草稿总数 | GET | /cgi-bin/draft/count | YES | (draft *Draft) CountDraft |
| 获取草稿列表 | POST | /cgi-bin/draft/batchget | YES | (draft *Draft) PaginateDraft |
| MP端开关仅内测期间使用 | POST | /cgi-bin/draft/switch<br />/cgi-bin/draft/switch?checkonly=1 | NO | |
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| --------------------------- | -------- | ------------------------------------------------------------ | ---------- | ----------------------------- |
| 新建草稿 | POST | /cgi-bin/draft/add | YES | (draft \*Draft) AddDraft |
| 获取草稿 | POST | /cgi-bin/draft/get | YES | (draft \*Draft) GetDraft |
| 删除草稿 | POST | /cgi-bin/draft/delete | YES | (draft \*Draft) DeleteDraft |
| 修改草稿 | POST | /cgi-bin/draft/update | YES | (draft \*Draft) UpdateDraft |
| 获取草稿总数 | GET | /cgi-bin/draft/count | YES | (draft \*Draft) CountDraft |
| 获取草稿列表 | POST | /cgi-bin/draft/batchget | YES | (draft \*Draft) PaginateDraft |
| MP 端开关(仅内测期间使用) | POST | /cgi-bin/draft/switch<br />/cgi-bin/draft/switch?checkonly=1 | NO | |
## 发布能力
@@ -185,20 +185,40 @@
- 群发:主动推送给粉丝,历史消息可看,被搜一搜收录,可以限定部分的粉丝接收到。
- 发布:不会主动推给粉丝,历史消息列表看不到,但是是公开给所有人的文章。也不会占用群发的次数。每天可以发布多篇内容。可以用于自动回复、自定义菜单、页面模板和话题中,发布成功时会生成一个永久链接。
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| ------------------------------ | -------- | ------------------------------- | ---------- | --------------------------------------- |
| 发布接口 | POST | /cgi-bin/freepublish/submit | YES | (freePublish *FreePublish) Publish |
| 发布状态轮询接口 | POST | /cgi-bin/freepublish/get | YES | (freePublish *FreePublish) SelectStatus |
| 事件推送发布结果 | | | YES | EventPublishJobFinish |
| 删除发布 | POST | /cgi-bin/freepublish/delete | YES | (freePublish *FreePublish) Delete |
| 通过 article_id 获取已发布文章 | POST | /cgi-bin/freepublish/getarticle | YES | (freePublish *FreePublish) First |
| 获取成功发布列表 | POST | /cgi-bin/freepublish/batchget | YES | (freePublish *FreePublish) Paginate |
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| ------------------------------ | -------- | ------------------------------- | ---------- | ---------------------------------------- |
| 发布接口 | POST | /cgi-bin/freepublish/submit | YES | (freePublish \*FreePublish) Publish |
| 发布状态轮询接口 | POST | /cgi-bin/freepublish/get | YES | (freePublish \*FreePublish) SelectStatus |
| 事件推送发布结果 | | | YES | EventPublishJobFinish |
| 删除发布 | POST | /cgi-bin/freepublish/delete | YES | (freePublish \*FreePublish) Delete |
| 通过 article_id 获取已发布文章 | POST | /cgi-bin/freepublish/getarticle | YES | (freePublish \*FreePublish) First |
| 获取成功发布列表 | POST | /cgi-bin/freepublish/batchget | YES | (freePublish \*FreePublish) Paginate |
## 图文消息留言管理
## 用户管理
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| ------------------------------------------ | -------- | -------------------------------------- | ---------- | ---------------------------------- |
| 获取指定 OpenID 变化列表(公众号账号迁移) | POST | /cgi-bin/changeopenid | YES | (user \*User) ListChangeOpenIDs |
| 获取所有用户 OpenID 列表(公众号账号迁移) | | | YES | (user \*User) ListAllChangeOpenIDs |
| 获取用户基本信息 | GET | /cgi-bin/user/info | YES | (user \*User) GetUserInfo |
| 设置用户备注名 | POST | /cgi-bin/user/info/updateremark | YES | (user \*User) UpdateRemark |
| 获取用户列表 | GET | /cgi-bin/user/get | YES | (user \*User) ListUserOpenIDs |
| 获取所有用户 OpenID 列表 | | | YES | (user \*User) ListAllUserOpenIDs |
| 获取公众号的黑名单列表 | POST | /cgi-bin/tags/members/getblacklist | YES | (user \*User) GetBlackList |
| 获取公众号的所有黑名单列表 | | | YES | (user \*User) GetAllBlackList |
| 拉黑用户 | POST | /cgi-bin/tags/members/batchblacklist | YES | (user \*User) BatchBlackList |
| 取消拉黑用户 | POST | /cgi-bin/tags/members/batchunblacklist | YES | (user \*User) BatchUnBlackList |
| 创建标签 | POST | /cgi-bin/tags/create | YES | (user \*User) CreateTag |
| 删除标签 | POST | /cgi-bin/tags/delete | YES | (user \*User) DeleteTag |
| 编辑标签 | POST | /cgi-bin/tags/update | YES | (user \*User) UpdateTag |
| 获取公众号已创建的标签 | GET | /cgi-bin/tags/get | YES | (user \*User) GetTag |
| 获取标签下粉丝列表 | POST | /cgi-bin/user/tag/get | YES | (user \*User) OpenIDListByTag |
| 批量为用户打标签 | POST | /cgi-bin/tags/members/batchtagging | YES | (user \*User) BatchTag |
| 批量为用户取消标签 | POST | /cgi-bin/tags/members/batchuntagging | YES | (user \*User) BatchUntag |
| 获取用户身上的标签列表 | POST | /cgi-bin/tags/getidlist | YES | (user \*User) UserTidList |
## 账号管理
## 数据统计
@@ -215,5 +235,4 @@
## 微信发票
## 微信非税缴费
## 微信非税缴费

View File

@@ -60,15 +60,61 @@ host: https://qyapi.weixin.qq.com/
| 获取视频号绑定状态 | GET | /cgi-bin/kf/get_corp_qualification | YES | (r *Client) GetCorpQualification | NICEXAI |
### 客户联系
[官方文档](https://developer.work.weixin.qq.com/document/path/92132/92133)
[官方文档](https://developer.work.weixin.qq.com/document/path/92132/92133/92228)
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 | 贡献者 |
|:---------------:| -------- | :---------------------------------------| ---------- | ------------------------------- |----------|
| 获取「联系客户统计」数据 | POST | /cgi-bin/externalcontact/get_user_behavior_data | YES | (r *Client) GetUserBehaviorData | MARKWANG |
| 获取「群聊数据统计」数据 (按群主聚合的方式) | POST | /cgi-bin/externalcontact/groupchat/statistic | YES | (r *Client) GetGroupChatStat | MARKWANG |
| 获取「群聊数据统计」数据 (按自然日聚合的方式) | POST | /cgi-bin/externalcontact/groupchat/statistic_group_by_day | YES | (r *Client) GetGroupChatStatByDay | MARKWANG |
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 | 贡献者 |
|:------------------------:| -------- |:-------------------------------------------------------------| ---------- | ------------------------------- |----------|
| 获取「联系客户统计」数据 | POST | /cgi-bin/externalcontact/get_user_behavior_data | YES | (r *Client) GetUserBehaviorData | MARKWANG |
| 获取「群聊数据统计」数据 (按群主聚合的方式) | POST | /cgi-bin/externalcontact/groupchat/statistic | YES | (r *Client) GetGroupChatStat | MARKWANG |
| 获取「群聊数据统计」数据 (按自然日聚合的方式) | POST | /cgi-bin/externalcontact/groupchat/statistic_group_by_day | YES | (r *Client) GetGroupChatStatByDay | MARKWANG |
| 配置客户联系「联系我」方式 | POST | /cgi-bin/externalcontact/add_contact_way | YES | (r *Client) AddContactWay | MARKWANG |
| 获取企业已配置的「联系我」方式 | POST | /cgi-bin/externalcontact/get_contact_way | YES | (r *Client) GetContactWay | MARKWANG |
| 更新企业已配置的「联系我」方式 | POST | /cgi-bin/externalcontact/update_contact_way | YES | (r *Client) UpdateContactWay | MARKWANG |
| 获取企业已配置的「联系我」列表 | POST | /cgi-bin/externalcontact/list_contact_way | YES | (r *Client) ListContactWay | MARKWANG |
| 删除企业已配置的「联系我」方式 | POST | /cgi-bin/externalcontact/del_contact_way | YES | (r *Client) DelContactWay | MARKWANG |
| 创建企业群发 | POST | /cgi-bin/externalcontact/add_msg_template | YES | (r *Client) AddMsgTemplate | MARKWANG |
| 获取群发记录列表 | POST | /cgi-bin/externalcontact/get_groupmsg_list_v2 | YES | (r *Client) GetGroupMsgListV2 | MARKWANG |
| 获取群发成员发送任务列表 | POST | /cgi-bin/externalcontact/get_groupmsg_task | YES | (r *Client) GetGroupMsgTask | MARKWANG |
| 获取企业群发成员执行结果 | POST | /cgi-bin/externalcontact/get_groupmsg_send_result | YES | (r *Client) GetGroupMsgSendResult | MARKWANG |
| 发送新客户欢迎语 | POST | /cgi-bin/externalcontact/send_welcome_msg | YES | (r *Client) SendWelcomeMsg | MARKWANG |
| 添加入群欢迎语素材 | POST | /cgi-bin/externalcontact/group_welcome_template/add | YES | (r *Client) AddGroupWelcomeTemplate | MARKWANG |
| 编辑入群欢迎语素材 | POST | /cgi-bin/externalcontact/group_welcome_template/edit | YES | (r *Client) EditGroupWelcomeTemplate | MARKWANG |
| 获取入群欢迎语素材 | POST | /cgi-bin/externalcontact/group_welcome_template/get | YES | (r *Client) GetGroupWelcomeTemplate | MARKWANG |
| 删除入群欢迎语素材 | POST | /cgi-bin/externalcontact/group_welcome_template/del | YES | (r *Client) DelGroupWelcomeTemplate | MARKWANG |
## 通讯录管理
[官方文档](https://developer.work.weixin.qq.com/document/path/90193)
### 部门管理
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 | 贡献者 |
|:---------:|------|:----------------------------------------| ---------- | ------------------------------- |----------|
| 获取子部门ID列表 | GET | /cgi-bin/department/simplelist | YES | (r *Client) DepartmentSimpleList| MARKWANG |
| 获取部门成员 | GET | /cgi-bin/user/simplelist | YES | (r *Client) UserSimpleList | MARKWANG |
| 获取成员ID列表 | Post | /cgi-bin/user/list_id | YES | (r *Client) UserListId | MARKWANG |
## 素材管理
[官方文档](https://developer.work.weixin.qq.com/document/path/91054)
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 | 贡献者 |
|:---------:|------|:----------------------------------------| ---------- | ------------------------------- |----------|
| 上传图片 | POST | /cgi-bin/media/uploadimg | YES | (r *Client) UploadImg| MARKWANG |
### 成员管理
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 | 贡献者 |
| -------- | -------- | ----------------- | ---------- | ------------------- | -------- |
| 读取成员 | GET | /cgi-bin/user/get | YES | (r *Client) UserGet | chcthink |
## 群机器人
[官方文档](https://developer.work.weixin.qq.com/document/path/91770)
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 | 贡献者 |
| ---------------- | -------- | --------------------- | ---------- | -------------------------- | -------- |
| 群机器人发送消息 | POST | /cgi-bin/webhook/send | YES | (r *Client) RobotBroadcast | chcthink |
## 应用管理
TODO

36
domain/openapi/mgnt.go Normal file
View File

@@ -0,0 +1,36 @@
package openapi
import "github.com/silenceper/wechat/v2/util"
// GetAPIQuotaParams 查询API调用额度参数
type GetAPIQuotaParams struct {
CgiPath string `json:"cgi_path"` // api的请求地址例如"/cgi-bin/message/custom/send";不要前缀“https://api.weixin.qq.com” ,也不要漏了"/",否则都会76003的报错
}
// APIQuota API调用额度
type APIQuota struct {
util.CommonError
Quota struct {
DailyLimit int64 `json:"daily_limit"` // 当天该账号可调用该接口的次数
Used int64 `json:"used"` // 当天已经调用的次数
Remain int64 `json:"remain"` // 当天剩余调用次数
} `json:"quota"` // 详情
}
// GetRidInfoParams 查询rid信息参数
type GetRidInfoParams struct {
Rid string `json:"rid"` // 调用接口报错返回的rid
}
// RidInfo rid信息
type RidInfo struct {
util.CommonError
Request struct {
InvokeTime int64 `json:"invoke_time"` // 发起请求的时间戳
CostInMs int64 `json:"cost_in_ms"` // 请求毫秒级耗时
RequestURL string `json:"request_url"` // 请求的URL参数
RequestBody string `json:"request_body"` // post请求的请求参数
ResponseBody string `json:"response_body"` // 接口请求返回参数
ClientIP string `json:"client_ip"` // 接口请求的客户端ip
} `json:"request"` // 该rid对应的请求详情
}

3
go.mod
View File

@@ -1,8 +1,9 @@
module github.com/silenceper/wechat/v2
go 1.15
go 1.16
require (
github.com/alicebob/miniredis/v2 v2.30.0
github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d
github.com/fatih/structs v1.1.0
github.com/go-redis/redis/v8 v8.11.5

12
go.sum
View File

@@ -1,3 +1,7 @@
github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a h1:HbKu58rmZpUGpz5+4FfNmIU+FmZg2P3Xaj2v2bfNWmk=
github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
github.com/alicebob/miniredis/v2 v2.30.0 h1:uA3uhDbCxfO9+DI/DuGeAMr9qI+noVWwGPNTFuKID5M=
github.com/alicebob/miniredis/v2 v2.30.0/go.mod h1:84TWKZlxYkfgMucPBf5SOQBYJceZeQRFIaQgNMiCX6Q=
github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d h1:pVrfxiGfwelyab6n21ZBkbkmbevaf+WvMIiR7sr97hw=
github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
@@ -26,12 +30,10 @@ github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:W
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw=
@@ -48,7 +50,6 @@ github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
github.com/onsi/ginkgo/v2 v2.0.0 h1:CcuG/HvWNkkaqCUpJifQY8z7qEMBJya6aLPx6ftGyjQ=
github.com/onsi/ginkgo/v2 v2.0.0/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
@@ -74,6 +75,8 @@ github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JT
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/gopher-lua v0.0.0-20220504180219-658193537a64 h1:5mLPGnFdSsevFRFc9q3yYbBkB6tsm4aCwwQV/j1JQAQ=
github.com/yuin/gopher-lua v0.0.0-20220504180219-658193537a64/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
@@ -92,6 +95,7 @@ golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -118,7 +122,6 @@ golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4f
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
@@ -127,7 +130,6 @@ google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miE
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

127
internal/openapi/mgnt.go Normal file
View File

@@ -0,0 +1,127 @@
package openapi
import (
"errors"
"fmt"
"github.com/silenceper/wechat/v2/domain/openapi"
mpContext "github.com/silenceper/wechat/v2/miniprogram/context"
ocContext "github.com/silenceper/wechat/v2/officialaccount/context"
"github.com/silenceper/wechat/v2/util"
)
const (
clearQuotaURL = "https://api.weixin.qq.com/cgi-bin/clear_quota" // 重置API调用次数
getAPIQuotaURL = "https://api.weixin.qq.com/cgi-bin/openapi/quota/get" // 查询API调用额度
getRidInfoURL = "https://api.weixin.qq.com/cgi-bin/openapi/rid/get" // 查询rid信息
clearQuotaByAppSecretURL = "https://api.weixin.qq.com/cgi-bin/clear_quota/v2" // 使用AppSecret重置 API 调用次数
)
// OpenAPI openApi管理
type OpenAPI struct {
ctx interface{}
}
// NewOpenAPI 实例化
func NewOpenAPI(ctx interface{}) *OpenAPI {
return &OpenAPI{ctx: ctx}
}
// ClearQuota 重置API调用次数
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/openApi-mgnt/clearQuota.html
func (o *OpenAPI) ClearQuota() error {
appID, _, err := o.getAppIDAndSecret()
if err != nil {
return err
}
var payload = struct {
AppID string `json:"appid"`
}{
AppID: appID,
}
res, err := o.doPostRequest(clearQuotaURL, payload)
if err != nil {
return err
}
return util.DecodeWithCommonError(res, "ClearQuota")
}
// GetAPIQuota 查询API调用额度
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/openApi-mgnt/getApiQuota.html
func (o *OpenAPI) GetAPIQuota(params openapi.GetAPIQuotaParams) (quota openapi.APIQuota, err error) {
res, err := o.doPostRequest(getAPIQuotaURL, params)
if err != nil {
return
}
err = util.DecodeWithError(res, &quota, "GetAPIQuota")
return
}
// GetRidInfo 查询rid信息
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/openApi-mgnt/getRidInfo.html
func (o *OpenAPI) GetRidInfo(params openapi.GetRidInfoParams) (r openapi.RidInfo, err error) {
res, err := o.doPostRequest(getRidInfoURL, params)
if err != nil {
return
}
err = util.DecodeWithError(res, &r, "GetRidInfo")
return
}
// ClearQuotaByAppSecret 使用AppSecret重置 API 调用次数
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/openApi-mgnt/clearQuotaByAppSecret.html
func (o *OpenAPI) ClearQuotaByAppSecret() error {
id, secret, err := o.getAppIDAndSecret()
if err != nil {
return err
}
uri := fmt.Sprintf("%s?appid=%s&appsecret=%s", clearQuotaByAppSecretURL, id, secret)
res, err := util.HTTPPost(uri, "")
if err != nil {
return err
}
return util.DecodeWithCommonError(res, "ClearQuotaByAppSecret")
}
// 获取 AppID 和 AppSecret
func (o *OpenAPI) getAppIDAndSecret() (string, string, error) {
switch o.ctx.(type) {
case *mpContext.Context:
c := o.ctx.(*mpContext.Context)
return c.AppID, c.AppSecret, nil
case *ocContext.Context:
c := o.ctx.(*ocContext.Context)
return c.AppID, c.AppSecret, nil
default:
return "", "", errors.New("invalid context type")
}
}
// 获取 AccessToken
func (o *OpenAPI) getAccessToken() (string, error) {
switch o.ctx.(type) {
case *mpContext.Context:
return o.ctx.(*mpContext.Context).GetAccessToken()
case *ocContext.Context:
return o.ctx.(*ocContext.Context).GetAccessToken()
default:
return "", errors.New("invalid context type")
}
}
// 创建 POST 请求
func (o *OpenAPI) doPostRequest(uri string, payload interface{}) ([]byte, error) {
ak, err := o.getAccessToken()
if err != nil {
return nil, err
}
uri = fmt.Sprintf("%s?access_token=%s", uri, ak)
return util.PostJSON(uri, payload)
}

View File

@@ -190,9 +190,9 @@ func (analysis *Analysis) GetAnalysisWeeklyVisitTrend(beginDate, endDate string)
// UserPortraitItem 用户画像项目
type UserPortraitItem struct {
ID int `json:"id"` // 属性值id
Name string `json:"name"` // 属性值名称
AccessSourceVisitUV int `json:"access_source_visit_uv"` // 该场景访问uv
ID int `json:"id"` // 属性值id
Name string `json:"name"` // 属性值名称
Value int `json:"value"` // 该场景访问uv
}
// UserPortrait 用户画像

View File

@@ -40,8 +40,8 @@ type ResCode2Session struct {
type RspCheckEncryptedData struct {
util.CommonError
Vaild bool `json:"vaild"` // 是否是合法的数据
CreateTime uint `json:"create_time"` // 加密数据生成的时间戳
Vaild bool `json:"vaild"` // 是否是合法的数据
CreateTime uint64 `json:"create_time"` // 加密数据生成的时间戳
}
// Code2Session 登录凭证校验。

View File

@@ -2,6 +2,7 @@ package miniprogram
import (
"github.com/silenceper/wechat/v2/credential"
"github.com/silenceper/wechat/v2/internal/openapi"
"github.com/silenceper/wechat/v2/miniprogram/analysis"
"github.com/silenceper/wechat/v2/miniprogram/auth"
"github.com/silenceper/wechat/v2/miniprogram/business"
@@ -126,3 +127,8 @@ func (miniProgram *MiniProgram) GetShortLink() *shortlink.ShortLink {
func (miniProgram *MiniProgram) GetSURLScheme() *urlscheme.URLScheme {
return urlscheme.NewURLScheme(miniProgram.ctx)
}
// GetOpenAPI openApi管理接口
func (miniProgram *MiniProgram) GetOpenAPI() *openapi.OpenAPI {
return openapi.NewOpenAPI(miniProgram.ctx)
}

View File

@@ -37,7 +37,7 @@ type ShortLinker struct {
// resShortLinker 返回结构体
type resShortLinker struct {
// 通用错误
*util.CommonError
util.CommonError
// 返回的 shortLink
Link string `json:"link"`

View File

@@ -121,7 +121,7 @@ type UniformMessage struct {
URL string `json:"url"`
Miniprogram struct {
Appid string `json:"appid"`
Pagepath string `json:"page"`
Pagepath string `json:"pagepath"`
} `json:"miniprogram"`
Data map[string]*DataItem `json:"data"`
} `json:"mp_template_msg"`

View File

@@ -18,6 +18,7 @@ type InvokeCloudFunctionRes struct {
}
// InvokeCloudFunction 云函数调用
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/functions/invokeCloudFunction.html
func (tcb *Tcb) InvokeCloudFunction(env, name, args string) (*InvokeCloudFunctionRes, error) {
accessToken, err := tcb.GetAccessToken()

View File

@@ -192,6 +192,7 @@ type DatabaseCountRes struct {
}
// DatabaseMigrateImport 数据库导入
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/database/databaseMigrateImport.html
func (tcb *Tcb) DatabaseMigrateImport(req *DatabaseMigrateImportReq) (*DatabaseMigrateImportRes, error) {
accessToken, err := tcb.GetAccessToken()
@@ -209,6 +210,7 @@ func (tcb *Tcb) DatabaseMigrateImport(req *DatabaseMigrateImportReq) (*DatabaseM
}
// DatabaseMigrateExport 数据库导出
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/database/databaseMigrateExport.html
func (tcb *Tcb) DatabaseMigrateExport(req *DatabaseMigrateExportReq) (*DatabaseMigrateExportRes, error) {
accessToken, err := tcb.GetAccessToken()
@@ -226,6 +228,7 @@ func (tcb *Tcb) DatabaseMigrateExport(req *DatabaseMigrateExportReq) (*DatabaseM
}
// DatabaseMigrateQueryInfo 数据库迁移状态查询
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/database/databaseMigrateQueryInfo.html
func (tcb *Tcb) DatabaseMigrateQueryInfo(env string, jobID int64) (*DatabaseMigrateQueryInfoRes, error) {
accessToken, err := tcb.GetAccessToken()
@@ -261,6 +264,7 @@ func (tcb *Tcb) UpdateIndex(req *UpdateIndexReq) error {
}
// DatabaseCollectionAdd 新增集合
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/database/databaseCollectionAdd.html
func (tcb *Tcb) DatabaseCollectionAdd(env, collectionName string) error {
accessToken, err := tcb.GetAccessToken()
@@ -279,6 +283,7 @@ func (tcb *Tcb) DatabaseCollectionAdd(env, collectionName string) error {
}
// DatabaseCollectionDelete 删除集合
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/database/databaseCollectionDelete.html
func (tcb *Tcb) DatabaseCollectionDelete(env, collectionName string) error {
accessToken, err := tcb.GetAccessToken()
@@ -297,6 +302,7 @@ func (tcb *Tcb) DatabaseCollectionDelete(env, collectionName string) error {
}
// DatabaseCollectionGet 获取特定云环境下集合信息
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/database/databaseCollectionGet.html
func (tcb *Tcb) DatabaseCollectionGet(env string, limit, offset int64) (*DatabaseCollectionGetRes, error) {
accessToken, err := tcb.GetAccessToken()
@@ -318,6 +324,7 @@ func (tcb *Tcb) DatabaseCollectionGet(env string, limit, offset int64) (*Databas
}
// DatabaseAdd 数据库插入记录
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/database/databaseAdd.html
func (tcb *Tcb) DatabaseAdd(env, query string) (*DatabaseAddRes, error) {
accessToken, err := tcb.GetAccessToken()
@@ -338,6 +345,7 @@ func (tcb *Tcb) DatabaseAdd(env, query string) (*DatabaseAddRes, error) {
}
// DatabaseDelete 数据库插入记录
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/database/databaseDelete.html
func (tcb *Tcb) DatabaseDelete(env, query string) (*DatabaseDeleteRes, error) {
accessToken, err := tcb.GetAccessToken()
@@ -358,6 +366,7 @@ func (tcb *Tcb) DatabaseDelete(env, query string) (*DatabaseDeleteRes, error) {
}
// DatabaseUpdate 数据库插入记录
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/database/databaseUpdate.html
func (tcb *Tcb) DatabaseUpdate(env, query string) (*DatabaseUpdateRes, error) {
accessToken, err := tcb.GetAccessToken()
@@ -378,6 +387,7 @@ func (tcb *Tcb) DatabaseUpdate(env, query string) (*DatabaseUpdateRes, error) {
}
// DatabaseQuery 数据库查询记录
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/database/databaseQuery.html
func (tcb *Tcb) DatabaseQuery(env, query string) (*DatabaseQueryRes, error) {
accessToken, err := tcb.GetAccessToken()
@@ -398,6 +408,7 @@ func (tcb *Tcb) DatabaseQuery(env, query string) (*DatabaseQueryRes, error) {
}
// DatabaseCount 统计集合记录数或统计查询语句对应的结果记录数
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/database/databaseCount.html
func (tcb *Tcb) DatabaseCount(env, query string) (*DatabaseCountRes, error) {
accessToken, err := tcb.GetAccessToken()

View File

@@ -71,6 +71,7 @@ type BatchDeleteFileRes struct {
}
// UploadFile 上传文件
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/storage/uploadFile.html
func (tcb *Tcb) UploadFile(env, path string) (*UploadFileRes, error) {
accessToken, err := tcb.GetAccessToken()
@@ -92,6 +93,7 @@ func (tcb *Tcb) UploadFile(env, path string) (*UploadFileRes, error) {
}
// BatchDownloadFile 获取文件下载链接
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/storage/batchDownloadFile.html
func (tcb *Tcb) BatchDownloadFile(env string, fileList []*DownloadFile) (*BatchDownloadFileRes, error) {
accessToken, err := tcb.GetAccessToken()
@@ -113,6 +115,7 @@ func (tcb *Tcb) BatchDownloadFile(env string, fileList []*DownloadFile) (*BatchD
}
// BatchDeleteFile 批量删除文件
//
//reference:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/storage/batchDeleteFile.html
func (tcb *Tcb) BatchDeleteFile(env string, fileIDList []string) (*BatchDeleteFileRes, error) {
accessToken, err := tcb.GetAccessToken()

View File

@@ -0,0 +1,253 @@
package customerservice
import (
"fmt"
"github.com/silenceper/wechat/v2/officialaccount/context"
"github.com/silenceper/wechat/v2/util"
)
// TypingStatus 输入状态类型
type TypingStatus string
const (
customerServiceListURL = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist"
customerServiceOnlineListURL = "https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist"
customerServiceAddURL = "https://api.weixin.qq.com/customservice/kfaccount/add"
customerServiceUpdateURL = "https://api.weixin.qq.com/customservice/kfaccount/update"
customerServiceDeleteURL = "https://api.weixin.qq.com/customservice/kfaccount/del"
customerServiceInviteURL = "https://api.weixin.qq.com/customservice/kfaccount/inviteworker"
customerServiceUploadHeadImg = "https://api.weixin.qq.com/customservice/kfaccount/uploadheadimg"
customerServiceTypingURL = "https://api.weixin.qq.com/cgi-bin/message/custom/typing"
)
const (
// Typing 表示正在输入状态
Typing TypingStatus = "Typing"
// CancelTyping 表示取消正在输入状态
CancelTyping TypingStatus = "CancelTyping"
)
// Manager 客服管理者,可以管理客服
type Manager struct {
*context.Context
}
// NewCustomerServiceManager 实例化客服管理
func NewCustomerServiceManager(ctx *context.Context) *Manager {
csm := new(Manager)
csm.Context = ctx
return csm
}
// KeFuInfo 客服基本信息
type KeFuInfo struct {
KfAccount string `json:"kf_account"` // 完整客服帐号,格式为:帐号前缀@公众号微信号
KfNick string `json:"kf_nick"` // 客服昵称
KfID int `json:"kf_id"` // 客服编号
KfHeadImgURL string `json:"kf_headimgurl"` // 客服头像
KfWX string `json:"kf_wx"` // 如果客服帐号已绑定了客服人员微信号, 则此处显示微信号
InviteWX string `json:"invite_wx"` // 如果客服帐号尚未绑定微信号,但是已经发起了一个绑定邀请, 则此处显示绑定邀请的微信号
InviteExpTime int `json:"invite_expire_time"` // 如果客服帐号尚未绑定微信号,但是已经发起过一个绑定邀请, 邀请的过期时间为unix 时间戳
InviteStatus string `json:"invite_status"` // 邀请的状态有等待确认“waiting”被拒绝“rejected” 过期“expired”
}
type resKeFuList struct {
util.CommonError
KfList []*KeFuInfo `json:"kf_list"`
}
// List 获取所有客服基本信息
func (csm *Manager) List() (customerServiceList []*KeFuInfo, err error) {
var accessToken string
accessToken, err = csm.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?access_token=%s", customerServiceListURL, accessToken)
var response []byte
response, err = util.HTTPGet(uri)
if err != nil {
return
}
var res resKeFuList
err = util.DecodeWithError(response, &res, "ListCustomerService")
if err != nil {
return
}
customerServiceList = res.KfList
return
}
// KeFuOnlineInfo 客服在线信息
type KeFuOnlineInfo struct {
KfAccount string `json:"kf_account"`
Status int `json:"status"`
KfID int `json:"kf_id"`
AcceptedCase int `json:"accepted_case"`
}
type resKeFuOnlineList struct {
util.CommonError
KfOnlineList []*KeFuOnlineInfo `json:"kf_online_list"`
}
// OnlineList 获取在线客服列表
func (csm *Manager) OnlineList() (customerServiceOnlineList []*KeFuOnlineInfo, err error) {
var accessToken string
accessToken, err = csm.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?access_token=%s", customerServiceOnlineListURL, accessToken)
var response []byte
response, err = util.HTTPGet(uri)
if err != nil {
return
}
var res resKeFuOnlineList
err = util.DecodeWithError(response, &res, "ListOnlineCustomerService")
if err != nil {
return
}
customerServiceOnlineList = res.KfOnlineList
return
}
// Add 添加客服账号
func (csm *Manager) Add(kfAccount, nickName string) (err error) {
// kfAccount完整客服帐号格式为帐号前缀@公众号微信号帐号前缀最多10个字符必须是英文、数字字符或者下划线后缀为公众号微信号长度不超过30个字符
// nickName客服昵称最长16个字
// 参数此处均不做校验
var accessToken string
accessToken, err = csm.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?access_token=%s", customerServiceAddURL, accessToken)
data := struct {
KfAccount string `json:"kf_account"`
NickName string `json:"nickname"`
}{
KfAccount: kfAccount,
NickName: nickName,
}
var response []byte
response, err = util.PostJSON(uri, data)
if err != nil {
return
}
err = util.DecodeWithCommonError(response, "AddCustomerService")
return
}
// Update 修改客服账号
func (csm *Manager) Update(kfAccount, nickName string) (err error) {
var accessToken string
accessToken, err = csm.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?access_token=%s", customerServiceUpdateURL, accessToken)
data := struct {
KfAccount string `json:"kf_account"`
NickName string `json:"nickname"`
}{
KfAccount: kfAccount,
NickName: nickName,
}
var response []byte
response, err = util.PostJSON(uri, data)
if err != nil {
return
}
err = util.DecodeWithCommonError(response, "UpdateCustomerService")
return
}
// Delete 删除客服帐号
func (csm *Manager) Delete(kfAccount string) (err error) {
var accessToken string
accessToken, err = csm.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?access_token=%s", customerServiceDeleteURL, accessToken)
data := struct {
KfAccount string `json:"kf_account"`
}{
KfAccount: kfAccount,
}
var response []byte
response, err = util.PostJSON(uri, data)
if err != nil {
return
}
err = util.DecodeWithCommonError(response, "DeleteCustomerService")
return
}
// InviteBind 邀请绑定客服帐号和微信号
func (csm *Manager) InviteBind(kfAccount, inviteWX string) (err error) {
var accessToken string
accessToken, err = csm.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?access_token=%s", customerServiceInviteURL, accessToken)
data := struct {
KfAccount string `json:"kf_account"`
InviteWX string `json:"invite_wx"`
}{
KfAccount: kfAccount,
InviteWX: inviteWX,
}
var response []byte
response, err = util.PostJSON(uri, data)
if err != nil {
return
}
err = util.DecodeWithCommonError(response, "InviteBindCustomerService")
return
}
// UploadHeadImg 上传客服头像
func (csm *Manager) UploadHeadImg(kfAccount, fileName string) (err error) {
var accessToken string
accessToken, err = csm.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?access_token=%s&kf_account=%s", customerServiceUploadHeadImg, accessToken, kfAccount)
var response []byte
response, err = util.PostFile("media", fileName, uri)
if err != nil {
return
}
err = util.DecodeWithCommonError(response, "UploadCustomerServiceHeadImg")
return
}
// SendTypingStatus 下发客服输入状态给用户
func (csm *Manager) SendTypingStatus(openid string, cmd TypingStatus) (err error) {
var accessToken string
accessToken, err = csm.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?access_token=%s", customerServiceTypingURL, accessToken)
data := struct {
ToUser string `json:"touser"`
Command string `json:"command"`
}{
ToUser: openid,
Command: string(cmd),
}
var response []byte
response, err = util.PostJSON(uri, data)
if err != nil {
return
}
err = util.DecodeWithCommonError(response, "SendTypingStatus")
return
}

View File

@@ -302,6 +302,7 @@ type reqBatchGetMaterial struct {
}
// BatchGetMaterial 批量获取永久素材
//
//reference:https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Get_materials_list.html
func (material *Material) BatchGetMaterial(permanentMaterialType PermanentMaterialType, offset, count int64) (list ArticleList, err error) {
var accessToken string

View File

@@ -38,6 +38,7 @@ type CustomerMessage struct {
Wxcard *MediaWxcard `json:"wxcard,omitempty"` // 可选
Msgmenu *MediaMsgmenu `json:"msgmenu,omitempty"` // 可选
Miniprogrampage *MediaMiniprogrampage `json:"miniprogrampage,omitempty"` // 可选
Mpnewsarticle *MediaArticle `json:"mpnewsarticle,omitempty"` // 可选
}
// NewCustomerTextMessage 文本消息结构体构造方法
@@ -97,6 +98,11 @@ type MediaResource struct {
MediaID string `json:"media_id"`
}
// MediaArticle 消息使用的已发布文章id
type MediaArticle struct {
ArticleID string `json:"article_id"`
}
// MediaVideo 视频消息包含的内容
type MediaVideo struct {
MediaID string `json:"media_id"`

View File

@@ -80,6 +80,12 @@ const (
EventSubscribeMsgPopupEvent EventType = "subscribe_msg_popup_event"
// EventPublishJobFinish 发布任务完成
EventPublishJobFinish EventType = "PUBLISHJOBFINISH"
// EventWeappAuditSuccess 审核通过
EventWeappAuditSuccess EventType = "weapp_audit_success"
// EventWeappAuditFail 审核不通过
EventWeappAuditFail EventType = "weapp_audit_fail"
// EventWeappAuditDelay 审核延后
EventWeappAuditDelay EventType = "weapp_audit_delay"
)
const (
@@ -117,6 +123,7 @@ type MixMessage struct {
Title string `xml:"Title"`
Description string `xml:"Description"`
URL string `xml:"Url"`
BizMsgMenuID int64 `xml:"bizmsgmenuid"`
// 事件相关
Event EventType `xml:"Event" json:"Event"`
@@ -189,6 +196,14 @@ type MixMessage struct {
LegalPersonaName string `xml:"legal_persona_name"`
ComponentPhone string `xml:"component_phone"`
} `xml:"info"`
ResultInfo struct {
APIName string `xml:"api_name"`
ApplyTime string `xml:"apply_time"`
AuditID string `xml:"audit_id"`
AuditTime string `xml:"audit_time"`
Reason string `xml:"reason"`
Status string `xml:"status"`
} `xml:"result_info"`
// 卡券相关
CardID string `xml:"CardId"`
@@ -207,8 +222,19 @@ type MixMessage struct {
TraceID string `xml:"trace_id"`
StatusCode int `xml:"status_code"`
//小程序名称审核结果事件推送
Ret int32 `xml:"ret"` //审核结果 2失败3成功
NickName string `xml:"nickname"` //小程序昵称
// 设备相关
device.MsgDevice
//小程序审核通知
SuccTime int `xml:"SuccTime"` //审核成功时的时间戳
FailTime int `xml:"FailTime"` //审核不通过的时间戳
DelayTime int `xml:"DelayTime"` //审核延后时的时间戳
Reason string `xml:"Reason"` //审核不通过的原因
ScreenShot string `xml:"ScreenShot"` //审核不通过的截图示例。用 | 分隔的 media_id 的列表,可通过获取永久素材接口拉取截图内容
}
// SubscribeMsgPopupEvent 订阅通知事件推送的消息体

View File

@@ -151,8 +151,8 @@ func (tpl *Subscribe) Delete(templateID string) (err error) {
// PublicTemplateCategory 公众号类目
type PublicTemplateCategory struct {
ID int `json:"id"` //类目ID
Name string `json:"name"` //类目的中文名
ID int `json:"id"` // 类目ID
Name string `json:"name"` // 类目的中文名
}
type resSubscribeCategoryList struct {
@@ -186,13 +186,13 @@ func (tpl *Subscribe) GetCategory() (categoryList []*PublicTemplateCategory, err
type PublicTemplateKeyWords struct {
KeyWordsID int `json:"kid"` // 关键词 id
Name string `json:"name"` // 关键词内容
Example string `json:"example"` //关键词内容对应的示例
Example string `json:"example"` // 关键词内容对应的示例
Rule string `json:"rule"` // 参数类型
}
type resPublicTemplateKeyWordsList struct {
util.CommonError
KeyWordsList []*PublicTemplateKeyWords `json:"data"` //关键词列表
KeyWordsList []*PublicTemplateKeyWords `json:"data"` // 关键词列表
}
// GetPubTplKeyWordsByID 获取模板中的关键词
@@ -227,8 +227,8 @@ type PublicTemplateTitle struct {
type resPublicTemplateTitleList struct {
util.CommonError
Count int `json:"count"` //公共模板列表总数
TemplateTitleList []*PublicTemplateTitle `json:"data"` //模板标题列表
Count int `json:"count"` // 公共模板列表总数
TemplateTitleList []*PublicTemplateTitle `json:"data"` // 模板标题列表
}
// GetPublicTemplateTitleList 获取类目下的公共模板

View File

@@ -29,11 +29,12 @@ func NewTemplate(context *context.Context) *Template {
// TemplateMessage 发送的模板消息内容
type TemplateMessage struct {
ToUser string `json:"touser"` // 必须, 接受者OpenID
TemplateID string `json:"template_id"` // 必须, 模版ID
URL string `json:"url,omitempty"` // 可选, 用户点击后跳转的URL, 该URL必须处于开发者在公众平台网站中设置的域中
Color string `json:"color,omitempty"` // 可选, 整个消息的颜色, 可以不设置
Data map[string]*TemplateDataItem `json:"data"` // 必须, 模板数据
ToUser string `json:"touser"` // 必须, 接受者OpenID
TemplateID string `json:"template_id"` // 必须, 模版ID
URL string `json:"url,omitempty"` // 可选, 用户点击后跳转的URL, 该URL必须处于开发者在公众平台网站中设置的域中
Color string `json:"color,omitempty"` // 可选, 整个消息的颜色, 可以不设置
Data map[string]*TemplateDataItem `json:"data"` // 必须, 模板数据
ClientMsgID string `json:"client_msg_id,omitempty"` // 可选, 防重入ID
MiniProgram struct {
AppID string `json:"appid"` // 所需跳转到的小程序appid该小程序appid必须与发模板消息的公众号是绑定关联关系

View File

@@ -64,6 +64,10 @@ type ResAccessToken struct {
OpenID string `json:"openid"`
Scope string `json:"scope"`
// IsSnapShotUser 是否为快照页模式虚拟账号只有当用户是快照页模式虚拟账号时返回值为1
// 公众号文档 https://developers.weixin.qq.com/community/minihome/doc/000c2c34068880629ced91a2f56001
IsSnapShotUser int `json:"is_snapshotuser"`
// UnionID 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
// 公众号文档 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
UnionID string `json:"unionid"`

View File

@@ -154,134 +154,120 @@ func NewOCR(c *context.Context) *OCR {
}
// IDCard 身份证OCR识别接口
func (ocr *OCR) IDCard(path string) (ResIDCard ResIDCard, err error) {
func (ocr *OCR) IDCard(path string) (resIDCard ResIDCard, err error) {
accessToken, err := ocr.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrIDCardURL, url.QueryEscape(path), accessToken)
response, err := util.HTTPPost(uri, "")
response, err := util.HTTPPost(fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrIDCardURL, url.QueryEscape(path), accessToken), "")
if err != nil {
return
}
err = util.DecodeWithError(response, &ResIDCard, "OCRIDCard")
err = util.DecodeWithError(response, &resIDCard, "OCRIDCard")
return
}
// BankCard 银行卡OCR识别接口
func (ocr *OCR) BankCard(path string) (ResBankCard ResBankCard, err error) {
func (ocr *OCR) BankCard(path string) (resBankCard ResBankCard, err error) {
accessToken, err := ocr.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrBankCardURL, url.QueryEscape(path), accessToken)
response, err := util.HTTPPost(uri, "")
response, err := util.HTTPPost(fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrBankCardURL, url.QueryEscape(path), accessToken), "")
if err != nil {
return
}
err = util.DecodeWithError(response, &ResBankCard, "OCRBankCard")
err = util.DecodeWithError(response, &resBankCard, "OCRBankCard")
return
}
// Driving 行驶证OCR识别接口
func (ocr *OCR) Driving(path string) (ResDriving ResDriving, err error) {
func (ocr *OCR) Driving(path string) (resDriving ResDriving, err error) {
accessToken, err := ocr.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrDrivingURL, url.QueryEscape(path), accessToken)
response, err := util.HTTPPost(uri, "")
response, err := util.HTTPPost(fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrDrivingURL, url.QueryEscape(path), accessToken), "")
if err != nil {
return
}
err = util.DecodeWithError(response, &ResDriving, "OCRDriving")
err = util.DecodeWithError(response, &resDriving, "OCRDriving")
return
}
// DrivingLicense 驾驶证OCR识别接口
func (ocr *OCR) DrivingLicense(path string) (ResDrivingLicense ResDrivingLicense, err error) {
func (ocr *OCR) DrivingLicense(path string) (resDrivingLicense ResDrivingLicense, err error) {
accessToken, err := ocr.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrDrivingLicenseURL, url.QueryEscape(path), accessToken)
response, err := util.HTTPPost(uri, "")
response, err := util.HTTPPost(fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrDrivingLicenseURL, url.QueryEscape(path), accessToken), "")
if err != nil {
return
}
err = util.DecodeWithError(response, &ResDrivingLicense, "OCRDrivingLicense")
err = util.DecodeWithError(response, &resDrivingLicense, "OCRDrivingLicense")
return
}
// BizLicense 营业执照OCR识别接口
func (ocr *OCR) BizLicense(path string) (ResBizLicense ResBizLicense, err error) {
func (ocr *OCR) BizLicense(path string) (resBizLicense ResBizLicense, err error) {
accessToken, err := ocr.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrBizLicenseURL, url.QueryEscape(path), accessToken)
response, err := util.HTTPPost(uri, "")
response, err := util.HTTPPost(fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrBizLicenseURL, url.QueryEscape(path), accessToken), "")
if err != nil {
return
}
err = util.DecodeWithError(response, &ResBizLicense, "OCRBizLicense")
err = util.DecodeWithError(response, &resBizLicense, "OCRBizLicense")
return
}
// Common 通用印刷体OCR识别接口
func (ocr *OCR) Common(path string) (ResCommon ResCommon, err error) {
func (ocr *OCR) Common(path string) (resCommon ResCommon, err error) {
accessToken, err := ocr.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrCommonURL, url.QueryEscape(path), accessToken)
response, err := util.HTTPPost(uri, "")
response, err := util.HTTPPost(fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrCommonURL, url.QueryEscape(path), accessToken), "")
if err != nil {
return
}
err = util.DecodeWithError(response, &ResCommon, "OCRCommon")
err = util.DecodeWithError(response, &resCommon, "OCRCommon")
return
}
// PlateNumber 车牌OCR识别接口
func (ocr *OCR) PlateNumber(path string) (ResPlateNumber ResPlateNumber, err error) {
func (ocr *OCR) PlateNumber(path string) (resPlateNumber ResPlateNumber, err error) {
accessToken, err := ocr.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrPlateNumberURL, url.QueryEscape(path), accessToken)
response, err := util.HTTPPost(uri, "")
response, err := util.HTTPPost(fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrPlateNumberURL, url.QueryEscape(path), accessToken), "")
if err != nil {
return
}
err = util.DecodeWithError(response, &ResPlateNumber, "OCRPlateNumber")
err = util.DecodeWithError(response, &resPlateNumber, "OCRPlateNumber")
return
}

View File

@@ -1,8 +1,10 @@
package officialaccount
import (
stdcontext "context"
"net/http"
"github.com/silenceper/wechat/v2/internal/openapi"
"github.com/silenceper/wechat/v2/officialaccount/draft"
"github.com/silenceper/wechat/v2/officialaccount/freepublish"
"github.com/silenceper/wechat/v2/officialaccount/ocr"
@@ -14,6 +16,7 @@ import (
"github.com/silenceper/wechat/v2/officialaccount/broadcast"
"github.com/silenceper/wechat/v2/officialaccount/config"
"github.com/silenceper/wechat/v2/officialaccount/context"
"github.com/silenceper/wechat/v2/officialaccount/customerservice"
"github.com/silenceper/wechat/v2/officialaccount/device"
"github.com/silenceper/wechat/v2/officialaccount/js"
"github.com/silenceper/wechat/v2/officialaccount/material"
@@ -93,6 +96,14 @@ func (officialAccount *OfficialAccount) GetAccessToken() (string, error) {
return officialAccount.ctx.GetAccessToken()
}
// GetAccessTokenContext 获取access_token
func (officialAccount *OfficialAccount) GetAccessTokenContext(ctx stdcontext.Context) (string, error) {
if c, ok := officialAccount.ctx.AccessTokenHandle.(credential.AccessTokenContextHandle); ok {
return c.GetAccessTokenContext(ctx)
}
return officialAccount.ctx.GetAccessToken()
}
// GetOauth oauth2网页授权
func (officialAccount *OfficialAccount) GetOauth() *oauth.Oauth {
if officialAccount.oauth == nil {
@@ -197,3 +208,13 @@ func (officialAccount *OfficialAccount) GetSubscribe() *message.Subscribe {
}
return officialAccount.subscribeMsg
}
// GetCustomerServiceManager 客服管理
func (officialAccount *OfficialAccount) GetCustomerServiceManager() *customerservice.Manager {
return customerservice.NewCustomerServiceManager(officialAccount.ctx)
}
// GetOpenAPI openApi管理接口
func (officialAccount *OfficialAccount) GetOpenAPI() *openapi.OpenAPI {
return openapi.NewOpenAPI(officialAccount.ctx)
}

View File

@@ -5,7 +5,7 @@ import (
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"io"
"net/http"
"reflect"
"runtime/debug"
@@ -13,11 +13,11 @@ import (
"strings"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/silenceper/wechat/v2/officialaccount/context"
"github.com/silenceper/wechat/v2/officialaccount/message"
"github.com/silenceper/wechat/v2/util"
"github.com/tidwall/gjson"
)
// Server struct
@@ -106,7 +106,7 @@ func (srv *Server) handleRequest() (reply *message.Reply, err error) {
srv.isSafeMode = true
}
//set request contentType
// set request contentType
contentType := srv.Request.Header.Get("Content-Type")
srv.isJSONContent = strings.Contains(contentType, "application/json")
@@ -162,7 +162,7 @@ func (srv *Server) getMessage() (interface{}, error) {
return nil, fmt.Errorf("消息解密失败, err=%v", err)
}
} else {
rawXMLMsgBytes, err = ioutil.ReadAll(srv.Request.Body)
rawXMLMsgBytes, err = io.ReadAll(srv.Request.Body)
if err != nil {
return nil, fmt.Errorf("从body中解析xml失败, err=%v", err)
}
@@ -193,7 +193,7 @@ func (srv *Server) parseRequestMessage(rawXMLMsgBytes []byte) (msg *message.MixM
err = xml.Unmarshal(rawXMLMsgBytes, msg)
return
}
//parse json
// parse json
err = json.Unmarshal(rawXMLMsgBytes, msg)
if err != nil {
return

View File

@@ -0,0 +1,116 @@
// Package user blacklist 公众号用户黑名单管理
// 参考文档https://developers.weixin.qq.com/doc/offiaccount/User_Management/Manage_blacklist.html
package user
import (
"errors"
"fmt"
"github.com/silenceper/wechat/v2/util"
)
const (
// 获取公众号的黑名单列表
getblacklistURL = "https://api.weixin.qq.com/cgi-bin/tags/members/getblacklist?access_token=%s"
// 拉黑用户
batchblacklistURL = "https://api.weixin.qq.com/cgi-bin/tags/members/batchblacklist?access_token=%s"
// 取消拉黑用户
batchunblacklistURL = "https://api.weixin.qq.com/cgi-bin/tags/members/batchunblacklist?access_token=%s"
)
// GetBlackList 获取公众号的黑名单列表
// 该接口每次调用最多可拉取 1000 个OpenID当列表数较多时可以通过多次拉取的方式来满足需求。
// 参数 beginOpenid当 begin_openid 为空时,默认从开头拉取。
func (user *User) GetBlackList(beginOpenid ...string) (userlist *OpenidList, err error) {
if len(beginOpenid) > 1 {
return nil, errors.New("参数 beginOpenid 错误:请传递 1 个openID若需要从头开始拉取列表请留空。")
}
// 获取 AccessToken
var accessToken string
if accessToken, err = user.GetAccessToken(); err != nil {
return
}
// 处理 request 内容
request := map[string]string{"begin_openid": ""}
if len(beginOpenid) == 1 {
request["begin_openid"] = beginOpenid[0]
}
// 调用接口
var resp []byte
url := fmt.Sprintf(getblacklistURL, accessToken)
if resp, err = util.PostJSON(url, &request); err != nil {
return nil, err
}
// 处理返回
userlist = &OpenidList{}
if err = util.DecodeWithError(resp, userlist, "GetBlackList"); err != nil {
return nil, err
}
return
}
// GetAllBlackList 获取公众号的所有黑名单列表
func (user *User) GetAllBlackList() (openIDList []string, err error) {
var (
beginOpenid string
count int
userlist *OpenidList
)
for {
// 获取列表每次1k条
if userlist, err = user.GetBlackList(beginOpenid); err != nil {
return nil, err
}
openIDList = append(openIDList, userlist.Data.OpenIDs...) // 存储本次获得的OpenIDs
count += userlist.Count // 记录获得的总数量
beginOpenid = userlist.NextOpenID // 记录下次循环的起始openID
if count >= userlist.Total {
break // 获得的数量=total结束循环
}
}
return
}
// BatchBlackList 拉黑用户
// 参数 openidList需要拉入黑名单的用户的openid每次拉黑最多允许20个
func (user *User) BatchBlackList(openidList ...string) (err error) {
return user.batch(batchblacklistURL, "BatchBlackList", openidList...)
}
// BatchUnBlackList 取消拉黑用户
// 参数 openidList需要取消拉入黑名单的用户的openid每次拉黑最多允许20个
func (user *User) BatchUnBlackList(openidList ...string) (err error) {
return user.batch(batchunblacklistURL, "BatchUnBlackList", openidList...)
}
// batch 公共方法
func (user *User) batch(url, apiName string, openidList ...string) (err error) {
// 检查参数
if len(openidList) == 0 || len(openidList) > 20 {
return errors.New("参数 openidList 错误每次操作黑名单用户数量为1-20个。")
}
// 获取 AccessToken
var accessToken string
if accessToken, err = user.GetAccessToken(); err != nil {
return
}
// 处理 request 内容
request := map[string][]string{"openid_list": openidList}
// 调用接口
var resp []byte
url = fmt.Sprintf(url, accessToken)
if resp, err = util.PostJSON(url, &request); err != nil {
return
}
return util.DecodeWithCommonError(resp, apiName)
}

View File

@@ -2,6 +2,7 @@ package user
import (
"encoding/json"
"errors"
"fmt"
"net/url"
@@ -10,9 +11,10 @@ import (
)
const (
userInfoURL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN"
updateRemarkURL = "https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=%s"
userListURL = "https://api.weixin.qq.com/cgi-bin/user/get"
userInfoURL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN"
userInfoBatchURL = "https://api.weixin.qq.com/cgi-bin/user/info/batchget"
updateRemarkURL = "https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=%s"
userListURL = "https://api.weixin.qq.com/cgi-bin/user/get"
)
// User 用户管理
@@ -30,7 +32,11 @@ func NewUser(context *context.Context) *User {
// Info 用户基本信息
type Info struct {
util.CommonError
userInfo
}
// 用户基本信息
type userInfo struct {
Subscribe int32 `json:"subscribe"`
OpenID string `json:"openid"`
Nickname string `json:"nickname"`
@@ -88,6 +94,48 @@ func (user *User) GetUserInfo(openID string) (userInfo *Info, err error) {
return
}
// BatchGetUserInfoParams 批量获取用户基本信息参数
type BatchGetUserInfoParams struct {
UserList []BatchGetUserListItem `json:"user_list"` // 需要批量获取基本信息的用户列表
}
// BatchGetUserListItem 需要获取基本信息的用户
type BatchGetUserListItem struct {
OpenID string `json:"openid"` // 用户的标识,对当前公众号唯一
Lang string `json:"lang"` // 国家地区语言版本zh_CN 简体zh_TW 繁体en 英语默认为zh-CN
}
// InfoList 用户基本信息列表
type InfoList struct {
util.CommonError
UserInfoList []userInfo `json:"user_info_list"`
}
// BatchGetUserInfo 批量获取用户基本信息
func (user *User) BatchGetUserInfo(params BatchGetUserInfoParams) (*InfoList, error) {
if len(params.UserList) > 100 {
return nil, errors.New("params length must be less than or equal to 100")
}
ak, err := user.GetAccessToken()
if err != nil {
return nil, err
}
uri := fmt.Sprintf("%s?access_token=%s", userInfoBatchURL, ak)
res, err := util.PostJSON(uri, params)
if err != nil {
return nil, err
}
var data InfoList
err = util.DecodeWithError(res, &data, "BatchGetUserInfo")
if err != nil {
return nil, err
}
return &data, nil
}
// UpdateRemark 设置用户备注名
func (user *User) UpdateRemark(openID, remark string) (err error) {
var accessToken string

View File

@@ -2,11 +2,13 @@
package context
import (
"context"
"encoding/json"
"fmt"
"net/url"
"time"
"github.com/silenceper/wechat/v2/cache"
"github.com/silenceper/wechat/v2/util"
)
@@ -31,24 +33,29 @@ type ComponentAccessToken struct {
ExpiresIn int64 `json:"expires_in"`
}
// GetComponentAccessToken 获取 ComponentAccessToken
func (ctx *Context) GetComponentAccessToken() (string, error) {
// GetComponentAccessTokenContext 获取 ComponentAccessToken
func (ctx *Context) GetComponentAccessTokenContext(stdCtx context.Context) (string, error) {
accessTokenCacheKey := fmt.Sprintf("component_access_token_%s", ctx.AppID)
val := ctx.Cache.Get(accessTokenCacheKey)
val := cache.GetContext(stdCtx, ctx.Cache, accessTokenCacheKey)
if val == nil {
return "", fmt.Errorf("cann't get component access token")
}
return val.(string), nil
}
// SetComponentAccessToken 通过component_verify_ticket 获取 ComponentAccessToken
func (ctx *Context) SetComponentAccessToken(verifyTicket string) (*ComponentAccessToken, error) {
// GetComponentAccessToken 获取 ComponentAccessToken
func (ctx *Context) GetComponentAccessToken() (string, error) {
return ctx.GetComponentAccessTokenContext(context.Background())
}
// SetComponentAccessTokenContext 通过component_verify_ticket 获取 ComponentAccessToken
func (ctx *Context) SetComponentAccessTokenContext(stdCtx context.Context, verifyTicket string) (*ComponentAccessToken, error) {
body := map[string]string{
"component_appid": ctx.AppID,
"component_appsecret": ctx.AppSecret,
"component_verify_ticket": verifyTicket,
}
respBody, err := util.PostJSON(componentAccessTokenURL, body)
respBody, err := util.PostJSONContext(stdCtx, componentAccessTokenURL, body)
if err != nil {
return nil, err
}
@@ -64,15 +71,20 @@ func (ctx *Context) SetComponentAccessToken(verifyTicket string) (*ComponentAcce
accessTokenCacheKey := fmt.Sprintf("component_access_token_%s", ctx.AppID)
expires := at.ExpiresIn - 1500
if err := ctx.Cache.Set(accessTokenCacheKey, at.AccessToken, time.Duration(expires)*time.Second); err != nil {
if err := cache.SetContext(stdCtx, ctx.Cache, accessTokenCacheKey, at.AccessToken, time.Duration(expires)*time.Second); err != nil {
return nil, nil
}
return at, nil
}
// GetPreCode 获取预授权码
func (ctx *Context) GetPreCode() (string, error) {
cat, err := ctx.GetComponentAccessToken()
// SetComponentAccessToken 通过component_verify_ticket 获取 ComponentAccessToken
func (ctx *Context) SetComponentAccessToken(stdCtx context.Context, verifyTicket string) (*ComponentAccessToken, error) {
return ctx.SetComponentAccessTokenContext(stdCtx, verifyTicket)
}
// GetPreCodeContext 获取预授权码
func (ctx *Context) GetPreCodeContext(stdCtx context.Context) (string, error) {
cat, err := ctx.GetComponentAccessTokenContext(stdCtx)
if err != nil {
return "", err
}
@@ -80,7 +92,7 @@ func (ctx *Context) GetPreCode() (string, error) {
"component_appid": ctx.AppID,
}
uri := fmt.Sprintf(getPreCodeURL, cat)
body, err := util.PostJSON(uri, req)
body, err := util.PostJSONContext(stdCtx, uri, req)
if err != nil {
return "", err
}
@@ -95,24 +107,39 @@ func (ctx *Context) GetPreCode() (string, error) {
return ret.PreCode, nil
}
// GetComponentLoginPage 获取第三方公众号授权链接(扫码授权)
func (ctx *Context) GetComponentLoginPage(redirectURI string, authType int, bizAppID string) (string, error) {
code, err := ctx.GetPreCode()
// GetPreCode 获取预授权码
func (ctx *Context) GetPreCode() (string, error) {
return ctx.GetPreCodeContext(context.Background())
}
// GetComponentLoginPageContext 获取第三方公众号授权链接(扫码授权)
func (ctx *Context) GetComponentLoginPageContext(stdCtx context.Context, redirectURI string, authType int, bizAppID string) (string, error) {
code, err := ctx.GetPreCodeContext(stdCtx)
if err != nil {
return "", err
}
return fmt.Sprintf(componentLoginURL, ctx.AppID, code, url.QueryEscape(redirectURI), authType, bizAppID), nil
}
// GetBindComponentURL 获取第三方公众号授权链接(链接跳转,适用移动端)
func (ctx *Context) GetBindComponentURL(redirectURI string, authType int, bizAppID string) (string, error) {
code, err := ctx.GetPreCode()
// GetComponentLoginPage 获取第三方公众号授权链接(扫码授权)
func (ctx *Context) GetComponentLoginPage(redirectURI string, authType int, bizAppID string) (string, error) {
return ctx.GetComponentLoginPageContext(context.Background(), redirectURI, authType, bizAppID)
}
// GetBindComponentURLContext 获取第三方公众号授权链接(链接跳转,适用移动端)
func (ctx *Context) GetBindComponentURLContext(stdCtx context.Context, redirectURI string, authType int, bizAppID string) (string, error) {
code, err := ctx.GetPreCodeContext(stdCtx)
if err != nil {
return "", err
}
return fmt.Sprintf(bindComponentURL, authType, ctx.AppID, code, url.QueryEscape(redirectURI), bizAppID), nil
}
// GetBindComponentURL 获取第三方公众号授权链接(链接跳转,适用移动端)
func (ctx *Context) GetBindComponentURL(redirectURI string, authType int, bizAppID string) (string, error) {
return ctx.GetBindComponentURLContext(context.Background(), redirectURI, authType, bizAppID)
}
// ID 微信返回接口中各种类型字段
type ID struct {
ID int `json:"id"`
@@ -137,9 +164,9 @@ type AuthrAccessToken struct {
RefreshToken string `json:"authorizer_refresh_token"`
}
// QueryAuthCode 使用授权码换取公众号或小程序的接口调用凭据和授权信息
func (ctx *Context) QueryAuthCode(authCode string) (*AuthBaseInfo, error) {
cat, err := ctx.GetComponentAccessToken()
// QueryAuthCodeContext 使用授权码换取公众号或小程序的接口调用凭据和授权信息
func (ctx *Context) QueryAuthCodeContext(stdCtx context.Context, authCode string) (*AuthBaseInfo, error) {
cat, err := ctx.GetComponentAccessTokenContext(stdCtx)
if err != nil {
return nil, err
}
@@ -149,7 +176,7 @@ func (ctx *Context) QueryAuthCode(authCode string) (*AuthBaseInfo, error) {
"authorization_code": authCode,
}
uri := fmt.Sprintf(queryAuthURL, cat)
body, err := util.PostJSON(uri, req)
body, err := util.PostJSONContext(stdCtx, uri, req)
if err != nil {
return nil, err
}
@@ -169,9 +196,14 @@ func (ctx *Context) QueryAuthCode(authCode string) (*AuthBaseInfo, error) {
return ret.Info, nil
}
// RefreshAuthrToken 获取(刷新)授权公众号或小程序的接口调用凭据(令牌)
func (ctx *Context) RefreshAuthrToken(appid, refreshToken string) (*AuthrAccessToken, error) {
cat, err := ctx.GetComponentAccessToken()
// QueryAuthCode 使用授权码换取公众号或小程序的接口调用凭据和授权信息
func (ctx *Context) QueryAuthCode(authCode string) (*AuthBaseInfo, error) {
return ctx.QueryAuthCodeContext(context.Background(), authCode)
}
// RefreshAuthrTokenContext 获取(刷新)授权公众号或小程序的接口调用凭据(令牌)
func (ctx *Context) RefreshAuthrTokenContext(stdCtx context.Context, appid, refreshToken string) (*AuthrAccessToken, error) {
cat, err := ctx.GetComponentAccessTokenContext(stdCtx)
if err != nil {
return nil, err
}
@@ -182,7 +214,7 @@ func (ctx *Context) RefreshAuthrToken(appid, refreshToken string) (*AuthrAccessT
"authorizer_refresh_token": refreshToken,
}
uri := fmt.Sprintf(refreshTokenURL, cat)
body, err := util.PostJSON(uri, req)
body, err := util.PostJSONContext(stdCtx, uri, req)
if err != nil {
return nil, err
}
@@ -193,22 +225,32 @@ func (ctx *Context) RefreshAuthrToken(appid, refreshToken string) (*AuthrAccessT
}
authrTokenKey := "authorizer_access_token_" + appid
if err := ctx.Cache.Set(authrTokenKey, ret.AccessToken, time.Minute*80); err != nil {
if err := cache.SetContext(stdCtx, ctx.Cache, authrTokenKey, ret.AccessToken, time.Second*time.Duration(ret.ExpiresIn-30)); err != nil {
return nil, err
}
return ret, nil
}
// GetAuthrAccessToken 获取授权方AccessToken
func (ctx *Context) GetAuthrAccessToken(appid string) (string, error) {
// RefreshAuthrToken 获取(刷新)授权公众号或小程序的接口调用凭据(令牌)
func (ctx *Context) RefreshAuthrToken(appid, refreshToken string) (*AuthrAccessToken, error) {
return ctx.RefreshAuthrTokenContext(context.Background(), appid, refreshToken)
}
// GetAuthrAccessTokenContext 获取授权方AccessToken
func (ctx *Context) GetAuthrAccessTokenContext(stdCtx context.Context, appid string) (string, error) {
authrTokenKey := "authorizer_access_token_" + appid
val := ctx.Cache.Get(authrTokenKey)
val := cache.GetContext(stdCtx, ctx.Cache, authrTokenKey)
if val == nil {
return "", fmt.Errorf("cannot get authorizer %s access token", appid)
}
return val.(string), nil
}
// GetAuthrAccessToken 获取授权方AccessToken
func (ctx *Context) GetAuthrAccessToken(appid string) (string, error) {
return ctx.GetAuthrAccessTokenContext(context.Background(), appid)
}
// AuthorizerInfo 授权方详细信息
type AuthorizerInfo struct {
NickName string `json:"nick_name"`
@@ -258,9 +300,9 @@ type CategoriesInfo struct {
Second string `wx:"second"`
}
// GetAuthrInfo 获取授权方的帐号基本信息
func (ctx *Context) GetAuthrInfo(appid string) (*AuthorizerInfo, *AuthBaseInfo, error) {
cat, err := ctx.GetComponentAccessToken()
// GetAuthrInfoContext 获取授权方的帐号基本信息
func (ctx *Context) GetAuthrInfoContext(stdCtx context.Context, appid string) (*AuthorizerInfo, *AuthBaseInfo, error) {
cat, err := ctx.GetComponentAccessTokenContext(stdCtx)
if err != nil {
return nil, nil, err
}
@@ -271,7 +313,7 @@ func (ctx *Context) GetAuthrInfo(appid string) (*AuthorizerInfo, *AuthBaseInfo,
}
uri := fmt.Sprintf(getComponentInfoURL, cat)
body, err := util.PostJSON(uri, req)
body, err := util.PostJSONContext(stdCtx, uri, req)
if err != nil {
return nil, nil, err
}
@@ -286,3 +328,8 @@ func (ctx *Context) GetAuthrInfo(appid string) (*AuthorizerInfo, *AuthBaseInfo,
return ret.AuthorizerInfo, ret.AuthorizationInfo, nil
}
// GetAuthrInfo 获取授权方的帐号基本信息
func (ctx *Context) GetAuthrInfo(appid string) (*AuthorizerInfo, *AuthBaseInfo, error) {
return ctx.GetAuthrInfoContext(context.Background(), appid)
}

View File

@@ -28,6 +28,7 @@ type AccountBasicInfo struct {
}
// GetAccountBasicInfo 获取小程序基础信息
//
//reference:https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/Mini_Programs/Mini_Program_Information_Settings.html
func (basic *Basic) GetAccountBasicInfo() (*AccountBasicInfo, error) {
ak, err := basic.GetAuthrAccessToken(basic.AppID)

View File

@@ -36,7 +36,7 @@ type RegisterMiniProgramParam struct {
func (component *Component) RegisterMiniProgram(param *RegisterMiniProgramParam) error {
componentAK, err := component.GetComponentAccessToken()
if err != nil {
return nil
return err
}
url := fmt.Sprintf(fastregisterweappURL+"?action=create&component_access_token=%s", componentAK)
data, err := util.PostJSON(url, param)
@@ -58,7 +58,7 @@ type GetRegistrationStatusParam struct {
func (component *Component) GetRegistrationStatus(param *GetRegistrationStatusParam) error {
componentAK, err := component.GetComponentAccessToken()
if err != nil {
return nil
return err
}
url := fmt.Sprintf(fastregisterweappURL+"?action=search&component_access_token=%s", componentAK)
data, err := util.PostJSON(url, param)

View File

@@ -3,6 +3,9 @@ package miniprogram
import (
"fmt"
"github.com/silenceper/wechat/v2/credential"
"github.com/silenceper/wechat/v2/miniprogram"
miniConfig "github.com/silenceper/wechat/v2/miniprogram/config"
miniContext "github.com/silenceper/wechat/v2/miniprogram/context"
"github.com/silenceper/wechat/v2/miniprogram/urllink"
openContext "github.com/silenceper/wechat/v2/openplatform/context"
@@ -14,7 +17,7 @@ import (
type MiniProgram struct {
AppID string
openContext *openContext.Context
*miniprogram.MiniProgram
authorizerRefreshToken string
}
@@ -42,10 +45,13 @@ func (miniProgram *MiniProgram) SetAuthorizerRefreshToken(authorizerRefreshToken
// NewMiniProgram 实例化
func NewMiniProgram(opCtx *openContext.Context, appID string) *MiniProgram {
return &MiniProgram{
openContext: opCtx,
AppID: appID,
}
miniProgram := miniprogram.NewMiniProgram(&miniConfig.Config{
AppID: opCtx.AppID,
Cache: opCtx.Cache,
})
// 设置获取access_token的函数
miniProgram.SetAccessTokenHandle(NewDefaultAuthrAccessToken(opCtx, appID))
return &MiniProgram{AppID: appID, MiniProgram: miniProgram, openContext: opCtx}
}
// GetComponent get component
@@ -65,3 +71,22 @@ func (miniProgram *MiniProgram) GetURLLink() *urllink.URLLink {
AccessTokenHandle: miniProgram,
})
}
// DefaultAuthrAccessToken 默认获取授权ak的方法
type DefaultAuthrAccessToken struct {
opCtx *openContext.Context
appID string
}
// NewDefaultAuthrAccessToken 设置access_token
func NewDefaultAuthrAccessToken(opCtx *openContext.Context, appID string) credential.AccessTokenHandle {
return &DefaultAuthrAccessToken{
opCtx: opCtx,
appID: appID,
}
}
// GetAccessToken 获取ak
func (ak *DefaultAuthrAccessToken) GetAccessToken() (string, error) {
return ak.opCtx.GetAuthrAccessToken(ak.appID)
}

View File

@@ -18,9 +18,6 @@ type OpenPlatform struct {
// NewOpenPlatform new openplatform
func NewOpenPlatform(cfg *config.Config) *OpenPlatform {
if cfg.Cache == nil {
panic("cache 未设置")
}
ctx := &context.Context{
Config: cfg,
}

View File

@@ -17,6 +17,15 @@ func (c *CommonError) Error() string {
return fmt.Sprintf("%s Error , errcode=%d , errmsg=%s", c.apiName, c.ErrCode, c.ErrMsg)
}
// NewCommonError 新建CommonError错误对于无errcode和errmsg的返回也可以返回该通用错误
func NewCommonError(apiName string, code int64, msg string) *CommonError {
return &CommonError{
apiName: apiName,
ErrCode: code,
ErrMsg: msg,
}
}
// DecodeWithCommonError 将返回值按照CommonError解析
func DecodeWithCommonError(response []byte, apiName string) (err error) {
var commError CommonError

View File

@@ -9,7 +9,6 @@ import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
@@ -38,7 +37,7 @@ func HTTPGetContext(ctx context.Context, uri string) ([]byte, error) {
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("http get error : uri=%v , statusCode=%v", uri, response.StatusCode)
}
return ioutil.ReadAll(response.Body)
return io.ReadAll(response.Body)
}
// HTTPPost post 请求
@@ -67,11 +66,11 @@ func HTTPPostContext(ctx context.Context, uri string, data []byte, header map[st
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("http post error : uri=%v , statusCode=%v", uri, response.StatusCode)
}
return ioutil.ReadAll(response.Body)
return io.ReadAll(response.Body)
}
// PostJSON post json 数据请求
func PostJSON(uri string, obj interface{}) ([]byte, error) {
// PostJSONContext post json 数据请求
func PostJSONContext(ctx context.Context, uri string, obj interface{}) ([]byte, error) {
jsonBuf := new(bytes.Buffer)
enc := json.NewEncoder(jsonBuf)
enc.SetEscapeHTML(false)
@@ -79,7 +78,12 @@ func PostJSON(uri string, obj interface{}) ([]byte, error) {
if err != nil {
return nil, err
}
response, err := http.Post(uri, "application/json;charset=utf-8", jsonBuf)
req, err := http.NewRequestWithContext(ctx, "POST", uri, jsonBuf)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json;charset=utf-8")
response, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
@@ -88,7 +92,12 @@ func PostJSON(uri string, obj interface{}) ([]byte, error) {
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("http get error : uri=%v , statusCode=%v", uri, response.StatusCode)
}
return ioutil.ReadAll(response.Body)
return io.ReadAll(response.Body)
}
// PostJSON post json 数据请求
func PostJSON(uri string, obj interface{}) ([]byte, error) {
return PostJSONContext(context.Background(), uri, obj)
}
// PostJSONWithRespContentType post json数据请求且返回数据类型
@@ -110,7 +119,7 @@ func PostJSONWithRespContentType(uri string, obj interface{}) ([]byte, string, e
if response.StatusCode != http.StatusOK {
return nil, "", fmt.Errorf("http get error : uri=%v , statusCode=%v", uri, response.StatusCode)
}
responseData, err := ioutil.ReadAll(response.Body)
responseData, err := io.ReadAll(response.Body)
contentType := response.Header.Get("Content-Type")
return responseData, contentType, err
}
@@ -183,7 +192,7 @@ func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte
if resp.StatusCode != http.StatusOK {
return nil, err
}
respBody, err = ioutil.ReadAll(resp.Body)
respBody, err = io.ReadAll(resp.Body)
return
}
@@ -204,13 +213,13 @@ func PostXML(uri string, obj interface{}) ([]byte, error) {
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("http code error : uri=%v , statusCode=%v", uri, response.StatusCode)
}
return ioutil.ReadAll(response.Body)
return io.ReadAll(response.Body)
}
// httpWithTLS CA证书
func httpWithTLS(rootCa, key string) (*http.Client, error) {
var client *http.Client
certData, err := ioutil.ReadFile(rootCa)
certData, err := os.ReadFile(rootCa)
if err != nil {
return nil, fmt.Errorf("unable to find cert path=%s, error=%v", rootCa, err)
}
@@ -269,5 +278,5 @@ func PostXMLWithTLS(uri string, obj interface{}, ca, key string) ([]byte, error)
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("http code error : uri=%v , statusCode=%v", uri, response.StatusCode)
}
return ioutil.ReadAll(response.Body)
return io.ReadAll(response.Body)
}

24
util/query.go Normal file
View File

@@ -0,0 +1,24 @@
package util
import (
"fmt"
"strings"
)
// Query 将Map序列化为Query参数
func Query(params map[string]interface{}) string {
finalString := make([]string, 0)
for key, value := range params {
valueString := ""
switch v := value.(type) {
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
valueString = fmt.Sprintf("%d", v)
case bool:
valueString = fmt.Sprintf("%v", v)
default:
valueString = fmt.Sprintf("%s", v)
}
finalString = append(finalString, strings.Join([]string{key, valueString}, "="))
}
return strings.Join(finalString, "&")
}

19
util/query_test.go Normal file
View File

@@ -0,0 +1,19 @@
package util
import (
"testing"
)
// TestQuery query method test case
func TestQuery(t *testing.T) {
result := Query(map[string]interface{}{
"age": 12,
"name": "Alan",
"cat": "Peter",
})
if result == "" {
// 由于hash是乱序 所以没法很好的预测输出的字符串
// 将会输出符合Query规则的字符串 "age=12&name=Alan&cat=Peter"
t.Error("NOT PASS")
}
}

24
util/template.go Normal file
View File

@@ -0,0 +1,24 @@
package util
import (
"fmt"
"strings"
)
// Template 对字符串中的和map的key相同的字符串进行模板替换 仅支持 形如: {name}
func Template(source string, data map[string]interface{}) string {
sourceCopy := &source
for k, val := range data {
valStr := ""
switch v := val.(type) {
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
valStr = fmt.Sprintf("%d", v)
case bool:
valStr = fmt.Sprintf("%v", v)
default:
valStr = fmt.Sprintf("%s", v)
}
*sourceCopy = strings.Replace(*sourceCopy, strings.Join([]string{"{", k, "}"}, ""), valStr, 1)
}
return *sourceCopy
}

20
util/template_test.go Normal file
View File

@@ -0,0 +1,20 @@
package util
import (
"testing"
)
// TestTemplate testing case about Template method
func TestTemplate(t *testing.T) {
result := Template("{name}={age};{with}={another};any={any};boolean={boolean}", map[string]interface{}{
"name": "Helan",
"age": "33",
"with": "Pep",
"another": "C",
"any": 33,
"boolean": false,
})
if result != "Helan=33;Pep=C;any=33;boolean=false" {
t.Error("NOT PSS testing")
}
}

View File

@@ -68,10 +68,16 @@ func (wc *Wechat) GetPay(cfg *payConfig.Config) *pay.Pay {
// GetOpenPlatform 获取微信开放平台的实例
func (wc *Wechat) GetOpenPlatform(cfg *openConfig.Config) *openplatform.OpenPlatform {
if cfg.Cache == nil {
cfg.Cache = wc.cache
}
return openplatform.NewOpenPlatform(cfg)
}
// GetWork 获取企业微信的实例
func (wc *Wechat) GetWork(cfg *workConfig.Config) *work.Work {
if cfg.Cache == nil {
cfg.Cache = wc.cache
}
return work.NewWork(cfg)
}

View File

@@ -0,0 +1,17 @@
package addresslist
import (
"github.com/silenceper/wechat/v2/work/context"
)
// Client 通讯录管理接口实例
type Client struct {
*context.Context
}
// NewClient 初始化实例
func NewClient(ctx *context.Context) *Client {
return &Client{
ctx,
}
}

View File

@@ -0,0 +1,47 @@
package addresslist
import (
"fmt"
"github.com/silenceper/wechat/v2/util"
)
const (
// departmentSimpleListURL 获取子部门ID列表
departmentSimpleListURL = "https://qyapi.weixin.qq.com/cgi-bin/department/simplelist?access_token=%s&id=%d"
)
type (
// DepartmentSimpleListResponse 获取子部门ID列表响应
DepartmentSimpleListResponse struct {
util.CommonError
DepartmentID []*DepartmentID `json:"department_id"`
}
// DepartmentID 子部门ID
DepartmentID struct {
ID int `json:"id"`
ParentID int `json:"parentid"`
Order int `json:"order"`
}
)
// DepartmentSimpleList 获取子部门ID列表
// see https://developer.work.weixin.qq.com/document/path/95350
func (r *Client) DepartmentSimpleList(departmentID int) ([]*DepartmentID, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.HTTPGet(fmt.Sprintf(departmentSimpleListURL, accessToken, departmentID)); err != nil {
return nil, err
}
result := &DepartmentSimpleListResponse{}
if err = util.DecodeWithError(response, result, "DepartmentSimpleList"); err != nil {
return nil, err
}
return result.DepartmentID, nil
}

View File

@@ -0,0 +1,230 @@
package addresslist
import (
"fmt"
"github.com/silenceper/wechat/v2/util"
)
const (
// getPermListURL 获取应用的可见范围
getPermListURL = "https://qyapi.weixin.qq.com/cgi-bin/linkedcorp/agent/get_perm_list?access_token=%s"
// getLinkedCorpUserURL 获取互联企业成员详细信息
getLinkedCorpUserURL = "https://qyapi.weixin.qq.com/cgi-bin/linkedcorp/user/get?access_token=%s"
// linkedCorpSimpleListURL 获取互联企业部门成员
linkedCorpSimpleListURL = "https://qyapi.weixin.qq.com/cgi-bin/linkedcorp/user/simplelist?access_token=%s"
// linkedCorpUserListURL 获取互联企业部门成员详情
linkedCorpUserListURL = "https://qyapi.weixin.qq.com/cgi-bin/linkedcorp/user/list?access_token=%s"
// linkedCorpDepartmentListURL 获取互联企业部门列表
linkedCorpDepartmentListURL = "https://qyapi.weixin.qq.com/cgi-bin/linkedcorp/department/list?access_token=%s"
)
// GetPermListResponse 获取应用的可见范围响应
type GetPermListResponse struct {
util.CommonError
UserIDs []string `json:"userids"`
DepartmentIDs []string `json:"department_ids"`
}
// GetPermList 获取应用的可见范围
// see https://developer.work.weixin.qq.com/document/path/93172
func (r *Client) GetPermList() (*GetPermListResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.HTTPPost(fmt.Sprintf(getPermListURL, accessToken), ""); err != nil {
return nil, err
}
result := &GetPermListResponse{}
if err = util.DecodeWithError(response, result, "GetPermList"); err != nil {
return nil, err
}
return result, nil
}
// GetLinkedCorpUserRequest 获取互联企业成员详细信息请求
type GetLinkedCorpUserRequest struct {
UserID string `json:"userid"`
}
// GetLinkedCorpUserResponse 获取互联企业成员详细信息响应
type GetLinkedCorpUserResponse struct {
util.CommonError
UserInfo LinkedCorpUserInfo `json:"user_info"`
}
// LinkedCorpUserInfo 互联企业成员详细信息
type LinkedCorpUserInfo struct {
UserID string `json:"userid"`
Name string `json:"name"`
Department []string `json:"department"`
Mobile string `json:"mobile"`
Telephone string `json:"telephone"`
Email string `json:"email"`
Position string `json:"position"`
CorpID string `json:"corpid"`
Extattr Extattr `json:"extattr"`
}
// Extattr 互联企业成员详细信息扩展属性
type Extattr struct {
Attrs []ExtattrItem `json:"attrs"`
}
// ExtattrItem 互联企业成员详细信息扩展属性条目
type ExtattrItem struct {
Name string `json:"name"`
Value string `json:"value,omitempty"`
Type int `json:"type"`
Text ExtattrItemText `json:"text,omitempty"`
Web ExtattrItemWeb `json:"web,omitempty"`
}
// ExtattrItemText 互联企业成员详细信息自定义属性(文本)
type ExtattrItemText struct {
Value string `json:"value"`
}
// ExtattrItemWeb 互联企业成员详细信息自定义属性(网页)
type ExtattrItemWeb struct {
URL string `json:"url"`
Title string `json:"title"`
}
// GetLinkedCorpUser 获取互联企业成员详细信息
// see https://developer.work.weixin.qq.com/document/path/93171
func (r *Client) GetLinkedCorpUser(req *GetLinkedCorpUserRequest) (*GetLinkedCorpUserResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(getLinkedCorpUserURL, accessToken), req); err != nil {
return nil, err
}
result := &GetLinkedCorpUserResponse{}
if err = util.DecodeWithError(response, result, "GetLinkedCorpUser"); err != nil {
return nil, err
}
return result, nil
}
// LinkedCorpSimpleListRequest 获取互联企业部门成员请求
type LinkedCorpSimpleListRequest struct {
DepartmentID string `json:"department_id"`
}
// LinkedCorpSimpleListResponse 获取互联企业部门成员响应
type LinkedCorpSimpleListResponse struct {
util.CommonError
Userlist []LinkedCorpUser `json:"userlist"`
}
// LinkedCorpUser 企业部门成员
type LinkedCorpUser struct {
UserID string `json:"userid"`
Name string `json:"name"`
Department []string `json:"department"`
CorpID string `json:"corpid"`
}
// LinkedCorpSimpleList 获取互联企业部门成员
// see https://developer.work.weixin.qq.com/document/path/93168
func (r *Client) LinkedCorpSimpleList(req *LinkedCorpSimpleListRequest) (*LinkedCorpSimpleListResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(linkedCorpSimpleListURL, accessToken), req); err != nil {
return nil, err
}
result := &LinkedCorpSimpleListResponse{}
if err = util.DecodeWithError(response, result, "LinkedCorpSimpleList"); err != nil {
return nil, err
}
return result, nil
}
// LinkedCorpUserListRequest 获取互联企业部门成员详情请求
type LinkedCorpUserListRequest struct {
DepartmentID string `json:"department_id"`
}
// LinkedCorpUserListResponse 获取互联企业部门成员详情响应
type LinkedCorpUserListResponse struct {
util.CommonError
UserList []LinkedCorpUserInfo `json:"userlist"`
}
// LinkedCorpUserList 获取互联企业部门成员详情
// see https://developer.work.weixin.qq.com/document/path/93169
func (r *Client) LinkedCorpUserList(req *LinkedCorpUserListRequest) (*LinkedCorpUserListResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(linkedCorpUserListURL, accessToken), req); err != nil {
return nil, err
}
result := &LinkedCorpUserListResponse{}
if err = util.DecodeWithError(response, result, "LinkedCorpUserList"); err != nil {
return nil, err
}
return result, nil
}
// LinkedCorpDepartmentListRequest 获取互联企业部门列表请求
type LinkedCorpDepartmentListRequest struct {
DepartmentID string `json:"department_id"`
}
// LinkedCorpDepartmentListResponse 获取互联企业部门列表响应
type LinkedCorpDepartmentListResponse struct {
util.CommonError
DepartmentList []LinkedCorpDepartment `json:"department_list"`
}
// LinkedCorpDepartment 互联企业部门
type LinkedCorpDepartment struct {
DepartmentID string `json:"department_id"`
DepartmentName string `json:"department_name"`
ParentID string `json:"parentid"`
Order int `json:"order"`
}
// LinkedCorpDepartmentList 获取互联企业部门列表
// see https://developer.work.weixin.qq.com/document/path/93170
func (r *Client) LinkedCorpDepartmentList(req *LinkedCorpDepartmentListRequest) (*LinkedCorpDepartmentListResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(linkedCorpDepartmentListURL, accessToken), req); err != nil {
return nil, err
}
result := &LinkedCorpDepartmentListResponse{}
if err = util.DecodeWithError(response, result, "LinkedCorpDepartmentList"); err != nil {
return nil, err
}
return result, nil
}

242
work/addresslist/tag.go Normal file
View File

@@ -0,0 +1,242 @@
package addresslist
import (
"fmt"
"github.com/silenceper/wechat/v2/util"
)
const (
// createTagURL 创建标签
createTagURL = "https://qyapi.weixin.qq.com/cgi-bin/tag/create?access_token=%s"
// updateTagURL 更新标签名字
updateTagURL = "https://qyapi.weixin.qq.com/cgi-bin/tag/update?access_token=%s"
// deleteTagURL 删除标签
deleteTagURL = "https://qyapi.weixin.qq.com/cgi-bin/tag/delete?access_token=%s&tagid=%d"
// getTagURL 获取标签成员
getTagURL = "https://qyapi.weixin.qq.com/cgi-bin/tag/get?access_token=%s&tagid=%d"
// addTagUsersURL 增加标签成员
addTagUsersURL = "https://qyapi.weixin.qq.com/cgi-bin/tag/addtagusers?access_token=%s"
// delTagUsersURL 删除标签成员
delTagUsersURL = "https://qyapi.weixin.qq.com/cgi-bin/tag/deltagusers?access_token=%s"
// listTagURL 获取标签列表
listTagURL = "https://qyapi.weixin.qq.com/cgi-bin/tag/list?access_token=%s"
)
type (
// CreateTagRequest 创建标签请求
CreateTagRequest struct {
TagName string `json:"tagname"`
TagID int `json:"tagid,omitempty"`
}
// CreateTagResponse 创建标签响应
CreateTagResponse struct {
util.CommonError
TagID int `json:"tagid"`
}
)
// CreateTag 创建标签
// see https://developer.work.weixin.qq.com/document/path/90210
func (r *Client) CreateTag(req *CreateTagRequest) (*CreateTagResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(createTagURL, accessToken), req); err != nil {
return nil, err
}
result := &CreateTagResponse{}
if err = util.DecodeWithError(response, result, "CreateTag"); err != nil {
return nil, err
}
return result, nil
}
type (
// UpdateTagRequest 更新标签名字请求
UpdateTagRequest struct {
TagID int `json:"tagid"`
TagName string `json:"tagname"`
}
)
// UpdateTag 更新标签名字
// see https://developer.work.weixin.qq.com/document/path/90211
func (r *Client) UpdateTag(req *UpdateTagRequest) error {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(updateTagURL, accessToken), req); err != nil {
return err
}
return util.DecodeWithCommonError(response, "UpdateTag")
}
// DeleteTag 删除标签
// @see https://developer.work.weixin.qq.com/document/path/90212
func (r *Client) DeleteTag(tagID int) error {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return err
}
var response []byte
if response, err = util.HTTPGet(fmt.Sprintf(deleteTagURL, accessToken, tagID)); err != nil {
return err
}
return util.DecodeWithCommonError(response, "DeleteTag")
}
type (
// GetTagResponse 获取标签成员响应
GetTagResponse struct {
util.CommonError
TagName string `json:"tagname"`
UserList []GetTagUserList `json:"userlist"`
PartyList []int `json:"partylist"`
}
// GetTagUserList 标签中包含的成员列表
GetTagUserList struct {
UserID string `json:"userid"`
Name string `json:"name"`
}
)
// GetTag 获取标签成员
// @see https://developer.work.weixin.qq.com/document/path/90213
func (r *Client) GetTag(tagID int) (*GetTagResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.HTTPGet(fmt.Sprintf(getTagURL, accessToken, tagID)); err != nil {
return nil, err
}
result := &GetTagResponse{}
if err = util.DecodeWithError(response, result, "GetTag"); err != nil {
return nil, err
}
return result, nil
}
type (
// AddTagUsersRequest 增加标签成员请求
AddTagUsersRequest struct {
TagID int `json:"tagid"`
UserList []string `json:"userlist"`
PartyList []int `json:"partylist"`
}
// AddTagUsersResponse 增加标签成员响应
AddTagUsersResponse struct {
util.CommonError
InvalidList string `json:"invalidlist"`
InvalidParty []int `json:"invalidparty"`
}
)
// AddTagUsers 增加标签成员
// see https://developer.work.weixin.qq.com/document/path/90214
func (r *Client) AddTagUsers(req *AddTagUsersRequest) (*AddTagUsersResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(addTagUsersURL, accessToken), req); err != nil {
return nil, err
}
result := &AddTagUsersResponse{}
if err = util.DecodeWithError(response, result, "AddTagUsers"); err != nil {
return nil, err
}
return result, nil
}
type (
// DelTagUsersRequest 删除标签成员请求
DelTagUsersRequest struct {
TagID int `json:"tagid"`
UserList []string `json:"userlist"`
PartyList []int `json:"partylist"`
}
// DelTagUsersResponse 删除标签成员响应
DelTagUsersResponse struct {
util.CommonError
InvalidList string `json:"invalidlist"`
InvalidParty []int `json:"invalidparty"`
}
)
// DelTagUsers 删除标签成员
// see https://developer.work.weixin.qq.com/document/path/90215
func (r *Client) DelTagUsers(req *DelTagUsersRequest) (*DelTagUsersResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(delTagUsersURL, accessToken), req); err != nil {
return nil, err
}
result := &DelTagUsersResponse{}
if err = util.DecodeWithError(response, result, "DelTagUsers"); err != nil {
return nil, err
}
return result, nil
}
type (
// ListTagResponse 获取标签列表响应
ListTagResponse struct {
util.CommonError
TagList []Tag `json:"taglist"`
}
// Tag 标签
Tag struct {
TagID int `json:"tagid"`
TagName string `json:"tagname"`
}
)
// ListTag 获取标签列表
// @see https://developer.work.weixin.qq.com/document/path/90216
func (r *Client) ListTag() (*ListTagResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.HTTPGet(fmt.Sprintf(listTagURL, accessToken)); err != nil {
return nil, err
}
result := &ListTagResponse{}
if err = util.DecodeWithError(response, result, "ListTag"); err != nil {
return nil, err
}
return result, nil
}

284
work/addresslist/user.go Normal file
View File

@@ -0,0 +1,284 @@
package addresslist
import (
"strings"
"github.com/silenceper/wechat/v2/util"
)
const (
// userSimpleListURL 获取部门成员
userSimpleListURL = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist"
// userGetURL 读取成员
userGetURL = "https://qyapi.weixin.qq.com/cgi-bin/user/get"
// userListIDURL 获取成员ID列表
userListIDURL = "https://qyapi.weixin.qq.com/cgi-bin/user/list_id"
// convertToOpenIDURL userID转openID
convertToOpenIDURL = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid"
// convertToUserIDURL openID转userID
convertToUserIDURL = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid"
)
type (
// UserSimpleListResponse 获取部门成员响应
UserSimpleListResponse struct {
util.CommonError
UserList []*UserList
}
// UserList 部门成员
UserList struct {
UserID string `json:"userid"`
Name string `json:"name"`
Department []int `json:"department"`
OpenUserID string `json:"open_userid"`
}
)
// UserSimpleList 获取部门成员
// @see https://developer.work.weixin.qq.com/document/path/90200
func (r *Client) UserSimpleList(departmentID int) ([]*UserList, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.HTTPGet(strings.Join([]string{
userSimpleListURL,
util.Query(map[string]interface{}{
"access_token": accessToken,
"department_id": departmentID,
}),
}, "?")); err != nil {
return nil, err
}
result := &UserSimpleListResponse{}
err = util.DecodeWithError(response, result, "UserSimpleList")
if err != nil {
return nil, err
}
return result.UserList, nil
}
// UserGetResponse 获取部门成员响应
type UserGetResponse struct {
util.CommonError
UserID string `json:"userid"` // 成员UserID。对应管理端的帐号企业内必须唯一。不区分大小写长度为1~64个字节第三方应用返回的值为open_userid
Name string `json:"name"` // 成员名称第三方不可获取调用时返回userid以代替name代开发自建应用需要管理员授权才返回对于非第三方创建的成员第三方通讯录应用也不可获取未返回name的情况需要通过通讯录展示组件来展示名字
Department []int `json:"department"` // 成员所属部门id列表仅返回该应用有查看权限的部门id成员授权模式下固定返回根部门id即固定为1。对授权了“组织架构信息”权限的第三方应用返回成员所属的全部部门id
Order []int `json:"order"` // 部门内的排序值默认为0。数量必须和department一致数值越大排序越前面。值范围是[0, 2^32)。成员授权模式下不返回该字段
Position string `json:"position"` // 职务信息;代开发自建应用需要管理员授权才返回;第三方仅通讯录应用可获取;对于非第三方创建的成员,第三方通讯录应用也不可获取;上游企业不可获取下游企业成员该字段
Mobile string `json:"mobile"` // 手机号码代开发自建应用需要管理员授权且成员oauth2授权获取第三方仅通讯录应用可获取对于非第三方创建的成员第三方通讯录应用也不可获取上游企业不可获取下游企业成员该字段
Gender string `json:"gender"` // 性别。0表示未定义1表示男性2表示女性。代开发自建应用需要管理员授权且成员oauth2授权获取第三方仅通讯录应用可获取对于非第三方创建的成员第三方通讯录应用也不可获取上游企业不可获取下游企业成员该字段。注不可获取指返回值0
Email string `json:"email"` // 邮箱代开发自建应用需要管理员授权且成员oauth2授权获取第三方仅通讯录应用可获取对于非第三方创建的成员第三方通讯录应用也不可获取上游企业不可获取下游企业成员该字段
BizMail string `json:"biz_mail"` // 企业邮箱代开发自建应用需要管理员授权且成员oauth2授权获取第三方仅通讯录应用可获取对于非第三方创建的成员第三方通讯录应用也不可获取上游企业不可获取下游企业成员该字段
IsLeaderInDept []int `json:"is_leader_in_dept"` // 表示在所在的部门内是否为部门负责人数量与department一致第三方通讯录应用或者授权了“组织架构信息-应用可获取企业的部门组织架构信息-部门负责人”权限的第三方应用可获取;对于非第三方创建的成员,第三方通讯录应用不可获取;上游企业不可获取下游企业成员该字段
DirectLeader []string `json:"direct_leader"` // 直属上级UserID返回在应用可见范围内的直属上级列表最多有五个直属上级第三方通讯录应用或者授权了“组织架构信息-应用可获取可见范围内成员组织架构信息-直属上级”权限的第三方应用可获取;对于非第三方创建的成员,第三方通讯录应用不可获取;上游企业不可获取下游企业成员该字段;代开发自建应用不可获取该字段
Avatar string `json:"avatar"` // 头像url。 代开发自建应用需要管理员授权且成员oauth2授权获取第三方仅通讯录应用可获取对于非第三方创建的成员第三方通讯录应用也不可获取上游企业不可获取下游企业成员该字段
ThumbAvatar string `json:"thumb_avatar"` // 头像缩略图url。第三方仅通讯录应用可获取对于非第三方创建的成员第三方通讯录应用也不可获取上游企业不可获取下游企业成员该字段
Telephone string `json:"telephone"` // 座机。代开发自建应用需要管理员授权才返回;第三方仅通讯录应用可获取;对于非第三方创建的成员,第三方通讯录应用也不可获取;上游企业不可获取下游企业成员该字段
Alias string `json:"alias"` // 别名;第三方仅通讯录应用可获取;对于非第三方创建的成员,第三方通讯录应用也不可获取;上游企业不可获取下游企业成员该字段
Address string `json:"address"` // 地址。代开发自建应用需要管理员授权且成员oauth2授权获取第三方仅通讯录应用可获取对于非第三方创建的成员第三方通讯录应用也不可获取上游企业不可获取下游企业成员该字段
OpenUserid string `json:"open_userid"` // 全局唯一。对于同一个服务商不同应用获取到企业内同一个成员的open_userid是相同的最多64个字节。仅第三方应用可获取
MainDepartment int `json:"main_department"` // 主部门,仅当应用对主部门有查看权限时返回。
Extattr struct {
Attrs []struct {
Type int `json:"type"`
Name string `json:"name"`
Text struct {
Value string `json:"value"`
} `json:"text,omitempty"`
Web struct {
URL string `json:"url"`
Title string `json:"title"`
} `json:"web,omitempty"`
} `json:"attrs"`
} `json:"extattr"` // 扩展属性,代开发自建应用需要管理员授权才返回;第三方仅通讯录应用可获取;对于非第三方创建的成员,第三方通讯录应用也不可获取;上游企业不可获取下游企业成员该字段
Status int `json:"status"` // 激活状态: 1=已激活2=已禁用4=未激活5=退出企业。 已激活代表已激活企业微信或已关注微信插件(原企业号)。未激活代表既未激活企业微信又未关注微信插件(原企业号)。
QrCode string `json:"qr_code"` // 员工个人二维码,扫描可添加为外部联系人(注意返回的是一个url可在浏览器上打开该url以展示二维码)代开发自建应用需要管理员授权且成员oauth2授权获取第三方仅通讯录应用可获取对于非第三方创建的成员第三方通讯录应用也不可获取上游企业不可获取下游企业成员该字段
ExternalPosition string `json:"external_position"` // 对外职务如果设置了该值则以此作为对外展示的职务否则以position来展示。代开发自建应用需要管理员授权才返回第三方仅通讯录应用可获取对于非第三方创建的成员第三方通讯录应用也不可获取上游企业不可获取下游企业成员该字段
ExternalProfile struct {
ExternalCorpName string `json:"external_corp_name"`
WechatChannels struct {
Nickname string `json:"nickname"`
Status int `json:"status"`
} `json:"wechat_channels"`
ExternalAttr []struct {
Type int `json:"type"`
Name string `json:"name"`
Text struct {
Value string `json:"value"`
} `json:"text,omitempty"`
Web struct {
URL string `json:"url"`
Title string `json:"title"`
} `json:"web,omitempty"`
Miniprogram struct {
Appid string `json:"appid"`
Pagepath string `json:"pagepath"`
Title string `json:"title"`
} `json:"miniprogram,omitempty"`
} `json:"external_attr"`
} `json:"external_profile"` // 成员对外属性,字段详情见对外属性;代开发自建应用需要管理员授权才返回;第三方仅通讯录应用可获取;对于非第三方创建的成员,第三方通讯录应用也不可获取;上游企业不可获取下游企业成员该字段
}
// UserGet 获取部门成员
// @see https://developer.work.weixin.qq.com/document/path/90196
func (r *Client) UserGet(UserID string) (*UserGetResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.HTTPGet(
strings.Join([]string{
userGetURL,
util.Query(map[string]interface{}{
"access_token": accessToken,
"department_id": UserID,
}),
}, "?")); err != nil {
return nil, err
}
result := &UserGetResponse{}
err = util.DecodeWithError(response, result, "UserGet")
if err != nil {
return nil, err
}
return result, nil
}
// UserListIDRequest 获取成员ID列表请求
type UserListIDRequest struct {
Cursor string `json:"cursor"`
Limit int `json:"limit"`
}
// UserListIDResponse 获取成员ID列表响应
type UserListIDResponse struct {
util.CommonError
NextCursor string `json:"next_cursor"`
DeptUser []*DeptUser `json:"dept_user"`
}
// DeptUser 用户-部门关系
type DeptUser struct {
UserID string `json:"userid"`
Department int `json:"department"`
}
// UserListID 获取成员ID列表
// see https://developer.work.weixin.qq.com/document/path/96067
func (r *Client) UserListID(req *UserListIDRequest) (*UserListIDResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(strings.Join([]string{
userListIDURL,
util.Query(map[string]interface{}{
"access_token": accessToken,
}),
}, "?"), req); err != nil {
return nil, err
}
result := &UserListIDResponse{}
if err = util.DecodeWithError(response, result, "UserListID"); err != nil {
return nil, err
}
return result, nil
}
type (
// convertToOpenIDRequest userID转openID请求
convertToOpenIDRequest struct {
UserID string `json:"userid"`
}
// convertToOpenIDResponse userID转openID响应
convertToOpenIDResponse struct {
util.CommonError
OpenID string `json:"openid"`
}
)
// ConvertToOpenID userID转openID
// see https://developer.work.weixin.qq.com/document/path/90202
func (r *Client) ConvertToOpenID(userID string) (string, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return "", err
}
var response []byte
if response, err = util.PostJSON(strings.Join([]string{
convertToOpenIDURL,
util.Query(map[string]interface{}{
"access_token": accessToken,
}),
}, "?"), &convertToOpenIDRequest{
UserID: userID,
}); err != nil {
return "", err
}
result := &convertToOpenIDResponse{}
if err = util.DecodeWithError(response, result, "ConvertToOpenID"); err != nil {
return "", err
}
return result.OpenID, nil
}
type (
// convertToUserIDRequest openID转userID请求
convertToUserIDRequest struct {
OpenID string `json:"openid"`
}
// convertToUserIDResponse openID转userID响应
convertToUserIDResponse struct {
util.CommonError
UserID string `json:"userid"`
}
)
// ConvertToUserID openID转userID
// see https://developer.work.weixin.qq.com/document/path/90202
func (r *Client) ConvertToUserID(openID string) (string, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return "", err
}
var response []byte
if response, err = util.PostJSON(strings.Join([]string{
convertToUserIDURL,
util.Query(map[string]interface{}{
"access_token": accessToken,
}),
}, "?"), &convertToUserIDRequest{
OpenID: openID,
}); err != nil {
return "", err
}
result := &convertToUserIDResponse{}
if err = util.DecodeWithError(response, result, "ConvertToUserID"); err != nil {
return "", err
}
return result.UserID, nil
}

115
work/appchat/appchat.go Normal file
View File

@@ -0,0 +1,115 @@
package appchat
import (
"encoding/json"
"fmt"
"github.com/silenceper/wechat/v2/util"
)
const (
// 应用推送消息接口地址
sendURL = "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=%s"
)
type (
// SendRequestCommon 发送应用推送消息请求公共参数
SendRequestCommon struct {
// 群聊id
ChatID string `json:"chatid"`
// 消息类型
MsgType string `json:"msgtype"`
// 表示是否是保密消息0表示否1表示是默认0
Safe int `json:"safe"`
}
// SendResponse 发送应用消息响应参数
SendResponse struct {
util.CommonError
}
// SendTextRequest 发送文本消息的请求
SendTextRequest struct {
*SendRequestCommon
Text TextField `json:"text"`
}
// TextField 文本消息参数
TextField struct {
// 消息内容最长不超过2048个字节
Content string `json:"content"`
}
// SendImageRequest 发送图片消息的请求
SendImageRequest struct {
*SendRequestCommon
Image ImageField `json:"image"`
}
// ImageField 图片消息参数
ImageField struct {
// 图片媒体文件id可以调用上传临时素材接口获取
MediaID string `json:"media_id"`
}
// SendVoiceRequest 发送语音消息的请求
SendVoiceRequest struct {
*SendRequestCommon
Voice VoiceField `json:"voice"`
}
// VoiceField 语音消息参数
VoiceField struct {
// 语音文件id可以调用上传临时素材接口获取
MediaID string `json:"media_id"`
}
)
// Send 发送应用消息
// @desc 实现企业微信发送应用消息接口https://developer.work.weixin.qq.com/document/path/90248
func (r *Client) Send(apiName string, request interface{}) (*SendResponse, error) {
// 获取accessToken
accessToken, err := r.GetAccessToken()
if err != nil {
return nil, err
}
// 请求参数转 JSON 格式
jsonData, err := json.Marshal(request)
if err != nil {
return nil, err
}
// 发起http请求
response, err := util.HTTPPost(fmt.Sprintf(sendURL, accessToken), string(jsonData))
if err != nil {
return nil, err
}
// 按照结构体解析返回值
result := &SendResponse{}
if err = util.DecodeWithError(response, result, apiName); err != nil {
return nil, err
}
// 返回数据
return result, nil
}
// SendText 发送文本消息
func (r *Client) SendText(request SendTextRequest) (*SendResponse, error) {
// 发送文本消息MsgType参数固定为text
request.MsgType = "text"
return r.Send("MessageSendText", request)
}
// SendImage 发送图片消息
func (r *Client) SendImage(request SendImageRequest) (*SendResponse, error) {
// 发送图片消息MsgType参数固定为image
request.MsgType = "image"
return r.Send("MessageSendImage", request)
}
// SendVoice 发送语音消息
func (r *Client) SendVoice(request SendVoiceRequest) (*SendResponse, error) {
// 发送语音消息MsgType参数固定为voice
request.MsgType = "voice"
return r.Send("MessageSendVoice", request)
}
// 以上实现了部分常用消息推送SendText 发送文本消息、SendImage 发送图片消息、SendVoice 发送语音消息,
// 如需扩展其他消息类型,建议按照以上格式,扩展对应消息类型的参数即可
// 也可以直接使用Send方法按照企业微信消息推送的接口文档传对应消息类型的参数来使用

16
work/appchat/client.go Normal file
View File

@@ -0,0 +1,16 @@
// Package appchat 应用发送消息到群聊会话,企业微信接口https://developer.work.weixin.qq.com/document/path/90248
package appchat
import (
"github.com/silenceper/wechat/v2/work/context"
)
// Client 接口实例
type Client struct {
*context.Context
}
// NewClient 初始化实例
func NewClient(ctx *context.Context) *Client {
return &Client{ctx}
}

View File

@@ -0,0 +1,45 @@
package externalcontact
import (
"encoding/xml"
"github.com/silenceper/wechat/v2/util"
)
// 原始回调消息内容
type callbackOriginMessage struct {
ToUserName string // 企业微信的CorpID当为第三方套件回调事件时CorpID的内容为suiteid
AgentID string // 接收的应用id可在应用的设置页面获取
Encrypt string // 消息结构体加密后的字符串
}
// EventCallbackMessage 微信客户联系回调消息
// https://developer.work.weixin.qq.com/document/path/92130
type EventCallbackMessage struct {
ToUserName string `json:"to_user_name"`
FromUserName string `json:"from_user_name"`
CreateTime int64 `json:"create_time"`
MsgType string `json:"msg_type"`
Event string `json:"event"`
ChangeType string `json:"change_type"`
UserID string `json:"user_id"`
ExternalUserID string `json:"external_user_id"`
State string `json:"state"`
WelcomeCode string `json:"welcome_code"`
}
// GetCallbackMessage 获取联系客户回调事件中的消息内容
func (r *Client) GetCallbackMessage(encryptedMsg []byte) (msg EventCallbackMessage, err error) {
var origin callbackOriginMessage
if err = xml.Unmarshal(encryptedMsg, &origin); err != nil {
return
}
_, bData, err := util.DecryptMsg(r.CorpID, origin.Encrypt, r.EncodingAESKey)
if err != nil {
return
}
if err = xml.Unmarshal(bData, &msg); err != nil {
return
}
return
}

View File

@@ -0,0 +1,275 @@
package externalcontact
import (
"fmt"
"github.com/silenceper/wechat/v2/util"
)
const (
// addContactWayURL 配置客户联系「联系我」方式
addContactWayURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_contact_way?access_token=%s"
// getContactWayURL 获取企业已配置的「联系我」方式
getContactWayURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_contact_way?access_token=%s"
// updateContactWayURL 更新企业已配置的「联系我」方式
updateContactWayURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/update_contact_way?access_token=%s"
// listContactWayURL 获取企业已配置的「联系我」列表
listContactWayURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list_contact_way?access_token=%s"
// delContactWayURL 删除企业已配置的「联系我」方式
delContactWayURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_contact_way?access_token=%s"
)
type (
// ConclusionsRequest 结束语请求
ConclusionsRequest struct {
Text ConclusionsText `json:"text"`
Image ConclusionsImageRequest `json:"image"`
Link ConclusionsLink `json:"link"`
MiniProgram ConclusionsMiniProgram `json:"miniprogram"`
}
// ConclusionsText 文本格式结束语
ConclusionsText struct {
Content string `json:"content"`
}
// ConclusionsImageRequest 图片格式结束语请求
ConclusionsImageRequest struct {
MediaID string `json:"media_id"`
}
// ConclusionsLink 链接格式结束语
ConclusionsLink struct {
Title string `json:"title"`
PicURL string `json:"picurl"`
Desc string `json:"desc"`
URL string `json:"url"`
}
// ConclusionsMiniProgram 小程序格式结束语
ConclusionsMiniProgram struct {
Title string `json:"title"`
PicMediaID string `json:"pic_media_id"`
AppID string `json:"appid"`
Page string `json:"page"`
}
// ConclusionsResponse 结束语响应
ConclusionsResponse struct {
Text ConclusionsText `json:"text"`
Image ConclusionsImageResponse `json:"image"`
Link ConclusionsLink `json:"link"`
MiniProgram ConclusionsMiniProgram `json:"miniprogram"`
}
// ConclusionsImageResponse 图片格式结束语响应
ConclusionsImageResponse struct {
PicURL string `json:"pic_url"`
}
)
type (
// AddContactWayRequest 配置客户联系「联系我」方式请求
AddContactWayRequest struct {
Type int `json:"type"`
Scene int `json:"scene"`
Style int `json:"style"`
Remark string `json:"remark"`
SkipVerify bool `json:"skip_verify"`
State string `json:"state"`
User []string `json:"user"`
Party []int `json:"party"`
IsTemp bool `json:"is_temp"`
ExpiresIn int `json:"expires_in"`
ChatExpiresIn int `json:"chat_expires_in"`
UnionID string `json:"unionid"`
Conclusions ConclusionsRequest `json:"conclusions"`
}
// AddContactWayResponse 配置客户联系「联系我」方式响应
AddContactWayResponse struct {
util.CommonError
ConfigID string `json:"config_id"`
QrCode string `json:"qr_code"`
}
)
// AddContactWay 配置客户联系「联系我」方式
// see https://developer.work.weixin.qq.com/document/path/92228
func (r *Client) AddContactWay(req *AddContactWayRequest) (*AddContactWayResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(addContactWayURL, accessToken), req); err != nil {
return nil, err
}
result := &AddContactWayResponse{}
if err = util.DecodeWithError(response, result, "AddContactWay"); err != nil {
return nil, err
}
return result, nil
}
type (
// GetContactWayRequest 获取企业已配置的「联系我」方式请求
GetContactWayRequest struct {
ConfigID string `json:"config_id"`
}
// GetContactWayResponse 获取企业已配置的「联系我」方式响应
GetContactWayResponse struct {
util.CommonError
ContactWay ContactWay `json:"contact_way"`
}
// ContactWay 「联系我」配置
ContactWay struct {
ConfigID string `json:"config_id"`
Type int `json:"type"`
Scene int `json:"scene"`
Style int `json:"style"`
Remark string `json:"remark"`
SkipVerify bool `json:"skip_verify"`
State string `json:"state"`
QrCode string `json:"qr_code"`
User []string `json:"user"`
Party []int `json:"party"`
IsTemp bool `json:"is_temp"`
ExpiresIn int `json:"expires_in"`
ChatExpiresIn int `json:"chat_expires_in"`
UnionID string `json:"unionid"`
Conclusions ConclusionsResponse `json:"conclusions"`
}
)
// GetContactWay 获取企业已配置的「联系我」方式
// see https://developer.work.weixin.qq.com/document/path/92228
func (r *Client) GetContactWay(req *GetContactWayRequest) (*GetContactWayResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(getContactWayURL, accessToken), req); err != nil {
return nil, err
}
result := &GetContactWayResponse{}
if err = util.DecodeWithError(response, result, "GetContactWay"); err != nil {
return nil, err
}
return result, nil
}
type (
// UpdateContactWayRequest 更新企业已配置的「联系我」方式请求
UpdateContactWayRequest struct {
ConfigID string `json:"config_id"`
Remark string `json:"remark"`
SkipVerify bool `json:"skip_verify"`
Style int `json:"style"`
State string `json:"state"`
User []string `json:"user"`
Party []int `json:"party"`
ExpiresIn int `json:"expires_in"`
ChatExpiresIn int `json:"chat_expires_in"`
UnionID string `json:"unionid"`
Conclusions ConclusionsRequest `json:"conclusions"`
}
// UpdateContactWayResponse 更新企业已配置的「联系我」方式响应
UpdateContactWayResponse struct {
util.CommonError
}
)
// UpdateContactWay 更新企业已配置的「联系我」方式
// see https://developer.work.weixin.qq.com/document/path/92228
func (r *Client) UpdateContactWay(req *UpdateContactWayRequest) (*UpdateContactWayResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(updateContactWayURL, accessToken), req); err != nil {
return nil, err
}
result := &UpdateContactWayResponse{}
if err = util.DecodeWithError(response, result, "UpdateContactWay"); err != nil {
return nil, err
}
return result, nil
}
type (
//ListContactWayRequest 获取企业已配置的「联系我」列表请求
ListContactWayRequest struct {
StartTime int `json:"start_time"`
EndTime int `json:"end_time"`
Cursor string `json:"cursor"`
Limit int `json:"limit"`
}
//ListContactWayResponse 获取企业已配置的「联系我」列表响应
ListContactWayResponse struct {
util.CommonError
ContactWay []*ContactWayForList `json:"contact_way"`
NextCursor string `json:"next_cursor"`
}
// ContactWayForList 「联系我」配置
ContactWayForList struct {
ConfigID string `json:"config_id"`
}
)
// ListContactWay 获取企业已配置的「联系我」列表
// see https://developer.work.weixin.qq.com/document/path/92228
func (r *Client) ListContactWay(req *ListContactWayRequest) (*ListContactWayResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(listContactWayURL, accessToken), req); err != nil {
return nil, err
}
result := &ListContactWayResponse{}
if err = util.DecodeWithError(response, result, "ListContactWay"); err != nil {
return nil, err
}
return result, nil
}
type (
// DelContactWayRequest 删除企业已配置的「联系我」方式请求
DelContactWayRequest struct {
ConfigID string `json:"config_id"`
}
// DelContactWayResponse 删除企业已配置的「联系我」方式响应
DelContactWayResponse struct {
util.CommonError
}
)
// DelContactWay 删除企业已配置的「联系我」方式
// see https://developer.work.weixin.qq.com/document/path/92228
func (r *Client) DelContactWay(req *DelContactWayRequest) (*DelContactWayResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(delContactWayURL, accessToken), req); err != nil {
return nil, err
}
result := &DelContactWayResponse{}
if err = util.DecodeWithError(response, result, "DelContactWay"); err != nil {
return nil, err
}
return result, nil
}

View File

@@ -8,14 +8,26 @@ import (
)
const (
// FetchExternalContactUserListURL 获取客户列表
FetchExternalContactUserListURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list"
// FetchExternalContactUserDetailURL 获取客户详情
FetchExternalContactUserDetailURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get"
// FetchBatchExternalContactUserDetailURL 批量获取客户详情
FetchBatchExternalContactUserDetailURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user"
// UpdateUserRemarkURL 更新客户备注信息
UpdateUserRemarkURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/remark"
// fetchExternalContactUserListURL 获取客户列表
fetchExternalContactUserListURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list"
// fetchExternalContactUserDetailURL 获取客户详情
fetchExternalContactUserDetailURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get"
// fetchBatchExternalContactUserDetailURL 批量获取客户详情
fetchBatchExternalContactUserDetailURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user"
// updateUserRemarkURL 更新客户备注信息
updateUserRemarkURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/remark"
// listCustomerStrategyURL 获取规则组列表
listCustomerStrategyURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_strategy/list?access_token=%s"
// getCustomerStrategyURL 获取规则组详情
getCustomerStrategyURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_strategy/get?access_token=%s"
// getRangeCustomerStrategyURL 获取规则组管理范围
getRangeCustomerStrategyURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_strategy/get_range?access_token=%s"
// createCustomerStrategyURL 创建新的规则组
createCustomerStrategyURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_strategy/create?access_token=%s"
// editCustomerStrategyURL 编辑规则组及其管理范围
editCustomerStrategyURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_strategy/edit?access_token=%s"
// delCustomerStrategyURL 删除规则组
delCustomerStrategyURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_strategy/del?access_token=%s"
)
// ExternalUserListResponse 外部联系人列表响应
@@ -32,7 +44,7 @@ func (r *Client) GetExternalUserList(userID string) ([]string, error) {
return nil, err
}
var response []byte
response, err = util.HTTPGet(fmt.Sprintf("%s?access_token=%v&userid=%v", FetchExternalContactUserListURL, accessToken, userID))
response, err = util.HTTPGet(fmt.Sprintf("%s?access_token=%v&userid=%v", fetchExternalContactUserListURL, accessToken, userID))
if err != nil {
return nil, err
}
@@ -47,23 +59,23 @@ func (r *Client) GetExternalUserList(userID string) ([]string, error) {
// ExternalUserDetailResponse 外部联系人详情响应
type ExternalUserDetailResponse struct {
util.CommonError
ExternalUser
ExternalContact ExternalUser `json:"external_contact"`
FollowUser []FollowUser `json:"follow_user"`
NextCursor string `json:"next_cursor"`
}
// ExternalUser 外部联系人
type ExternalUser struct {
ExternalUserID string `json:"external_userid"`
Name string `json:"name"`
Avatar string `json:"avatar"`
Type int64 `json:"type"`
Gender int64 `json:"gender"`
UnionID string `json:"unionid"`
Position string `json:"position"`
CorpName string `json:"corp_name"`
CorpFullName string `json:"corp_full_name"`
ExternalProfile string `json:"external_profile"`
FollowUser []FollowUser `json:"follow_user"`
NextCursor string `json:"next_cursor"`
ExternalUserID string `json:"external_userid"`
Name string `json:"name"`
Avatar string `json:"avatar"`
Type int64 `json:"type"`
Gender int64 `json:"gender"`
UnionID string `json:"unionid"`
Position string `json:"position"`
CorpName string `json:"corp_name"`
CorpFullName string `json:"corp_full_name"`
ExternalProfile string `json:"external_profile"`
}
// FollowUser 跟进用户(指企业内部用户)
@@ -71,7 +83,7 @@ type FollowUser struct {
UserID string `json:"userid"`
Remark string `json:"remark"`
Description string `json:"description"`
CreateTime string `json:"create_time"`
CreateTime int64 `json:"createtime"`
Tags []Tag `json:"tags"`
RemarkCorpName string `json:"remark_corp_name"`
RemarkMobiles []string `json:"remark_mobiles"`
@@ -96,45 +108,89 @@ type WechatChannel struct {
}
// GetExternalUserDetail 获取外部联系人详情
func (r *Client) GetExternalUserDetail(externalUserID string, nextCursor ...string) (*ExternalUser, error) {
// @see https://developer.work.weixin.qq.com/document/path/92114
func (r *Client) GetExternalUserDetail(externalUserID string, nextCursor ...string) (*ExternalUserDetailResponse, error) {
accessToken, err := r.GetAccessToken()
if err != nil {
return nil, err
}
var response []byte
response, err = util.HTTPGet(fmt.Sprintf("%s?access_token=%v&external_userid=%v&cursor=%v", FetchExternalContactUserDetailURL, accessToken, externalUserID, nextCursor))
var cursor string
if len(nextCursor) > 0 {
cursor = nextCursor[0]
}
response, err = util.HTTPGet(fmt.Sprintf("%s?access_token=%v&external_userid=%v&cursor=%v", fetchExternalContactUserDetailURL, accessToken, externalUserID, cursor))
if err != nil {
return nil, err
}
var result ExternalUserDetailResponse
err = util.DecodeWithError(response, &result, "get_external_user_detail")
result := &ExternalUserDetailResponse{}
err = util.DecodeWithError(response, result, "get_external_user_detail")
if err != nil {
return nil, err
}
return &result.ExternalUser, nil
return result, nil
}
// BatchGetExternalUserDetailsRequest 批量获取外部联系人详情请求
type BatchGetExternalUserDetailsRequest struct {
UserIDList []string `json:"userid_list"`
Cursor string `json:"cursor"`
Limit int `json:"limit,omitempty"`
}
// ExternalUserDetailListResponse 批量获取外部联系人详情响应
type ExternalUserDetailListResponse struct {
util.CommonError
ExternalContactList []ExternalUser `json:"external_contact_list"`
ExternalContactList []ExternalUserForBatch `json:"external_contact_list"`
}
// ExternalUserForBatch 批量获取外部联系人客户列表
type ExternalUserForBatch struct {
ExternalContact ExternalContact `json:"external_contact"`
FollowInfo FollowInfo `json:"follow_info"`
}
// ExternalContact 批量获取外部联系人用户信息
type ExternalContact struct {
ExternalUserID string `json:"external_userid"`
Name string `json:"name"`
Position string `json:"position"`
Avatar string `json:"avatar"`
CorpName string `json:"corp_name"`
CorpFullName string `json:"corp_full_name"`
Type int64 `json:"type"`
Gender int64 `json:"gender"`
UnionID string `json:"unionid"`
ExternalProfile string `json:"external_profile"`
}
// FollowInfo 批量获取外部联系人跟进人信息
type FollowInfo struct {
UserID string `json:"userid"`
Remark string `json:"remark"`
Description string `json:"description"`
CreateTime int64 `json:"createtime"`
TagID []string `json:"tag_id"`
RemarkCorpName string `json:"remark_corp_name"`
RemarkMobiles []string `json:"remark_mobiles"`
OperUserID string `json:"oper_userid"`
AddWay int64 `json:"add_way"`
WeChatChannels WechatChannel `json:"wechat_channels"`
}
// BatchGetExternalUserDetails 批量获取外部联系人详情
func (r *Client) BatchGetExternalUserDetails(request BatchGetExternalUserDetailsRequest) ([]ExternalUser, error) {
// @see https://developer.work.weixin.qq.com/document/path/92994
func (r *Client) BatchGetExternalUserDetails(request BatchGetExternalUserDetailsRequest) ([]ExternalUserForBatch, error) {
accessToken, err := r.GetAccessToken()
if err != nil {
return nil, err
}
var response []byte
jsonData, _ := json.Marshal(request)
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", FetchBatchExternalContactUserDetailURL, accessToken), string(jsonData))
jsonData, err := json.Marshal(request)
if err != nil {
return nil, err
}
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", fetchBatchExternalContactUserDetailURL, accessToken), string(jsonData))
if err != nil {
return nil, err
}
@@ -158,16 +214,253 @@ type UpdateUserRemarkRequest struct {
}
// UpdateUserRemark 修改客户备注信息
// @see https://developer.work.weixin.qq.com/document/path/92115
func (r *Client) UpdateUserRemark(request UpdateUserRemarkRequest) error {
accessToken, err := r.GetAccessToken()
if err != nil {
return err
}
var response []byte
jsonData, _ := json.Marshal(request)
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", UpdateUserRemarkURL, accessToken), string(jsonData))
jsonData, err := json.Marshal(request)
if err != nil {
return err
}
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", updateUserRemarkURL, accessToken), string(jsonData))
if err != nil {
return err
}
return util.DecodeWithCommonError(response, "UpdateUserRemark")
}
// ListCustomerStrategyRequest 获取规则组列表请求
type ListCustomerStrategyRequest struct {
Cursor string `json:"cursor"`
Limit int `json:"limit"`
}
// ListCustomerStrategyResponse 获取规则组列表响应
type ListCustomerStrategyResponse struct {
util.CommonError
Strategy []StrategyID `json:"strategy"`
NextCursor string `json:"next_cursor"`
}
// StrategyID 规则组ID
type StrategyID struct {
StrategyID int `json:"strategy_id"`
}
// ListCustomerStrategy 获取规则组列表
// @see https://developer.work.weixin.qq.com/document/path/94883#%E8%8E%B7%E5%8F%96%E8%A7%84%E5%88%99%E7%BB%84%E5%88%97%E8%A1%A8
func (r *Client) ListCustomerStrategy(req *ListCustomerStrategyRequest) (*ListCustomerStrategyResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(listCustomerStrategyURL, accessToken), req); err != nil {
return nil, err
}
result := &ListCustomerStrategyResponse{}
if err = util.DecodeWithError(response, result, "ListCustomerStrategy"); err != nil {
return nil, err
}
return result, nil
}
// GetCustomerStrategyRequest 获取规则组详情请求
type GetCustomerStrategyRequest struct {
StrategyID int `json:"strategy_id"`
}
// GetCustomerStrategyResponse 获取规则组详情响应
type GetCustomerStrategyResponse struct {
util.CommonError
Strategy Strategy `json:"strategy"`
}
// Strategy 规则组
type Strategy struct {
StrategyID int `json:"strategy_id"`
ParentID int `json:"parent_id"`
StrategyName string `json:"strategy_name"`
CreateTime int64 `json:"create_time"`
AdminList []string `json:"admin_list"`
Privilege Privilege `json:"privilege"`
}
// Privilege 权限
type Privilege struct {
ViewCustomerList bool `json:"view_customer_list"`
ViewCustomerData bool `json:"view_customer_data"`
ViewRoomList bool `json:"view_room_list"`
ContactMe bool `json:"contact_me"`
JoinRoom bool `json:"join_room"`
ShareCustomer bool `json:"share_customer"`
OperResignCustomer bool `json:"oper_resign_customer"`
OperResignGroup bool `json:"oper_resign_group"`
SendCustomerMsg bool `json:"send_customer_msg"`
EditWelcomeMsg bool `json:"edit_welcome_msg"`
ViewBehaviorData bool `json:"view_behavior_data"`
ViewRoomData bool `json:"view_room_data"`
SendGroupMsg bool `json:"send_group_msg"`
RoomDeduplication bool `json:"room_deduplication"`
RapidReply bool `json:"rapid_reply"`
OnjobCustomerTransfer bool `json:"onjob_customer_transfer"`
EditAntiSpamRule bool `json:"edit_anti_spam_rule"`
ExportCustomerList bool `json:"export_customer_list"`
ExportCustomerData bool `json:"export_customer_data"`
ExportCustomerGroupList bool `json:"export_customer_group_list"`
ManageCustomerTag bool `json:"manage_customer_tag"`
}
// GetCustomerStrategy 获取规则组详情
// @see https://developer.work.weixin.qq.com/document/path/94883#%E8%8E%B7%E5%8F%96%E8%A7%84%E5%88%99%E7%BB%84%E8%AF%A6%E6%83%85
func (r *Client) GetCustomerStrategy(req *GetCustomerStrategyRequest) (*GetCustomerStrategyResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(getCustomerStrategyURL, accessToken), req); err != nil {
return nil, err
}
result := &GetCustomerStrategyResponse{}
if err = util.DecodeWithError(response, result, "GetCustomerStrategy"); err != nil {
return nil, err
}
return result, nil
}
// GetRangeCustomerStrategyRequest 获取规则组管理范围请求
type GetRangeCustomerStrategyRequest struct {
StrategyID int `json:"strategy_id"`
Cursor string `json:"cursor"`
Limit int `json:"limit"`
}
// GetRangeCustomerStrategyResponse 获取规则组管理范围响应
type GetRangeCustomerStrategyResponse struct {
util.CommonError
Range []Range `json:"range"`
NextCursor string `json:"next_cursor"`
}
// Range 管理范围节点
type Range struct {
Type int `json:"type"`
UserID string `json:"userid,omitempty"`
PartyID int `json:"partyid,omitempty"`
}
// GetRangeCustomerStrategy 获取规则组管理范围
// @see https://developer.work.weixin.qq.com/document/path/94883#%E8%8E%B7%E5%8F%96%E8%A7%84%E5%88%99%E7%BB%84%E7%AE%A1%E7%90%86%E8%8C%83%E5%9B%B4
func (r *Client) GetRangeCustomerStrategy(req *GetRangeCustomerStrategyRequest) (*GetRangeCustomerStrategyResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(getRangeCustomerStrategyURL, accessToken), req); err != nil {
return nil, err
}
result := &GetRangeCustomerStrategyResponse{}
if err = util.DecodeWithError(response, result, "GetRangeCustomerStrategy"); err != nil {
return nil, err
}
return result, nil
}
// CreateCustomerStrategyRequest 创建新的规则组请求
type CreateCustomerStrategyRequest struct {
ParentID int `json:"parent_id"`
StrategyName string `json:"strategy_name"`
AdminList []string `json:"admin_list"`
Privilege Privilege `json:"privilege"`
Range []Range `json:"range"`
}
// CreateCustomerStrategyResponse 创建新的规则组响应
type CreateCustomerStrategyResponse struct {
util.CommonError
StrategyID int `json:"strategy_id"`
}
// CreateCustomerStrategy 创建新的规则组
// @see https://developer.work.weixin.qq.com/document/path/94883#%E5%88%9B%E5%BB%BA%E6%96%B0%E7%9A%84%E8%A7%84%E5%88%99%E7%BB%84
func (r *Client) CreateCustomerStrategy(req *CreateCustomerStrategyRequest) (*CreateCustomerStrategyResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(createCustomerStrategyURL, accessToken), req); err != nil {
return nil, err
}
result := &CreateCustomerStrategyResponse{}
if err = util.DecodeWithError(response, result, "CreateCustomerStrategy"); err != nil {
return nil, err
}
return result, nil
}
// EditCustomerStrategyRequest 编辑规则组及其管理范围请求
type EditCustomerStrategyRequest struct {
StrategyID int `json:"strategy_id"`
StrategyName string `json:"strategy_name"`
AdminList []string `json:"admin_list"`
Privilege Privilege `json:"privilege"`
RangeAdd []Range `json:"range_add"`
RangeDel []Range `json:"range_del"`
}
// EditCustomerStrategy 编辑规则组及其管理范围
// see https://developer.work.weixin.qq.com/document/path/94883#%E7%BC%96%E8%BE%91%E8%A7%84%E5%88%99%E7%BB%84%E5%8F%8A%E5%85%B6%E7%AE%A1%E7%90%86%E8%8C%83%E5%9B%B4
func (r *Client) EditCustomerStrategy(req *EditCustomerStrategyRequest) error {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(editCustomerStrategyURL, accessToken), req); err != nil {
return err
}
return util.DecodeWithCommonError(response, "EditCustomerStrategy")
}
// DelCustomerStrategyRequest 删除规则组请求
type DelCustomerStrategyRequest struct {
StrategyID int `json:"strategy_id"`
}
// DelCustomerStrategy 删除规则组
// see https://developer.work.weixin.qq.com/document/path/94883#%E5%88%A0%E9%99%A4%E8%A7%84%E5%88%99%E7%BB%84
func (r *Client) DelCustomerStrategy(req *DelCustomerStrategyRequest) error {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(delCustomerStrategyURL, accessToken), req); err != nil {
return err
}
return util.DecodeWithCommonError(response, "DelCustomerStrategy")
}

View File

@@ -7,8 +7,8 @@ import (
)
const (
// FetchFollowUserListURL 获取配置了客户联系功能的成员列表
FetchFollowUserListURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_follow_user_list"
// fetchFollowUserListURL 获取配置了客户联系功能的成员列表
fetchFollowUserListURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_follow_user_list"
)
// followerUserResponse 客户联系功能的成员列表响应
@@ -25,7 +25,7 @@ func (r *Client) GetFollowUserList() ([]string, error) {
return nil, err
}
var response []byte
response, err = util.HTTPGet(fmt.Sprintf("%s?access_token=%s", FetchFollowUserListURL, accessToken))
response, err = util.HTTPGet(fmt.Sprintf("%s?access_token=%s", fetchFollowUserListURL, accessToken))
if err != nil {
return nil, err
}

View File

@@ -0,0 +1,143 @@
package externalcontact
import (
"fmt"
"github.com/silenceper/wechat/v2/util"
)
// opengIDToChatIDURL 客户群opengid转换URL
const opengIDToChatIDURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/opengid_to_chatid"
type (
//GroupChatListRequest 获取客户群列表的请求参数
GroupChatListRequest struct {
StatusFilter int `json:"status_filter"` // 非必填 客户群跟进状态过滤。0 - 所有列表(即不过滤) 1 - 离职待继承 2 - 离职继承中 3 - 离职继承完成
OwnerFilter OwnerFilter `json:"owner_filter"` //非必填 群主过滤。如果不填表示获取应用可见范围内全部群主的数据但是不建议这么用如果可见范围人数超过1000人为了防止数据包过大会报错 81017
Cursor string `json:"cursor"` //非必填 用于分页查询的游标,字符串类型,由上一次调用返回,首次调用不填
Limit int `json:"limit"` //必填 分页,预期请求的数据量,取值范围 1 ~ 1000
}
//GroupChatList 客户群列表
GroupChatList struct {
ChatID string `json:"chat_id"`
Status int `json:"status"`
}
//GroupChatListResponse 获取客户群列表的返回值
GroupChatListResponse struct {
util.CommonError
GroupChatList []GroupChatList `json:"group_chat_list"`
NextCursor string `json:"next_cursor"` //游标
}
)
// GetGroupChatList 获取客户群列表
// @see https://developer.work.weixin.qq.com/document/path/92120
func (r *Client) GetGroupChatList(req *GroupChatListRequest) (*GroupChatListResponse, error) {
accessToken, err := r.GetAccessToken()
if err != nil {
return nil, err
}
var response []byte
response, err = util.PostJSON(fmt.Sprintf("%s/list?access_token=%s", groupChatURL, accessToken), req)
if err != nil {
return nil, err
}
result := &GroupChatListResponse{}
if err = util.DecodeWithError(response, result, "GetGroupChatList"); err != nil {
return nil, err
}
return result, nil
}
type (
//GroupChatDetailRequest 客户群详情 请求参数
GroupChatDetailRequest struct {
ChatID string `json:"chat_id"`
NeedName int `json:"need_name"`
}
//Invitor 邀请者
Invitor struct {
UserID string `json:"userid"` //邀请者的userid
}
//GroupChatMember 群成员
GroupChatMember struct {
UserID string `json:"userid"` //群成员id
Type int `json:"type"` //成员类型。 1 - 企业成员 2 - 外部联系人
JoinTime int `json:"join_time"` //入群时间
JoinScene int `json:"join_scene"` //入群方式 1 - 由群成员邀请入群(直接邀请入群) 2 - 由群成员邀请入群(通过邀请链接入群) 3 - 通过扫描群二维码入群
Invitor Invitor `json:"invitor,omitempty"` //邀请者。目前仅当是由本企业内部成员邀请入群时会返回该值
GroupNickname string `json:"group_nickname"` //在群里的昵称
Name string `json:"name"` //名字。仅当 need_name = 1 时返回 如果是微信用户,则返回其在微信中设置的名字 如果是企业微信联系人,则返回其设置对外展示的别名或实名
UnionID string `json:"unionid,omitempty"` //外部联系人在微信开放平台的唯一身份标识微信unionid通过此字段企业可将外部联系人与公众号/小程序用户关联起来。仅当群成员类型是微信用户包括企业成员未添加好友且企业绑定了微信开发者ID有此字段查看绑定方法。第三方不可获取上游企业不可获取下游企业客户的unionid字段
}
//GroupChatAdmin 群管理员
GroupChatAdmin struct {
UserID string `json:"userid"` //群管理员userid
}
//GroupChat 客户群详情
GroupChat struct {
ChatID string `json:"chat_id"` //客户群ID
Name string `json:"name"` //群名
Owner string `json:"owner"` //群主ID
CreateTime int64 `json:"create_time"` //群的创建时间
Notice string `json:"notice"` //群公告
MemberList []GroupChatMember `json:"member_list"` //群成员列表
AdminList []GroupChatAdmin `json:"admin_list"` //群管理员列表
}
//GroupChatDetailResponse 客户群详情 返回值
GroupChatDetailResponse struct {
util.CommonError
GroupChat GroupChat `json:"group_chat"` //客户群详情
}
)
// GetGroupChatDetail 获取客户群详情
// @see https://developer.work.weixin.qq.com/document/path/92122
func (r *Client) GetGroupChatDetail(req *GroupChatDetailRequest) (*GroupChatDetailResponse, error) {
accessToken, err := r.GetAccessToken()
if err != nil {
return nil, err
}
var response []byte
response, err = util.PostJSON(fmt.Sprintf("%s/get?access_token=%s", groupChatURL, accessToken), req)
if err != nil {
return nil, err
}
result := &GroupChatDetailResponse{}
if err = util.DecodeWithError(response, result, "GetGroupChatDetail"); err != nil {
return nil, err
}
return result, nil
}
type (
//OpengIDToChatIDRequest 客户群opengid转换 请求参数
OpengIDToChatIDRequest struct {
OpengID string `json:"opengid"`
}
//OpengIDToChatIDResponse 客户群opengid转换 返回值
OpengIDToChatIDResponse struct {
util.CommonError
ChatID string `json:"chat_id"` //客户群ID
}
)
// OpengIDToChatID 客户群opengid转换
// @see https://developer.work.weixin.qq.com/document/path/94828
func (r *Client) OpengIDToChatID(req *OpengIDToChatIDRequest) (*OpengIDToChatIDResponse, error) {
accessToken, err := r.GetAccessToken()
if err != nil {
return nil, err
}
var response []byte
response, err = util.PostJSON(fmt.Sprintf("%s?access_token=%s", opengIDToChatIDURL, accessToken), req)
if err != nil {
return nil, err
}
result := &OpengIDToChatIDResponse{}
if err = util.DecodeWithError(response, result, "GetGroupChatDetail"); err != nil {
return nil, err
}
return result, nil
}

View File

@@ -0,0 +1,146 @@
package externalcontact
import (
"fmt"
"github.com/silenceper/wechat/v2/util"
)
// groupChatURL 客户群
const groupChatURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat"
type (
// AddJoinWayRequest 添加群配置请求参数
AddJoinWayRequest struct {
Scene int `json:"scene"` // 必填 1 - 群的小程序插件,2 - 群的二维码插件
Remark string `json:"remark"` //非必填 联系方式的备注信息用于助记超过30个字符将被截断
AutoCreateRoom int `json:"auto_create_room"` //非必填 当群满了后是否自动新建群。0-否1-是。 默认为1
RoomBaseName string `json:"room_base_name"` //非必填 自动建群的群名前缀当auto_create_room为1时有效。最长40个utf8字符
RoomBaseID int `json:"room_base_id"` //非必填 自动建群的群起始序号当auto_create_room为1时有效
ChatIDList []string `json:"chat_id_list"` //必填 使用该配置的客户群ID列表支持5个。见客户群ID获取方法
State string `json:"state"` //非必填 企业自定义的state参数用于区分不同的入群渠道。不超过30个UTF-8字符
}
// AddJoinWayResponse 添加群配置返回值
AddJoinWayResponse struct {
util.CommonError
ConfigID string `json:"config_id"`
}
)
// AddJoinWay 加入群聊
// @see https://developer.work.weixin.qq.com/document/path/92229
func (r *Client) AddJoinWay(req *AddJoinWayRequest) (*AddJoinWayResponse, error) {
var (
accessToken string
err error
response []byte
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
response, err = util.PostJSON(fmt.Sprintf("%s/add_join_way?access_token=%s", groupChatURL, accessToken), req)
if err != nil {
return nil, err
}
result := &AddJoinWayResponse{}
if err = util.DecodeWithError(response, result, "AddJoinWay"); err != nil {
return nil, err
}
return result, nil
}
type (
//JoinWayConfigRequest 获取或删除群配置的请求参数
JoinWayConfigRequest struct {
ConfigID string `json:"config_id"`
}
//JoinWay 群配置
JoinWay struct {
ConfigID string `json:"config_id"`
Scene int `json:"scene"`
Remark string `json:"remark"`
AutoCreateRoom int `json:"auto_create_room"`
RoomBaseName string `json:"room_base_name"`
RoomBaseID int `json:"room_base_id"`
ChatIDList []string `json:"chat_id_list"`
QrCode string `json:"qr_code"`
State string `json:"state"`
}
//GetJoinWayResponse 获取群配置的返回值
GetJoinWayResponse struct {
util.CommonError
JoinWay JoinWay `json:"join_way"`
}
)
// GetJoinWay 获取客户群进群方式配置
// @see https://developer.work.weixin.qq.com/document/path/92229
func (r *Client) GetJoinWay(req *JoinWayConfigRequest) (*GetJoinWayResponse, error) {
var (
accessToken string
err error
response []byte
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
response, err = util.PostJSON(fmt.Sprintf("%s/get_join_way?access_token=%s", groupChatURL, accessToken), req)
if err != nil {
return nil, err
}
result := &GetJoinWayResponse{}
if err = util.DecodeWithError(response, result, "GetJoinWay"); err != nil {
return nil, err
}
return result, nil
}
// UpdateJoinWayRequest 更新群配置的请求参数
type UpdateJoinWayRequest struct {
ConfigID string `json:"config_id"`
Scene int `json:"scene"` // 必填 1 - 群的小程序插件,2 - 群的二维码插件
Remark string `json:"remark"` //非必填 联系方式的备注信息用于助记超过30个字符将被截断
AutoCreateRoom int `json:"auto_create_room"` //非必填 当群满了后是否自动新建群。0-否1-是。 默认为1
RoomBaseName string `json:"room_base_name"` //非必填 自动建群的群名前缀当auto_create_room为1时有效。最长40个utf8字符
RoomBaseID int `json:"room_base_id"` //非必填 自动建群的群起始序号当auto_create_room为1时有效
ChatIDList []string `json:"chat_id_list"` //必填 使用该配置的客户群ID列表支持5个。见客户群ID获取方法
State string `json:"state"` //非必填 企业自定义的state参数用于区分不同的入群渠道。不超过30个UTF-8字符
}
// UpdateJoinWay 更新客户群进群方式配置
// @see https://developer.work.weixin.qq.com/document/path/92229
func (r *Client) UpdateJoinWay(req *UpdateJoinWayRequest) error {
var (
accessToken string
err error
response []byte
)
if accessToken, err = r.GetAccessToken(); err != nil {
return err
}
response, err = util.PostJSON(fmt.Sprintf("%s/update_join_way?access_token=%s", groupChatURL, accessToken), req)
if err != nil {
return err
}
return util.DecodeWithCommonError(response, "UpdateJoinWay")
}
// DelJoinWay 删除客户群进群方式配置
// @see https://developer.work.weixin.qq.com/document/path/92229
func (r *Client) DelJoinWay(req *JoinWayConfigRequest) error {
var (
accessToken string
err error
response []byte
)
if accessToken, err = r.GetAccessToken(); err != nil {
return err
}
response, err = util.PostJSON(fmt.Sprintf("%s/del_join_way?access_token=%s", groupChatURL, accessToken), req)
if err != nil {
return err
}
return util.DecodeWithCommonError(response, "DelJoinWay")
}

424
work/externalcontact/msg.go Normal file
View File

@@ -0,0 +1,424 @@
package externalcontact
import (
"fmt"
"github.com/silenceper/wechat/v2/util"
)
const (
// addMsgTemplateURL 创建企业群发
addMsgTemplateURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_msg_template?access_token=%s"
// getGroupMsgListV2URL 获取群发记录列表
getGroupMsgListV2URL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_groupmsg_list_v2?access_token=%s"
// getGroupMsgTaskURL 获取群发成员发送任务列表
getGroupMsgTaskURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_groupmsg_task?access_token=%s"
// getGroupMsgSendResultURL 获取企业群发成员执行结果
getGroupMsgSendResultURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_groupmsg_send_result?access_token=%s"
// sendWelcomeMsgURL 发送新客户欢迎语
sendWelcomeMsgURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/send_welcome_msg?access_token=%s"
// addGroupWelcomeTemplateURL 添加入群欢迎语素材
addGroupWelcomeTemplateURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/add?access_token=%s"
// editGroupWelcomeTemplateURL 编辑入群欢迎语素材
editGroupWelcomeTemplateURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/edit?access_token=%s"
// getGroupWelcomeTemplateURL 获取入群欢迎语素材
getGroupWelcomeTemplateURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/get?access_token=%s"
// delGroupWelcomeTemplateURL 删除入群欢迎语素材
delGroupWelcomeTemplateURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/del?access_token=%s"
)
// AddMsgTemplateRequest 创建企业群发请求
type AddMsgTemplateRequest struct {
ChatType string `json:"chat_type"`
ExternalUserID []string `json:"external_userid"`
Sender string `json:"sender,omitempty"`
Text MsgText `json:"text"`
Attachments []*Attachment `json:"attachments"`
}
// MsgText 文本消息
type MsgText struct {
Content string `json:"content"`
}
type (
// Attachment 附件
Attachment struct {
MsgType string `json:"msgtype"`
Image AttachmentImg `json:"image,omitempty"`
Link AttachmentLink `json:"link,omitempty"`
MiniProgram AttachmentMiniProgram `json:"miniprogram,omitempty"`
Video AttachmentVideo `json:"video,omitempty"`
File AttachmentFile `json:"file,omitempty"`
}
// AttachmentImg 图片消息
AttachmentImg struct {
MediaID string `json:"media_id"`
PicURL string `json:"pic_url"`
}
// AttachmentLink 图文消息
AttachmentLink struct {
Title string `json:"title"`
PicURL string `json:"picurl"`
Desc string `json:"desc"`
URL string `json:"url"`
}
// AttachmentMiniProgram 小程序消息
AttachmentMiniProgram struct {
Title string `json:"title"`
PicMediaID string `json:"pic_media_id"`
AppID string `json:"appid"`
Page string `json:"page"`
}
// AttachmentVideo 视频消息
AttachmentVideo struct {
MediaID string `json:"media_id"`
}
// AttachmentFile 文件消息
AttachmentFile struct {
MediaID string `json:"media_id"`
}
)
// AddMsgTemplateResponse 创建企业群发响应
type AddMsgTemplateResponse struct {
util.CommonError
FailList []string `json:"fail_list"`
MsgID string `json:"msgid"`
}
// AddMsgTemplate 创建企业群发
// see https://developer.work.weixin.qq.com/document/path/92135
func (r *Client) AddMsgTemplate(req *AddMsgTemplateRequest) (*AddMsgTemplateResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(addMsgTemplateURL, accessToken), req); err != nil {
return nil, err
}
result := &AddMsgTemplateResponse{}
if err = util.DecodeWithError(response, result, "AddMsgTemplate"); err != nil {
return nil, err
}
return result, nil
}
// GetGroupMsgListV2Request 获取群发记录列表请求
type GetGroupMsgListV2Request struct {
ChatType string `json:"chat_type"`
StartTime int64 `json:"start_time"`
EndTime int64 `json:"end_time"`
Creator string `json:"creator,omitempty"`
FilterType int `json:"filter_type"`
Limit int `json:"limit"`
Cursor string `json:"cursor"`
}
// GetGroupMsgListV2Response 获取群发记录列表响应
type GetGroupMsgListV2Response struct {
util.CommonError
NextCursor string `json:"next_cursor"`
GroupMsgList []*GroupMsg `json:"group_msg_list"`
}
// GroupMsg 群发消息
type GroupMsg struct {
MsgID string `json:"msgid"`
Creator string `json:"creator"`
CreateTime int64 `json:"create_time"`
CreateType int `json:"create_type"`
Text MsgText `json:"text"`
Attachments []*Attachment `json:"attachments"`
}
// GetGroupMsgListV2 获取群发记录列表
// see https://developer.work.weixin.qq.com/document/path/93338#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%8F%91%E8%AE%B0%E5%BD%95%E5%88%97%E8%A1%A8
func (r *Client) GetGroupMsgListV2(req *GetGroupMsgListV2Request) (*GetGroupMsgListV2Response, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(getGroupMsgListV2URL, accessToken), req); err != nil {
return nil, err
}
result := &GetGroupMsgListV2Response{}
if err = util.DecodeWithError(response, result, "GetGroupMsgListV2"); err != nil {
return nil, err
}
return result, nil
}
// GetGroupMsgTaskRequest 获取群发成员发送任务列表请求
type GetGroupMsgTaskRequest struct {
MsgID string `json:"msgid"`
Limit int `json:"limit"`
Cursor string `json:"cursor"`
}
// GetGroupMsgTaskResponse 获取群发成员发送任务列表响应
type GetGroupMsgTaskResponse struct {
util.CommonError
NextCursor string `json:"next_cursor"`
TaskList []*Task `json:"task_list"`
}
// Task 获取群发成员发送任务列表任务
type Task struct {
UserID string `json:"userid"`
Status int `json:"status"`
SendTime int `json:"send_time"`
}
// GetGroupMsgTask 获取群发成员发送任务列表
// see https://developer.work.weixin.qq.com/document/path/93338#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%8F%91%E6%88%90%E5%91%98%E5%8F%91%E9%80%81%E4%BB%BB%E5%8A%A1%E5%88%97%E8%A1%A8
func (r *Client) GetGroupMsgTask(req *GetGroupMsgTaskRequest) (*GetGroupMsgTaskResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(getGroupMsgTaskURL, accessToken), req); err != nil {
return nil, err
}
result := &GetGroupMsgTaskResponse{}
if err = util.DecodeWithError(response, result, "GetGroupMsgTask"); err != nil {
return nil, err
}
return result, nil
}
// GetGroupMsgSendResultRequest 获取企业群发成员执行结果请求
type GetGroupMsgSendResultRequest struct {
MsgID string `json:"msgid"`
UserID string `json:"userid"`
Limit int `json:"limit"`
Cursor string `json:"cursor"`
}
// GetGroupMsgSendResultResponse 获取企业群发成员执行结果响应
type GetGroupMsgSendResultResponse struct {
util.CommonError
NextCursor string `json:"next_cursor"`
SendList []*Send `json:"send_list"`
}
// Send 企业群发成员执行结果
type Send struct {
ExternalUserID string `json:"external_userid"`
ChatID string `json:"chat_id"`
UserID string `json:"userid"`
Status int `json:"status"`
SendTime int `json:"send_time"`
}
// GetGroupMsgSendResult 获取企业群发成员执行结果
// see https://developer.work.weixin.qq.com/document/path/93338#%E8%8E%B7%E5%8F%96%E4%BC%81%E4%B8%9A%E7%BE%A4%E5%8F%91%E6%88%90%E5%91%98%E6%89%A7%E8%A1%8C%E7%BB%93%E6%9E%9C
func (r *Client) GetGroupMsgSendResult(req *GetGroupMsgSendResultRequest) (*GetGroupMsgSendResultResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(getGroupMsgSendResultURL, accessToken), req); err != nil {
return nil, err
}
result := &GetGroupMsgSendResultResponse{}
if err = util.DecodeWithError(response, result, "GetGroupMsgSendResult"); err != nil {
return nil, err
}
return result, nil
}
// SendWelcomeMsgRequest 发送新客户欢迎语请求
type SendWelcomeMsgRequest struct {
WelcomeCode string `json:"welcome_code"`
Text MsgText `json:"text"`
Attachments []*Attachment `json:"attachments"`
}
// SendWelcomeMsgResponse 发送新客户欢迎语响应
type SendWelcomeMsgResponse struct {
util.CommonError
}
// SendWelcomeMsg 发送新客户欢迎语
// see https://developer.work.weixin.qq.com/document/path/92137
func (r *Client) SendWelcomeMsg(req *SendWelcomeMsgRequest) error {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(sendWelcomeMsgURL, accessToken), req); err != nil {
return err
}
result := &SendWelcomeMsgResponse{}
if err = util.DecodeWithError(response, result, "SendWelcomeMsg"); err != nil {
return err
}
return nil
}
// AddGroupWelcomeTemplateRequest 添加入群欢迎语素材请求
type AddGroupWelcomeTemplateRequest struct {
Text MsgText `json:"text"`
Image AttachmentImg `json:"image"`
Link AttachmentLink `json:"link"`
MiniProgram AttachmentMiniProgram `json:"miniprogram"`
File AttachmentFile `json:"file"`
Video AttachmentVideo `json:"video"`
AgentID int `json:"agentid"`
Notify int `json:"notify"`
}
// AddGroupWelcomeTemplateResponse 添加入群欢迎语素材响应
type AddGroupWelcomeTemplateResponse struct {
util.CommonError
TemplateID string `json:"template_id"`
}
// AddGroupWelcomeTemplate 添加入群欢迎语素材
// see https://developer.work.weixin.qq.com/document/path/92366#%E6%B7%BB%E5%8A%A0%E5%85%A5%E7%BE%A4%E6%AC%A2%E8%BF%8E%E8%AF%AD%E7%B4%A0%E6%9D%90
func (r *Client) AddGroupWelcomeTemplate(req *AddGroupWelcomeTemplateRequest) (*AddGroupWelcomeTemplateResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(addGroupWelcomeTemplateURL, accessToken), req); err != nil {
return nil, err
}
result := &AddGroupWelcomeTemplateResponse{}
if err = util.DecodeWithError(response, result, "AddGroupWelcomeTemplate"); err != nil {
return nil, err
}
return result, nil
}
// EditGroupWelcomeTemplateRequest 编辑入群欢迎语素材请求
type EditGroupWelcomeTemplateRequest struct {
TemplateID string `json:"template_id"`
Text MsgText `json:"text"`
Image AttachmentImg `json:"image"`
Link AttachmentLink `json:"link"`
MiniProgram AttachmentMiniProgram `json:"miniprogram"`
File AttachmentFile `json:"file"`
Video AttachmentVideo `json:"video"`
AgentID int `json:"agentid"`
}
// EditGroupWelcomeTemplateResponse 编辑入群欢迎语素材响应
type EditGroupWelcomeTemplateResponse struct {
util.CommonError
}
// EditGroupWelcomeTemplate 编辑入群欢迎语素材
// see https://developer.work.weixin.qq.com/document/path/92366#%E7%BC%96%E8%BE%91%E5%85%A5%E7%BE%A4%E6%AC%A2%E8%BF%8E%E8%AF%AD%E7%B4%A0%E6%9D%90
func (r *Client) EditGroupWelcomeTemplate(req *EditGroupWelcomeTemplateRequest) error {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(editGroupWelcomeTemplateURL, accessToken), req); err != nil {
return err
}
result := &EditGroupWelcomeTemplateResponse{}
if err = util.DecodeWithError(response, result, "EditGroupWelcomeTemplate"); err != nil {
return err
}
return nil
}
// GetGroupWelcomeTemplateRequest 获取入群欢迎语素材请求
type GetGroupWelcomeTemplateRequest struct {
TemplateID string `json:"template_id"`
}
// GetGroupWelcomeTemplateResponse 获取入群欢迎语素材响应
type GetGroupWelcomeTemplateResponse struct {
util.CommonError
Text MsgText `json:"text"`
Image AttachmentImg `json:"image"`
Link AttachmentLink `json:"link"`
MiniProgram AttachmentMiniProgram `json:"miniprogram"`
File AttachmentFile `json:"file"`
Video AttachmentVideo `json:"video"`
}
// GetGroupWelcomeTemplate 获取入群欢迎语素材
// see https://developer.work.weixin.qq.com/document/path/92366#%E8%8E%B7%E5%8F%96%E5%85%A5%E7%BE%A4%E6%AC%A2%E8%BF%8E%E8%AF%AD%E7%B4%A0%E6%9D%90
func (r *Client) GetGroupWelcomeTemplate(req *GetGroupWelcomeTemplateRequest) (*GetGroupWelcomeTemplateResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(getGroupWelcomeTemplateURL, accessToken), req); err != nil {
return nil, err
}
result := &GetGroupWelcomeTemplateResponse{}
if err = util.DecodeWithError(response, result, "GetGroupWelcomeTemplate"); err != nil {
return nil, err
}
return result, nil
}
// DelGroupWelcomeTemplateRequest 删除入群欢迎语素材请求
type DelGroupWelcomeTemplateRequest struct {
TemplateID string `json:"template_id"`
AgentID int `json:"agentid"`
}
// DelGroupWelcomeTemplateResponse 删除入群欢迎语素材响应
type DelGroupWelcomeTemplateResponse struct {
util.CommonError
}
// DelGroupWelcomeTemplate 删除入群欢迎语素材
// see https://developer.work.weixin.qq.com/document/path/92366#%E5%88%A0%E9%99%A4%E5%85%A5%E7%BE%A4%E6%AC%A2%E8%BF%8E%E8%AF%AD%E7%B4%A0%E6%9D%90
func (r *Client) DelGroupWelcomeTemplate(req *DelGroupWelcomeTemplateRequest) error {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(delGroupWelcomeTemplateURL, accessToken), req); err != nil {
return err
}
result := &DelGroupWelcomeTemplateResponse{}
if err = util.DecodeWithError(response, result, "DelGroupWelcomeTemplate"); err != nil {
return err
}
return nil
}

View File

@@ -8,12 +8,12 @@ import (
)
const (
// GetUserBehaviorDataURL 获取「联系客户统计」数据
GetUserBehaviorDataURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_user_behavior_data"
// GetGroupChatStatURL 获取「群聊数据统计」数据 按群主聚合的方式
GetGroupChatStatURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic"
// GetGroupChatStatByDayURL 获取「群聊数据统计」数据 按自然日聚合的方式
GetGroupChatStatByDayURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic_group_by_day"
// getUserBehaviorDataURL 获取「联系客户统计」数据
getUserBehaviorDataURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_user_behavior_data"
// getGroupChatStatURL 获取「群聊数据统计」数据 按群主聚合的方式
getGroupChatStatURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic"
// getGroupChatStatByDayURL 获取「群聊数据统计」数据 按自然日聚合的方式
getGroupChatStatByDayURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic_group_by_day"
)
type (
@@ -54,7 +54,7 @@ func (r *Client) GetUserBehaviorData(req *GetUserBehaviorRequest) ([]BehaviorDat
if err != nil {
return nil, err
}
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", GetUserBehaviorDataURL, accessToken), string(jsonData))
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", getUserBehaviorDataURL, accessToken), string(jsonData))
if err != nil {
return nil, err
}
@@ -120,7 +120,7 @@ func (r *Client) GetGroupChatStat(req *GetGroupChatStatRequest) (*GetGroupChatSt
if err != nil {
return nil, err
}
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", GetGroupChatStatURL, accessToken), string(jsonData))
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", getGroupChatStatURL, accessToken), string(jsonData))
if err != nil {
return nil, err
}
@@ -163,7 +163,7 @@ func (r *Client) GetGroupChatStatByDay(req *GetGroupChatStatByDayRequest) ([]Get
if err != nil {
return nil, err
}
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", GetGroupChatStatByDayURL, accessToken), string(jsonData))
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", getGroupChatStatByDayURL, accessToken), string(jsonData))
if err != nil {
return nil, err
}

View File

@@ -8,16 +8,24 @@ import (
)
const (
// GetCropTagURL 获取标签列表
GetCropTagURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list"
// AddCropTagURL 添加标签
AddCropTagURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_corp_tag"
// EditCropTagURL 修改标签
EditCropTagURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/edit_corp_tag"
// DelCropTagURL 删除标签
DelCropTagURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_corp_tag"
// MarkCropTagURL 为客户打上、删除标签
MarkCropTagURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag"
// getCropTagURL 获取标签列表
getCropTagURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list"
// addCropTagURL 添加标签
addCropTagURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_corp_tag"
// editCropTagURL 修改标签
editCropTagURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/edit_corp_tag"
// delCropTagURL 删除标签
delCropTagURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_corp_tag"
// markCropTagURL 为客户打上、删除标签
markCropTagURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag"
// getStrategyTagListURL 获取指定规则组下的企业客户标签
getStrategyTagListURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_strategy_tag_list?access_token=%s"
// addStrategyTagURL 为指定规则组创建企业客户标签
addStrategyTagURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_strategy_tag?access_token=%s"
// editStrategyTagURL 编辑指定规则组下的企业客户标签
editStrategyTagURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/edit_strategy_tag?access_token=%s"
// delStrategyTagURL 删除指定规则组下的企业客户标签
delStrategyTagURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_strategy_tag?access_token=%s"
)
// GetCropTagRequest 获取企业标签请求
@@ -36,7 +44,7 @@ type GetCropTagListResponse struct {
type TagGroup struct {
GroupID string `json:"group_id"`
GroupName string `json:"group_name"`
CreateTime string `json:"create_time"`
CreateTime int64 `json:"create_time"`
GroupOrder int `json:"group_order"`
Deleted bool `json:"deleted"`
Tag []TagGroupTagItem `json:"tag"`
@@ -46,7 +54,7 @@ type TagGroup struct {
type TagGroupTagItem struct {
ID string `json:"id"`
Name string `json:"name"`
CreateTime int `json:"create_time"`
CreateTime int64 `json:"create_time"`
Order int `json:"order"`
Deleted bool `json:"deleted"`
}
@@ -59,8 +67,11 @@ func (r *Client) GetCropTagList(req GetCropTagRequest) ([]TagGroup, error) {
return nil, err
}
var response []byte
jsonData, _ := json.Marshal(req)
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", GetCropTagURL, accessToken), string(jsonData))
jsonData, err := json.Marshal(req)
if err != nil {
return nil, err
}
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", getCropTagURL, accessToken), string(jsonData))
if err != nil {
return nil, err
}
@@ -74,7 +85,7 @@ func (r *Client) GetCropTagList(req GetCropTagRequest) ([]TagGroup, error) {
// AddCropTagRequest 添加企业标签请求
type AddCropTagRequest struct {
GroupID string `json:"group_id"`
GroupID string `json:"group_id,omitempty"`
GroupName string `json:"group_name"`
Order int `json:"order"`
Tag []AddCropTagItem `json:"tag"`
@@ -102,8 +113,11 @@ func (r *Client) AddCropTag(req AddCropTagRequest) (*TagGroup, error) {
return nil, err
}
var response []byte
jsonData, _ := json.Marshal(req)
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", AddCropTagURL, accessToken), string(jsonData))
jsonData, err := json.Marshal(req)
if err != nil {
return nil, err
}
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", addCropTagURL, accessToken), string(jsonData))
if err != nil {
return nil, err
}
@@ -131,8 +145,11 @@ func (r *Client) EditCropTag(req EditCropTagRequest) error {
return err
}
var response []byte
jsonData, _ := json.Marshal(req)
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", EditCropTagURL, accessToken), string(jsonData))
jsonData, err := json.Marshal(req)
if err != nil {
return err
}
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", editCropTagURL, accessToken), string(jsonData))
if err != nil {
return err
}
@@ -154,8 +171,11 @@ func (r *Client) DeleteCropTag(req DeleteCropTagRequest) error {
return err
}
var response []byte
jsonData, _ := json.Marshal(req)
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", DelCropTagURL, accessToken), string(jsonData))
jsonData, err := json.Marshal(req)
if err != nil {
return err
}
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", delCropTagURL, accessToken), string(jsonData))
if err != nil {
return err
}
@@ -179,10 +199,171 @@ func (r *Client) MarkTag(request MarkTagRequest) error {
return err
}
var response []byte
jsonData, _ := json.Marshal(request)
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", MarkCropTagURL, accessToken), string(jsonData))
jsonData, err := json.Marshal(request)
if err != nil {
return err
}
response, err = util.HTTPPost(fmt.Sprintf("%s?access_token=%v", markCropTagURL, accessToken), string(jsonData))
if err != nil {
return err
}
return util.DecodeWithCommonError(response, "MarkTag")
}
// GetStrategyTagListRequest 获取指定规则组下的企业客户标签请求
type GetStrategyTagListRequest struct {
StrategyID int `json:"strategy_id"`
TagID []string `json:"tag_id"`
GroupID []string `json:"group_id"`
}
// GetStrategyTagListResponse 获取指定规则组下的企业客户标签响应
type GetStrategyTagListResponse struct {
util.CommonError
TagGroup []StrategyTagGroup `json:"tag_group"`
}
// StrategyTagGroup 规则组下的企业标签组
type StrategyTagGroup struct {
GroupID string `json:"group_id"`
GroupName string `json:"group_name"`
CreateTime int64 `json:"create_time"`
Order int `json:"order"`
StrategyID int `json:"strategy_id"`
Tag []StrategyTag `json:"tag"`
}
// StrategyTag 规则组下的企业标签
type StrategyTag struct {
ID string `json:"id"`
Name string `json:"name"`
CreateTime int64 `json:"create_time"`
Order int `json:"order"`
}
// GetStrategyTagList 获取指定规则组下的企业客户标签
// @see https://developer.work.weixin.qq.com/document/path/94882#%E8%8E%B7%E5%8F%96%E6%8C%87%E5%AE%9A%E8%A7%84%E5%88%99%E7%BB%84%E4%B8%8B%E7%9A%84%E4%BC%81%E4%B8%9A%E5%AE%A2%E6%88%B7%E6%A0%87%E7%AD%BE
func (r *Client) GetStrategyTagList(req *GetStrategyTagListRequest) (*GetStrategyTagListResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(getStrategyTagListURL, accessToken), req); err != nil {
return nil, err
}
result := &GetStrategyTagListResponse{}
if err = util.DecodeWithError(response, result, "GetStrategyTagList"); err != nil {
return nil, err
}
return result, nil
}
// AddStrategyTagRequest 为指定规则组创建企业客户标签请求
type AddStrategyTagRequest struct {
StrategyID int `json:"strategy_id"`
GroupID string `json:"group_id"`
GroupName string `json:"group_name"`
Order int `json:"order"`
Tag []AddStrategyTagRequestItem `json:"tag"`
}
// AddStrategyTagRequestItem 为指定规则组创建企业客户标签请求条目
type AddStrategyTagRequestItem struct {
Name string `json:"name"`
Order int `json:"order"`
}
// AddStrategyTagResponse 为指定规则组创建企业客户标签响应
type AddStrategyTagResponse struct {
util.CommonError
TagGroup AddStrategyTagResponseTagGroup `json:"tag_group"`
}
// AddStrategyTagResponseTagGroup 为指定规则组创建企业客户标签响应标签组
type AddStrategyTagResponseTagGroup struct {
GroupID string `json:"group_id"`
GroupName string `json:"group_name"`
CreateTime int64 `json:"create_time"`
Order int `json:"order"`
Tag []AddStrategyTagResponseItem `json:"tag"`
}
// AddStrategyTagResponseItem 标签组内的标签列表
type AddStrategyTagResponseItem struct {
ID string `json:"id"`
Name string `json:"name"`
CreateTime int64 `json:"create_time"`
Order int `json:"order"`
}
// AddStrategyTag 为指定规则组创建企业客户标签
// @see https://developer.work.weixin.qq.com/document/path/94882#%E4%B8%BA%E6%8C%87%E5%AE%9A%E8%A7%84%E5%88%99%E7%BB%84%E5%88%9B%E5%BB%BA%E4%BC%81%E4%B8%9A%E5%AE%A2%E6%88%B7%E6%A0%87%E7%AD%BE
func (r *Client) AddStrategyTag(req *AddStrategyTagRequest) (*AddStrategyTagResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(addStrategyTagURL, accessToken), req); err != nil {
return nil, err
}
result := &AddStrategyTagResponse{}
if err = util.DecodeWithError(response, result, "AddStrategyTag"); err != nil {
return nil, err
}
return result, nil
}
// EditStrategyTagRequest 编辑指定规则组下的企业客户标签请求
type EditStrategyTagRequest struct {
ID string `json:"id"`
Name string `json:"name"`
Order int `json:"order"`
}
// EditStrategyTag 编辑指定规则组下的企业客户标签
// see https://developer.work.weixin.qq.com/document/path/94882#%E7%BC%96%E8%BE%91%E6%8C%87%E5%AE%9A%E8%A7%84%E5%88%99%E7%BB%84%E4%B8%8B%E7%9A%84%E4%BC%81%E4%B8%9A%E5%AE%A2%E6%88%B7%E6%A0%87%E7%AD%BE
func (r *Client) EditStrategyTag(req *EditStrategyTagRequest) error {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(editStrategyTagURL, accessToken), req); err != nil {
return err
}
return util.DecodeWithCommonError(response, "EditStrategyTag")
}
// DelStrategyTagRequest 删除指定规则组下的企业客户标签请求
type DelStrategyTagRequest struct {
TagID []string `json:"tag_id"`
GroupID []string `json:"group_id"`
}
// DelStrategyTag 删除指定规则组下的企业客户标签
// see https://developer.work.weixin.qq.com/document/path/94882#%E5%88%A0%E9%99%A4%E6%8C%87%E5%AE%9A%E8%A7%84%E5%88%99%E7%BB%84%E4%B8%8B%E7%9A%84%E4%BC%81%E4%B8%9A%E5%AE%A2%E6%88%B7%E6%A0%87%E7%AD%BE
func (r *Client) DelStrategyTag(req *DelStrategyTagRequest) error {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(delStrategyTagURL, accessToken), req); err != nil {
return err
}
return util.DecodeWithCommonError(response, "DelStrategyTag")
}

17
work/invoice/client.go Normal file
View File

@@ -0,0 +1,17 @@
package invoice
import (
"github.com/silenceper/wechat/v2/work/context"
)
// Client 电子发票接口实例
type Client struct {
*context.Context
}
// NewClient 初始化实例
func NewClient(ctx *context.Context) *Client {
return &Client{
ctx,
}
}

191
work/invoice/invoice.go Normal file
View File

@@ -0,0 +1,191 @@
package invoice
import (
"fmt"
"github.com/silenceper/wechat/v2/util"
)
const (
// getInvoiceInfoURL 查询电子发票
getInvoiceInfoURL = "https://qyapi.weixin.qq.com/cgi-bin/card/invoice/reimburse/getinvoiceinfo?access_token=%s"
// updateInvoiceStatusURL 更新发票状态
updateInvoiceStatusURL = "https://qyapi.weixin.qq.com/cgi-bin/card/invoice/reimburse/updateinvoicestatus?access_token=%s"
// updateStatusBatchURL 批量更新发票状态
updateStatusBatchURL = "https://qyapi.weixin.qq.com/cgi-bin/card/invoice/reimburse/updatestatusbatch?access_token=%s"
// getInvoiceInfoBatchURL 批量查询电子发票
getInvoiceInfoBatchURL = "https://qyapi.weixin.qq.com/cgi-bin/card/invoice/reimburse/getinvoiceinfobatch?access_token=%s"
)
// GetInvoiceInfoRequest 查询电子发票请求
type GetInvoiceInfoRequest struct {
CardID string `json:"card_id"`
EncryptCode string `json:"encrypt_code"`
}
// GetInvoiceInfoResponse 查询电子发票响应
type GetInvoiceInfoResponse struct {
util.CommonError
CardID string `json:"card_id"`
BeginTime int64 `json:"begin_time"`
EndTime int64 `json:"end_time"`
OpenID string `json:"openid"`
Type string `json:"type"`
Payee string `json:"payee"`
Detail string `json:"detail"`
UserInfo UserInfo `json:"user_info"`
}
// UserInfo 发票的用户信息
type UserInfo struct {
Fee int64 `json:"fee"`
Title string `json:"title"`
BillingTime int64 `json:"billing_time"`
BillingNo string `json:"billing_no"`
BillingCode string `json:"billing_code"`
Info []Info `json:"info"`
FeeWithoutTax int64 `json:"fee_without_tax"`
Tax int64 `json:"tax"`
Detail string `json:"detail"`
PdfURL string `json:"pdf_url"`
TripPdfURL string `json:"trip_pdf_url"`
ReimburseStatus string `json:"reimburse_status"`
CheckCode string `json:"check_code"`
BuyerNumber string `json:"buyer_number"`
BuyerAddressAndPhone string `json:"buyer_address_and_phone"`
BuyerBankAccount string `json:"buyer_bank_account"`
SellerNumber string `json:"seller_number"`
SellerAddressAndPhone string `json:"seller_address_and_phone"`
SellerBankAccount string `json:"seller_bank_account"`
Remarks string `json:"remarks"`
Cashier string `json:"cashier"`
Maker string `json:"maker"`
}
// Info 商品信息结构
type Info struct {
Name string `json:"name"`
Num int64 `json:"num"`
Unit string `json:"unit"`
Fee int64 `json:"fee"`
Price int64 `json:"price"`
}
// GetInvoiceInfo 查询电子发票
// see https://developer.work.weixin.qq.com/document/path/90284
func (r *Client) GetInvoiceInfo(req *GetInvoiceInfoRequest) (*GetInvoiceInfoResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(getInvoiceInfoURL, accessToken), req); err != nil {
return nil, err
}
result := &GetInvoiceInfoResponse{}
if err = util.DecodeWithError(response, result, "GetInvoiceInfo"); err != nil {
return nil, err
}
return result, nil
}
// UpdateInvoiceStatusRequest 更新发票状态请求
type UpdateInvoiceStatusRequest struct {
CardID string `json:"card_id"`
EncryptCode string `json:"encrypt_code"`
ReimburseStatus string `json:"reimburse_status"`
}
// UpdateInvoiceStatus 更新发票状态
// see https://developer.work.weixin.qq.com/document/path/90285
func (r *Client) UpdateInvoiceStatus(req *UpdateInvoiceStatusRequest) error {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(updateInvoiceStatusURL, accessToken), req); err != nil {
return err
}
return util.DecodeWithCommonError(response, "UpdateInvoiceStatus")
}
// UpdateStatusBatchRequest 批量更新发票状态
type UpdateStatusBatchRequest struct {
OpenID string `json:"openid"`
ReimburseStatus string `json:"reimburse_status"`
InvoiceList []Invoice `json:"invoice_list"`
}
// Invoice 发票卡券
type Invoice struct {
CardID string `json:"card_id"`
EncryptCode string `json:"encrypt_code"`
}
// UpdateStatusBatch 批量更新发票状态
// see https://developer.work.weixin.qq.com/document/path/90286
func (r *Client) UpdateStatusBatch(req *UpdateStatusBatchRequest) error {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(updateStatusBatchURL, accessToken), req); err != nil {
return err
}
return util.DecodeWithCommonError(response, "UpdateStatusBatch")
}
// GetInvoiceInfoBatchRequest 批量查询电子发票请求
type GetInvoiceInfoBatchRequest struct {
ItemList []Invoice `json:"item_list"`
}
// GetInvoiceInfoBatchResponse 批量查询电子发票响应
type GetInvoiceInfoBatchResponse struct {
util.CommonError
ItemList []Item `json:"item_list"`
}
// Item 电子发票的结构化信息
type Item struct {
CardID string `json:"card_id"`
BeginTime int64 `json:"begin_time"`
EndTime int64 `json:"end_time"`
OpenID string `json:"openid"`
Type string `json:"type"`
Payee string `json:"payee"`
Detail string `json:"detail"`
UserInfo UserInfo `json:"user_info"`
}
// GetInvoiceInfoBatch 批量查询电子发票
// see https://developer.work.weixin.qq.com/document/path/90287
func (r *Client) GetInvoiceInfoBatch(req *GetInvoiceInfoBatchRequest) (*GetInvoiceInfoBatchResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(getInvoiceInfoBatchURL, accessToken), req); err != nil {
return nil, err
}
result := &GetInvoiceInfoBatchResponse{}
if err = util.DecodeWithError(response, result, "GetInvoiceInfoBatch"); err != nil {
return nil, err
}
return result, nil
}

View File

@@ -15,21 +15,22 @@ type SignatureOptions struct {
}
// VerifyURL 验证请求参数是否合法并返回解密后的消息内容
// //Gin框架的使用示例
// r.GET("/v1/event/callback", func(c *gin.Context) {
// options := kf.SignatureOptions{}
// //获取回调的的校验参数
// if = c.ShouldBindQuery(&options); err != nil {
// c.String(http.StatusUnauthorized, "参数解析失败")
// }
// // 调用VerifyURL方法校验当前请求如果合法则把解密后的内容作为响应返回给微信服务器
// echo, err := kfClient.VerifyURL(options)
// if err == nil {
// c.String(http.StatusOK, echo)
// } else {
// c.String(http.StatusUnauthorized, "非法请求来源")
// }
// })
//
// //Gin框架的使用示例
// r.GET("/v1/event/callback", func(c *gin.Context) {
// options := kf.SignatureOptions{}
// //获取回调的的校验参数
// if = c.ShouldBindQuery(&options); err != nil {
// c.String(http.StatusUnauthorized, "参数解析失败")
// }
// // 调用VerifyURL方法校验当前请求如果合法则把解密后的内容作为响应返回给微信服务器
// echo, err := kfClient.VerifyURL(options)
// if err == nil {
// c.String(http.StatusOK, echo)
// } else {
// c.String(http.StatusUnauthorized, "非法请求来源")
// }
// })
func (r *Client) VerifyURL(options SignatureOptions) (string, error) {
if options.Signature != util.Signature(r.ctx.Token, options.TimeStamp, options.Nonce, options.EchoStr) {
return "", NewSDKErr(40015)
@@ -51,35 +52,37 @@ type callbackOriginMessage struct {
// CallbackMessage 微信客服回调消息
type CallbackMessage struct {
ToUserName string `json:"to_user_name"` // 微信客服组件ID
CreateTime int `json:"create_time"` // 消息创建时间unix时间戳
MsgType string `json:"msgtype"` // 消息的类型,此时固定为 event
Event string `json:"event"` // 事件的类型,此时固定为 kf_msg_or_event
Token string `json:"token"` // 调用拉取消息接口时需要传此token用于校验请求的合法性
ToUserName string `json:"to_user_name" xml:"ToUserName"` // 微信客服组件ID
CreateTime int64 `json:"create_time" xml:"CreateTime"` // 消息创建时间unix时间戳
MsgType string `json:"msgtype" xml:"MsgType"` // 消息的类型,此时固定为 event
Event string `json:"event" xml:"Event"` // 事件的类型,此时固定为 kf_msg_or_event
Token string `json:"token" xml:"Token"` // 调用拉取消息接口时需要传此token用于校验请求的合法性
OpenKfID string `json:"open_kfid" xml:"OpenKfId"` // 有新消息的客服帐号。可通过sync_msg接口指定open_kfid获取此客服帐号的消息
}
// GetCallbackMessage 获取回调事件中的消息内容
// //Gin框架的使用示例
// r.POST("/v1/event/callback", func(c *gin.Context) {
// var (
// message kf.CallbackMessage
// body []byte
// )
// // 读取原始消息内容
// body, err = c.GetRawData()
// if err != nil {
// c.String(http.StatusInternalServerError, err.Error())
// return
// }
// // 解析原始数据
// message, err = kfClient.GetCallbackMessage(body)
// if err != nil {
// c.String(http.StatusInternalServerError, "消息获取失败")
// return
// }
// fmt.Println(message)
// c.String(200, "ok")
// })
//
// //Gin框架的使用示例
// r.POST("/v1/event/callback", func(c *gin.Context) {
// var (
// message kf.CallbackMessage
// body []byte
// )
// // 读取原始消息内容
// body, err = c.GetRawData()
// if err != nil {
// c.String(http.StatusInternalServerError, err.Error())
// return
// }
// // 解析原始数据
// message, err = kfClient.GetCallbackMessage(body)
// if err != nil {
// c.String(http.StatusInternalServerError, "消息获取失败")
// return
// }
// fmt.Println(message)
// c.String(200, "ok")
// })
func (r *Client) GetCallbackMessage(encryptedMsg []byte) (msg CallbackMessage, err error) {
var origin callbackOriginMessage
if err = xml.Unmarshal(encryptedMsg, &origin); err != nil {

View File

@@ -16,9 +16,11 @@ const (
// SyncMsgOptions 获取消息查询参数
type SyncMsgOptions struct {
Cursor string `json:"cursor"` // 上一次调用时返回的next_cursor第一次拉取可以不填, 不多于64字节
Token string `json:"token"` // 回调事件返回的token字段10分钟内有效可不填如果不填接口有严格的频率限制, 不多于128字节
Limit uint `json:"limit"` // 期望请求的数据量默认值和最大值都为1000, 注意可能会出现返回条数少于limit的情况需结合返回的has_more字段判断是否继续请求。
Cursor string `json:"cursor"` // 上一次调用时返回的next_cursor第一次拉取可以不填, 不多于64字节
Token string `json:"token"` // 回调事件返回的token字段10分钟内有效可不填如果不填接口有严格的频率限制, 不多于128字节
Limit uint `json:"limit"` // 期望请求的数据量默认值和最大值都为1000, 注意可能会出现返回条数少于limit的情况需结合返回的has_more字段判断是否继续请求。
VoiceFormat uint `json:"voice_format,omitempty"` // 语音消息类型0-Amr 1-Silk默认0。可通过该参数控制返回的语音格式开发者可按需选择自己程序支持的一种格式
OpenKfID string `json:"open_kfid,omitempty"` // 指定拉取某个客服帐号的消息否则默认返回有权限的客服帐号的消息。当客服帐号较多建议按open_kfid来拉取以获取更好的性能。
}
// SyncMsgSchema 获取消息查询响应内容

17
work/material/client.go Normal file
View File

@@ -0,0 +1,17 @@
package material
import (
"github.com/silenceper/wechat/v2/work/context"
)
// Client 素材管理接口实例
type Client struct {
*context.Context
}
// NewClient 初始化实例
func NewClient(ctx *context.Context) *Client {
return &Client{
ctx,
}
}

71
work/material/media.go Normal file
View File

@@ -0,0 +1,71 @@
package material
import (
"fmt"
"github.com/silenceper/wechat/v2/util"
)
const (
// uploadImgURL 上传图片
uploadImgURL = "https://qyapi.weixin.qq.com/cgi-bin/media/uploadimg?access_token=%s"
// uploadTempFile 上传临时素材
uploadTempFile = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s"
)
// UploadImgResponse 上传图片响应
type UploadImgResponse struct {
util.CommonError
URL string `json:"url"`
}
// UploadTempFileResponse 上传临时素材响应
type UploadTempFileResponse struct {
util.CommonError
MediaID string `json:"media_id"`
CreateAt string `json:"created_at"`
Type string `json:"type"`
}
// UploadImg 上传图片
// @see https://developer.work.weixin.qq.com/document/path/90256
func (r *Client) UploadImg(filename string) (*UploadImgResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostFile("media", filename, fmt.Sprintf(uploadImgURL, accessToken)); err != nil {
return nil, err
}
result := &UploadImgResponse{}
if err = util.DecodeWithError(response, result, "UploadImg"); err != nil {
return nil, err
}
return result, nil
}
// UploadTempFile 上传临时素材
// @see https://developer.work.weixin.qq.com/document/path/90253
// @mediaType 媒体文件类型分别有图片image、语音voice、视频video普通文件file
func (r *Client) UploadTempFile(filename string, mediaType string) (*UploadTempFileResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = r.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostFile("media", filename, fmt.Sprintf(uploadTempFile, accessToken, mediaType)); err != nil {
return nil, err
}
result := &UploadTempFileResponse{}
if err = util.DecodeWithError(response, result, "UploadTempFile"); err != nil {
return nil, err
}
return result, nil
}

16
work/message/client.go Normal file
View File

@@ -0,0 +1,16 @@
// Package message 消息推送,实现企业微信消息推送相关接口https://developer.work.weixin.qq.com/document/path/90235
package message
import (
"github.com/silenceper/wechat/v2/work/context"
)
// Client 消息推送接口实例
type Client struct {
*context.Context
}
// NewClient 初始化实例
func NewClient(ctx *context.Context) *Client {
return &Client{ctx}
}

132
work/message/message.go Normal file
View File

@@ -0,0 +1,132 @@
package message
import (
"encoding/json"
"fmt"
"github.com/silenceper/wechat/v2/util"
)
const (
// 发送应用消息的接口地址
sendURL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s"
)
type (
// SendRequestCommon 发送应用消息请求公共参数
SendRequestCommon struct {
// 指定接收消息的成员成员ID列表多个接收者用|分隔最多支持1000个。 特殊情况:指定为"@all",则向该企业应用的全部成员发送
ToUser string `json:"touser"`
// 指定接收消息的部门部门ID列表多个接收者用|分隔最多支持100个。 当touser为"@all"时忽略本参数
ToParty string `json:"toparty"`
// 指定接收消息的标签标签ID列表多个接收者用|分隔最多支持100个。 当touser为"@all"时忽略本参数
ToTag string `json:"totag"`
// 消息类型此时固定为text
MsgType string `json:"msgtype"`
// 企业应用的id整型。企业内部开发可在应用的设置页面查看第三方服务商可通过接口 获取企业授权信息 获取该参数值
AgentID string `json:"agentid"`
// 表示是否是保密消息0表示可对外分享1表示不能分享且内容显示水印默认为0
Safe int `json:"safe"`
// 表示是否开启id转译0表示否1表示是默认0。仅第三方应用需要用到企业自建应用可以忽略。
EnableIDTrans int `json:"enable_id_trans"`
// 表示是否开启重复消息检查0表示否1表示是默认0
EnableDuplicateCheck int `json:"enable_duplicate_check"`
// 表示是否重复消息检查的时间间隔默认1800s最大不超过4小时
DuplicateCheckInterval int `json:"duplicate_check_interval"`
}
// SendResponse 发送应用消息响应参数
SendResponse struct {
util.CommonError
InvalidUser string `json:"invaliduser"` // 不合法的userid不区分大小写统一转为小写
InvalidParty string `json:"invalidparty"` // 不合法的partyid
InvalidTag string `json:"invalidtag"` // 不合法的标签id
UnlicensedUser string `json:"unlicenseduser"` // 没有基础接口许可(包含已过期)的userid
MsgID string `json:"msgid"` // 消息id
ResponseCode string `json:"response_code"`
}
// SendTextRequest 发送文本消息的请求
SendTextRequest struct {
*SendRequestCommon
Text TextField `json:"text"`
}
// TextField 文本消息参数
TextField struct {
// 消息内容最长不超过2048个字节超过将截断支持id转译
Content string `json:"content"`
}
// SendImageRequest 发送图片消息的请求
SendImageRequest struct {
*SendRequestCommon
Image ImageField `json:"image"`
}
// ImageField 图片消息参数
ImageField struct {
// 图片媒体文件id可以调用上传临时素材接口获取
MediaID string `json:"media_id"`
}
// SendVoiceRequest 发送语音消息的请求
SendVoiceRequest struct {
*SendRequestCommon
Voice VoiceField `json:"voice"`
}
// VoiceField 语音消息参数
VoiceField struct {
// 语音文件id可以调用上传临时素材接口获取
MediaID string `json:"media_id"`
}
)
// Send 发送应用消息
// @desc 实现企业微信发送应用消息接口https://developer.work.weixin.qq.com/document/path/90236
func (r *Client) Send(apiName string, request interface{}) (*SendResponse, error) {
// 获取accessToken
accessToken, err := r.GetAccessToken()
if err != nil {
return nil, err
}
// 请求参数转 JSON 格式
jsonData, err := json.Marshal(request)
if err != nil {
return nil, err
}
// 发起http请求
response, err := util.HTTPPost(fmt.Sprintf(sendURL, accessToken), string(jsonData))
if err != nil {
return nil, err
}
// 按照结构体解析返回值
result := &SendResponse{}
if err = util.DecodeWithError(response, result, apiName); err != nil {
return nil, err
}
// 返回数据
return result, nil
}
// SendText 发送文本消息
func (r *Client) SendText(request SendTextRequest) (*SendResponse, error) {
// 发送文本消息MsgType参数固定为text
request.MsgType = "text"
return r.Send("MessageSendText", request)
}
// SendImage 发送图片消息
func (r *Client) SendImage(request SendImageRequest) (*SendResponse, error) {
// 发送图片消息MsgType参数固定为image
request.MsgType = "image"
return r.Send("MessageSendImage", request)
}
// SendVoice 发送语音消息
func (r *Client) SendVoice(request SendVoiceRequest) (*SendResponse, error) {
// 发送语音消息MsgType参数固定为voice
request.MsgType = "voice"
return r.Send("MessageSendVoice", request)
}
// 以上实现了部分常用消息推送SendText 发送文本消息、SendImage 发送图片消息、SendVoice 发送语音消息,
// 如需扩展其他消息类型,建议按照以上格式,扩展对应消息类型的参数即可
// 也可以直接使用Send方法按照企业微信消息推送的接口文档传对应消息类型的参数来使用

View File

@@ -150,7 +150,7 @@ type TodoMessage struct {
BaseMessage
Todo struct {
Title string `json:"title,omitempty"` // 代办的来源文本
Content string `json:"content,omitempty"` // 代办的具体内容
Content string `json:"content,omitempty"` // 代办的具体内容
} `json:"todo,omitempty"`
}
@@ -169,7 +169,7 @@ type CollectMessage struct {
Collect struct {
RoomName string `json:"room_name,omitempty"` // 填表消息所在的群名称。
Creator string `json:"creator,omitempty"` // 创建者在群中的名字
CreateTime string `json:"create_time,omitempty"` // 创建的时间
CreateTime int64 `json:"create_time,omitempty"` // 创建的时间
Details []CollectDetails `json:"details,omitempty"` // 表内容
} `json:"collect,omitempty"`
}
@@ -266,10 +266,10 @@ type VoipDocShareMessage struct {
type ExternalRedPacketMessage struct {
BaseMessage
RedPacket struct {
Type int32 `json:"type,omitempty"` // 红包消息类型。1 普通红包、2 拼手气群红包。Uint32类型
Wish int32 `json:"wish,omitempty"` // 红包祝福语。String类型
TotalCnt int32 `json:"totalcnt,omitempty"` // 红包总个数。Uint32类型
TotalAmount int32 `json:"totalamount,omitempty"` // 红包消息类型。1 普通红包、2 拼手气群红包。Uint32类型
Type uint32 `json:"type,omitempty"` // 红包消息类型。1 普通红包、2 拼手气群红包。Uint32类型
Wish string `json:"wish,omitempty"` // 红包祝福语。String类型
TotalCnt uint32 `json:"totalcnt,omitempty"` // 红包总个数。Uint32类型
TotalAmount uint32 `json:"totalamount,omitempty"` // 红包总金额。Uint32类型,单位为分。
} `json:"redpacket,omitempty"`
}
@@ -277,9 +277,9 @@ type ExternalRedPacketMessage struct {
type SphFeedMessage struct {
BaseMessage
SphFeed struct {
FeedType string `json:"feed_type,omitempty"` // 视频号消息类型
SphName string `json:"sph_name,omitempty"` // 视频号账号名称
FeedDesc uint64 `json:"feed_desc,omitempty"` // 视频号账号名称
FeedType uint32 `json:"feed_type,omitempty"` // 视频号消息类型。2 图片、4 视频、9 直播。Uint32类型
SphName string `json:"sph_name,omitempty"` // 视频号账号名称。String类型
FeedDesc string `json:"feed_desc,omitempty"` // 视频号消息描述。String类型
}
}

View File

@@ -17,10 +17,16 @@ type Oauth struct {
var (
// oauthTargetURL 企业微信内跳转地址
oauthTargetURL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
// oauthTargetURL 企业微信内跳转地址(获取成员的详细信息)
oauthTargetPrivateURL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_privateinfo&agentid=%s&state=STATE#wechat_redirect"
// oauthUserInfoURL 获取用户信息地址
oauthUserInfoURL = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=%s&code=%s"
// oauthQrContentTargetURL 构造独立窗口登录二维码
oauthQrContentTargetURL = "https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=%s&agentid=%s&redirect_uri=%s&state=%s"
// getUserInfoURL 获取访问用户身份&获取用户登录身份
getUserInfoURL = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=%s&code=%s"
// getUserDetailURL 获取访问用户敏感信息
getUserDetailURL = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?access_token=%s"
)
// NewOauth new init oauth
@@ -40,6 +46,17 @@ func (ctr *Oauth) GetTargetURL(callbackURL string) string {
)
}
// GetTargetPrivateURL 获取个人信息授权地址
func (ctr *Oauth) GetTargetPrivateURL(callbackURL string, agentID string) string {
// url encode
return fmt.Sprintf(
oauthTargetPrivateURL,
ctr.CorpID,
url.QueryEscape(callbackURL),
agentID,
)
}
// GetQrContentTargetURL 构造独立窗口登录二维码
func (ctr *Oauth) GetQrContentTargetURL(callbackURL string) string {
// url encode
@@ -80,3 +97,73 @@ func (ctr *Oauth) UserFromCode(code string) (result ResUserInfo, err error) {
}
return
}
// GetUserInfoResponse 获取访问用户身份&获取用户登录身份响应
type GetUserInfoResponse struct {
util.CommonError
UserID string `json:"userid"`
UserTicket string `json:"user_ticket"`
OpenID string `json:"openid"`
ExternalUserID string `json:"external_userid"`
}
// GetUserInfo 获取访问用户身份&获取用户登录身份
// @see https://developer.work.weixin.qq.com/document/path/90213 获取访问用户身份
// @see https://developer.work.weixin.qq.com/document/path/98176 获取用户登录身份
func (ctr *Oauth) GetUserInfo(code string) (*GetUserInfoResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = ctr.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.HTTPGet(fmt.Sprintf(getUserInfoURL, accessToken, code)); err != nil {
return nil, err
}
result := &GetUserInfoResponse{}
if err = util.DecodeWithError(response, result, "GetUserInfo"); err != nil {
return nil, err
}
return result, nil
}
// GetUserDetailRequest 获取访问用户敏感信息请求
type GetUserDetailRequest struct {
UserTicket string `json:"user_ticket"`
}
// GetUserDetailResponse 获取访问用户敏感信息响应
type GetUserDetailResponse struct {
util.CommonError
UserID string `json:"userid"`
Gender string `json:"gender"`
Avatar string `json:"avatar"`
QrCode string `json:"qr_code"`
Mobile string `json:"mobile"`
Email string `json:"email"`
BizMail string `json:"biz_mail"`
Address string `json:"address"`
}
// GetUserDetail 获取访问用户敏感信息
// @see https://developer.work.weixin.qq.com/document/path/95833
func (ctr *Oauth) GetUserDetail(req *GetUserDetailRequest) (*GetUserDetailResponse, error) {
var (
accessToken string
err error
)
if accessToken, err = ctr.GetAccessToken(); err != nil {
return nil, err
}
var response []byte
if response, err = util.PostJSON(fmt.Sprintf(getUserDetailURL, accessToken), req); err != nil {
return nil, err
}
result := &GetUserDetailResponse{}
if err = util.DecodeWithError(response, result, "GetUserDetail"); err != nil {
return nil, err
}
return result, nil
}

17
work/robot/client.go Normal file
View File

@@ -0,0 +1,17 @@
package robot
import (
"github.com/silenceper/wechat/v2/work/context"
)
// Client 群聊机器人接口实例
type Client struct {
*context.Context
}
// NewClient 初始化实例
func NewClient(ctx *context.Context) *Client {
return &Client{
ctx,
}
}

29
work/robot/robot.go Normal file
View File

@@ -0,0 +1,29 @@
package robot
import (
"encoding/json"
"fmt"
"github.com/silenceper/wechat/v2/util"
)
const (
// webhookSendURL 机器人发送群组消息
webhookSendURL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s"
)
// RobotBroadcast 群机器人消息发送
// @see https://developer.work.weixin.qq.com/document/path/91770
func (r *Client) RobotBroadcast(webhookKey string, options interface{}) (info util.CommonError, err error) {
var data []byte
if data, err = util.PostJSON(fmt.Sprintf(webhookSendURL, webhookKey), options); err != nil {
return
}
if err = json.Unmarshal(data, &info); err != nil {
return
}
if info.ErrCode != 0 {
return info, err
}
return info, nil
}

126
work/robot/send_option.go Normal file
View File

@@ -0,0 +1,126 @@
package robot
import "github.com/silenceper/wechat/v2/util"
// WebhookSendResponse 机器人发送群组消息响应
type WebhookSendResponse struct {
util.CommonError
}
// WebhookSendTextOption 机器人发送文本消息请求参数
type WebhookSendTextOption struct {
MsgType string `json:"msgtype"` // 消息类型,此时固定为text
Text struct {
Content string `json:"content"` // 文本内容最长不超过2048个字节必须是utf8编码
MentionedList []string `json:"mentioned_list"` // userid的列表提醒群中的指定成员(@某个成员)@all表示提醒所有人如果开发者获取不到userid可以使用mentioned_mobile_list
MentionedMobileList []string `json:"mentioned_mobile_list"` // 手机号列表,提醒手机号对应的群成员(@某个成员)@all表示提醒所有人
} `json:"text"` // 文本消息内容
}
// WebhookSendMarkdownOption 机器人发送markdown消息请求参数
// 支持语法参考 https://developer.work.weixin.qq.com/document/path/91770
type WebhookSendMarkdownOption struct {
MsgType string `json:"msgtype"` // 消息类型,此时固定为markdown
Markdown struct {
Content string `json:"content"` // markdown内容最长不超过4096个字节必须是utf8编码
} `json:"markdown"` // markdown消息内容
}
// WebhookSendImageOption 机器人发送图片消息请求参数
type WebhookSendImageOption struct {
MsgType string `json:"msgtype"` // 消息类型,此时固定为image
Image struct {
Base64 string `json:"base64"` // 图片内容的base64编码
MD5 string `json:"md5"` // 图片内容base64编码前的md5值
} `json:"image"` // 图片消息内容
}
// WebhookSendNewsOption 机器人发送图文消息请求参数
type WebhookSendNewsOption struct {
MsgType string `json:"msgtype"` // 消息类型,此时固定为news
News struct {
Articles []struct {
Title string `json:"title"` // 标题不超过128个字节超过会自动截断
Description string `json:"description"` // 描述不超过512个字节超过会自动截断
URL string `json:"url"` // 点击后跳转的链接
PicURL string `json:"picurl"` // 图文消息的图片链接支持JPG、PNG格式较好的效果为大图 1068*455小图150*150
} `json:"articles"` // 图文消息列表 一个图文消息支持1到8条图文
} `json:"news"` // 图文消息内容
}
// WebhookSendFileOption 机器人发送文件消息请求参数
type WebhookSendFileOption struct {
MsgType string `json:"msgtype"` // 消息类型此时固定为file
File struct {
MediaID string `json:"media_id"` // 文件id通过下文的文件上传接口获取
} `json:"file"` // 文件类型
}
// WebHookSendTempNoticeOption 机器人发送文本通知模版消息请求参数
type WebHookSendTempNoticeOption struct {
MsgType string `json:"msgtype"` // 消息类型此时的消息类型固定为template_card
TemplateCard TemplateCard `json:"template_card"` // 具体的模版卡片参数
}
// TemplateCard 具体的模版卡片参数
type TemplateCard struct {
CardType string `json:"card_type"` // 模版卡片的模版类型文本通知模版卡片的类型为text_notice
Source CardSource `json:"source"` // 卡片来源样式信息,不需要来源样式可不填写
MainTitle CardTitle `json:"main_title"` // 模版卡片的主要内容,包括一级标题和标题辅助信息
EmphasisContent CardTitle `json:"emphasis_content"` // 关键数据样式
QuoteArea CardQuoteArea `json:"quote_area"` // 引用文献样式,建议不与关键数据共用
SubTitleText string `json:"sub_title_text"` // 二级普通文本建议不超过112个字。模版卡片主要内容的一级标题main_title.title和二级普通文本sub_title_text必须有一项填写
HorizontalContentList []CardContent `json:"horizontal_content_list"` // 二级标题+文本列表该字段可为空数组但有数据的话需确认对应字段是否必填列表长度不超过6
JumpList []JumpContent `json:"jump_list"` // 跳转指引样式的列表该字段可为空数组但有数据的话需确认对应字段是否必填列表长度不超过3
CardAction CardAction `json:"card_action"` // 整体卡片的点击跳转事件text_notice模版卡片中该字段为必填项
}
// CardSource 卡片来源样式信息,不需要来源样式可不填写
type CardSource struct {
IconURL string `json:"icon_url"` // 来源图片的url
Desc string `json:"desc"` // 来源图片的描述建议不超过13个字
DescColor int `json:"desc_color"` // 来源文字的颜色目前支持0(默认) 灰色1 黑色2 红色3 绿色
}
// CardTitle 标题和标题辅助信息
type CardTitle struct {
Title string `json:"title"` // 标题建议不超过26个字。模版卡片主要内容的一级标题main_title.title和二级普通文本sub_title_text必须有一项填写
Desc string `json:"desc"` // 标题辅助信息建议不超过30个字
}
// CardQuoteArea 引用文献样式,建议不与关键数据共用
type CardQuoteArea struct {
Type int `json:"type"` // 引用文献样式区域点击事件0或不填代表没有点击事件1 代表跳转url2 代表跳转小程序
URL string `json:"url,omitempty"` // 点击跳转的urlquote_area.type是1时必填
Appid string `json:"appid,omitempty"` // 点击跳转的小程序的appidquote_area.type是2时必填
Pagepath string `json:"pagepath,omitempty"` // 点击跳转的小程序的pagepathquote_area.type是2时选填
Title string `json:"title"` // 引用文献样式的标题
QuoteText string `json:"quote_text"` // 引用文献样式的引用文案
}
// CardContent 二级标题+文本列表该字段可为空数组但有数据的话需确认对应字段是否必填列表长度不超过6
type CardContent struct {
KeyName string `json:"keyname"` // 链接类型0或不填代表是普通文本1 代表跳转url2 代表下载附件3 代表@员工
Value string `json:"value"` // 二级标题建议不超过5个字
Type int `json:"type,omitempty"` // 二级文本如果horizontal_content_list.type是2该字段代表文件名称要包含文件类型建议不超过26个字
URL string `json:"url,omitempty"` // 链接跳转的urlhorizontal_content_list.type是1时必填
MediaID string `json:"media_id,omitempty"` // 附件的media_idhorizontal_content_list.type是2时必填
UserID string `json:"userid,omitempty"` // 被@的成员的useridhorizontal_content_list.type是3时必填
}
// JumpContent 跳转指引样式的列表该字段可为空数组但有数据的话需确认对应字段是否必填列表长度不超过3
type JumpContent struct {
Type int `json:"type"` // 跳转链接类型0或不填代表不是链接1 代表跳转url2 代表跳转小程序
URL string `json:"url,omitempty"` // 跳转链接的urljump_list.type是1时必填
Title string `json:"title"` // 跳转链接样式的文案内容建议不超过13个字
AppID string `json:"appid,omitempty"` // 跳转链接的小程序的appidjump_list.type是2时必填
PagePath string `json:"pagepath,omitempty"` // 跳转链接的小程序的pagepathjump_list.type是2时选填
}
// CardAction 整体卡片的点击跳转事件text_notice模版卡片中该字段为必填项
type CardAction struct {
Type int `json:"type"` // 卡片跳转类型1 代表跳转url2 代表打开小程序。text_notice模版卡片中该字段取值范围为[1,2]
URL string `json:"url,omitempty"` // 跳转事件的urlcard_action.type是1时必填
Appid string `json:"appid,omitempty"` // 跳转事件的小程序的appidcard_action.type是2时必填
PagePath string `json:"pagepath,omitempty"` // 跳转事件的小程序的pagepathcard_action.type是2时选填
}

View File

@@ -2,12 +2,18 @@ package work
import (
"github.com/silenceper/wechat/v2/credential"
"github.com/silenceper/wechat/v2/work/addresslist"
"github.com/silenceper/wechat/v2/work/appchat"
"github.com/silenceper/wechat/v2/work/config"
"github.com/silenceper/wechat/v2/work/context"
"github.com/silenceper/wechat/v2/work/externalcontact"
"github.com/silenceper/wechat/v2/work/invoice"
"github.com/silenceper/wechat/v2/work/kf"
"github.com/silenceper/wechat/v2/work/material"
"github.com/silenceper/wechat/v2/work/message"
"github.com/silenceper/wechat/v2/work/msgaudit"
"github.com/silenceper/wechat/v2/work/oauth"
"github.com/silenceper/wechat/v2/work/robot"
)
// Work 企业微信
@@ -49,3 +55,33 @@ func (wk *Work) GetKF() (*kf.Client, error) {
func (wk *Work) GetExternalContact() *externalcontact.Client {
return externalcontact.NewClient(wk.ctx)
}
// GetAddressList get address_list
func (wk *Work) GetAddressList() *addresslist.Client {
return addresslist.NewClient(wk.ctx)
}
// GetMaterial get material
func (wk *Work) GetMaterial() *material.Client {
return material.NewClient(wk.ctx)
}
// GetRobot get robot
func (wk *Work) GetRobot() *robot.Client {
return robot.NewClient(wk.ctx)
}
// GetMessage 获取发送应用消息接口实例
func (wk *Work) GetMessage() *message.Client {
return message.NewClient(wk.ctx)
}
// GetAppChat 获取应用发送消息到群聊会话接口实例
func (wk *Work) GetAppChat() *appchat.Client {
return appchat.NewClient(wk.ctx)
}
// GetInvoice get invoice
func (wk *Work) GetInvoice() *invoice.Client {
return invoice.NewClient(wk.ctx)
}