mirror of
https://github.com/silenceper/wechat.git
synced 2026-02-04 21:02:25 +08:00
Compare commits
28 Commits
v2.0.7-rc.
...
v2.0.9-rc.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3afe499e70 | ||
|
|
beb2f9506d | ||
|
|
b535cd116a | ||
|
|
3cfa9e6c71 | ||
|
|
80d91d8316 | ||
|
|
c61154105b | ||
|
|
d392ff776b | ||
|
|
df82432f6c | ||
|
|
917f1817e5 | ||
|
|
6fdb986911 | ||
|
|
8ceabc2d0b | ||
|
|
fc1fc7e84e | ||
|
|
13611466f3 | ||
|
|
08008e1c86 | ||
|
|
01addecd53 | ||
|
|
4433fc18a6 | ||
|
|
e8c90848e4 | ||
|
|
6df8453378 | ||
|
|
2ff99d41dc | ||
|
|
b1144e3a38 | ||
|
|
51778fab8f | ||
|
|
6edaa7888a | ||
|
|
b27dca624f | ||
|
|
3f9aed72cd | ||
|
|
dc508f7341 | ||
|
|
1005807328 | ||
|
|
c1e4e2c9d0 | ||
|
|
c8522f1875 |
21
.github/ISSUE_TEMPLATE/bug.md
vendored
Normal file
21
.github/ISSUE_TEMPLATE/bug.md
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
---
|
||||
name: 报告Bug
|
||||
about: 反馈BUG信息
|
||||
title: "[BUG]"
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**描述**
|
||||
|
||||
**如何复现**
|
||||
步骤:
|
||||
1、
|
||||
2、
|
||||
|
||||
**关联日志信息**
|
||||
|
||||
|
||||
**使用的版本**
|
||||
- SDK版本: [比如 v0.0.0]
|
||||
15
.github/ISSUE_TEMPLATE/feature.md
vendored
Normal file
15
.github/ISSUE_TEMPLATE/feature.md
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
name: API需求
|
||||
about: 待实现的API接口,SDK的强大离不开社区的帮助,欢迎为项目贡献PR
|
||||
title: "[Feature]"
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
<!--
|
||||
!!!SDK的强大离不开社区的帮助,欢迎为本项目贡献PR!!!
|
||||
-->
|
||||
**你想要实现的模块或API**
|
||||
|
||||
|
||||
15
.github/ISSUE_TEMPLATE/question.md
vendored
Normal file
15
.github/ISSUE_TEMPLATE/question.md
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
name: 使用咨询
|
||||
about: 关于SDK使用相关的咨询,在使用前请先阅读官方微信文档
|
||||
title: "[咨询]"
|
||||
labels: question
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
<!--
|
||||
重要:
|
||||
1、在使用本SDK前请先阅读对应的官方微信API文档:https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html
|
||||
2、本SDK部分接口文档: https://silenceper.com/wechat/
|
||||
-->
|
||||
**请描述您的问题**
|
||||
4
.github/workflows/go.yml
vendored
4
.github/workflows/go.yml
vendored
@@ -2,9 +2,9 @@ name: Go
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master,release-* ]
|
||||
branches: [ master,release-*,v2 ]
|
||||
pull_request:
|
||||
branches: [ master,release-* ]
|
||||
branches: [ master,release-*,v2 ]
|
||||
|
||||
jobs:
|
||||
golangci:
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -26,4 +26,5 @@ _testmain.go
|
||||
.vscode/
|
||||
vendor
|
||||
.idea/
|
||||
example/*
|
||||
example/*
|
||||
/test
|
||||
|
||||
@@ -12,11 +12,15 @@ import (
|
||||
|
||||
const (
|
||||
//AccessTokenURL 获取access_token的接口
|
||||
accessTokenURL = "https://api.weixin.qq.com/cgi-bin/token"
|
||||
accessTokenURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"
|
||||
//AccessTokenURL 企业微信获取access_token的接口
|
||||
workAccessTokenURL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s"
|
||||
//CacheKeyOfficialAccountPrefix 微信公众号cache key前缀
|
||||
CacheKeyOfficialAccountPrefix = "gowechat_officialaccount_"
|
||||
//CacheKeyMiniProgramPrefix 小程序cache key前缀
|
||||
CacheKeyMiniProgramPrefix = "gowechat_miniprogram_"
|
||||
//CacheKeyWorkPrefix 企业微信cache key前缀
|
||||
CacheKeyWorkPrefix = "gowechat_work_"
|
||||
)
|
||||
|
||||
//DefaultAccessToken 默认AccessToken 获取
|
||||
@@ -52,11 +56,66 @@ type ResAccessToken struct {
|
||||
|
||||
//GetAccessToken 获取access_token,先从cache中获取,没有则从服务端获取
|
||||
func (ak *DefaultAccessToken) GetAccessToken() (accessToken string, err error) {
|
||||
// 先从cache中取
|
||||
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.appID)
|
||||
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
|
||||
return val.(string), nil
|
||||
}
|
||||
|
||||
//加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
|
||||
ak.accessTokenLock.Lock()
|
||||
defer ak.accessTokenLock.Unlock()
|
||||
|
||||
accessTokenCacheKey := fmt.Sprintf("%s_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 = GetTokenFromServer(fmt.Sprintf(accessTokenURL, ak.appID, ak.appSecret))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
expires := resAccessToken.ExpiresIn - 1500
|
||||
err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
accessToken = resAccessToken.AccessToken
|
||||
return
|
||||
}
|
||||
|
||||
//WorkAccessToken 企业微信AccessToken 获取
|
||||
type WorkAccessToken struct {
|
||||
CorpID string
|
||||
CorpSecret string
|
||||
cacheKeyPrefix string
|
||||
cache cache.Cache
|
||||
accessTokenLock *sync.Mutex
|
||||
}
|
||||
|
||||
//NewWorkAccessToken new WorkAccessToken
|
||||
func NewWorkAccessToken(corpID, corpSecret, cacheKeyPrefix string, cache cache.Cache) AccessTokenHandle {
|
||||
if cache == nil {
|
||||
panic("cache the not exist")
|
||||
}
|
||||
return &WorkAccessToken{
|
||||
CorpID: corpID,
|
||||
CorpSecret: corpSecret,
|
||||
cache: cache,
|
||||
cacheKeyPrefix: cacheKeyPrefix,
|
||||
accessTokenLock: new(sync.Mutex),
|
||||
}
|
||||
}
|
||||
|
||||
//GetAccessToken 企业微信获取access_token,先从cache中获取,没有则从服务端获取
|
||||
func (ak *WorkAccessToken) GetAccessToken() (accessToken string, err error) {
|
||||
//加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
|
||||
ak.accessTokenLock.Lock()
|
||||
defer ak.accessTokenLock.Unlock()
|
||||
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.CorpID)
|
||||
val := ak.cache.Get(accessTokenCacheKey)
|
||||
if val != nil {
|
||||
accessToken = val.(string)
|
||||
@@ -65,7 +124,7 @@ func (ak *DefaultAccessToken) GetAccessToken() (accessToken string, err error) {
|
||||
|
||||
//cache失效,从微信服务器获取
|
||||
var resAccessToken ResAccessToken
|
||||
resAccessToken, err = GetTokenFromServer(ak.appID, ak.appSecret)
|
||||
resAccessToken, err = GetTokenFromServer(fmt.Sprintf(workAccessTokenURL, ak.CorpID, ak.CorpSecret))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -80,8 +139,7 @@ func (ak *DefaultAccessToken) GetAccessToken() (accessToken string, err error) {
|
||||
}
|
||||
|
||||
//GetTokenFromServer 强制从微信服务器获取token
|
||||
func GetTokenFromServer(appID, appSecret string) (resAccessToken ResAccessToken, err error) {
|
||||
url := fmt.Sprintf("%s?grant_type=client_credential&appid=%s&secret=%s", accessTokenURL, appID, appSecret)
|
||||
func GetTokenFromServer(url string) (resAccessToken ResAccessToken, err error) {
|
||||
var body []byte
|
||||
body, err = util.HTTPGet(url)
|
||||
if err != nil {
|
||||
@@ -91,7 +149,7 @@ func GetTokenFromServer(appID, appSecret string) (resAccessToken ResAccessToken,
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if resAccessToken.ErrMsg != "" {
|
||||
if resAccessToken.ErrCode != 0 {
|
||||
err = fmt.Errorf("get access_token error : errcode=%v , errormsg=%v", resAccessToken.ErrCode, resAccessToken.ErrMsg)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -42,16 +42,20 @@ type ResTicket struct {
|
||||
|
||||
//GetTicket 获取jsapi_ticket
|
||||
func (js *DefaultJsTicket) GetTicket(accessToken string) (ticketStr string, err error) {
|
||||
//先从cache中取
|
||||
jsAPITicketCacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", js.cacheKeyPrefix, js.appID)
|
||||
if val := js.cache.Get(jsAPITicketCacheKey); val != nil {
|
||||
return val.(string), nil
|
||||
}
|
||||
|
||||
js.jsAPITicketLock.Lock()
|
||||
defer js.jsAPITicketLock.Unlock()
|
||||
|
||||
//先从cache中取
|
||||
jsAPITicketCacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", js.cacheKeyPrefix, js.appID)
|
||||
val := js.cache.Get(jsAPITicketCacheKey)
|
||||
if val != nil {
|
||||
ticketStr = val.(string)
|
||||
return
|
||||
// 双检,防止重复从微信服务器获取
|
||||
if val := js.cache.Get(jsAPITicketCacheKey); val != nil {
|
||||
return val.(string), nil
|
||||
}
|
||||
|
||||
var ticket ResTicket
|
||||
ticket, err = GetTicketFromServer(accessToken)
|
||||
if err != nil {
|
||||
|
||||
1
go.sum
1
go.sum
@@ -24,7 +24,6 @@ github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE
|
||||
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
|
||||
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
|
||||
61
miniprogram/content/content.go
Normal file
61
miniprogram/content/content.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package content
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/miniprogram/context"
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const (
|
||||
checkTextURL = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=%s"
|
||||
checkImageURL = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=%s"
|
||||
)
|
||||
|
||||
//Content 内容安全
|
||||
type Content struct {
|
||||
*context.Context
|
||||
}
|
||||
|
||||
//NewContent 内容安全接口
|
||||
func NewContent(ctx *context.Context) *Content {
|
||||
return &Content{ctx}
|
||||
}
|
||||
|
||||
//CheckText 检测文字
|
||||
//@text 需要检测的文字
|
||||
func (content *Content) CheckText(text string) error {
|
||||
accessToken, err := content.GetAccessToken()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
response, err := util.PostJSON(
|
||||
fmt.Sprintf(checkTextURL, accessToken),
|
||||
map[string]string{
|
||||
"content": text,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "ContentCheckText")
|
||||
}
|
||||
|
||||
//CheckImage 检测图片
|
||||
//所传参数为要检测的图片文件的绝对路径,图片格式支持PNG、JPEG、JPG、GIF, 像素不超过 750 x 1334,同时文件大小以不超过 300K 为宜,否则可能报错
|
||||
//@media 图片文件的绝对路径
|
||||
func (content *Content) CheckImage(media string) error {
|
||||
accessToken, err := content.GetAccessToken()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
response, err := util.PostFile(
|
||||
"media",
|
||||
media,
|
||||
fmt.Sprintf(checkImageURL, accessToken),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "ContentCheckImage")
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"github.com/silenceper/wechat/v2/miniprogram/analysis"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/auth"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/config"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/content"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/context"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/encryptor"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/message"
|
||||
@@ -78,3 +79,8 @@ func (miniProgram *MiniProgram) GetCustomerMessage() *message.Manager {
|
||||
func (miniProgram *MiniProgram) GetWeRun() *werun.WeRun {
|
||||
return werun.NewWeRun(miniProgram.ctx)
|
||||
}
|
||||
|
||||
// GetContentSecurity 内容安全接口
|
||||
func (miniProgram *MiniProgram) GetContentSecurity() *content.Content {
|
||||
return content.NewContent(miniProgram.ctx)
|
||||
}
|
||||
|
||||
@@ -16,6 +16,14 @@ const (
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.getTemplateList.html
|
||||
getTemplateURL = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate"
|
||||
|
||||
// 添加订阅模板
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.addTemplate.html
|
||||
addTemplateURL = "https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate"
|
||||
|
||||
// 删除私有模板
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.deleteTemplate.html
|
||||
delTemplateURL = "https://api.weixin.qq.com/wxaapi/newtmpl/deltemplate"
|
||||
|
||||
// 统一服务消息
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/uniform-message/uniformMessage.send.html
|
||||
uniformMessageSend = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send"
|
||||
@@ -133,3 +141,55 @@ func (s *Subscribe) UniformSend(msg *UniformMessage) (err error) {
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "UniformSend")
|
||||
}
|
||||
|
||||
type resSubscribeAdd struct {
|
||||
util.CommonError
|
||||
|
||||
TemplateID string `json:"priTmplId"`
|
||||
}
|
||||
|
||||
// Add 添加订阅消息模板
|
||||
func (s *Subscribe) Add(ShortID string, kidList []int, sceneDesc string) (templateID string, err error) {
|
||||
var accessToken string
|
||||
accessToken, err = s.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var msg = struct {
|
||||
TemplateIDShort string `json:"tid"`
|
||||
SceneDesc string `json:"sceneDesc"`
|
||||
KidList []int `json:"kidList"`
|
||||
}{TemplateIDShort: ShortID, SceneDesc: sceneDesc, KidList: kidList}
|
||||
uri := fmt.Sprintf("%s?access_token=%s", addTemplateURL, accessToken)
|
||||
var response []byte
|
||||
response, err = util.PostJSON(uri, msg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var result resSubscribeAdd
|
||||
err = util.DecodeWithError(response, &result, "AddSubscribe")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
templateID = result.TemplateID
|
||||
return
|
||||
}
|
||||
|
||||
// Delete 删除私有模板
|
||||
func (s *Subscribe) Delete(templateID string) (err error) {
|
||||
var accessToken string
|
||||
accessToken, err = s.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var msg = struct {
|
||||
TemplateID string `json:"priTmplId"`
|
||||
}{TemplateID: templateID}
|
||||
uri := fmt.Sprintf("%s?access_token=%s", delTemplateURL, accessToken)
|
||||
var response []byte
|
||||
response, err = util.PostJSON(uri, msg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "DeleteSubscribe")
|
||||
}
|
||||
|
||||
@@ -10,16 +10,18 @@ import (
|
||||
const (
|
||||
subscribeSendURL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend"
|
||||
subscribeTemplateListURL = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate"
|
||||
subscribeTemplateAddURL = "https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate"
|
||||
subscribeTemplateDelURL = "https://api.weixin.qq.com/wxaapi/newtmpl/deltemplate"
|
||||
)
|
||||
|
||||
//Subscrib 订阅消息
|
||||
type Subscrib struct {
|
||||
//Subscribe 订阅消息
|
||||
type Subscribe struct {
|
||||
*context.Context
|
||||
}
|
||||
|
||||
//NewSubscrib 实例化
|
||||
func NewSubscrib(context *context.Context) *Subscrib {
|
||||
tpl := new(Subscrib)
|
||||
//NewSubscribe 实例化
|
||||
func NewSubscribe(context *context.Context) *Subscribe {
|
||||
tpl := new(Subscribe)
|
||||
tpl.Context = context
|
||||
return tpl
|
||||
}
|
||||
@@ -42,7 +44,7 @@ type SubscribeDataItem struct {
|
||||
}
|
||||
|
||||
//Send 发送订阅消息
|
||||
func (tpl *Subscrib) Send(msg *SubscribeMessage) (err error) {
|
||||
func (tpl *Subscribe) Send(msg *SubscribeMessage) (err error) {
|
||||
var accessToken string
|
||||
accessToken, err = tpl.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -53,11 +55,11 @@ func (tpl *Subscrib) Send(msg *SubscribeMessage) (err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "SendSubscribMessage")
|
||||
return util.DecodeWithCommonError(response, "SendSubscribeMessage")
|
||||
}
|
||||
|
||||
// PrivateSubscribItem 私有订阅消息模板
|
||||
type PrivateSubscribItem struct {
|
||||
// PrivateSubscribeItem 私有订阅消息模板
|
||||
type PrivateSubscribeItem struct {
|
||||
PriTmplID string `json:"priTmplId"` // 添加至帐号下的模板 id,发送订阅通知时所需
|
||||
Title string `json:"title"` //模版标题
|
||||
Content string `json:"content"` //模版内容
|
||||
@@ -65,13 +67,13 @@ type PrivateSubscribItem struct {
|
||||
SubType int `json:"type"` //模版类型,2 为一次性订阅,3 为长期订阅
|
||||
}
|
||||
|
||||
type resPrivateSubscribList struct {
|
||||
type resPrivateSubscribeList struct {
|
||||
util.CommonError
|
||||
SubscriptionList []*PrivateSubscribItem `json:"data"`
|
||||
SubscriptionList []*PrivateSubscribeItem `json:"data"`
|
||||
}
|
||||
|
||||
//List 获取私有订阅消息模板列表
|
||||
func (tpl *Subscrib) List() (templateList []*PrivateSubscribItem, err error) {
|
||||
func (tpl *Subscribe) List() (templateList []*PrivateSubscribeItem, err error) {
|
||||
var accessToken string
|
||||
accessToken, err = tpl.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -83,11 +85,63 @@ func (tpl *Subscrib) List() (templateList []*PrivateSubscribItem, err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var res resPrivateSubscribList
|
||||
err = util.DecodeWithError(response, &res, "ListSubscription")
|
||||
var res resPrivateSubscribeList
|
||||
err = util.DecodeWithError(response, &res, "ListSubscribe")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
templateList = res.SubscriptionList
|
||||
return
|
||||
}
|
||||
|
||||
type resSubscribeAdd struct {
|
||||
util.CommonError
|
||||
|
||||
TemplateID string `json:"priTmplId"`
|
||||
}
|
||||
|
||||
// Add 添加订阅消息模板
|
||||
func (tpl *Subscribe) Add(ShortID string, kidList []int, sceneDesc string) (templateID string, err error) {
|
||||
var accessToken string
|
||||
accessToken, err = tpl.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var msg = struct {
|
||||
TemplateIDShort string `json:"tid"`
|
||||
SceneDesc string `json:"sceneDesc"`
|
||||
KidList []int `json:"kidList"`
|
||||
}{TemplateIDShort: ShortID, SceneDesc: sceneDesc, KidList: kidList}
|
||||
uri := fmt.Sprintf("%s?access_token=%s", subscribeTemplateAddURL, accessToken)
|
||||
var response []byte
|
||||
response, err = util.PostJSON(uri, msg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var result resSubscribeAdd
|
||||
err = util.DecodeWithError(response, &result, "AddSubscribe")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
templateID = result.TemplateID
|
||||
return
|
||||
}
|
||||
|
||||
// Delete 删除私有模板
|
||||
func (tpl *Subscribe) Delete(templateID string) (err error) {
|
||||
var accessToken string
|
||||
accessToken, err = tpl.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var msg = struct {
|
||||
TemplateID string `json:"priTmplId"`
|
||||
}{TemplateID: templateID}
|
||||
uri := fmt.Sprintf("%s?access_token=%s", subscribeTemplateDelURL, accessToken)
|
||||
var response []byte
|
||||
response, err = util.PostJSON(uri, msg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "DeleteSubscribe")
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ import (
|
||||
const (
|
||||
templateSendURL = "https://api.weixin.qq.com/cgi-bin/message/template/send"
|
||||
templateListURL = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template"
|
||||
templateAddURL = "https://api.weixin.qq.com/cgi-bin/template/api_add_template"
|
||||
templateDelURL = "https://api.weixin.qq.com/cgi-bin/template/del_private_template"
|
||||
)
|
||||
|
||||
//Template 模板消息
|
||||
@@ -59,7 +61,8 @@ func (tpl *Template) Send(msg *TemplateMessage) (msgID int64, err error) {
|
||||
return
|
||||
}
|
||||
uri := fmt.Sprintf("%s?access_token=%s", templateSendURL, accessToken)
|
||||
response, err := util.PostJSON(uri, msg)
|
||||
var response []byte
|
||||
response, err = util.PostJSON(uri, msg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -113,3 +116,55 @@ func (tpl *Template) List() (templateList []*TemplateItem, err error) {
|
||||
templateList = res.TemplateList
|
||||
return
|
||||
}
|
||||
|
||||
type resTemplateAdd struct {
|
||||
util.CommonError
|
||||
|
||||
TemplateID string `json:"template_id"`
|
||||
}
|
||||
|
||||
// Add 添加模板.
|
||||
func (tpl *Template) Add(shortID string) (templateID string, err error) {
|
||||
var accessToken string
|
||||
accessToken, err = tpl.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var msg = struct {
|
||||
ShortID string `json:"template_id_short"`
|
||||
}{ShortID: shortID}
|
||||
uri := fmt.Sprintf("%s?access_token=%s", templateAddURL, accessToken)
|
||||
var response []byte
|
||||
response, err = util.PostJSON(uri, msg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var result resTemplateAdd
|
||||
err = util.DecodeWithError(response, &result, "AddTemplate")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
templateID = result.TemplateID
|
||||
return
|
||||
}
|
||||
|
||||
// Delete 删除私有模板.
|
||||
func (tpl *Template) Delete(templateID string) (err error) {
|
||||
var accessToken string
|
||||
accessToken, err = tpl.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var msg = struct {
|
||||
TemplateID string `json:"template_id"`
|
||||
}{TemplateID: templateID}
|
||||
|
||||
uri := fmt.Sprintf("%s?access_token=%s", templateDelURL, accessToken)
|
||||
var response []byte
|
||||
response, err = util.PostJSON(uri, msg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "DeleteTemplate")
|
||||
}
|
||||
|
||||
@@ -120,3 +120,8 @@ func (officialAccount *OfficialAccount) GetDataCube() *datacube.DataCube {
|
||||
func (officialAccount *OfficialAccount) GetOCR() *ocr.OCR {
|
||||
return ocr.NewOCR(officialAccount.ctx)
|
||||
}
|
||||
|
||||
//GetSubscribe 公众号订阅消息
|
||||
func (officialAccount *OfficialAccount) GetSubscribe() *message.Subscribe {
|
||||
return message.NewSubscribe(officialAccount.ctx)
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ type PaidResult struct {
|
||||
OpenID *string `xml:"openid"`
|
||||
IsSubscribe *string `xml:"is_subscribe"`
|
||||
TradeType *string `xml:"trade_type"`
|
||||
TradeState *string `xml:"trade_state"`
|
||||
BankType *string `xml:"bank_type"`
|
||||
TotalFee *int `xml:"total_fee"`
|
||||
SettlementTotalFee *int `xml:"settlement_total_fee"`
|
||||
@@ -46,9 +47,9 @@ type PaidResult struct {
|
||||
CouponID0 *string `xml:"coupon_id_0"`
|
||||
CouponID1 *string `xml:"coupon_id_1"`
|
||||
CouponID2 *string `xml:"coupon_id_2"`
|
||||
CouponFeed0 *string `xml:"coupon_fee_0"`
|
||||
CouponFeed1 *string `xml:"coupon_fee_1"`
|
||||
CouponFeed2 *string `xml:"coupon_fee_2"`
|
||||
CouponFee0 *string `xml:"coupon_fee_0"`
|
||||
CouponFee1 *string `xml:"coupon_fee_1"`
|
||||
CouponFee2 *string `xml:"coupon_fee_2"`
|
||||
|
||||
TransactionID *string `xml:"transaction_id"`
|
||||
OutTradeNo *string `xml:"out_trade_no"`
|
||||
|
||||
@@ -35,7 +35,7 @@ type RefundedReqInfo struct {
|
||||
SettlementRefundFee *int `xml:"settlement_refund_fee"`
|
||||
RefundStatus *string `xml:"refund_status"`
|
||||
SuccessTime *string `xml:"success_time"`
|
||||
RefundRecvAccount *string `xml:"refund_recv_account"`
|
||||
RefundRecvAccount *string `xml:"refund_recv_accout"`
|
||||
RefundAccount *string `xml:"refund_account"`
|
||||
RefundRequestSource *string `xml:"refund_request_source"`
|
||||
}
|
||||
|
||||
136
pay/order/pay.go
136
pay/order/pay.go
@@ -35,6 +35,7 @@ type Params struct {
|
||||
CreateIP string
|
||||
Body string
|
||||
OutTradeNo string
|
||||
TimeExpire string // 订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。
|
||||
OpenID string
|
||||
TradeType string
|
||||
SignType string
|
||||
@@ -54,6 +55,17 @@ type Config struct {
|
||||
PaySign string `json:"paySign"`
|
||||
}
|
||||
|
||||
// ConfigForApp 是传出用于 app sdk 用的参数
|
||||
type ConfigForApp struct {
|
||||
AppID string `json:"appid"`
|
||||
MchID string `json:"partnerid"` // 微信支付分配的商户号
|
||||
PrePayID string `json:"prepayid"`
|
||||
Package string `json:"package"`
|
||||
NonceStr string `json:"nonceStr"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Sign string `json:"sign"`
|
||||
}
|
||||
|
||||
// PreOrder 是 Unified order 接口的返回
|
||||
type PreOrder struct {
|
||||
ReturnCode string `xml:"return_code"`
|
||||
@@ -99,6 +111,27 @@ type payRequest struct {
|
||||
XMLName struct{} `xml:"xml"`
|
||||
}
|
||||
|
||||
func (req *payRequest) BridgePayRequest(p *Params, AppID, MchID, nonceStr, sign string) *payRequest {
|
||||
request := payRequest{
|
||||
AppID: AppID,
|
||||
MchID: MchID,
|
||||
NonceStr: nonceStr,
|
||||
Sign: sign,
|
||||
Body: p.Body,
|
||||
OutTradeNo: p.OutTradeNo,
|
||||
TotalFee: p.TotalFee,
|
||||
SpbillCreateIP: p.CreateIP,
|
||||
NotifyURL: p.NotifyURL,
|
||||
TradeType: p.TradeType,
|
||||
OpenID: p.OpenID,
|
||||
SignType: p.SignType,
|
||||
Detail: p.Detail,
|
||||
Attach: p.Attach,
|
||||
GoodsTag: p.GoodsTag,
|
||||
}
|
||||
return &request
|
||||
}
|
||||
|
||||
// BridgeConfig get js bridge config
|
||||
func (o *Order) BridgeConfig(p *Params) (cfg Config, err error) {
|
||||
var (
|
||||
@@ -136,54 +169,85 @@ func (o *Order) BridgeConfig(p *Params) (cfg Config, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// BridgeAppConfig get app bridge config
|
||||
func (o *Order) BridgeAppConfig(p *Params) (cfg ConfigForApp, err error) {
|
||||
var (
|
||||
timestamp string = strconv.FormatInt(time.Now().Unix(), 10)
|
||||
noncestr string = util.RandomStr(32)
|
||||
_package string = "Sign=WXPay"
|
||||
)
|
||||
order, err := o.PrePayOrder(p)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
result := map[string]string{
|
||||
"appid": order.AppID,
|
||||
"partnerid": order.MchID,
|
||||
"prepayid": order.PrePayID,
|
||||
"package": _package,
|
||||
"noncestr": noncestr,
|
||||
"timestamp": timestamp,
|
||||
}
|
||||
// 签名
|
||||
sign, err := util.ParamSign(result, o.Key)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
result["sign"] = sign
|
||||
cfg = ConfigForApp{
|
||||
AppID: result["appid"],
|
||||
MchID: result["partnerid"],
|
||||
PrePayID: result["prepayid"],
|
||||
Package: result["package"],
|
||||
NonceStr: result["noncestr"],
|
||||
Timestamp: result["timestamp"],
|
||||
Sign: result["sign"],
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// PrePayOrder return data for invoke wechat payment
|
||||
func (o *Order) PrePayOrder(p *Params) (payOrder PreOrder, err error) {
|
||||
nonceStr := util.RandomStr(32)
|
||||
notifyURL := o.NotifyURL
|
||||
// 签名类型
|
||||
if p.SignType == "" {
|
||||
p.SignType = util.SignTypeMD5
|
||||
param := map[string]string{
|
||||
"appid": o.AppID,
|
||||
"body": p.Body,
|
||||
"mch_id": o.MchID,
|
||||
"nonce_str": nonceStr,
|
||||
"out_trade_no": p.OutTradeNo,
|
||||
"spbill_create_ip": p.CreateIP,
|
||||
"total_fee": p.TotalFee,
|
||||
"trade_type": p.TradeType,
|
||||
"openid": p.OpenID,
|
||||
"sign_type": p.SignType,
|
||||
"detail": p.Detail,
|
||||
"attach": p.Attach,
|
||||
"goods_tag": p.GoodsTag,
|
||||
}
|
||||
// 签名类型
|
||||
if param["sign_type"] == "" {
|
||||
param["sign_type"] = util.SignTypeMD5
|
||||
}
|
||||
|
||||
// 通知地址
|
||||
if p.NotifyURL != "" {
|
||||
notifyURL = p.NotifyURL
|
||||
param["notify_url"] = p.NotifyURL
|
||||
}
|
||||
|
||||
if p.TimeExpire != "" {
|
||||
// 如果有传入交易结束时间
|
||||
param["time_expire"] = p.TimeExpire
|
||||
}
|
||||
param := make(map[string]string)
|
||||
param["appid"] = o.AppID
|
||||
param["body"] = p.Body
|
||||
param["mch_id"] = o.MchID
|
||||
param["nonce_str"] = nonceStr
|
||||
param["out_trade_no"] = p.OutTradeNo
|
||||
param["spbill_create_ip"] = p.CreateIP
|
||||
param["total_fee"] = p.TotalFee
|
||||
param["trade_type"] = p.TradeType
|
||||
param["openid"] = p.OpenID
|
||||
param["sign_type"] = p.SignType
|
||||
param["detail"] = p.Detail
|
||||
param["attach"] = p.Attach
|
||||
param["goods_tag"] = p.GoodsTag
|
||||
param["notify_url"] = notifyURL
|
||||
|
||||
sign, err := util.ParamSign(param, o.Key)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
request := payRequest{
|
||||
AppID: o.AppID,
|
||||
MchID: o.MchID,
|
||||
NonceStr: nonceStr,
|
||||
Sign: sign,
|
||||
Body: p.Body,
|
||||
OutTradeNo: p.OutTradeNo,
|
||||
TotalFee: p.TotalFee,
|
||||
SpbillCreateIP: p.CreateIP,
|
||||
NotifyURL: notifyURL,
|
||||
TradeType: p.TradeType,
|
||||
OpenID: p.OpenID,
|
||||
SignType: p.SignType,
|
||||
Detail: p.Detail,
|
||||
Attach: p.Attach,
|
||||
GoodsTag: p.GoodsTag,
|
||||
request := new(payRequest).BridgePayRequest(p, o.AppID, o.MchID, nonceStr, sign)
|
||||
if len(p.TimeExpire) > 0 {
|
||||
// 如果有传入交易结束时间
|
||||
request.TimeExpire = p.TimeExpire
|
||||
}
|
||||
rawRet, err := util.PostXML(payGateway, request)
|
||||
if err != nil {
|
||||
|
||||
43
util/rsa.go
Normal file
43
util/rsa.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// RSADecrypt 数据解密
|
||||
func RSADecrypt(privateKey string, ciphertext []byte) ([]byte, error) {
|
||||
block, _ := pem.Decode([]byte(privateKey))
|
||||
if block == nil {
|
||||
return nil, errors.New("PrivateKey format error")
|
||||
}
|
||||
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
oldErr := err
|
||||
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ParsePKCS1PrivateKey error: %s, ParsePKCS8PrivateKey error: %s", oldErr.Error(), err.Error())
|
||||
}
|
||||
switch t := key.(type) {
|
||||
case *rsa.PrivateKey:
|
||||
priv = key.(*rsa.PrivateKey)
|
||||
default:
|
||||
return nil, fmt.Errorf("ParsePKCS1PrivateKey error: %s, ParsePKCS8PrivateKey error: Not supported privatekey format, should be *rsa.PrivateKey, got %T", oldErr.Error(), t)
|
||||
}
|
||||
}
|
||||
return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
|
||||
}
|
||||
|
||||
// RSADecryptBase64 Base64解码后再次进行RSA解密
|
||||
func RSADecryptBase64(privateKey string, cryptoText string) ([]byte, error) {
|
||||
encryptedData, err := base64.StdEncoding.DecodeString(cryptoText)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return RSADecrypt(privateKey, encryptedData)
|
||||
}
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
openConfig "github.com/silenceper/wechat/v2/openplatform/config"
|
||||
"github.com/silenceper/wechat/v2/pay"
|
||||
payConfig "github.com/silenceper/wechat/v2/pay/config"
|
||||
"github.com/silenceper/wechat/v2/work"
|
||||
workConfig "github.com/silenceper/wechat/v2/work/config"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
@@ -67,3 +69,8 @@ func (wc *Wechat) GetPay(cfg *payConfig.Config) *pay.Pay {
|
||||
func (wc *Wechat) GetOpenPlatform(cfg *openConfig.Config) *openplatform.OpenPlatform {
|
||||
return openplatform.NewOpenPlatform(cfg)
|
||||
}
|
||||
|
||||
// GetWork 获取企业微信的实例
|
||||
func (wc *Wechat) GetWork(cfg *workConfig.Config) *work.Work {
|
||||
return work.NewWork(cfg)
|
||||
}
|
||||
|
||||
18
work/config/config.go
Normal file
18
work/config/config.go
Normal file
@@ -0,0 +1,18 @@
|
||||
// Package config 企业微信config配置
|
||||
package config
|
||||
|
||||
import (
|
||||
"github.com/silenceper/wechat/v2/cache"
|
||||
)
|
||||
|
||||
// Config for 企业微信
|
||||
type Config struct {
|
||||
CorpID string `json:"corp_id"` // corp_id
|
||||
CorpSecret string `json:"corp_secret"` // corp_secret,如果需要获取会话存档实例,当前参数请填写聊天内容存档的Secret,可以在企业微信管理端--管理工具--聊天内容存档查看
|
||||
AgentID string `json:"agent_id"` // agent_id
|
||||
Cache cache.Cache
|
||||
RasPrivateKey string // 消息加密私钥,可以在企业微信管理端--管理工具--消息加密公钥查看对用公钥,私钥一般由自己保存
|
||||
|
||||
Token string `json:"token"` // 微信客服回调配置,用于生成签名校验回调请求的合法性
|
||||
EncodingAESKey string `json:"encoding_aes_key"` // 微信客服回调p配置,用于解密回调消息内容对应的密文
|
||||
}
|
||||
12
work/context/context.go
Normal file
12
work/context/context.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package context
|
||||
|
||||
import (
|
||||
"github.com/silenceper/wechat/v2/credential"
|
||||
"github.com/silenceper/wechat/v2/work/config"
|
||||
)
|
||||
|
||||
// Context struct
|
||||
type Context struct {
|
||||
*config.Config
|
||||
credential.AccessTokenHandle
|
||||
}
|
||||
3
work/kf/README.md
Normal file
3
work/kf/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
### 微信客服SDK
|
||||
|
||||
相关文档正在梳理中...
|
||||
189
work/kf/account.go
Normal file
189
work/kf/account.go
Normal file
@@ -0,0 +1,189 @@
|
||||
package kf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const (
|
||||
//添加客服账号
|
||||
accountAddAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/account/add?access_token=%s"
|
||||
// 删除客服账号
|
||||
accountDelAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/account/del?access_token=%s"
|
||||
// 修改客服账号
|
||||
accountUpdateAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/account/update?access_token=%s"
|
||||
// 获取客服账号列表
|
||||
accountListAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/account/list?access_token=%s"
|
||||
//获取客服账号链接
|
||||
addContactWayAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/add_contact_way?access_token=%s"
|
||||
)
|
||||
|
||||
// AccountAddOptions 添加客服账号请求参数
|
||||
type AccountAddOptions struct {
|
||||
Name string `json:"name"` // 客服帐号名称, 不多于16个字符
|
||||
MediaID string `json:"media_id"` // 客服头像临时素材。可以调用上传临时素材接口获取, 不多于128个字节
|
||||
}
|
||||
|
||||
// AccountAddSchema 添加客服账号响应内容
|
||||
type AccountAddSchema struct {
|
||||
util.CommonError
|
||||
OpenKFID string `json:"open_kfid"` // 新创建的客服张号ID
|
||||
}
|
||||
|
||||
// AccountAdd 添加客服账号
|
||||
func (r *Client) AccountAdd(options AccountAddOptions) (info AccountAddSchema, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(accountAddAddr, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// AccountDelOptions 删除客服账号请求参数
|
||||
type AccountDelOptions struct {
|
||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID, 不多于64字节
|
||||
}
|
||||
|
||||
// AccountDel 删除客服账号
|
||||
func (r *Client) AccountDel(options AccountDelOptions) (info util.CommonError, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(accountDelAddr, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// AccountUpdateOptions 修改客服账号请求参数
|
||||
type AccountUpdateOptions struct {
|
||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID, 不多于64字节
|
||||
Name string `json:"name"` // 客服帐号名称, 不多于16个字符
|
||||
MediaID string `json:"media_id"` // 客服头像临时素材。可以调用上传临时素材接口获取, 不多于128个字节
|
||||
}
|
||||
|
||||
// AccountUpdate 修复客服账号
|
||||
func (r *Client) AccountUpdate(options AccountUpdateOptions) (info util.CommonError, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(accountUpdateAddr, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// AccountInfoSchema 客服详情
|
||||
type AccountInfoSchema struct {
|
||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||
Name string `json:"name"` // 客服帐号名称
|
||||
Avatar string `json:"avatar"` // 客服头像URL
|
||||
}
|
||||
|
||||
// AccountListSchema 获取客服账号列表响应内容
|
||||
type AccountListSchema struct {
|
||||
util.CommonError
|
||||
AccountList []AccountInfoSchema `json:"account_list"` // 客服账号列表
|
||||
}
|
||||
|
||||
// AccountList 获取客服账号列表
|
||||
func (r *Client) AccountList() (info AccountListSchema, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.HTTPGet(fmt.Sprintf(accountListAddr, accessToken))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// AddContactWayOptions 获取客服账号链接
|
||||
// 1.若scene非空,返回的客服链接开发者可拼接scene_param=SCENE_PARAM参数使用,用户进入会话事件会将SCENE_PARAM原样返回。其中SCENE_PARAM需要urlencode,且长度不能超过128字节。
|
||||
// 如 https://work.weixin.qq.com/kf/kfcbf8f8d07ac7215f?enc_scene=ENCGFSDF567DF&scene_param=a%3D1%26b%3D2
|
||||
// 2.历史调用接口返回的客服链接(包含encScene=XXX参数),不支持scene_param参数。
|
||||
// 3.返回的客服链接,不能修改或复制参数到其他链接使用。否则进入会话事件参数校验不通过,导致无法回调。
|
||||
type AddContactWayOptions struct {
|
||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID, 不多于64字节
|
||||
Scene string `json:"scene"` // 场景值,字符串类型,由开发者自定义, 不多于32字节, 字符串取值范围(正则表达式):[0-9a-zA-Z_-]*
|
||||
}
|
||||
|
||||
// AddContactWaySchema 获取客服账号链接响应内容
|
||||
type AddContactWaySchema struct {
|
||||
util.CommonError
|
||||
URL string `json:"url"` // 客服链接,开发者可将该链接嵌入到H5页面中,用户点击链接即可向对应的微信客服帐号发起咨询。开发者也可根据该url自行生成需要的二维码图片
|
||||
}
|
||||
|
||||
// AddContactWay 获取客服账号链接
|
||||
func (r *Client) AddContactWay(options AddContactWayOptions) (info AddContactWaySchema, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(addContactWayAddr, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
96
work/kf/callback.go
Normal file
96
work/kf/callback.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package kf
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
// SignatureOptions 微信服务器验证参数
|
||||
type SignatureOptions struct {
|
||||
Signature string `form:"msg_signature"`
|
||||
TimeStamp string `form:"timestamp"`
|
||||
Nonce string `form:"nonce"`
|
||||
EchoStr string `form:"echostr"`
|
||||
}
|
||||
|
||||
// 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, "非法请求来源")
|
||||
// }
|
||||
// })
|
||||
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)
|
||||
}
|
||||
_, bData, err := util.DecryptMsg(r.corpID, options.EchoStr, r.encodingAESKey)
|
||||
if err != nil {
|
||||
return "", NewSDKErr(40016)
|
||||
}
|
||||
|
||||
return string(bData), nil
|
||||
}
|
||||
|
||||
// 原始回调消息内容
|
||||
type callbackOriginMessage struct {
|
||||
ToUserName string // 企业微信的CorpID,当为第三方套件回调事件时,CorpID的内容为suiteid
|
||||
AgentID string // 接收的应用id,可在应用的设置页面获取
|
||||
Encrypt string // 消息结构体加密后的字符串
|
||||
}
|
||||
|
||||
// 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,用于校验请求的合法性
|
||||
}
|
||||
|
||||
// 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")
|
||||
// })
|
||||
func (r *Client) GetCallbackMessage(encryptedMsg []byte) (msg CallbackMessage, err error) {
|
||||
var origin callbackOriginMessage
|
||||
if err = xml.Unmarshal(encryptedMsg, &origin); err != nil {
|
||||
return msg, err
|
||||
}
|
||||
_, bData, err := util.DecryptMsg(r.corpID, origin.Encrypt, r.encodingAESKey)
|
||||
if err != nil {
|
||||
return msg, NewSDKErr(40016)
|
||||
}
|
||||
if err = xml.Unmarshal(bData, &msg); err != nil {
|
||||
return msg, err
|
||||
}
|
||||
return msg, err
|
||||
}
|
||||
43
work/kf/client.go
Normal file
43
work/kf/client.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package kf
|
||||
|
||||
import (
|
||||
"github.com/silenceper/wechat/v2/cache"
|
||||
"github.com/silenceper/wechat/v2/credential"
|
||||
"github.com/silenceper/wechat/v2/work/config"
|
||||
"github.com/silenceper/wechat/v2/work/context"
|
||||
)
|
||||
|
||||
// Client 微信客服实例
|
||||
type Client struct {
|
||||
corpID string // 企业ID:企业开通的每个微信客服,都对应唯一的企业ID,企业可在微信客服管理后台的企业信息处查看
|
||||
secret string // Secret是微信客服用于校验开发者身份的访问密钥,企业成功注册微信客服后,可在「微信客服管理后台-开发配置」处获取
|
||||
token string // 用于生成签名校验回调请求的合法性
|
||||
encodingAESKey string // 回调消息加解密参数是AES密钥的Base64编码,用于解密回调消息内容对应的密文
|
||||
cache cache.Cache
|
||||
ctx *context.Context
|
||||
}
|
||||
|
||||
// NewClient 初始化微信客服实例
|
||||
func NewClient(cfg *config.Config) (client *Client, err error) {
|
||||
if cfg.Cache == nil {
|
||||
return nil, NewSDKErr(50001)
|
||||
}
|
||||
|
||||
//初始化 AccessToken Handle
|
||||
defaultAkHandle := credential.NewWorkAccessToken(cfg.CorpID, cfg.CorpSecret, credential.CacheKeyWorkPrefix, cfg.Cache)
|
||||
ctx := &context.Context{
|
||||
Config: cfg,
|
||||
AccessTokenHandle: defaultAkHandle,
|
||||
}
|
||||
|
||||
client = &Client{
|
||||
corpID: cfg.CorpID,
|
||||
secret: cfg.CorpSecret,
|
||||
token: cfg.Token,
|
||||
encodingAESKey: cfg.EncodingAESKey,
|
||||
cache: cfg.Cache,
|
||||
ctx: ctx,
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
56
work/kf/customer.go
Normal file
56
work/kf/customer.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package kf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const (
|
||||
customerBatchGetAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/customer/batchget?access_token=%s"
|
||||
)
|
||||
|
||||
// CustomerBatchGetOptions 客户基本信息获取请求参数
|
||||
type CustomerBatchGetOptions struct {
|
||||
ExternalUserIDList []string `json:"external_userid_list"` // external_userid列表
|
||||
}
|
||||
|
||||
// CustomerSchema 微信客户基本资料
|
||||
type CustomerSchema struct {
|
||||
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||
NickName string `json:"nickname"` // 微信昵称
|
||||
Avatar string `json:"avatar"` // 微信头像。第三方不可获取
|
||||
Gender int `json:"gender"` // 性别
|
||||
UnionID string `json:"unionid"` // unionid,需要绑定微信开发者帐号才能获取到,查看绑定方法: https://open.work.weixin.qq.com/kf/doc/92512/93143/94769#%E5%A6%82%E4%BD%95%E8%8E%B7%E5%8F%96%E5%BE%AE%E4%BF%A1%E5%AE%A2%E6%88%B7%E7%9A%84unionid
|
||||
}
|
||||
|
||||
// CustomerBatchGetSchema 获取客户基本信息响应内容
|
||||
type CustomerBatchGetSchema struct {
|
||||
util.CommonError
|
||||
CustomerList []CustomerSchema `json:"customer_list"` // 微信客户信息列表
|
||||
InvalidExternalUserID []string `json:"invalid_external_userid"` // 无效的微信客户ID
|
||||
}
|
||||
|
||||
// CustomerBatchGet 客户基本信息获取
|
||||
func (r *Client) CustomerBatchGet(options CustomerBatchGetOptions) (info CustomerBatchGetSchema, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(customerBatchGetAddr, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
91
work/kf/error.go
Normal file
91
work/kf/error.go
Normal file
@@ -0,0 +1,91 @@
|
||||
package kf
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Error 错误
|
||||
type Error string
|
||||
|
||||
const (
|
||||
// SDKInitFailed 错误码:50001
|
||||
SDKInitFailed Error = "SDK初始化失败"
|
||||
// SDKCacheUnavailable 错误码:50002
|
||||
SDKCacheUnavailable Error = "缓存无效"
|
||||
// SDKUnknownError 错误码:50003
|
||||
SDKUnknownError Error = "未知错误"
|
||||
// SDKInvalidCredential 错误码:40001
|
||||
SDKInvalidCredential Error = "不合法的secret参数"
|
||||
// SDKInvalidCorpID 错误码:40013
|
||||
SDKInvalidCorpID Error = "无效的 CorpID"
|
||||
// SDKAccessTokenInvalid 错误码:40014
|
||||
SDKAccessTokenInvalid Error = "AccessToken 无效"
|
||||
// SDKValidateSignatureFailed 错误码:40015
|
||||
SDKValidateSignatureFailed Error = "校验签名错误"
|
||||
// SDKDecryptMSGFailed 错误码:40016
|
||||
SDKDecryptMSGFailed Error = "消息解密失败"
|
||||
// SDKAccessTokenMissing 错误码:41001
|
||||
SDKAccessTokenMissing Error = "缺少AccessToken参数"
|
||||
// SDKAccessTokenExpired 错误码:42001
|
||||
SDKAccessTokenExpired Error = "AccessToken 已过期"
|
||||
// SDKApiFreqOutOfLimit 错误码:45009
|
||||
SDKApiFreqOutOfLimit Error = "接口请求次数超频"
|
||||
// SDKApiForbidden 错误码:48002
|
||||
SDKApiForbidden Error = "API 禁止调用"
|
||||
// SDKInvalidOpenKFID 错误码:95000
|
||||
SDKInvalidOpenKFID Error = "无效的 open_kfid"
|
||||
// SDKOpenKFIDNotExist 错误码:95004
|
||||
SDKOpenKFIDNotExist Error = "open_kfid 不存在"
|
||||
// SDKWeWorkAlready 错误码:95011
|
||||
SDKWeWorkAlready Error = "已在企业微信使用微信客服"
|
||||
// SDKApiNotOpen 错误码:95017
|
||||
SDKApiNotOpen Error = "API 功能没有被开启"
|
||||
)
|
||||
|
||||
//Error 输出错误信息
|
||||
func (r Error) Error() string {
|
||||
return reflect.ValueOf(r).String()
|
||||
}
|
||||
|
||||
// NewSDKErr 初始化SDK实例错误信息
|
||||
func NewSDKErr(code int64, msgList ...string) Error {
|
||||
switch code {
|
||||
case 50001:
|
||||
return SDKInitFailed
|
||||
case 50002:
|
||||
return SDKCacheUnavailable
|
||||
case 40001:
|
||||
return SDKInvalidCredential
|
||||
case 41001:
|
||||
return SDKAccessTokenMissing
|
||||
case 42001:
|
||||
return SDKAccessTokenExpired
|
||||
case 40013:
|
||||
return SDKInvalidCorpID
|
||||
case 40014:
|
||||
return SDKAccessTokenInvalid
|
||||
case 40015:
|
||||
return SDKValidateSignatureFailed
|
||||
case 40016:
|
||||
return SDKDecryptMSGFailed
|
||||
case 45009:
|
||||
return SDKApiFreqOutOfLimit
|
||||
case 48002:
|
||||
return SDKApiForbidden
|
||||
case 95000:
|
||||
return SDKInvalidOpenKFID
|
||||
case 95004:
|
||||
return SDKOpenKFIDNotExist
|
||||
case 95011:
|
||||
return SDKWeWorkAlready
|
||||
case 95017:
|
||||
return SDKApiNotOpen
|
||||
default:
|
||||
//返回未知的自定义错误
|
||||
if len(msgList) > 0 {
|
||||
return Error(strings.Join(msgList, ","))
|
||||
}
|
||||
return SDKUnknownError
|
||||
}
|
||||
}
|
||||
42
work/kf/sendmsg.go
Normal file
42
work/kf/sendmsg.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package kf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const (
|
||||
//发送消息
|
||||
sendMsgAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg?access_token=%s"
|
||||
)
|
||||
|
||||
// SendMsgSchema 发送消息响应内容
|
||||
type SendMsgSchema struct {
|
||||
util.CommonError
|
||||
MsgID string `json:"msgid"` // 消息ID。如果请求参数指定了msgid,则原样返回,否则系统自动生成并返回。不多于32字节, 字符串取值范围(正则表达式):[0-9a-zA-Z_-]*
|
||||
}
|
||||
|
||||
// SendMsg 获取消息
|
||||
func (r *Client) SendMsg(options interface{}) (info SendMsgSchema, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(sendMsgAddr, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
127
work/kf/sendmsg/message.go
Normal file
127
work/kf/sendmsg/message.go
Normal file
@@ -0,0 +1,127 @@
|
||||
package sendmsg
|
||||
|
||||
// Message 发送消息
|
||||
type Message struct {
|
||||
ToUser string `json:"touser"` // 指定接收消息的客户UserID
|
||||
OpenKFID string `json:"open_kfid"` // 指定发送消息的客服帐号ID
|
||||
MsgID string `json:"msgid"` // 指定消息ID
|
||||
}
|
||||
|
||||
// Text 发送文本消息
|
||||
type Text struct {
|
||||
Message
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:text
|
||||
Text struct {
|
||||
Content string `json:"content"` // 消息内容,最长不超过2048个字节
|
||||
} `json:"text"` // 文本消息
|
||||
}
|
||||
|
||||
// Image 发送图片消息
|
||||
type Image struct {
|
||||
Message
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:image
|
||||
Image struct {
|
||||
MediaID string `json:"media_id"` // 图片文件id,可以调用上传临时素材接口获取
|
||||
} `json:"image"` // 图片消息
|
||||
}
|
||||
|
||||
// Voice 发送语音消息
|
||||
type Voice struct {
|
||||
Message
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:voice
|
||||
Voice struct {
|
||||
MediaID string `json:"media_id"` // 语音文件id,可以调用上传临时素材接口获取
|
||||
} `json:"voice"` // 语音消息
|
||||
}
|
||||
|
||||
// Video 发送视频消息
|
||||
type Video struct {
|
||||
Message
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:video
|
||||
Video struct {
|
||||
MediaID string `json:"media_id"` // 视频文件id,可以调用上传临时素材接口获取
|
||||
} `json:"video"` // 视频消息
|
||||
}
|
||||
|
||||
// File 发送文件消息
|
||||
type File struct {
|
||||
Message
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:file
|
||||
File struct {
|
||||
MediaID string `json:"media_id"` // 文件id,可以调用上传临时素材接口获取
|
||||
} `json:"file"` // 文件消息
|
||||
}
|
||||
|
||||
// Link 图文链接消息
|
||||
type Link struct {
|
||||
Message
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:link
|
||||
Link struct {
|
||||
Title string `json:"title"` // 标题,不超过128个字节,超过会自动截断
|
||||
Desc string `json:"desc"` // 描述,不超过512个字节,超过会自动截断
|
||||
URL string `json:"url"` // 点击后跳转的链接。 最长2048字节,请确保包含了协议头(http/https)
|
||||
ThumbMediaID string `json:"thumb_media_id"` // 缩略图的media_id, 可以通过素材管理接口获得。此处thumb_media_id即上传接口返回的media_id
|
||||
} `json:"link"` // 链接消息
|
||||
}
|
||||
|
||||
// MiniProgram 小程序消息
|
||||
type MiniProgram struct {
|
||||
Message
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:miniprogram
|
||||
MiniProgram struct {
|
||||
AppID string `json:"appid"` // 小程序appid,必须是关联到企业的小程序应用
|
||||
Title string `json:"title"` // 小程序消息标题,最多64个字节,超过会自动截断
|
||||
ThumbMediaID string `json:"thumb_media_id"` // 小程序消息封面的mediaid,封面图建议尺寸为520*416
|
||||
PagePath string `json:"pagepath"` // 点击消息卡片后进入的小程序页面路径
|
||||
} `json:"miniprogram"` // 小程序消息
|
||||
}
|
||||
|
||||
// Menu 发送菜单消息
|
||||
type Menu struct {
|
||||
Message
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:msgmenu
|
||||
MsgMenu struct {
|
||||
HeadContent string `json:"head_content"` // 消息内容,不多于1024字节
|
||||
List []interface{} `json:"list"` // 菜单项配置
|
||||
} `json:"msgmenu"`
|
||||
}
|
||||
|
||||
// MenuClick 回复菜单
|
||||
type MenuClick struct {
|
||||
Type string `json:"type"` // 菜单类型: click 回复菜单
|
||||
Click struct {
|
||||
ID string `json:"id"` // 菜单ID, 不少于1字节, 不多于64字节
|
||||
Content string `json:"content"` // 菜单显示内容, 不少于1字节, 不多于128字节
|
||||
} `json:"click"`
|
||||
}
|
||||
|
||||
// MenuView 超链接菜单
|
||||
type MenuView struct {
|
||||
Type string `json:"type"` // 菜单类型: view 超链接菜单
|
||||
View struct {
|
||||
URL string `json:"url"` // 点击后跳转的链接, 不少于1字节, 不多于2048字节
|
||||
Content string `json:"content"` // 菜单显示内容, 不少于1字节, 不多于1024字节
|
||||
} `json:"view"`
|
||||
}
|
||||
|
||||
// MenuMiniProgram 小程序菜单
|
||||
type MenuMiniProgram struct {
|
||||
Type string `json:"type"` // 菜单类型: miniprogram 小程序菜单
|
||||
MiniProgram struct {
|
||||
AppID string `json:"appid"` // 小程序appid, 不少于1字节, 不多于32字节
|
||||
PagePath string `json:"pagepath"` // 点击后进入的小程序页面, 不少于1字节, 不多于1024字节
|
||||
Content string `json:"content"` // 菜单显示内容, 不少于1字节, 不多于1024字节
|
||||
} `json:"miniprogram"`
|
||||
}
|
||||
|
||||
// Location 地理位置消息
|
||||
type Location struct {
|
||||
Message
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:location
|
||||
Location struct {
|
||||
Latitude float32 `json:"latitude"` // 纬度, 浮点数,范围为90 ~ -90
|
||||
Longitude float32 `json:"longitude"` // 经度, 浮点数,范围为180 ~ -180
|
||||
Name string `json:"name"` // 位置名
|
||||
Address string `json:"address"` // 地址详情说明
|
||||
} `json:"location"`
|
||||
}
|
||||
1
work/kf/sendmsg/sendmsg.go
Normal file
1
work/kf/sendmsg/sendmsg.go
Normal file
@@ -0,0 +1 @@
|
||||
package sendmsg
|
||||
110
work/kf/servicer.go
Normal file
110
work/kf/servicer.go
Normal file
@@ -0,0 +1,110 @@
|
||||
package kf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const (
|
||||
//添加接待人员
|
||||
receptionistAddAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/servicer/add?access_token=%s"
|
||||
//删除接待人员
|
||||
receptionistDelAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/servicer/del?access_token=%s"
|
||||
//获取接待人员列表
|
||||
receptionistListAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/servicer/list?access_token=%s&open_kfid=%s"
|
||||
)
|
||||
|
||||
// ReceptionistOptions 添加接待人员请求参数
|
||||
type ReceptionistOptions struct {
|
||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||
UserIDList []string `json:"userid_list"` // 接待人员userid列表
|
||||
}
|
||||
|
||||
// ReceptionistSchema 添加接待人员响应内容
|
||||
type ReceptionistSchema struct {
|
||||
util.CommonError
|
||||
ResultList []struct {
|
||||
UserID string `json:"userid"`
|
||||
util.CommonError
|
||||
} `json:"result_list"`
|
||||
}
|
||||
|
||||
// ReceptionistAdd 添加接待人员
|
||||
func (r *Client) ReceptionistAdd(options ReceptionistOptions) (info ReceptionistSchema, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(receptionistAddAddr, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// ReceptionistDel 删除接待人员
|
||||
func (r *Client) ReceptionistDel(options ReceptionistOptions) (info ReceptionistSchema, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(receptionistDelAddr, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// ReceptionistListSchema 获取接待人员列表响应内容
|
||||
type ReceptionistListSchema struct {
|
||||
util.CommonError
|
||||
ReceptionistList []struct {
|
||||
UserID string `json:"userid"` // 接待人员的userid。第三方应用获取到的为密文userid,即open_userid
|
||||
Status int `json:"status"` // 接待人员的接待状态。0:接待中,1:停止接待。第三方应用需具有“管理帐号、分配会话和收发消息”权限才可获取
|
||||
} `json:"servicer_list"`
|
||||
}
|
||||
|
||||
// ReceptionistList 获取接待人员列表
|
||||
func (r *Client) ReceptionistList(kfID string) (info ReceptionistListSchema, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.HTTPGet(fmt.Sprintf(receptionistListAddr, accessToken, kfID))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
88
work/kf/servicestate.go
Normal file
88
work/kf/servicestate.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package kf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const (
|
||||
//获取会话状态
|
||||
serviceStateGetAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/service_state/get?access_token=%s"
|
||||
// 变更会话状态
|
||||
serviceStateTransAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/service_state/trans?access_token=%s"
|
||||
)
|
||||
|
||||
// ServiceStateGetOptions 获取会话状态请求参数
|
||||
type ServiceStateGetOptions struct {
|
||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||
}
|
||||
|
||||
// ServiceStateGetSchema 获取会话状态响应内容
|
||||
type ServiceStateGetSchema struct {
|
||||
util.CommonError
|
||||
ServiceState int `json:"service_state"` // 当前的会话状态,状态定义参考概述中的表格
|
||||
ServiceUserID string `json:"service_userid"` // 接待人员的userid,仅当state=3时有效
|
||||
}
|
||||
|
||||
// ServiceStateGet 获取会话状态
|
||||
//0 未处理 新会话接入。可选择:1.直接用API自动回复消息。2.放进待接入池等待接待人员接待。3.指定接待人员进行接待
|
||||
//1 由智能助手接待 可使用API回复消息。可选择转入待接入池或者指定接待人员处理。
|
||||
//2 待接入池排队中 在待接入池中排队等待接待人员接入。可选择转为指定人员接待
|
||||
//3 由人工接待 人工接待中。可选择结束会话
|
||||
//4 已结束 会话已经结束或未开始。不允许变更会话状态,等待用户发起咨询
|
||||
// 注:一个微信用户向一个客服帐号发起咨询后,在48h内,或主动结束会话前(包括接待人员手动结束,或企业通过API结束会话),都算是一次会话
|
||||
func (r *Client) ServiceStateGet(options ServiceStateGetOptions) (info ServiceStateGetSchema, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(serviceStateGetAddr, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// ServiceStateTransOptions 变更会话状态请求参数
|
||||
type ServiceStateTransOptions struct {
|
||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||
ServiceState int `json:"service_state"` // 变更的目标状态,状态定义和所允许的变更可参考概述中的流程图和表格
|
||||
ServicerUserID string `json:"servicer_userid"` // 接待人员的userid,当state=3时要求必填,接待人员须处于“正在接待”中
|
||||
}
|
||||
|
||||
// ServiceStateTrans 变更会话状态
|
||||
func (r *Client) ServiceStateTrans(options ServiceStateTransOptions) (info util.CommonError, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(serviceStateTransAddr, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
108
work/kf/syncmsg.go
Normal file
108
work/kf/syncmsg.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package kf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
"github.com/silenceper/wechat/v2/work/kf/syncmsg"
|
||||
)
|
||||
|
||||
const (
|
||||
//获取消息
|
||||
syncMsgAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/sync_msg?access_token=%s"
|
||||
)
|
||||
|
||||
// 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字段判断是否继续请求。
|
||||
}
|
||||
|
||||
// SyncMsgSchema 获取消息查询响应内容
|
||||
type syncMsgSchema struct {
|
||||
ErrCode int32 `json:"errcode"` // 返回码
|
||||
ErrMsg string `json:"errmsg"` // 错误码描述
|
||||
NextCursor string `json:"next_cursor"` // 下次调用带上该值,则从当前的位置继续往后拉,以实现增量拉取。强烈建议对改该字段入库保存,每次请求读取带上,请求结束后更新。避免因意外丢,导致必须从头开始拉取,引起消息延迟。
|
||||
HasMore uint32 `json:"has_more"` // 是否还有更多数据。0-否;1-是。不能通过判断msg_list是否空来停止拉取,可能会出现has_more为1,而msg_list为空的情况
|
||||
MsgList []map[string]interface{} `json:"msg_list"` // 消息列表
|
||||
}
|
||||
|
||||
// SyncMsgSchema 获取消息查询响应内容
|
||||
type SyncMsgSchema struct {
|
||||
ErrCode int32 `json:"errcode"` // 返回码
|
||||
ErrMsg string `json:"errmsg"` // 错误码描述
|
||||
NextCursor string `json:"next_cursor"` // 下次调用带上该值则从该key值往后拉,用于增量拉取
|
||||
HasMore uint32 `json:"has_more"` // 是否还有更多数据。0-否;1-是。不能通过判断msg_list是否空来停止拉取,可能会出现has_more为1,而msg_list为空的情况
|
||||
MsgList []syncmsg.Message `json:"msg_list"` // 消息列表
|
||||
}
|
||||
|
||||
// SyncMsg 获取消息
|
||||
func (r *Client) SyncMsg(options SyncMsgOptions) (info SyncMsgSchema, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(syncMsgAddr, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
originInfo := syncMsgSchema{}
|
||||
if err = json.Unmarshal(data, &originInfo); err != nil {
|
||||
return
|
||||
}
|
||||
if originInfo.ErrCode != 0 {
|
||||
return info, errors.New(originInfo.ErrMsg)
|
||||
}
|
||||
msgList := make([]syncmsg.Message, 0)
|
||||
if len(originInfo.MsgList) > 0 {
|
||||
for _, msg := range originInfo.MsgList {
|
||||
newMsg := syncmsg.Message{}
|
||||
if val, ok := msg["msgid"].(string); ok {
|
||||
newMsg.MsgID = val
|
||||
}
|
||||
if val, ok := msg["open_kfid"].(string); ok {
|
||||
newMsg.OpenKFID = val
|
||||
}
|
||||
if val, ok := msg["external_userid"].(string); ok {
|
||||
newMsg.ExternalUserID = val
|
||||
}
|
||||
if val, ok := msg["send_time"].(float64); ok {
|
||||
newMsg.SendTime = uint64(val)
|
||||
}
|
||||
if val, ok := msg["origin"].(float64); ok {
|
||||
newMsg.Origin = uint32(val)
|
||||
}
|
||||
|
||||
if val, ok := msg["msgtype"].(string); ok {
|
||||
newMsg.MsgType = val
|
||||
}
|
||||
if newMsg.MsgType == "event" {
|
||||
if event, ok := msg["event"].(map[string]interface{}); ok {
|
||||
if eType, ok := event["event_type"].(string); ok {
|
||||
newMsg.EventType = eType
|
||||
}
|
||||
}
|
||||
}
|
||||
originData, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
newMsg.OriginData = originData
|
||||
msgList = append(msgList, newMsg)
|
||||
}
|
||||
}
|
||||
return SyncMsgSchema{
|
||||
ErrCode: originInfo.ErrCode,
|
||||
ErrMsg: originInfo.ErrMsg,
|
||||
NextCursor: originInfo.NextCursor,
|
||||
HasMore: originInfo.HasMore,
|
||||
MsgList: msgList,
|
||||
}, nil
|
||||
}
|
||||
162
work/kf/syncmsg/message.go
Normal file
162
work/kf/syncmsg/message.go
Normal file
@@ -0,0 +1,162 @@
|
||||
package syncmsg
|
||||
|
||||
// BaseMessage 接收消息
|
||||
type BaseMessage struct {
|
||||
MsgID string `json:"msgid"` // 消息ID
|
||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID(msgtype为event,该字段不返回)
|
||||
ExternalUserID string `json:"external_userid"` // 客户UserID(msgtype为event,该字段不返回)
|
||||
ReceptionistUserID string `json:"servicer_userid"` // 接待客服userID
|
||||
SendTime uint64 `json:"send_time"` // 消息发送时间
|
||||
Origin uint32 `json:"origin"` // 消息来源。3-微信客户发送的消息 4-系统推送的事件消息 5-接待人员在企业微信客户端发送的消息
|
||||
}
|
||||
|
||||
// Text 文本消息
|
||||
type Text struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:text
|
||||
Text struct {
|
||||
Content string `json:"content"` // 文本内容
|
||||
MenuID string `json:"menu_id"` // 客户点击菜单消息,触发的回复消息中附带的菜单ID
|
||||
} `json:"text"` // 文本消息
|
||||
}
|
||||
|
||||
// Image 图片消息
|
||||
type Image struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:image
|
||||
Image struct {
|
||||
MediaID string `json:"media_id"` // 图片文件ID
|
||||
} `json:"image"` // 图片消息
|
||||
}
|
||||
|
||||
// Voice 语音消息
|
||||
type Voice struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:voice
|
||||
Voice struct {
|
||||
MediaID string `json:"media_id"` // 语音文件ID
|
||||
} `json:"voice"` // 语音消息
|
||||
}
|
||||
|
||||
// Video 视频消息
|
||||
type Video struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:video
|
||||
Video struct {
|
||||
MediaID string `json:"media_id"` // 文件ID
|
||||
} `json:"video"` // 视频消息
|
||||
}
|
||||
|
||||
// File 文件消息
|
||||
type File struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:file
|
||||
File struct {
|
||||
MediaID string `json:"media_id"` // 文件ID
|
||||
} `json:"file"` // 文件消息
|
||||
}
|
||||
|
||||
// Location 地理位置消息
|
||||
type Location struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:location
|
||||
Location struct {
|
||||
Latitude float32 `json:"latitude"` // 纬度
|
||||
Longitude float32 `json:"longitude"` // 经度
|
||||
Name string `json:"name"` // 位置名
|
||||
Address string `json:"address"` // 地址详情说明
|
||||
} `json:"location"` // 地理位置消息
|
||||
}
|
||||
|
||||
// Link 链接消息
|
||||
type Link struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:link
|
||||
Link struct {
|
||||
Title string `json:"title"` // 标题
|
||||
Desc string `json:"desc"` // 描述
|
||||
URL string `json:"url"` // 点击后跳转的链接
|
||||
PicURL string `json:"pic_url"` // 缩略图链接
|
||||
} `json:"link"` // 链接消息
|
||||
}
|
||||
|
||||
// BusinessCard 名片消息
|
||||
type BusinessCard struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:business_card
|
||||
BusinessCard struct {
|
||||
UserID string `json:"userid"` // 名片 userid
|
||||
} `json:"business_card"` // 名片消息
|
||||
}
|
||||
|
||||
// MiniProgram 小程序消息
|
||||
type MiniProgram struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:miniprogram
|
||||
MiniProgram struct {
|
||||
AppID string `json:"appid"` // 小程序appid,必须是关联到企业的小程序应用
|
||||
Title string `json:"title"` // 小程序消息标题,最多64个字节,超过会自动截断
|
||||
ThumbMediaID string `json:"thumb_media_id"` // 小程序消息封面的mediaid,封面图建议尺寸为520*416
|
||||
PagePath string `json:"pagepath"` // 点击消息卡片后进入的小程序页面路径
|
||||
} `json:"miniprogram"` // 小程序消息
|
||||
}
|
||||
|
||||
// EventMessage 事件消息
|
||||
type EventMessage struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:event
|
||||
Event struct {
|
||||
EventType string `json:"event_type"` // 事件类型
|
||||
} `json:"event"` // 事件消息
|
||||
}
|
||||
|
||||
// EnterSessionEvent 用户进入会话事件
|
||||
type EnterSessionEvent struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:event
|
||||
Event struct {
|
||||
EventType string `json:"event_type"` // 事件类型。此处固定为:enter_session
|
||||
OpenKFID string `json:"open_kfid"` // 客服账号ID
|
||||
ExternalUserID string `json:"external_userid"` // 客户UserID
|
||||
Scene string `json:"scene"` // 进入会话的场景值,获取客服帐号链接开发者自定义的场景值
|
||||
SceneParam string `json:"scene_param"` // 进入会话的自定义参数,获取客服帐号链接返回的url,开发者按规范拼接的scene_param参数
|
||||
} `json:"event"` // 事件消息
|
||||
}
|
||||
|
||||
// MsgSendFailEvent 消息发送失败事件
|
||||
type MsgSendFailEvent struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:event
|
||||
Event struct {
|
||||
EventType string `json:"event_type"` // 事件类型。此处固定为:msg_send_fail
|
||||
OpenKFID string `json:"open_kfid"` // 客服账号ID
|
||||
ExternalUserID string `json:"external_userid"` // 客户UserID
|
||||
FailMsgID string `json:"fail_msgid"` // 发送失败的消息msgid
|
||||
FailType uint32 `json:"fail_type"` // 失败类型。0-未知原因 1-客服账号已删除 2-应用已关闭 4-会话已过期,超过48小时 5-会话已关闭 6-超过5条限制 7-未绑定视频号 8-主体未验证 9-未绑定视频号且主体未验证 10-用户拒收
|
||||
} `json:"event"` // 事件消息
|
||||
}
|
||||
|
||||
// ReceptionistStatusChangeEvent 客服人员接待状态变更事件
|
||||
type ReceptionistStatusChangeEvent struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:event
|
||||
Event struct {
|
||||
EventType string `json:"event_type"` // 事件类型。此处固定为:servicer_status_change
|
||||
ReceptionistUserID string `json:"servicer_userid"` // 客服人员userid
|
||||
Status uint32 `json:"status"` // 状态类型。1-接待中 2-停止接待
|
||||
} `json:"event"`
|
||||
}
|
||||
|
||||
// SessionStatusChangeEvent 会话状态变更事件
|
||||
type SessionStatusChangeEvent struct {
|
||||
BaseMessage
|
||||
MsgType string `json:"msgtype"` // 消息类型,此时固定为:event
|
||||
Event struct {
|
||||
EventType string `json:"event_type"` // 事件类型。此处固定为:session_status_change
|
||||
OpenKFID string `json:"open_kfid"` // 客服账号ID
|
||||
ExternalUserID string `json:"external_userid"` // 客户UserID
|
||||
ChangeType uint32 `json:"change_type"` // 变更类型。1-从接待池接入会话 2-转接会话 3-结束会话
|
||||
OldReceptionistUserID string `json:"old_servicer_userid"` // 老的客服人员userid。仅change_type为2和3有值
|
||||
NewReceptionistUserID string `json:"new_servicer_userid"` // 新的客服人员userid。仅change_type为1和2有值
|
||||
} `json:"event"` // 事件消息
|
||||
}
|
||||
102
work/kf/syncmsg/syncmsg.go
Normal file
102
work/kf/syncmsg/syncmsg.go
Normal file
@@ -0,0 +1,102 @@
|
||||
package syncmsg
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// Message 同步的消息内容
|
||||
type Message struct {
|
||||
MsgID string `json:"msgid"` // 消息ID
|
||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||
ExternalUserID string `json:"external_userid"` // 客户UserID
|
||||
SendTime uint64 `json:"send_time"` // 消息发送时间
|
||||
Origin uint32 `json:"origin"` // 消息来源。3-客户回复的消息 4-系统推送的消 息
|
||||
MsgType string `json:"msgtype"` // 消息类型
|
||||
EventType string `json:"event_type"` // 事件类型
|
||||
OriginData []byte `json:"origin_data"` // 原始数据内容
|
||||
}
|
||||
|
||||
// GetOriginMessage 获取原始消息
|
||||
func (r Message) GetOriginMessage() (info []byte) {
|
||||
return r.OriginData
|
||||
}
|
||||
|
||||
// GetTextMessage 获取文本消息
|
||||
func (r Message) GetTextMessage() (info Text, err error) {
|
||||
err = json.Unmarshal(r.OriginData, &info)
|
||||
return info, err
|
||||
}
|
||||
|
||||
// GetImageMessage 获取图片消息
|
||||
func (r Message) GetImageMessage() (info Image, err error) {
|
||||
err = json.Unmarshal(r.OriginData, &info)
|
||||
return info, err
|
||||
}
|
||||
|
||||
// GetVoiceMessage 获取语音消息
|
||||
func (r Message) GetVoiceMessage() (info Voice, err error) {
|
||||
err = json.Unmarshal(r.OriginData, &info)
|
||||
return info, err
|
||||
}
|
||||
|
||||
// GetVideoMessage 获取视频消息
|
||||
func (r Message) GetVideoMessage() (info Video, err error) {
|
||||
err = json.Unmarshal(r.OriginData, &info)
|
||||
return info, err
|
||||
}
|
||||
|
||||
// GetFileMessage 获取文件消息
|
||||
func (r Message) GetFileMessage() (info File, err error) {
|
||||
err = json.Unmarshal(r.OriginData, &info)
|
||||
return info, err
|
||||
}
|
||||
|
||||
// GetLocationMessage 获取文件消息
|
||||
func (r Message) GetLocationMessage() (info Location, err error) {
|
||||
err = json.Unmarshal(r.OriginData, &info)
|
||||
return info, err
|
||||
}
|
||||
|
||||
// GetLinkMessage 获取链接消息
|
||||
func (r Message) GetLinkMessage() (info Link, err error) {
|
||||
err = json.Unmarshal(r.OriginData, &info)
|
||||
return info, err
|
||||
}
|
||||
|
||||
// GetBusinessCardMessage 获取名片消息
|
||||
func (r Message) GetBusinessCardMessage() (info BusinessCard, err error) {
|
||||
err = json.Unmarshal(r.OriginData, &info)
|
||||
return info, err
|
||||
}
|
||||
|
||||
// GetMiniProgramMessage 获取小程序消息
|
||||
func (r Message) GetMiniProgramMessage() (info MiniProgram, err error) {
|
||||
err = json.Unmarshal(r.OriginData, &info)
|
||||
return info, err
|
||||
}
|
||||
|
||||
// GetEnterSessionEvent 用户进入会话事件
|
||||
func (r Message) GetEnterSessionEvent() (info EnterSessionEvent, err error) {
|
||||
err = json.Unmarshal(r.OriginData, &info)
|
||||
info.OpenKFID = info.Event.OpenKFID
|
||||
info.ExternalUserID = info.Event.ExternalUserID
|
||||
return info, err
|
||||
}
|
||||
|
||||
// GetMsgSendFailEvent 消息发送失败事件
|
||||
func (r Message) GetMsgSendFailEvent() (info MsgSendFailEvent, err error) {
|
||||
err = json.Unmarshal(r.OriginData, &info)
|
||||
return info, err
|
||||
}
|
||||
|
||||
// GetReceptionistStatusChangeEvent 客服人员接待状态变更事件
|
||||
func (r Message) GetReceptionistStatusChangeEvent() (info ReceptionistStatusChangeEvent, err error) {
|
||||
err = json.Unmarshal(r.OriginData, &info)
|
||||
return info, err
|
||||
}
|
||||
|
||||
// GetSessionStatusChangeEvent 会话状态变更事件
|
||||
func (r Message) GetSessionStatusChangeEvent() (info SessionStatusChangeEvent, err error) {
|
||||
err = json.Unmarshal(r.OriginData, &info)
|
||||
info.OpenKFID = info.Event.OpenKFID
|
||||
info.ExternalUserID = info.Event.ExternalUserID
|
||||
return info, err
|
||||
}
|
||||
187
work/kf/upgrade.go
Normal file
187
work/kf/upgrade.go
Normal file
@@ -0,0 +1,187 @@
|
||||
package kf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const (
|
||||
//获取配置的专员与客户群
|
||||
upgradeServiceConfigAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/customer/get_upgrade_service_config?access_token=%s"
|
||||
// 为客户升级为专员或客户群服务
|
||||
upgradeService = "https://qyapi.weixin.qq.com/cgi-bin/kf/customer/upgrade_service?access_token=%s"
|
||||
//为客户取消推荐
|
||||
upgradeServiceCancel = "https://qyapi.weixin.qq.com/cgi-bin/kf/customer/cancel_upgrade_service?access_token=%s"
|
||||
)
|
||||
|
||||
// UpgradeServiceConfigSchema 获取配置的专员与客户群
|
||||
type UpgradeServiceConfigSchema struct {
|
||||
util.CommonError
|
||||
MemberRange struct {
|
||||
UserIDList []string `json:"userid_list"` // 专员userid列表
|
||||
DepartmentIDList []string `json:"department_id_list"` // 专员部门列表
|
||||
} `json:"member_range"` // 专员服务配置范围
|
||||
GroupChatRange struct {
|
||||
ChatIDList []string `json:"chat_id_list"` // 客户群列表
|
||||
} `json:"groupchat_range"` // 客户群配置范围
|
||||
}
|
||||
|
||||
// UpgradeServiceConfig 获取配置的专员与客户群
|
||||
func (r *Client) UpgradeServiceConfig() (info UpgradeServiceConfigSchema, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.HTTPGet(fmt.Sprintf(upgradeServiceConfigAddr, accessToken))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// UpgradeServiceOptions 为客户升级为专员或客户群服务请求参数
|
||||
type UpgradeServiceOptions struct {
|
||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||
Type int `json:"type"` // 表示是升级到专员服务还是客户群服务。1:专员服务。2:客户群服务
|
||||
Member struct {
|
||||
UserID string `json:"userid"` // 服务专员的userid
|
||||
Wording string `json:"wording"` // 推荐语
|
||||
} `json:"member"` // 推荐的服务专员,type等于1时有效
|
||||
GroupChat struct {
|
||||
ChatID string `json:"chat_id"` // 客户群id
|
||||
Wording string `json:"wording"` // 推荐语
|
||||
} `json:"groupchat"` // 推荐的客户群,type等于2时有效
|
||||
}
|
||||
|
||||
// UpgradeService 为客户升级为专员或客户群服务
|
||||
func (r *Client) UpgradeService(options UpgradeServiceOptions) (info util.CommonError, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(upgradeService, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// UpgradeMemberServiceOptions 为客户升级为专员服务请求参数
|
||||
type UpgradeMemberServiceOptions struct {
|
||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||
Type int `json:"type"` // 表示是升级到专员服务还是客户群服务。1:专员服务
|
||||
Member struct {
|
||||
UserID string `json:"userid"` // 服务专员的userid
|
||||
Wording string `json:"wording"` // 推荐语
|
||||
} `json:"member"` // 推荐的服务专员,type等于1时有效
|
||||
}
|
||||
|
||||
// UpgradeMemberService 为客户升级为专员服务
|
||||
func (r *Client) UpgradeMemberService(options UpgradeMemberServiceOptions) (info util.CommonError, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(upgradeService, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// UpgradeServiceGroupChatOptions 为客户升级为客户群服务请求参数
|
||||
type UpgradeServiceGroupChatOptions struct {
|
||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||
Type int `json:"type"` // 表示是升级到专员服务还是客户群服务。2:客户群服务
|
||||
GroupChat struct {
|
||||
ChatID string `json:"chat_id"` // 客户群id
|
||||
Wording string `json:"wording"` // 推荐语
|
||||
} `json:"groupchat"` // 推荐的客户群,type等于2时有效
|
||||
}
|
||||
|
||||
// UpgradeGroupChatService 为客户升级为客户群服务
|
||||
func (r *Client) UpgradeGroupChatService(options UpgradeServiceGroupChatOptions) (info util.CommonError, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(upgradeService, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// UpgradeServiceCancelOptions 为客户取消推荐
|
||||
type UpgradeServiceCancelOptions struct {
|
||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||
}
|
||||
|
||||
// UpgradeServiceCancel 为客户取消推荐
|
||||
func (r *Client) UpgradeServiceCancel(options UpgradeServiceCancelOptions) (info util.CommonError, err error) {
|
||||
var (
|
||||
accessToken string
|
||||
data []byte
|
||||
)
|
||||
accessToken, err = r.ctx.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data, err = util.PostJSON(fmt.Sprintf(upgradeServiceCancel, accessToken), options)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(data, &info); err != nil {
|
||||
return
|
||||
}
|
||||
if info.ErrCode != 0 {
|
||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
95
work/msgaudit/README.md
Normal file
95
work/msgaudit/README.md
Normal file
@@ -0,0 +1,95 @@
|
||||
企业微信会话存档SDK(基于企业微信C版官方SDK封装),暂时只支持在`linux`环境下使用当前SDK。
|
||||
|
||||
### 官方文档地址
|
||||
https://open.work.weixin.qq.com/api/doc/90000/90135/91774
|
||||
|
||||
### 使用方式
|
||||
|
||||
1、安装 go module
|
||||
> go get -u github.com/silenceper/wechat/v2
|
||||
|
||||
2、从 `github.com/silenceper/wechat/v2/work/msgaudit/lib` 文件夹下复制 `libWeWorkFinanceSdk_C.so` 动态库文件到系统动态链接库默认文件夹下,或者复制到任意文件夹并在当前文件夹下执行 `export LD_LIBRARY_PATH=$(pwd)`命令设置动态链接库检索地址后即可正常使用
|
||||
|
||||
### Example
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/silenceper/wechat/v2"
|
||||
"github.com/silenceper/wechat/v2/work/msgaudit"
|
||||
"github.com/silenceper/wechat/v2/work/config"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
)
|
||||
|
||||
func main() {
|
||||
//初始化客户端
|
||||
wechatClient := wechat.NewWechat()
|
||||
|
||||
workClient := wechatClient.NewWork(&config.Config{
|
||||
CorpID: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
|
||||
CorpSecret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
|
||||
RasPrivateKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
|
||||
})
|
||||
|
||||
client, err := workClient.GetMsgAudit()
|
||||
if err != nil {
|
||||
fmt.Printf("SDK 初始化失败:%v \n", err)
|
||||
return
|
||||
}
|
||||
|
||||
//同步消息
|
||||
chatDataList, err := client.GetChatData(0, 100, "", "", 3)
|
||||
if err != nil {
|
||||
fmt.Printf("消息同步失败:%v \n", err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, chatData := range chatDataList {
|
||||
//消息解密
|
||||
chatInfo, err := client.DecryptData(chatData.EncryptRandomKey, chatData.EncryptChatMsg)
|
||||
if err != nil {
|
||||
fmt.Printf("消息解密失败:%v \n", err)
|
||||
return
|
||||
}
|
||||
|
||||
if chatInfo.Type == "image" {
|
||||
image, _ := chatInfo.GetImageMessage()
|
||||
sdkfileid := image.Image.SdkFileId
|
||||
|
||||
isFinish := false
|
||||
buffer := bytes.Buffer{}
|
||||
for !isFinish {
|
||||
//获取媒体数据
|
||||
mediaData, err := client.GetMediaData("", sdkfileid, "", "", 5)
|
||||
if err != nil {
|
||||
fmt.Printf("媒体数据拉取失败:%v \n", err)
|
||||
return
|
||||
}
|
||||
buffer.Write(mediaData.Data)
|
||||
if mediaData.IsFinish {
|
||||
isFinish = mediaData.IsFinish
|
||||
}
|
||||
}
|
||||
filePath, _ := os.Getwd()
|
||||
filePath = path.Join(filePath, "test.png")
|
||||
err := ioutil.WriteFile(filePath, buffer.Bytes(), 0666)
|
||||
if err != nil {
|
||||
fmt.Printf("文件存储失败:%v \n", err)
|
||||
return
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
//释放SDK实例
|
||||
client.Free()
|
||||
}
|
||||
|
||||
|
||||
|
||||
```
|
||||
207
work/msgaudit/chat.go
Normal file
207
work/msgaudit/chat.go
Normal file
@@ -0,0 +1,207 @@
|
||||
package msgaudit
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// ChatDataResponse 会话存档消息响应数据
|
||||
type ChatDataResponse struct {
|
||||
Error
|
||||
ChatDataList []ChatData `json:"chatdata,omitempty"`
|
||||
}
|
||||
|
||||
// IsError 判断是否正确响应
|
||||
func (c ChatDataResponse) IsError() bool {
|
||||
return c.ErrCode != 0
|
||||
}
|
||||
|
||||
// ChatData 会话存档原始数据
|
||||
type ChatData struct {
|
||||
Seq uint64 `json:"seq,omitempty"` // 消息的seq值,标识消息的序号。再次拉取需要带上上次回包中最大的seq。Uint64类型,范围0-pow(2,64)-1
|
||||
MsgID string `json:"msgid,omitempty"` // 消息id,消息的唯一标识,企业可以使用此字段进行消息去重。
|
||||
PublickeyVer uint32 `json:"publickey_ver,omitempty"` // 加密此条消息使用的公钥版本号。
|
||||
EncryptRandomKey string `json:"encrypt_random_key,omitempty"` // 使用publickey_ver指定版本的公钥进行非对称加密后base64加密的内容,需要业务方先base64 decode处理后,再使用指定版本的私钥进行解密,得出内容。
|
||||
EncryptChatMsg string `json:"encrypt_chat_msg,omitempty"` // 消息密文。需要业务方使用将encrypt_random_key解密得到的内容,与encrypt_chat_msg,传入sdk接口DecryptData,得到消息明文。
|
||||
}
|
||||
|
||||
// ChatMessage 会话存档消息
|
||||
type ChatMessage struct {
|
||||
ID string // 消息id,消息的唯一标识,企业可以使用此字段进行消息去重。
|
||||
From string // 消息发送方id。同一企业内容为userid,非相同企业为external_userid。消息如果是机器人发出,也为external_userid。
|
||||
ToList []string // 消息接收方列表,可能是多个,同一个企业内容为userid,非相同企业为external_userid。
|
||||
Action string // 消息动作,目前有send(发送消息)/recall(撤回消息)/switch(切换企业日志)三种类型。
|
||||
Type string // 消息类型
|
||||
originData []byte // 原始消息对象
|
||||
}
|
||||
|
||||
// GetOriginMessage 获取消息原始数据
|
||||
func (c ChatMessage) GetOriginMessage() (msg map[string]interface{}, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetTextMessage 获取文本消息
|
||||
func (c ChatMessage) GetTextMessage() (msg TextMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetImageMessage 获取图片消息
|
||||
func (c ChatMessage) GetImageMessage() (msg ImageMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetRevokeMessage 获取撤回消息
|
||||
func (c ChatMessage) GetRevokeMessage() (msg RevokeMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetAgreeMessage 获取同意会话聊天内容
|
||||
func (c ChatMessage) GetAgreeMessage() (msg AgreeMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetVoiceMessage 获取语音消息
|
||||
func (c ChatMessage) GetVoiceMessage() (msg VoiceMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetVideoMessage 获取视频消息
|
||||
func (c ChatMessage) GetVideoMessage() (msg VideoMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetCardMessage 获取名片消息
|
||||
func (c ChatMessage) GetCardMessage() (msg CardMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetLocationMessage 获取位置消息
|
||||
func (c ChatMessage) GetLocationMessage() (msg LocationMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetEmotionMessage 获取表情消息
|
||||
func (c ChatMessage) GetEmotionMessage() (msg EmotionMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetFileMessage 获取文件消息
|
||||
func (c ChatMessage) GetFileMessage() (msg FileMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetLinkMessage 获取链接消息
|
||||
func (c ChatMessage) GetLinkMessage() (msg LinkMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetWeappMessage 获取小程序消息
|
||||
func (c ChatMessage) GetWeappMessage() (msg WeappMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetChatRecordMessage 获取会话记录消息
|
||||
func (c ChatMessage) GetChatRecordMessage() (msg ChatRecordMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetTodoMessage 获取待办消息
|
||||
func (c ChatMessage) GetTodoMessage() (msg TodoMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetVoteMessage 获取投票消息
|
||||
func (c ChatMessage) GetVoteMessage() (msg VoteMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetCollectMessage 获取填表消息
|
||||
func (c ChatMessage) GetCollectMessage() (msg CollectMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetRedpacketMessage 获取红包消息
|
||||
func (c ChatMessage) GetRedpacketMessage() (msg RedpacketMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetMeetingMessage 获取会议邀请消息
|
||||
func (c ChatMessage) GetMeetingMessage() (msg MeetingMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetDocMessage 获取在线文档消息
|
||||
func (c ChatMessage) GetDocMessage() (msg DocMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetMarkdownMessage 获取MarkDown格式消息
|
||||
func (c ChatMessage) GetMarkdownMessage() (msg MarkdownMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetNewsMessage 获取图文消息
|
||||
func (c ChatMessage) GetNewsMessage() (msg NewsMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetCalendarMessage 获取日程消息
|
||||
func (c ChatMessage) GetCalendarMessage() (msg CalendarMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetMixedMessage 获取混合消息
|
||||
func (c ChatMessage) GetMixedMessage() (msg MixedMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetMeetingVoiceCallMessage 获取音频存档消息
|
||||
func (c ChatMessage) GetMeetingVoiceCallMessage() (msg MeetingVoiceCallMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetVoipDocShareMessage 获取音频共享消息
|
||||
func (c ChatMessage) GetVoipDocShareMessage() (msg VoipDocShareMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetExternalRedPacketMessage 获取互通红包消息
|
||||
func (c ChatMessage) GetExternalRedPacketMessage() (msg ExternalRedPacketMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetSphFeedMessage 获取视频号消息
|
||||
func (c ChatMessage) GetSphFeedMessage() (msg SphFeedMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetSwitchMessage 获取切换企业日志
|
||||
func (c ChatMessage) GetSwitchMessage() (msg SwitchMessage, err error) {
|
||||
err = json.Unmarshal(c.originData, &msg)
|
||||
return msg, err
|
||||
}
|
||||
264
work/msgaudit/client_linux.go
Normal file
264
work/msgaudit/client_linux.go
Normal file
@@ -0,0 +1,264 @@
|
||||
// +build linux
|
||||
|
||||
//Package msgaudit only for linux
|
||||
package msgaudit
|
||||
|
||||
// #cgo LDFLAGS: -L${SRCDIR}/lib -lWeWorkFinanceSdk_C
|
||||
// #cgo CFLAGS: -I ./lib/
|
||||
// #include <stdlib.h>
|
||||
// #include "WeWorkFinanceSdk_C.h"
|
||||
import "C"
|
||||
import (
|
||||
"encoding/json"
|
||||
"unsafe"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
"github.com/silenceper/wechat/v2/work/config"
|
||||
)
|
||||
|
||||
// Client 会话存档
|
||||
type Client struct {
|
||||
ptr *C.WeWorkFinanceSdk_t
|
||||
privateKey string
|
||||
}
|
||||
|
||||
// NewClient 初始会话会话存档实例
|
||||
/**
|
||||
* 初始化函数
|
||||
* Return值=0表示该API调用成功
|
||||
*
|
||||
* @param [in] sdk NewSdk返回的sdk指针
|
||||
* @param [in] corpid 调用企业的企业id,例如:wwd08c8exxxx5ab44d,可以在企业微信管理端--我的企业--企业信息查看
|
||||
* @param [in] secret 聊天内容存档的Secret,可以在企业微信管理端--管理工具--聊天内容存档查看
|
||||
* @param [in] privateKey 消息加密私钥,可以在企业微信管理端--管理工具--消息加密公钥查看对用公钥,私钥一般由自己保存
|
||||
*
|
||||
*
|
||||
* @return 返回是否初始化成功
|
||||
* 0 - 成功
|
||||
* !=0 - 失败
|
||||
*/
|
||||
func NewClient(cfg *config.Config) (*Client, error) {
|
||||
ptr := C.NewSdk()
|
||||
corpIDC := C.CString(cfg.CorpID)
|
||||
corpSecretC := C.CString(cfg.CorpSecret)
|
||||
defer func() {
|
||||
C.free(unsafe.Pointer(corpIDC))
|
||||
C.free(unsafe.Pointer(corpSecretC))
|
||||
}()
|
||||
retC := C.Init(ptr, corpIDC, corpSecretC)
|
||||
ret := int(retC)
|
||||
if ret != 0 {
|
||||
return nil, NewSDKErr(ret)
|
||||
}
|
||||
return &Client{
|
||||
ptr: ptr,
|
||||
privateKey: cfg.RasPrivateKey,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Free 释放SDK实例是可调用该方法释放内存
|
||||
func (s *Client) Free() {
|
||||
if s.ptr == nil {
|
||||
return
|
||||
}
|
||||
C.DestroySdk(s.ptr)
|
||||
s.ptr = nil
|
||||
}
|
||||
|
||||
// GetChatData 拉取聊天记录函数
|
||||
/**
|
||||
* 拉取聊天记录函数
|
||||
*
|
||||
*
|
||||
* @param [in] seq 从指定的seq开始拉取消息,注意的是返回的消息从seq+1开始返回,seq为之前接口返回的最大seq值。首次使用请使用seq:0
|
||||
* @param [in] limit 一次拉取的消息条数,最大值1000条,超过1000条会返回错误
|
||||
* @param [in] proxy 使用代理的请求,需要传入代理的链接。如:socks5://10.0.0.1:8081 或者 http://10.0.0.1:8081
|
||||
* @param [in] passwd 代理账号密码,需要传入代理的账号密码。如 user_name:passwd_123
|
||||
* @param [in] timeout 超时时间,单位秒
|
||||
* @return chatDatas 返回本次拉取消息的数据,slice结构体.内容包括errcode/errmsg,以及每条消息内容。示例如下:
|
||||
|
||||
{"errcode":0,"errmsg":"ok","chatdata":[{"seq":196,"msgid":"CAQQ2fbb4QUY0On2rYSAgAMgip/yzgs=","publickey_ver":3,"encrypt_random_key":"ftJ+uz3n/z1DsxlkwxNgE+mL38H42/KCvN8T60gbbtPD+Rta1hKTuQPzUzO6Hzne97MgKs7FfdDxDck/v8cDT6gUVjA2tZ/M7euSD0L66opJ/IUeBtpAtvgVSD5qhlaQjvfKJc/zPMGNK2xCLFYqwmQBZXbNT7uA69Fflm512nZKW/piK2RKdYJhRyvQnA1ISxK097sp9WlEgDg250fM5tgwMjujdzr7ehK6gtVBUFldNSJS7ndtIf6aSBfaLktZgwHZ57ONewWq8GJe7WwQf1hwcDbCh7YMG8nsweEwhDfUz+u8rz9an+0lgrYMZFRHnmzjgmLwrR7B/32Qxqd79A==","encrypt_chat_msg":"898WSfGMnIeytTsea7Rc0WsOocs0bIAerF6de0v2cFwqo9uOxrW9wYe5rCjCHHH5bDrNvLxBE/xOoFfcwOTYX0HQxTJaH0ES9OHDZ61p8gcbfGdJKnq2UU4tAEgGb8H+Q9n8syRXIjaI3KuVCqGIi4QGHFmxWenPFfjF/vRuPd0EpzUNwmqfUxLBWLpGhv+dLnqiEOBW41Zdc0OO0St6E+JeIeHlRZAR+E13Isv9eS09xNbF0qQXWIyNUi+ucLr5VuZnPGXBrSfvwX8f0QebTwpy1tT2zvQiMM2MBugKH6NuMzzuvEsXeD+6+3VRqL"}]}
|
||||
*/
|
||||
func (s *Client) GetChatData(seq uint64, limit uint64, proxy string, passwd string, timeout int) ([]ChatData, error) {
|
||||
proxyC := C.CString(proxy)
|
||||
passwdC := C.CString(passwd)
|
||||
chatSlice := C.NewSlice()
|
||||
defer func() {
|
||||
C.free(unsafe.Pointer(proxyC))
|
||||
C.free(unsafe.Pointer(passwdC))
|
||||
C.FreeSlice(chatSlice)
|
||||
}()
|
||||
|
||||
if s.ptr == nil {
|
||||
return nil, NewSDKErr(10002)
|
||||
}
|
||||
|
||||
retC := C.GetChatData(s.ptr, C.ulonglong(seq), C.uint(limit), proxyC, passwdC, C.int(timeout), chatSlice)
|
||||
ret := int(retC)
|
||||
if ret != 0 {
|
||||
return nil, NewSDKErr(ret)
|
||||
}
|
||||
buf := s.GetContentFromSlice(chatSlice)
|
||||
|
||||
var data ChatDataResponse
|
||||
err := json.Unmarshal(buf, &data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if data.ErrCode != 0 {
|
||||
return nil, data.Error
|
||||
}
|
||||
return data.ChatDataList, nil
|
||||
}
|
||||
|
||||
// GetRawChatData 拉取聊天记录函数
|
||||
/**
|
||||
* 拉取聊天记录函数
|
||||
*
|
||||
*
|
||||
* @param [in] seq 从指定的seq开始拉取消息,注意的是返回的消息从seq+1开始返回,seq为之前接口返回的最大seq值。首次使用请使用seq:0
|
||||
* @param [in] limit 一次拉取的消息条数,最大值1000条,超过1000条会返回错误
|
||||
* @param [in] proxy 使用代理的请求,需要传入代理的链接。如:socks5://10.0.0.1:8081 或者 http://10.0.0.1:8081
|
||||
* @param [in] passwd 代理账号密码,需要传入代理的账号密码。如 user_name:passwd_123
|
||||
* @param [in] timeout 超时时间,单位秒
|
||||
* @return chatDatas 返回本次拉取消息的数据,slice结构体.内容包括errcode/errmsg,以及每条消息内容。示例如下:
|
||||
|
||||
{"errcode":0,"errmsg":"ok","chatdata":[{"seq":196,"msgid":"CAQQ2fbb4QUY0On2rYSAgAMgip/yzgs=","publickey_ver":3,"encrypt_random_key":"ftJ+uz3n/z1DsxlkwxNgE+mL38H42/KCvN8T60gbbtPD+Rta1hKTuQPzUzO6Hzne97MgKs7FfdDxDck/v8cDT6gUVjA2tZ/M7euSD0L66opJ/IUeBtpAtvgVSD5qhlaQjvfKJc/zPMGNK2xCLFYqwmQBZXbNT7uA69Fflm512nZKW/piK2RKdYJhRyvQnA1ISxK097sp9WlEgDg250fM5tgwMjujdzr7ehK6gtVBUFldNSJS7ndtIf6aSBfaLktZgwHZ57ONewWq8GJe7WwQf1hwcDbCh7YMG8nsweEwhDfUz+u8rz9an+0lgrYMZFRHnmzjgmLwrR7B/32Qxqd79A==","encrypt_chat_msg":"898WSfGMnIeytTsea7Rc0WsOocs0bIAerF6de0v2cFwqo9uOxrW9wYe5rCjCHHH5bDrNvLxBE/xOoFfcwOTYX0HQxTJaH0ES9OHDZ61p8gcbfGdJKnq2UU4tAEgGb8H+Q9n8syRXIjaI3KuVCqGIi4QGHFmxWenPFfjF/vRuPd0EpzUNwmqfUxLBWLpGhv+dLnqiEOBW41Zdc0OO0St6E+JeIeHlRZAR+E13Isv9eS09xNbF0qQXWIyNUi+ucLr5VuZnPGXBrSfvwX8f0QebTwpy1tT2zvQiMM2MBugKH6NuMzzuvEsXeD+6+3VRqL"}]}
|
||||
*/
|
||||
func (s *Client) GetRawChatData(seq uint64, limit uint64, proxy string, passwd string, timeout int) (ChatDataResponse, error) {
|
||||
proxyC := C.CString(proxy)
|
||||
passwdC := C.CString(passwd)
|
||||
chatSlice := C.NewSlice()
|
||||
defer func() {
|
||||
C.free(unsafe.Pointer(proxyC))
|
||||
C.free(unsafe.Pointer(passwdC))
|
||||
C.FreeSlice(chatSlice)
|
||||
}()
|
||||
|
||||
if s.ptr == nil {
|
||||
return ChatDataResponse{}, NewSDKErr(10002)
|
||||
}
|
||||
|
||||
retC := C.GetChatData(s.ptr, C.ulonglong(seq), C.uint(limit), proxyC, passwdC, C.int(timeout), chatSlice)
|
||||
ret := int(retC)
|
||||
if ret != 0 {
|
||||
return ChatDataResponse{}, NewSDKErr(ret)
|
||||
}
|
||||
buf := s.GetContentFromSlice(chatSlice)
|
||||
|
||||
var data ChatDataResponse
|
||||
err := json.Unmarshal(buf, &data)
|
||||
if err != nil {
|
||||
return ChatDataResponse{}, err
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// DecryptData 解析密文.企业微信自有解密内容
|
||||
/**
|
||||
* @brief 解析密文.企业微信自有解密内容
|
||||
* @param [in] encrypt_key, getchatdata返回的encrypt_random_key,使用企业自持对应版本秘钥RSA解密后的内容
|
||||
* @param [in] encrypt_msg, getchatdata返回的encrypt_chat_msg
|
||||
* @param [out] msg, 解密的消息明文
|
||||
* @return 返回是否调用成功
|
||||
* 0 - 成功
|
||||
* !=0 - 失败
|
||||
*/
|
||||
func (s *Client) DecryptData(encryptRandomKey string, encryptMsg string) (msg ChatMessage, err error) {
|
||||
encryptKey, err := util.RSADecryptBase64(s.privateKey, encryptRandomKey)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
encryptKeyC := C.CString(string(encryptKey))
|
||||
encryptMsgC := C.CString(encryptMsg)
|
||||
msgSlice := C.NewSlice()
|
||||
defer func() {
|
||||
C.free(unsafe.Pointer(encryptKeyC))
|
||||
C.free(unsafe.Pointer(encryptMsgC))
|
||||
C.FreeSlice(msgSlice)
|
||||
}()
|
||||
|
||||
retC := C.DecryptData(encryptKeyC, encryptMsgC, msgSlice)
|
||||
ret := int(retC)
|
||||
if ret != 0 {
|
||||
return msg, NewSDKErr(ret)
|
||||
}
|
||||
buf := s.GetContentFromSlice(msgSlice)
|
||||
|
||||
// handle illegal escape character in text
|
||||
for i := 0; i < len(buf); {
|
||||
if buf[i] < 0x20 {
|
||||
buf = append(buf[:i], buf[i+1:]...)
|
||||
continue
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
var baseMessage BaseMessage
|
||||
err = json.Unmarshal(buf, &baseMessage)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
|
||||
msg.ID = baseMessage.MsgID
|
||||
msg.From = baseMessage.From
|
||||
msg.ToList = baseMessage.ToList
|
||||
msg.Action = baseMessage.Action
|
||||
msg.Type = baseMessage.MsgType
|
||||
msg.originData = buf
|
||||
return msg, err
|
||||
}
|
||||
|
||||
// GetMediaData 拉取媒体消息函数
|
||||
/**
|
||||
* 拉取媒体消息函数
|
||||
* Return值=0表示该API调用成功
|
||||
*
|
||||
*
|
||||
* @param [in] sdk NewSdk返回的sdk指针
|
||||
* @param [in] sdkFileid 从GetChatData返回的聊天消息中,媒体消息包括的sdkfileid
|
||||
* @param [in] proxy 使用代理的请求,需要传入代理的链接。如:socks5://10.0.0.1:8081 或者 http://10.0.0.1:8081
|
||||
* @param [in] passwd 代理账号密码,需要传入代理的账号密码。如 user_name:passwd_123
|
||||
* @param [in] indexbuf 媒体消息分片拉取,需要填入每次拉取的索引信息。首次不需要填写,默认拉取512k,后续每次调用只需要将上次调用返回的outindexbuf填入即可。
|
||||
* @param [in] timeout 超时时间,单位秒
|
||||
* @param [out] media_data 返回本次拉取的媒体数据.MediaData结构体.内容包括data(数据内容)/outindexbuf(下次索引)/is_finish(拉取完成标记)
|
||||
|
||||
*
|
||||
* @return 返回是否调用成功
|
||||
* 0 - 成功
|
||||
* !=0 - 失败
|
||||
*/
|
||||
func (s *Client) GetMediaData(indexBuf string, sdkFileID string, proxy string, passwd string, timeout int) (*MediaData, error) {
|
||||
indexBufC := C.CString(indexBuf)
|
||||
sdkFileIDC := C.CString(sdkFileID)
|
||||
proxyC := C.CString(proxy)
|
||||
passwdC := C.CString(passwd)
|
||||
mediaDataC := C.NewMediaData()
|
||||
defer func() {
|
||||
C.free(unsafe.Pointer(indexBufC))
|
||||
C.free(unsafe.Pointer(sdkFileIDC))
|
||||
C.free(unsafe.Pointer(proxyC))
|
||||
C.free(unsafe.Pointer(passwdC))
|
||||
C.FreeMediaData(mediaDataC)
|
||||
}()
|
||||
|
||||
if s.ptr == nil {
|
||||
return nil, NewSDKErr(10002)
|
||||
}
|
||||
|
||||
retC := C.GetMediaData(s.ptr, indexBufC, sdkFileIDC, proxyC, passwdC, C.int(timeout), mediaDataC)
|
||||
ret := int(retC)
|
||||
if ret != 0 {
|
||||
return nil, NewSDKErr(ret)
|
||||
}
|
||||
return &MediaData{
|
||||
OutIndexBuf: C.GoString(C.GetOutIndexBuf(mediaDataC)),
|
||||
Data: C.GoBytes(unsafe.Pointer(C.GetData(mediaDataC)), C.GetDataLen(mediaDataC)),
|
||||
IsFinish: int(C.IsMediaDataFinish(mediaDataC)) == 1,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetContentFromSlice 从切片内获取内容
|
||||
func (s *Client) GetContentFromSlice(slice *C.struct_Slice_t) []byte {
|
||||
return C.GoBytes(unsafe.Pointer(C.GetContentFromSlice(slice)), C.GetSliceLen(slice))
|
||||
}
|
||||
19
work/msgaudit/client_unsupport.go
Normal file
19
work/msgaudit/client_unsupport.go
Normal file
@@ -0,0 +1,19 @@
|
||||
// +build !linux linux,!cgo
|
||||
|
||||
//Package msgaudit for unsupport platform
|
||||
package msgaudit
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/work/config"
|
||||
)
|
||||
|
||||
// Client 会话存档
|
||||
type Client struct {
|
||||
}
|
||||
|
||||
// NewClient new
|
||||
func NewClient(cfg *config.Config) (*Client, error) {
|
||||
return nil, fmt.Errorf("会话存档功能目前只支持Linux平台运行,并且打开设置CGO_ENABLED=1")
|
||||
}
|
||||
8
work/msgaudit/config.go
Normal file
8
work/msgaudit/config.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package msgaudit
|
||||
|
||||
// Config 会话存档初始化参数
|
||||
type Config struct {
|
||||
CorpID string // 调用企业的企业id,例如:wwd08c8exxxx5ab44d,可以在企业微信管理端--我的企业--企业信息查看
|
||||
CorpSecret string // 聊天内容存档的Secret,可以在企业微信管理端--管理工具--聊天内容存档查看
|
||||
RasPrivateKey string // 消息加密私钥,可以在企业微信管理端--管理工具--消息加密公钥查看对用公钥,私钥一般由自己保存
|
||||
}
|
||||
76
work/msgaudit/error.go
Normal file
76
work/msgaudit/error.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package msgaudit
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
//返回码 错误说明
|
||||
//10000 参数错误,请求参数错误
|
||||
//10001 网络错误,网络请求错误
|
||||
//10002 数据解析失败
|
||||
//10003 系统失败
|
||||
//10004 密钥错误导致加密失败
|
||||
//10005 fileid错误
|
||||
//10006 解密失败
|
||||
//10007 找不到消息加密版本的私钥,需要重新传入私钥对
|
||||
//10008 解析encrypt_key出错
|
||||
//10009 ip非法
|
||||
//10010 数据过期
|
||||
//10011 证书错误
|
||||
const (
|
||||
SDKErrMsg = "sdk failed"
|
||||
SDKParamsErrMsg = "参数错误,请求参数错误"
|
||||
SDKNetworkErrMsg = "网络错误,网络请求错误"
|
||||
SDKParseErrMsg = "数据解析失败"
|
||||
SDKSystemErrMsg = "系统失败"
|
||||
SDKSecretErrMsg = "密钥错误导致加密失败"
|
||||
SDKFileIDErrMsg = "fileid错误"
|
||||
SDKDecryptErrMsg = "解密失败"
|
||||
SDKSecretMissErrMsg = "找不到消息加密版本的私钥,需要重新传入私钥对"
|
||||
SDKEncryptKeyErrMsg = "解析encrypt_key出错"
|
||||
SDKIPNotWhiteListErrMsg = "ip非法"
|
||||
SDKDataExpiredErrMsg = "数据过期"
|
||||
SDKTokenExpiredErrMsg = "证书过期"
|
||||
)
|
||||
|
||||
// Error 错误
|
||||
type Error struct {
|
||||
ErrCode int `json:"errcode,omitempty"`
|
||||
ErrMsg string `json:"errmsg,omitempty"`
|
||||
}
|
||||
|
||||
func (e Error) Error() string {
|
||||
return fmt.Sprintf("%d:%s", e.ErrCode, e.ErrMsg)
|
||||
}
|
||||
|
||||
// NewSDKErr 初始化新的SDK错误
|
||||
func NewSDKErr(code int) Error {
|
||||
msg := ""
|
||||
switch code {
|
||||
case 10000:
|
||||
msg = SDKParamsErrMsg
|
||||
case 10001:
|
||||
msg = SDKNetworkErrMsg
|
||||
case 10002:
|
||||
msg = SDKParseErrMsg
|
||||
case 10003:
|
||||
msg = SDKSystemErrMsg
|
||||
case 10004:
|
||||
msg = SDKSecretErrMsg
|
||||
case 10005:
|
||||
msg = SDKFileIDErrMsg
|
||||
case 10006:
|
||||
msg = SDKDecryptErrMsg
|
||||
case 10007:
|
||||
msg = SDKSecretMissErrMsg
|
||||
case 10008:
|
||||
msg = SDKEncryptKeyErrMsg
|
||||
case 10009:
|
||||
msg = SDKIPNotWhiteListErrMsg
|
||||
case 10010:
|
||||
msg = SDKDataExpiredErrMsg
|
||||
case 10011:
|
||||
msg = SDKTokenExpiredErrMsg
|
||||
}
|
||||
return Error{ErrCode: code, ErrMsg: msg}
|
||||
}
|
||||
152
work/msgaudit/lib/WeWorkFinanceSdk_C.h
Normal file
152
work/msgaudit/lib/WeWorkFinanceSdk_C.h
Normal file
@@ -0,0 +1,152 @@
|
||||
// All Rights Reserved.
|
||||
// *File : WeWorkFinanceSdk_C.h
|
||||
// @Brief:拉取企业聊天记录与媒体消息sdk头文件
|
||||
|
||||
#pragma once
|
||||
//返回码 错误说明
|
||||
//10000 参数错误,请求参数错误
|
||||
//10001 网络错误,网络请求错误
|
||||
//10002 数据解析失败
|
||||
//10003 系统失败
|
||||
//10004 密钥错误导致加密失败
|
||||
//10005 fileid错误
|
||||
//10006 解密失败
|
||||
//10007 找不到消息加密版本的私钥,需要重新传入私钥对
|
||||
//10008 解析encrypt_key出错
|
||||
//10009 ip非法
|
||||
//10010 数据过期
|
||||
//10011 证书错误
|
||||
|
||||
typedef struct WeWorkFinanceSdk_t WeWorkFinanceSdk_t;
|
||||
|
||||
// 数据
|
||||
typedef struct Slice_t {
|
||||
char* buf;
|
||||
int len;
|
||||
} Slice_t;
|
||||
|
||||
typedef struct MediaData {
|
||||
char* outindexbuf;
|
||||
int out_len;
|
||||
char* data;
|
||||
int data_len;
|
||||
int is_finish;
|
||||
} MediaData_t;
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
WeWorkFinanceSdk_t* NewSdk();
|
||||
|
||||
|
||||
/**
|
||||
* 初始化函数
|
||||
* Return值=0表示该API调用成功
|
||||
*
|
||||
* @param [in] sdk NewSdk返回的sdk指针
|
||||
* @param [in] corpid 调用企业的企业id,例如:wwd08c8exxxx5ab44d,可以在企业微信管理端--我的企业--企业信息查看
|
||||
* @param [in] secret 聊天内容存档的Secret,可以在企业微信管理端--管理工具--聊天内容存档查看
|
||||
*
|
||||
*
|
||||
* @return 返回是否初始化成功
|
||||
* 0 - 成功
|
||||
* !=0 - 失败
|
||||
*/
|
||||
int Init(WeWorkFinanceSdk_t* sdk, const char* corpid, const char* secret);
|
||||
|
||||
/**
|
||||
* 拉取聊天记录函数
|
||||
* Return值=0表示该API调用成功
|
||||
*
|
||||
*
|
||||
* @param [in] sdk NewSdk返回的sdk指针
|
||||
* @param [in] seq 从指定的seq开始拉取消息,注意的是返回的消息从seq+1开始返回,seq为之前接口返回的最大seq值。首次使用请使用seq:0
|
||||
* @param [in] limit 一次拉取的消息条数,最大值1000条,超过1000条会返回错误
|
||||
* @param [in] proxy 使用代理的请求,需要传入代理的链接。如:socks5://10.0.0.1:8081 或者 http://10.0.0.1:8081
|
||||
* @param [in] passwd 代理账号密码,需要传入代理的账号密码。如 user_name:passwd_123
|
||||
* @param [in] timeout 超时时间,单位秒
|
||||
* @param [out] chatDatas 返回本次拉取消息的数据,slice结构体.内容包括errcode/errmsg,以及每条消息内容。示例如下:
|
||||
|
||||
{"errcode":0,"errmsg":"ok","chatdata":[{"seq":196,"msgid":"CAQQ2fbb4QUY0On2rYSAgAMgip/yzgs=","publickey_ver":3,"encrypt_random_key":"ftJ+uz3n/z1DsxlkwxNgE+mL38H42/KCvN8T60gbbtPD+Rta1hKTuQPzUzO6Hzne97MgKs7FfdDxDck/v8cDT6gUVjA2tZ/M7euSD0L66opJ/IUeBtpAtvgVSD5qhlaQjvfKJc/zPMGNK2xCLFYqwmQBZXbNT7uA69Fflm512nZKW/piK2RKdYJhRyvQnA1ISxK097sp9WlEgDg250fM5tgwMjujdzr7ehK6gtVBUFldNSJS7ndtIf6aSBfaLktZgwHZ57ONewWq8GJe7WwQf1hwcDbCh7YMG8nsweEwhDfUz+u8rz9an+0lgrYMZFRHnmzjgmLwrR7B/32Qxqd79A==","encrypt_chat_msg":"898WSfGMnIeytTsea7Rc0WsOocs0bIAerF6de0v2cFwqo9uOxrW9wYe5rCjCHHH5bDrNvLxBE/xOoFfcwOTYX0HQxTJaH0ES9OHDZ61p8gcbfGdJKnq2UU4tAEgGb8H+Q9n8syRXIjaI3KuVCqGIi4QGHFmxWenPFfjF/vRuPd0EpzUNwmqfUxLBWLpGhv+dLnqiEOBW41Zdc0OO0St6E+JeIeHlRZAR+E13Isv9eS09xNbF0qQXWIyNUi+ucLr5VuZnPGXBrSfvwX8f0QebTwpy1tT2zvQiMM2MBugKH6NuMzzuvEsXeD+6+3VRqL"}]}
|
||||
|
||||
*
|
||||
* @return 返回是否调用成功
|
||||
* 0 - 成功
|
||||
* !=0 - 失败
|
||||
*/
|
||||
int GetChatData(WeWorkFinanceSdk_t* sdk, unsigned long long seq, unsigned int limit, const char *proxy,const char* passwd, int timeout,Slice_t* chatDatas);
|
||||
|
||||
/**
|
||||
* @brief 解析密文.企业微信自有解密内容
|
||||
* @param [in] encrypt_key, getchatdata返回的encrypt_random_key,使用企业自持对应版本秘钥RSA解密后的内容
|
||||
* @param [in] encrypt_msg, getchatdata返回的encrypt_chat_msg
|
||||
* @param [out] msg, 解密的消息明文
|
||||
* @return 返回是否调用成功
|
||||
* 0 - 成功
|
||||
* !=0 - 失败
|
||||
*/
|
||||
int DecryptData(const char* encrypt_key, const char* encrypt_msg, Slice_t* msg);
|
||||
|
||||
/**
|
||||
* 拉取媒体消息函数
|
||||
* Return值=0表示该API调用成功
|
||||
*
|
||||
*
|
||||
* @param [in] sdk NewSdk返回的sdk指针
|
||||
* @param [in] sdkFileid 从GetChatData返回的聊天消息中,媒体消息包括的sdkfileid
|
||||
* @param [in] proxy 使用代理的请求,需要传入代理的链接。如:socks5://10.0.0.1:8081 或者 http://10.0.0.1:8081
|
||||
* @param [in] passwd 代理账号密码,需要传入代理的账号密码。如 user_name:passwd_123
|
||||
* @param [in] indexbuf 媒体消息分片拉取,需要填入每次拉取的索引信息。首次不需要填写,默认拉取512k,后续每次调用只需要将上次调用返回的outindexbuf填入即可。
|
||||
* @param [in] timeout 超时时间,单位秒
|
||||
* @param [out] media_data 返回本次拉取的媒体数据.MediaData结构体.内容包括data(数据内容)/outindexbuf(下次索引)/is_finish(拉取完成标记)
|
||||
|
||||
*
|
||||
* @return 返回是否调用成功
|
||||
* 0 - 成功
|
||||
* !=0 - 失败
|
||||
*/
|
||||
int GetMediaData(WeWorkFinanceSdk_t* sdk, const char* indexbuf,
|
||||
const char* sdkFileid,const char *proxy,const char* passwd, int timeout, MediaData_t* media_data);
|
||||
|
||||
/**
|
||||
* @brief 释放sdk,和NewSdk成对使用
|
||||
* @return
|
||||
*/
|
||||
void DestroySdk(WeWorkFinanceSdk_t* sdk);
|
||||
|
||||
|
||||
//--------------下面接口为了其他语言例如python等调用c接口,酌情使用--------------
|
||||
Slice_t* NewSlice();
|
||||
|
||||
/**
|
||||
* @brief 释放slice,和NewSlice成对使用
|
||||
* @return
|
||||
*/
|
||||
void FreeSlice(Slice_t* slice);
|
||||
|
||||
/**
|
||||
* @brief 为其他语言提供读取接口
|
||||
* @return 返回buf指针
|
||||
* !=NULL - 成功
|
||||
* NULL - 失败
|
||||
*/
|
||||
char* GetContentFromSlice(Slice_t* slice);
|
||||
int GetSliceLen(Slice_t* slice);
|
||||
|
||||
// 媒体记录相关工具
|
||||
|
||||
MediaData_t* NewMediaData();
|
||||
|
||||
void FreeMediaData(MediaData_t* media_data);
|
||||
|
||||
char* GetOutIndexBuf(MediaData_t* media_data);
|
||||
char* GetData(MediaData_t* media_data);
|
||||
int GetIndexLen(MediaData_t* media_data);
|
||||
int GetDataLen(MediaData_t* media_data);
|
||||
int IsMediaDataFinish(MediaData_t* media_data);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
BIN
work/msgaudit/lib/libWeWorkFinanceSdk_C.so
Normal file
BIN
work/msgaudit/lib/libWeWorkFinanceSdk_C.so
Normal file
Binary file not shown.
1
work/msgaudit/lib/md5.txt
Normal file
1
work/msgaudit/lib/md5.txt
Normal file
@@ -0,0 +1 @@
|
||||
781ec3cbad904b1527023cc9df0f279b
|
||||
148
work/msgaudit/lib/tool_testSdk.cpp
Normal file
148
work/msgaudit/lib/tool_testSdk.cpp
Normal file
@@ -0,0 +1,148 @@
|
||||
#include "WeWorkFinanceSdk_C.h"
|
||||
#include <dlfcn.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string>
|
||||
using std::string;
|
||||
|
||||
typedef WeWorkFinanceSdk_t* newsdk_t();
|
||||
typedef int Init_t(WeWorkFinanceSdk_t*, const char*, const char*);
|
||||
typedef void DestroySdk_t(WeWorkFinanceSdk_t*);
|
||||
|
||||
typedef int GetChatData_t(WeWorkFinanceSdk_t*, unsigned long long, unsigned int, const char*, const char*, int, Slice_t*);
|
||||
typedef Slice_t* NewSlice_t();
|
||||
typedef void FreeSlice_t(Slice_t*);
|
||||
|
||||
typedef int GetMediaData_t(WeWorkFinanceSdk_t*, const char*, const char*, const char*, const char*, int, MediaData_t*);
|
||||
typedef int DecryptData_t(const char*, const char*, Slice_t*);
|
||||
typedef MediaData_t* NewMediaData_t();
|
||||
typedef void FreeMediaData_t(MediaData_t*);
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
int ret = 0;
|
||||
//seq 表示该企业存档消息序号,该序号单调递增,拉取序号建议设置为上次拉取返回结果中最大序号。首次拉取时seq传0,sdk会返回有效期内最早的消息。
|
||||
//limit 表示本次拉取的最大消息条数,取值范围为1~1000
|
||||
//proxy与passwd为代理参数,如果运行sdk的环境不能直接访问外网,需要配置代理参数。sdk访问的域名是"https://qyapi.weixin.qq.com"。
|
||||
//建议先通过curl访问"https://qyapi.weixin.qq.com",验证代理配置正确后,再传入sdk。
|
||||
//timeout 为拉取会话存档的超时时间,单位为秒,建议超时时间设置为5s。
|
||||
//sdkfileid 媒体文件id,从解密后的会话存档中得到
|
||||
//savefile 媒体文件保存路径
|
||||
//encrypt_key 拉取会话存档返回的encrypt_random_key,使用配置在企业微信管理台的rsa公钥对应的私钥解密后得到encrypt_key。
|
||||
//encrypt_chat_msg 拉取会话存档返回的encrypt_chat_msg
|
||||
if (argc < 2) {
|
||||
printf("./sdktools 1(chatmsg) 2(mediadata) 3(decryptdata)\n");
|
||||
printf("./sdktools 1 seq limit proxy passwd timeout\n");
|
||||
printf("./sdktools 2 fileid proxy passwd timeout savefile\n");
|
||||
printf("./sdktools 3 encrypt_key encrypt_chat_msg\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
void* so_handle = dlopen("./libWeWorkFinanceSdk_C.so", RTLD_LAZY);
|
||||
if (!so_handle) {
|
||||
printf("load sdk so fail:%s\n", dlerror());
|
||||
return -1;
|
||||
}
|
||||
newsdk_t* newsdk_fn = (newsdk_t*)dlsym(so_handle, "NewSdk");
|
||||
WeWorkFinanceSdk_t* sdk = newsdk_fn();
|
||||
|
||||
//使用sdk前需要初始化,初始化成功后的sdk可以一直使用。
|
||||
//如需并发调用sdk,建议每个线程持有一个sdk实例。
|
||||
//初始化时请填入自己企业的corpid与secrectkey。
|
||||
Init_t* init_fn = (Init_t*)dlsym(so_handle, "Init");
|
||||
DestroySdk_t* destroysdk_fn = (DestroySdk_t*)dlsym(so_handle, "DestroySdk");
|
||||
ret = init_fn(sdk, "wwd08c8e7c775ab44d", "zJ6k0naVVQ--gt9PUSSEvs03zW_nlDVmjLCTOTAfrew");
|
||||
if (ret != 0) {
|
||||
//sdk需要主动释放
|
||||
destroysdk_fn(sdk);
|
||||
printf("init sdk err ret:%d\n", ret);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int type = strtoul(argv[1], NULL, 10);
|
||||
if (type == 1) {
|
||||
//拉取会话存档
|
||||
uint64_t iSeq = strtoul(argv[2], NULL, 10);
|
||||
uint64_t iLimit = strtoul(argv[3], NULL, 10);
|
||||
uint64_t timeout = strtoul(argv[6], NULL, 10);
|
||||
|
||||
NewSlice_t* newslice_fn = (NewSlice_t*)dlsym(so_handle, "NewSlice");
|
||||
FreeSlice_t* freeslice_fn = (FreeSlice_t*)dlsym(so_handle, "FreeSlice");
|
||||
|
||||
//每次使用GetChatData拉取存档前需要调用NewSlice获取一个chatDatas,在使用完chatDatas中数据后,还需要调用FreeSlice释放。
|
||||
Slice_t* chatDatas = newslice_fn();
|
||||
GetChatData_t* getchatdata_fn = (GetChatData_t*)dlsym(so_handle, "GetChatData");
|
||||
ret = getchatdata_fn(sdk, iSeq, iLimit, argv[4], argv[5], timeout, chatDatas);
|
||||
if (ret != 0) {
|
||||
freeslice_fn(chatDatas);
|
||||
printf("GetChatData err ret:%d\n", ret);
|
||||
return -1;
|
||||
}
|
||||
printf("GetChatData len:%d data:%s\n", chatDatas->len, chatDatas->buf);
|
||||
freeslice_fn(chatDatas);
|
||||
}
|
||||
else if (type == 2) {
|
||||
//拉取媒体文件
|
||||
std::string index;
|
||||
uint64_t timeout = strtoul(argv[5], NULL, 10);
|
||||
int isfinish = 0;
|
||||
|
||||
GetMediaData_t* getmediadata_fn = (GetMediaData_t*)dlsym(so_handle, "GetMediaData");
|
||||
NewMediaData_t* newmediadata_fn = (NewMediaData_t*)dlsym(so_handle, "NewMediaData");
|
||||
FreeMediaData_t* freemediadata_fn = (FreeMediaData_t*)dlsym(so_handle, "FreeMediaData");
|
||||
|
||||
//媒体文件每次拉取的最大size为512k,因此超过512k的文件需要分片拉取。若该文件未拉取完整,mediaData中的is_finish会返回0,同时mediaData中的outindexbuf会返回下次拉取需要传入GetMediaData的indexbuf。
|
||||
//indexbuf一般格式如右侧所示,”Range:bytes=524288-1048575“,表示这次拉取的是从524288到1048575的分片。单个文件首次拉取填写的indexbuf为空字符串,拉取后续分片时直接填入上次返回的indexbuf即可。
|
||||
while (isfinish == 0) {
|
||||
//每次使用GetMediaData拉取存档前需要调用NewMediaData获取一个mediaData,在使用完mediaData中数据后,还需要调用FreeMediaData释放。
|
||||
printf("index:%s\n", index.c_str());
|
||||
MediaData_t* mediaData = newmediadata_fn();
|
||||
ret = getmediadata_fn(sdk, index.c_str(), argv[2], argv[3], argv[4], timeout, mediaData);
|
||||
if (ret != 0) {
|
||||
//单个分片拉取失败建议重试拉取该分片,避免从头开始拉取。
|
||||
freemediadata_fn(mediaData);
|
||||
printf("GetMediaData err ret:%d\n", ret);
|
||||
return -1;
|
||||
}
|
||||
printf("content size:%d isfin:%d outindex:%s\n", mediaData->data_len, mediaData->is_finish, mediaData->outindexbuf);
|
||||
|
||||
//大于512k的文件会分片拉取,此处需要使用追加写,避免后面的分片覆盖之前的数据。
|
||||
char file[200];
|
||||
snprintf(file, sizeof(file), "%s", argv[6]);
|
||||
FILE* fp = fopen(file, "ab+");
|
||||
printf("filename:%s \n", file);
|
||||
if (NULL == fp) {
|
||||
freemediadata_fn(mediaData);
|
||||
printf("open file err\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
fwrite(mediaData->data, mediaData->data_len, 1, fp);
|
||||
fclose(fp);
|
||||
|
||||
//获取下次拉取需要使用的indexbuf
|
||||
index.assign(string(mediaData->outindexbuf));
|
||||
isfinish = mediaData->is_finish;
|
||||
freemediadata_fn(mediaData);
|
||||
}
|
||||
}
|
||||
else if (type == 3) {
|
||||
//解密会话存档内容
|
||||
//sdk不会要求用户传入rsa私钥,保证用户会话存档数据只有自己能够解密。
|
||||
//此处需要用户先用rsa私钥解密encrypt_random_key后,作为encrypt_key参数传入sdk来解密encrypt_chat_msg获取会话存档明文。
|
||||
//每次使用DecryptData解密会话存档前需要调用NewSlice获取一个Msgs,在使用完Msgs中数据后,还需要调用FreeSlice释放。
|
||||
NewSlice_t* newslice_fn = (NewSlice_t*)dlsym(so_handle, "NewSlice");
|
||||
FreeSlice_t* freeslice_fn = (FreeSlice_t*)dlsym(so_handle, "FreeSlice");
|
||||
|
||||
Slice_t* Msgs = newslice_fn();
|
||||
// decryptdata api
|
||||
DecryptData_t* decryptdata_fn = (DecryptData_t*)dlsym(so_handle, "DecryptData");
|
||||
ret = decryptdata_fn(argv[2], argv[3], Msgs);
|
||||
printf("chatdata :%s ret :%d\n", Msgs->buf, ret);
|
||||
|
||||
freeslice_fn(Msgs);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
1
work/msgaudit/lib/version.txt
Normal file
1
work/msgaudit/lib/version.txt
Normal file
@@ -0,0 +1 @@
|
||||
200215
|
||||
8
work/msgaudit/media.go
Normal file
8
work/msgaudit/media.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package msgaudit
|
||||
|
||||
// MediaData 媒体文件数据
|
||||
type MediaData struct {
|
||||
OutIndexBuf string `json:"outindexbuf,omitempty"`
|
||||
IsFinish bool `json:"is_finish,omitempty"`
|
||||
Data []byte `json:"data,omitempty"`
|
||||
}
|
||||
352
work/msgaudit/message.go
Normal file
352
work/msgaudit/message.go
Normal file
@@ -0,0 +1,352 @@
|
||||
package msgaudit
|
||||
|
||||
// BaseMessage 基础消息
|
||||
type BaseMessage struct {
|
||||
MsgID string `json:"msgid,omitempty"` // 消息id,消息的唯一标识,企业可以使用此字段进行消息去重。
|
||||
Action string `json:"action,omitempty"` // 消息动作,目前有send(发送消息)/recall(撤回消息)/switch(切换企业日志)三种类型。
|
||||
From string `json:"from,omitempty"` // 消息发送方id。同一企业内容为userid,非相同企业为external_userid。消息如果是机器人发出,也为external_userid。
|
||||
ToList []string `json:"tolist,omitempty"` // 消息接收方列表,可能是多个,同一个企业内容为userid,非相同企业为external_userid。
|
||||
RoomID string `json:"roomid,omitempty"` // 群聊消息的群id。如果是单聊则为空。
|
||||
MsgTime int64 `json:"msgtime,omitempty"` // 消息发送时间戳,utc时间,ms单位。
|
||||
MsgType string `json:"msgtype,omitempty"` // 文本消息为:text。
|
||||
}
|
||||
|
||||
// TextMessage 文本消息
|
||||
type TextMessage struct {
|
||||
BaseMessage
|
||||
Text struct {
|
||||
Content string `json:"content,omitempty"` // 消息内容。
|
||||
} `json:"text,omitempty"`
|
||||
}
|
||||
|
||||
// ImageMessage 图片消息
|
||||
type ImageMessage struct {
|
||||
BaseMessage
|
||||
Image struct {
|
||||
SdkFileID string `json:"sdkfileid,omitempty"` // 媒体资源的id信息。
|
||||
Md5Sum string `json:"md5sum,omitempty"` // 图片资源的md5值,供进行校验。
|
||||
FileSize uint32 `json:"filesize,omitempty"` // 图片资源的文件大小。
|
||||
} `json:"image,omitempty"`
|
||||
}
|
||||
|
||||
// RevokeMessage 撤回消息
|
||||
type RevokeMessage struct {
|
||||
BaseMessage
|
||||
Revoke struct {
|
||||
PreMsgID string `json:"pre_msgid,omitempty"` // 标识撤回的原消息的msgid
|
||||
} `json:"revoke,omitempty"`
|
||||
}
|
||||
|
||||
// AgreeMessage 同意会话聊天内容
|
||||
type AgreeMessage struct {
|
||||
BaseMessage
|
||||
Agree struct {
|
||||
UserID string `json:"userid,omitempty"` // 同意/不同意协议者的userid,外部企业默认为external_userid。
|
||||
AgreeTime int64 `json:"agree_time,omitempty"` // 同意/不同意协议的时间,utc时间,ms单位。
|
||||
} `json:"agree,omitempty"`
|
||||
}
|
||||
|
||||
// VoiceMessage 语音消息
|
||||
type VoiceMessage struct {
|
||||
BaseMessage
|
||||
Voice struct {
|
||||
SdkFileID string `json:"sdkfileid,omitempty"` // 媒体资源的id信息。
|
||||
VoiceSize uint32 `json:"voice_size,omitempty"` // 语音消息大小。
|
||||
PlayLength uint32 `json:"play_length,omitempty"` // 播放长度。
|
||||
Md5Sum string `json:"md5sum,omitempty"` // 图片资源的md5值,供进行校验。
|
||||
} `json:"voice,omitempty"`
|
||||
}
|
||||
|
||||
// VideoMessage 视频消息
|
||||
type VideoMessage struct {
|
||||
BaseMessage
|
||||
Video struct {
|
||||
SdkFileID string `json:"sdkfileid,omitempty"` // 媒体资源的id信息。
|
||||
FileSize uint32 `json:"filesize,omitempty"` // 图片资源的文件大小。
|
||||
PlayLength uint32 `json:"play_length,omitempty"` // 播放长度。
|
||||
Md5Sum string `json:"md5sum,omitempty"` // 图片资源的md5值,供进行校验。
|
||||
} `json:"video,omitempty"`
|
||||
}
|
||||
|
||||
// CardMessage 名片消息
|
||||
type CardMessage struct {
|
||||
BaseMessage
|
||||
Card struct {
|
||||
CorpName string `json:"corpname,omitempty"` // 名片所有者所在的公司名称。
|
||||
UserID string `json:"userid,omitempty"` // 名片所有者的id,同一公司是userid,不同公司是external_userid
|
||||
} `json:"card,omitempty"`
|
||||
}
|
||||
|
||||
// LocationMessage 位置消息
|
||||
type LocationMessage struct {
|
||||
BaseMessage
|
||||
Location struct {
|
||||
Lng float64 `json:"longitude,omitempty"` // 经度,单位double
|
||||
Lat float64 `json:"latitude,omitempty"` // 纬度,单位double
|
||||
Address string `json:"address,omitempty"` // 地址信息
|
||||
Title string `json:"title,omitempty"` // 位置信息的title。
|
||||
Zoom uint32 `json:"zoom,omitempty"` // 缩放比例。
|
||||
} `json:"location,omitempty"`
|
||||
}
|
||||
|
||||
// EmotionMessage 表情消息
|
||||
type EmotionMessage struct {
|
||||
BaseMessage
|
||||
Emotion struct {
|
||||
Type uint32 `json:"type,omitempty"` // 表情类型,png或者gif.1表示gif 2表示png。
|
||||
Width uint32 `json:"width,omitempty"` // 表情图片宽度。
|
||||
Height uint32 `json:"height,omitempty"` // 表情图片高度。
|
||||
ImageSize uint32 `json:"imagesize,omitempty"` // 资源的文件大小。
|
||||
SdkFileID string `json:"sdkfileid,omitempty"` // 媒体资源的id信息。
|
||||
Md5Sum string `json:"md5sum,omitempty"` // 图片资源的md5值,供进行校验。
|
||||
} `json:"emotion,omitempty"`
|
||||
}
|
||||
|
||||
// FileMessage 文件消息
|
||||
type FileMessage struct {
|
||||
BaseMessage
|
||||
File struct {
|
||||
FileName string `json:"filename,omitempty"` // 文件名称。
|
||||
FileExt string `json:"fileext,omitempty"` // 文件类型后缀。
|
||||
SdkFileID string `json:"sdkfileid,omitempty"` // 媒体资源的id信息。
|
||||
FileSize uint32 `json:"filesize,omitempty"` // 文件大小。
|
||||
Md5Sum string `json:"md5sum,omitempty"` // 资源的md5值,供进行校验。
|
||||
} `json:"file,omitempty"`
|
||||
}
|
||||
|
||||
// LinkMessage 链接消息
|
||||
type LinkMessage struct {
|
||||
BaseMessage
|
||||
Link struct {
|
||||
Title string `json:"title,omitempty"` // 消息标题。
|
||||
Desc string `json:"description,omitempty"` // 消息描述。
|
||||
LinkURL string `json:"link_url,omitempty"` // 链接url地址
|
||||
ImageURL string `json:"image_url,omitempty"` // 链接图片url。
|
||||
} `json:"link,omitempty"`
|
||||
}
|
||||
|
||||
// WeappMessage 小程序消息
|
||||
type WeappMessage struct {
|
||||
BaseMessage
|
||||
WeApp struct {
|
||||
Title string `json:"title,omitempty"` // 消息标题。
|
||||
Desc string `json:"description,omitempty"` // 消息描述。
|
||||
Username string `json:"username,omitempty"` // 用户名称。
|
||||
DisplayName string `json:"displayname,omitempty"` // 小程序名称
|
||||
} `json:"weapp,omitempty"`
|
||||
}
|
||||
|
||||
// ChatRecordMessage 会话记录消息
|
||||
type ChatRecordMessage struct {
|
||||
BaseMessage
|
||||
ChatRecord struct {
|
||||
Title string `json:"title,omitempty"` // 聊天记录标题
|
||||
Item []ChatRecord `json:"item,omitempty"` // 消息记录内的消息内容,批量数据
|
||||
} `json:"chatrecord,omitempty"`
|
||||
}
|
||||
|
||||
// TodoMessage 待办消息
|
||||
type TodoMessage struct {
|
||||
BaseMessage
|
||||
Todo struct {
|
||||
Title string `json:"title,omitempty"` // 代办的来源文本
|
||||
Content string `json:"content,omitempty"` // 代办的具体内容
|
||||
} `json:"todo,omitempty"`
|
||||
}
|
||||
|
||||
// VoteMessage 投票消息
|
||||
type VoteMessage struct {
|
||||
BaseMessage
|
||||
VoteTitle string `json:"votetitle,omitempty"` // 投票主题。
|
||||
VoteItem []string `json:"voteitem,omitempty"` // 投票选项,可能多个内容。
|
||||
VoteType uint32 `json:"votetype,omitempty"` // 投票类型.101发起投票、102参与投票。
|
||||
VoteID string `json:"voteid,omitempty"` // 投票id,方便将参与投票消息与发起投票消息进行前后对照。
|
||||
}
|
||||
|
||||
// CollectMessage 填表消息
|
||||
type CollectMessage struct {
|
||||
BaseMessage
|
||||
Collect struct {
|
||||
RoomName string `json:"room_name,omitempty"` // 填表消息所在的群名称。
|
||||
Creator string `json:"creator,omitempty"` // 创建者在群中的名字
|
||||
CreateTime string `json:"create_time,omitempty"` // 创建的时间
|
||||
Details []CollectDetails `json:"details,omitempty"` // 表内容
|
||||
} `json:"collect,omitempty"`
|
||||
}
|
||||
|
||||
// RedpacketMessage 红包消息
|
||||
type RedpacketMessage struct {
|
||||
BaseMessage
|
||||
RedPacket struct {
|
||||
Type uint32 `json:"type,omitempty"` // 红包消息类型。1 普通红包、2 拼手气群红包、3 激励群红包。
|
||||
Wish string `json:"wish,omitempty"` // 红包祝福语
|
||||
TotalCnt uint32 `json:"totalcnt,omitempty"` // 红包总个数
|
||||
TotalAmount uint32 `json:"totalamount,omitempty"` // 红包总金额。单位为分。
|
||||
} `json:"redpacket,omitempty"`
|
||||
}
|
||||
|
||||
// MeetingMessage 会议邀请消息
|
||||
type MeetingMessage struct {
|
||||
BaseMessage
|
||||
Meeting struct {
|
||||
Topic string `json:"topic,omitempty"` // 会议主题
|
||||
StartTime int64 `json:"starttime,omitempty"` // 会议开始时间。Utc时间
|
||||
EndTime int64 `json:"endtime,omitempty"` // 会议结束时间。Utc时间
|
||||
Address string `json:"address,omitempty"` // 会议地址
|
||||
Remarks string `json:"remarks,omitempty"` // 会议备注
|
||||
MeetingType uint32 `json:"meetingtype,omitempty"` // 会议消息类型。101发起会议邀请消息、102处理会议邀请消息
|
||||
MeetingID uint64 `json:"meetingid,omitempty"` // 会议id。方便将发起、处理消息进行对照
|
||||
Status uint32 `json:"status,omitempty"` // 会议邀请处理状态。1 参加会议、2 拒绝会议、3 待定、4 未被邀请、5 会议已取消、6 会议已过期、7 不在房间内。
|
||||
} `json:"meeting,omitempty"`
|
||||
}
|
||||
|
||||
// DocMessage 在线文档消息
|
||||
type DocMessage struct {
|
||||
BaseMessage
|
||||
Doc struct {
|
||||
Title string `json:"title,omitempty"` // 在线文档名称
|
||||
LinkURL string `json:"link_url,omitempty"` // 在线文档链接
|
||||
DocCreator string `json:"doc_creator,omitempty"` // 在线文档创建者。本企业成员创建为userid;外部企业成员创建为external_userid
|
||||
} `json:"doc,omitempty"`
|
||||
}
|
||||
|
||||
// MarkdownMessage MarkDown消息
|
||||
type MarkdownMessage struct {
|
||||
BaseMessage
|
||||
Info struct {
|
||||
Content string `json:"content,omitempty"` // markdown消息内容,目前为机器人发出的消息
|
||||
} `json:"info,omitempty"`
|
||||
}
|
||||
|
||||
// NewsMessage 图文消息
|
||||
type NewsMessage struct {
|
||||
BaseMessage
|
||||
Info struct {
|
||||
Item []News `json:"item,omitempty"` // 图文消息数组
|
||||
} `json:"info,omitempty"` // 图文消息的内容
|
||||
}
|
||||
|
||||
// CalendarMessage 日程消息
|
||||
type CalendarMessage struct {
|
||||
BaseMessage
|
||||
Calendar struct {
|
||||
Title string `json:"title,omitempty"` // 日程主题
|
||||
CreatorName string `json:"creatorname,omitempty"` // 日程组织者
|
||||
AttendeeName []string `json:"attendeename,omitempty"` // 日程参与人。数组,内容为String类型
|
||||
StartTime int64 `json:"starttime,omitempty"` // 日程开始时间。Utc时间,单位秒
|
||||
EndTime int64 `json:"endtime,omitempty"` // 日程结束时间。Utc时间,单位秒
|
||||
Place string `json:"place,omitempty"` // 日程地点
|
||||
Remarks string `json:"remarks,omitempty"` // 日程备注
|
||||
} `json:"calendar,omitempty"`
|
||||
}
|
||||
|
||||
// MixedMessage 混合消息
|
||||
type MixedMessage struct {
|
||||
BaseMessage
|
||||
Mixed struct {
|
||||
Item []MixedMsg `json:"item,omitempty"`
|
||||
} `json:"mixed,omitempty"` // 消息内容。可包含图片、文字、表情等多种消息。Object类型
|
||||
}
|
||||
|
||||
// MeetingVoiceCallMessage 音频存档消息
|
||||
type MeetingVoiceCallMessage struct {
|
||||
BaseMessage
|
||||
VoiceID string `json:"voiceid,omitempty"` // 音频id
|
||||
MeetingVoiceCall *MeetingVoiceCall `json:"meeting_voice_call,omitempty"` // 音频消息内容。包括结束时间、fileid,可能包括多个demofiledata、sharescreendata消息,demofiledata表示文档共享信息,sharescreendata表示屏幕共享信息。Object类型
|
||||
}
|
||||
|
||||
// VoipDocShareMessage 音频共享消息
|
||||
type VoipDocShareMessage struct {
|
||||
BaseMessage
|
||||
VoipID string `json:"voipid,omitempty"` // 音频id
|
||||
VoipDocShare *VoipDocShare `json:"voip_doc_share,omitempty"` // 共享文档消息内容。包括filename、md5sum、filesize、sdkfileid字段。Object类型
|
||||
}
|
||||
|
||||
// ExternalRedPacketMessage 互通小红包消息
|
||||
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类型
|
||||
} `json:"redpacket,omitempty"`
|
||||
}
|
||||
|
||||
// SphFeedMessage 视频号消息
|
||||
type SphFeedMessage struct {
|
||||
BaseMessage
|
||||
SphFeed struct {
|
||||
FeedType string `json:"feed_type,omitempty"` // 视频号消息类型
|
||||
SphName string `json:"sph_name,omitempty"` // 视频号账号名称
|
||||
FeedDesc uint64 `json:"feed_desc,omitempty"` // 视频号账号名称
|
||||
}
|
||||
}
|
||||
|
||||
// SwitchMessage 企业切换日志
|
||||
type SwitchMessage struct {
|
||||
MsgID string `json:"msgid,omitempty"` // 消息id,消息的唯一标识,企业可以使用此字段进行消息去重
|
||||
Action string `json:"action,omitempty"` // 消息动作,切换企业为switch
|
||||
Time int64 `json:"time,omitempty"` // 消息发送时间戳,utc时间,ms单位。
|
||||
User string `json:"user,omitempty"` // 具体为切换企业的成员的userid。
|
||||
}
|
||||
|
||||
// ChatRecord 会话记录消息
|
||||
type ChatRecord struct {
|
||||
Type string `json:"type,omitempty"` // 每条聊天记录的具体消息类型:ChatRecordText/ ChatRecordFile/ ChatRecordImage/ ChatRecordVideo/ ChatRecordLink/ ChatRecordLocation/ ChatRecordMixed ….
|
||||
Content string `json:"content,omitempty"` // 消息内容。Json串,内容为对应类型的json
|
||||
MsgTime int64 `json:"msgtime,omitempty"` // 消息时间,utc时间,ms单位。
|
||||
FromChatroom bool `json:"from_chatroom,omitempty"` // 是否来自群会话。
|
||||
}
|
||||
|
||||
// CollectDetails 填表消息
|
||||
type CollectDetails struct {
|
||||
ID uint64 `json:"id,omitempty"` // 表项id
|
||||
Ques string `json:"ques,omitempty"` // 表项名称
|
||||
Type string `json:"type,omitempty"` // 表项类型,有Text(文本),Number(数字),Date(日期),Time(时间)
|
||||
}
|
||||
|
||||
// News 图文消息
|
||||
type News struct {
|
||||
Title string `json:"title,omitempty"` // 图文消息标题
|
||||
Desc string `json:"description,omitempty"` // 图文消息描述
|
||||
URL string `json:"url,omitempty"` // 图文消息点击跳转地址
|
||||
PicURL string `json:"picurl,omitempty"` // 图文消息配图的url
|
||||
}
|
||||
|
||||
// MixedMsg 混合消息
|
||||
type MixedMsg struct {
|
||||
Type string `json:"type,omitempty"`
|
||||
Content string `json:"content,omitempty"`
|
||||
}
|
||||
|
||||
// MeetingVoiceCall 音频存档消息
|
||||
type MeetingVoiceCall struct {
|
||||
EndTime int64 `json:"endtime,omitempty"` // 音频结束时间
|
||||
SdkFileID string `json:"sdkfileid,omitempty"` // 音频媒体下载的id
|
||||
DemoFileData []DemoFileData `json:"demofiledata,omitempty"` // 文档分享对象,Object类型
|
||||
ShareScreenData []ShareScreenData `json:"sharescreendata,omitempty"` // 屏幕共享对象,Object类型
|
||||
}
|
||||
|
||||
// DemoFileData 文档共享消息
|
||||
type DemoFileData struct {
|
||||
FileName string `json:"filename,omitempty"` // 文档共享名称
|
||||
DemoOperator string `json:"demooperator,omitempty"` // 文档共享操作用户的id
|
||||
StartTime int64 `json:"starttime,omitempty"` // 文档共享开始时间
|
||||
EndTime int64 `json:"endtime,omitempty"` // 文档共享结束时间
|
||||
}
|
||||
|
||||
// ShareScreenData 屏幕共享信息
|
||||
type ShareScreenData struct {
|
||||
Share string `json:"share,omitempty"` // 屏幕共享用户的id
|
||||
StartTime int64 `json:"starttime,omitempty"` // 屏幕共享开始时间
|
||||
EndTime int64 `json:"endtime,omitempty"` // 屏幕共享结束时间
|
||||
}
|
||||
|
||||
// VoipDocShare 音频共享文档消息
|
||||
type VoipDocShare struct {
|
||||
FileName string `json:"filename,omitempty"` // 文档共享文件名称
|
||||
Md5Sum string `json:"md5sum,omitempty"` // 共享文件的md5值
|
||||
FileSize uint64 `json:"filesize,omitempty"` // 共享文件的大小
|
||||
SdkFileID string `json:"sdkfileid,omitempty"` // 共享文件的sdkfile,通过此字段进行媒体数据下载
|
||||
}
|
||||
87
work/oauth/oauth.go
Normal file
87
work/oauth/oauth.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
"github.com/silenceper/wechat/v2/work/context"
|
||||
)
|
||||
|
||||
//Oauth auth
|
||||
type Oauth struct {
|
||||
*context.Context
|
||||
}
|
||||
|
||||
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"
|
||||
//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"
|
||||
)
|
||||
|
||||
//NewOauth new init oauth
|
||||
func NewOauth(ctx *context.Context) *Oauth {
|
||||
return &Oauth{
|
||||
ctx,
|
||||
}
|
||||
}
|
||||
|
||||
//GetTargetURL 获取授权地址
|
||||
func (ctr *Oauth) GetTargetURL(callbackURL string) string {
|
||||
//url encode
|
||||
urlStr := url.QueryEscape(callbackURL)
|
||||
return fmt.Sprintf(
|
||||
oauthTargetURL,
|
||||
ctr.CorpID,
|
||||
urlStr,
|
||||
)
|
||||
}
|
||||
|
||||
//GetQrContentTargetURL 构造独立窗口登录二维码
|
||||
func (ctr *Oauth) GetQrContentTargetURL(callbackURL string) string {
|
||||
//url encode
|
||||
urlStr := url.QueryEscape(callbackURL)
|
||||
return fmt.Sprintf(
|
||||
oauthQrContentTargetURL,
|
||||
ctr.CorpID,
|
||||
ctr.AgentID,
|
||||
urlStr,
|
||||
util.RandomStr(16),
|
||||
)
|
||||
}
|
||||
|
||||
//ResUserInfo 返回得用户信息
|
||||
type ResUserInfo struct {
|
||||
util.CommonError
|
||||
//当用户为企业成员时返回
|
||||
UserID string `json:"UserId"`
|
||||
DeviceID string `json:"DeviceId"`
|
||||
//非企业成员授权时返回
|
||||
OpenID string `json:"OpenId"`
|
||||
}
|
||||
|
||||
//UserFromCode 根据code获取用户信息
|
||||
func (ctr *Oauth) UserFromCode(code string) (result ResUserInfo, err error) {
|
||||
var accessToken string
|
||||
accessToken, err = ctr.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var response []byte
|
||||
response, err = util.HTTPGet(
|
||||
fmt.Sprintf(oauthUserInfoURL, accessToken, code),
|
||||
)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = json.Unmarshal(response, &result)
|
||||
if result.ErrCode != 0 {
|
||||
err = fmt.Errorf("GetUserAccessToken error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
45
work/work.go
Normal file
45
work/work.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package work
|
||||
|
||||
import (
|
||||
"github.com/silenceper/wechat/v2/credential"
|
||||
"github.com/silenceper/wechat/v2/work/config"
|
||||
"github.com/silenceper/wechat/v2/work/context"
|
||||
"github.com/silenceper/wechat/v2/work/kf"
|
||||
"github.com/silenceper/wechat/v2/work/msgaudit"
|
||||
"github.com/silenceper/wechat/v2/work/oauth"
|
||||
)
|
||||
|
||||
// Work 企业微信
|
||||
type Work struct {
|
||||
ctx *context.Context
|
||||
}
|
||||
|
||||
//NewWork init work
|
||||
func NewWork(cfg *config.Config) *Work {
|
||||
defaultAkHandle := credential.NewWorkAccessToken(cfg.CorpID, cfg.CorpSecret, credential.CacheKeyWorkPrefix, cfg.Cache)
|
||||
ctx := &context.Context{
|
||||
Config: cfg,
|
||||
AccessTokenHandle: defaultAkHandle,
|
||||
}
|
||||
return &Work{ctx: ctx}
|
||||
}
|
||||
|
||||
//GetContext get Context
|
||||
func (wk *Work) GetContext() *context.Context {
|
||||
return wk.ctx
|
||||
}
|
||||
|
||||
//GetOauth get oauth
|
||||
func (wk *Work) GetOauth() *oauth.Oauth {
|
||||
return oauth.NewOauth(wk.ctx)
|
||||
}
|
||||
|
||||
// GetMsgAudit get msgAudit
|
||||
func (wk *Work) GetMsgAudit() (*msgaudit.Client, error) {
|
||||
return msgaudit.NewClient(wk.ctx.Config)
|
||||
}
|
||||
|
||||
// GetKF get kf
|
||||
func (wk *Work) GetKF() (*kf.Client, error) {
|
||||
return kf.NewClient(wk.ctx.Config)
|
||||
}
|
||||
Reference in New Issue
Block a user