mirror of
https://github.com/silenceper/wechat.git
synced 2026-02-05 05:02:26 +08:00
Compare commits
44 Commits
v2.0.4-rc.
...
v2.0.7-rc.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
08008e1c86 | ||
|
|
01addecd53 | ||
|
|
4433fc18a6 | ||
|
|
e8c90848e4 | ||
|
|
6df8453378 | ||
|
|
2ff99d41dc | ||
|
|
b1144e3a38 | ||
|
|
51778fab8f | ||
|
|
6edaa7888a | ||
|
|
b27dca624f | ||
|
|
3f9aed72cd | ||
|
|
dc508f7341 | ||
|
|
1005807328 | ||
|
|
c1e4e2c9d0 | ||
|
|
c8522f1875 | ||
|
|
5d8fd1f5bd | ||
|
|
45caf61899 | ||
|
|
b42f1e1a7f | ||
|
|
2f88fad0bd | ||
|
|
13e5b3938b | ||
|
|
828ba7875b | ||
|
|
7a513080a8 | ||
|
|
0e8fc3f88b | ||
|
|
c95b844c83 | ||
|
|
34f1335d17 | ||
|
|
fb1aa60ae8 | ||
|
|
18abebe4de | ||
|
|
5472ac979b | ||
|
|
5ec4cc2269 | ||
|
|
d1241790cb | ||
|
|
813684e555 | ||
|
|
7ca0317d84 | ||
|
|
ad3cc913b0 | ||
|
|
64c2de7ab4 | ||
|
|
e7fdcf9534 | ||
|
|
05907d152e | ||
|
|
398f2ec6ae | ||
|
|
e8fb058740 | ||
|
|
d5a67eaf29 | ||
|
|
e5f0d5eab7 | ||
|
|
2eae660002 | ||
|
|
c0da806e03 | ||
|
|
185baa5d12 | ||
|
|
bf42c188cb |
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/
|
||||
-->
|
||||
**请描述您的问题**
|
||||
28
.github/workflows/go.yml
vendored
28
.github/workflows/go.yml
vendored
@@ -7,34 +7,38 @@ on:
|
||||
branches: [ master,release-* ]
|
||||
|
||||
jobs:
|
||||
golangci:
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [1.15.x]
|
||||
name: golangci-lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v2
|
||||
with:
|
||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||
version: v1.31
|
||||
build:
|
||||
name: Build
|
||||
name: Test
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
redis:
|
||||
image: redis
|
||||
ports:
|
||||
- 6379:6379
|
||||
- 6379:6379
|
||||
options: --entrypoint redis-server
|
||||
memcached:
|
||||
image: memcached
|
||||
ports:
|
||||
- 11211:11211
|
||||
steps:
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
- name: Set up Go 1.x
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: ^1.13
|
||||
id: go
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v1
|
||||
with:
|
||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||
version: v1.26
|
||||
|
||||
|
||||
- name: Test
|
||||
run: go test -v -race ./...
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -26,4 +26,5 @@ _testmain.go
|
||||
.vscode/
|
||||
vendor
|
||||
.idea/
|
||||
example/*
|
||||
example/*
|
||||
/test
|
||||
|
||||
@@ -11,7 +11,7 @@ linters:
|
||||
- errcheck
|
||||
- funlen
|
||||
- goconst
|
||||
- gocritic
|
||||
# - gocritic
|
||||
- gocyclo
|
||||
- gofmt
|
||||
- goimports
|
||||
|
||||
@@ -8,13 +8,13 @@
|
||||
|
||||
|
||||
## 文档 && 例子
|
||||
[Wechat SDK 2.0 文档](http://silenceper.com/wechat)
|
||||
[Wechat SDK 2.0 文档](https://silenceper.com/wechat)
|
||||
|
||||
[Wechat SDK 2.0 例子](https://github.com/gowechat/example)
|
||||
|
||||
## 快速开始
|
||||
```
|
||||
import github.com/silenceper/wechat/v2
|
||||
import "github.com/silenceper/wechat/v2"
|
||||
```
|
||||
|
||||
以下是一个微信公众号处理消息接收以及回复的例子:
|
||||
@@ -35,7 +35,7 @@ officialAccount := wc.GetOfficialAccount(cfg)
|
||||
// 传入request和responseWriter
|
||||
server := officialAccount.GetServer(req, rw)
|
||||
//设置接收消息的处理方法
|
||||
server.SetMessageHandler(func(msg message.MixMessage) *message.Reply {
|
||||
server.SetMessageHandler(func(msg *message.MixMessage) *message.Reply {
|
||||
|
||||
//回复消息:演示回复用户发送的消息
|
||||
text := message.NewText(msg.Content)
|
||||
@@ -58,7 +58,7 @@ server.Send()
|
||||
- miniprogram: 小程序API
|
||||
- minigame:小游戏API
|
||||
- pay:微信支付API
|
||||
- opernplatform:开放平台API
|
||||
- openplatform:开放平台API
|
||||
- work:企业微信
|
||||
- aispeech:智能对话
|
||||
|
||||
|
||||
2
cache/cache.go
vendored
2
cache/cache.go
vendored
@@ -2,7 +2,7 @@ package cache
|
||||
|
||||
import "time"
|
||||
|
||||
//Cache interface
|
||||
// Cache interface
|
||||
type Cache interface {
|
||||
Get(key string) interface{}
|
||||
Set(key string, val interface{}, timeout time.Duration) error
|
||||
|
||||
10
cache/memcache.go
vendored
10
cache/memcache.go
vendored
@@ -7,18 +7,18 @@ import (
|
||||
"github.com/bradfitz/gomemcache/memcache"
|
||||
)
|
||||
|
||||
//Memcache struct contains *memcache.Client
|
||||
// Memcache struct contains *memcache.Client
|
||||
type Memcache struct {
|
||||
conn *memcache.Client
|
||||
}
|
||||
|
||||
//NewMemcache create new memcache
|
||||
// NewMemcache create new memcache
|
||||
func NewMemcache(server ...string) *Memcache {
|
||||
mc := memcache.New(server...)
|
||||
return &Memcache{mc}
|
||||
}
|
||||
|
||||
//Get return cached value
|
||||
// Get return cached value
|
||||
func (mem *Memcache) Get(key string) interface{} {
|
||||
var err error
|
||||
var item *memcache.Item
|
||||
@@ -40,7 +40,7 @@ func (mem *Memcache) IsExist(key string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
//Set cached value with key and expire time.
|
||||
// Set cached value with key and expire time.
|
||||
func (mem *Memcache) Set(key string, val interface{}, timeout time.Duration) (err error) {
|
||||
var data []byte
|
||||
if data, err = json.Marshal(val); err != nil {
|
||||
@@ -51,7 +51,7 @@ func (mem *Memcache) Set(key string, val interface{}, timeout time.Duration) (er
|
||||
return mem.conn.Set(item)
|
||||
}
|
||||
|
||||
//Delete delete value in memcache.
|
||||
// Delete delete value in memcache.
|
||||
func (mem *Memcache) Delete(key string) error {
|
||||
return mem.conn.Delete(key)
|
||||
}
|
||||
|
||||
@@ -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 获取
|
||||
@@ -65,7 +69,58 @@ func (ak *DefaultAccessToken) GetAccessToken() (accessToken string, err error) {
|
||||
|
||||
//cache失效,从微信服务器获取
|
||||
var resAccessToken ResAccessToken
|
||||
resAccessToken, err = GetTokenFromServer(ak.appID, ak.appSecret)
|
||||
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)
|
||||
return
|
||||
}
|
||||
|
||||
//cache失效,从微信服务器获取
|
||||
var resAccessToken ResAccessToken
|
||||
resAccessToken, err = GetTokenFromServer(fmt.Sprintf(workAccessTokenURL, ak.CorpID, ak.CorpSecret))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -80,8 +135,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 +145,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
|
||||
}
|
||||
|
||||
12
go.mod
12
go.mod
@@ -5,10 +5,14 @@ go 1.14
|
||||
require (
|
||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b
|
||||
github.com/fatih/structs v1.1.0
|
||||
github.com/gomodule/redigo v1.8.1
|
||||
github.com/sirupsen/logrus v1.6.0
|
||||
github.com/gomodule/redigo v1.8.4
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
|
||||
github.com/sirupsen/logrus v1.8.1
|
||||
github.com/spf13/cast v1.3.1
|
||||
github.com/stretchr/testify v1.5.1
|
||||
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37
|
||||
github.com/stretchr/testify v1.7.0
|
||||
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83
|
||||
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
|
||||
gopkg.in/h2non/gock.v1 v1.0.15
|
||||
)
|
||||
|
||||
40
go.sum
40
go.sum
@@ -1,43 +1,49 @@
|
||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b h1:L/QXpzIa3pOvUGt1D1lA5KjYhPBAN/3iWdP7xeFS9F0=
|
||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
|
||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
|
||||
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
|
||||
github.com/gomodule/redigo v1.8.1 h1:Abmo0bI7Xf0IhdIPc7HZQzZcShdnmxeoVuDDtIQp8N8=
|
||||
github.com/gomodule/redigo v1.8.1/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0=
|
||||
github.com/gomodule/redigo v1.8.4 h1:Z5JUg94HMTR1XpwBaSH4vq3+PNSIykBLxMdglbw10gg=
|
||||
github.com/gomodule/redigo v1.8.4/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0=
|
||||
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw=
|
||||
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4=
|
||||
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
|
||||
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
||||
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/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 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw=
|
||||
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
|
||||
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 h1:/ZScEX8SfEmUGRHs0gxpqteO5nfNW6axyZbBdw9A12g=
|
||||
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2 h1:46ULzRKLh1CwgRq2dC5SlBzEqqNCi8rreOZnNrbqcIY=
|
||||
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/h2non/gock.v1 v1.0.15 h1:SzLqcIlb/fDfg7UvukMpNcWsu7sI5tWwL+KCATZqks0=
|
||||
gopkg.in/h2non/gock.v1 v1.0.15/go.mod h1:sX4zAkdYX1TRGJ2JY156cFspQn4yRWn6p9EMdODlynE=
|
||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
//Package config 小程序config配置
|
||||
// Package config 小程序config配置
|
||||
package config
|
||||
|
||||
import (
|
||||
"github.com/silenceper/wechat/v2/cache"
|
||||
)
|
||||
|
||||
//Config config for 小程序
|
||||
// Config config for 小程序
|
||||
type Config struct {
|
||||
AppID string `json:"app_id"` //appid
|
||||
AppSecret string `json:"app_secret"` //appsecret
|
||||
AppID string `json:"app_id"` // appid
|
||||
AppSecret string `json:"app_secret"` // appsecret
|
||||
Cache cache.Cache
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
@@ -45,6 +45,8 @@ type PlainData struct {
|
||||
AvatarURL string `json:"avatarUrl"`
|
||||
Language string `json:"language"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
OpenGID string `json:"openGId"`
|
||||
MsgTicket string `json:"msgTicket"`
|
||||
PurePhoneNumber string `json:"purePhoneNumber"`
|
||||
CountryCode string `json:"countryCode"`
|
||||
Watermark struct {
|
||||
@@ -74,8 +76,8 @@ func pkcs7Unpad(data []byte, blockSize int) ([]byte, error) {
|
||||
return data[:len(data)-n], nil
|
||||
}
|
||||
|
||||
// getCipherText returns slice of the cipher text
|
||||
func getCipherText(sessionKey, encryptedData, iv string) ([]byte, error) {
|
||||
// GetCipherText returns slice of the cipher text
|
||||
func GetCipherText(sessionKey, encryptedData, iv string) ([]byte, error) {
|
||||
aesKey, err := base64.StdEncoding.DecodeString(sessionKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -103,7 +105,7 @@ func getCipherText(sessionKey, encryptedData, iv string) ([]byte, error) {
|
||||
|
||||
// Decrypt 解密数据
|
||||
func (encryptor *Encryptor) Decrypt(sessionKey, encryptedData, iv string) (*PlainData, error) {
|
||||
cipherText, err := getCipherText(sessionKey, encryptedData, iv)
|
||||
cipherText, err := GetCipherText(sessionKey, encryptedData, iv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -5,12 +5,14 @@ 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"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/qrcode"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/subscribe"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/tcb"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/werun"
|
||||
)
|
||||
|
||||
//MiniProgram 微信小程序相关API
|
||||
@@ -72,3 +74,13 @@ func (miniProgram *MiniProgram) GetSubscribe() *subscribe.Subscribe {
|
||||
func (miniProgram *MiniProgram) GetCustomerMessage() *message.Manager {
|
||||
return message.NewCustomerMessageManager(miniProgram.ctx)
|
||||
}
|
||||
|
||||
// GetWeRun 微信运动接口
|
||||
func (miniProgram *MiniProgram) GetWeRun() *werun.WeRun {
|
||||
return werun.NewWeRun(miniProgram.ctx)
|
||||
}
|
||||
|
||||
// GetContentSecurity 内容安全接口
|
||||
func (miniProgram *MiniProgram) GetContentSecurity() *content.Content {
|
||||
return content.NewContent(miniProgram.ctx)
|
||||
}
|
||||
|
||||
@@ -15,6 +15,10 @@ 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/uniform-message/uniformMessage.send.html
|
||||
uniformMessageSend = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send"
|
||||
)
|
||||
|
||||
// Subscribe 订阅消息
|
||||
@@ -39,7 +43,8 @@ type Message struct {
|
||||
|
||||
//DataItem 模版内某个 .DATA 的值
|
||||
type DataItem struct {
|
||||
Value string `json:"value"`
|
||||
Value interface{} `json:"value"`
|
||||
Color string `json:"color"`
|
||||
}
|
||||
|
||||
//TemplateItem template item
|
||||
@@ -91,3 +96,40 @@ func (s *Subscribe) ListTemplates() (*TemplateList, error) {
|
||||
}
|
||||
return &templateList, nil
|
||||
}
|
||||
|
||||
// UniformMessage 统一服务消息
|
||||
type UniformMessage struct {
|
||||
ToUser string `json:"touser"`
|
||||
WeappTemplateMsg struct {
|
||||
TemplateID string `json:"template_id"`
|
||||
Page string `json:"page"`
|
||||
FormID string `json:"form_id"`
|
||||
Data map[string]*DataItem `json:"data"`
|
||||
EmphasisKeyword string `json:"emphasis_keyword"`
|
||||
} `json:"weapp_template_msg"`
|
||||
MpTemplateMsg struct {
|
||||
Appid string `json:"appid"`
|
||||
TemplateID string `json:"template_id"`
|
||||
URL string `json:"url"`
|
||||
Miniprogram struct {
|
||||
Appid string `json:"appid"`
|
||||
Pagepath string `json:"pagepath"`
|
||||
} `json:"miniprogram"`
|
||||
Data map[string]*DataItem `json:"data"`
|
||||
} `json:"mp_template_msg"`
|
||||
}
|
||||
|
||||
// UniformSend 发送统一服务消息
|
||||
func (s *Subscribe) UniformSend(msg *UniformMessage) (err error) {
|
||||
var accessToken string
|
||||
accessToken, err = s.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
uri := fmt.Sprintf("%s?access_token=%s", uniformMessageSend, accessToken)
|
||||
response, err := util.PostJSON(uri, msg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "UniformSend")
|
||||
}
|
||||
|
||||
40
miniprogram/werun/werun.go
Normal file
40
miniprogram/werun/werun.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package werun
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/silenceper/wechat/v2/miniprogram/context"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/encryptor"
|
||||
)
|
||||
|
||||
// WeRun 微信运动
|
||||
type WeRun struct {
|
||||
*context.Context
|
||||
}
|
||||
|
||||
// Data 微信运动数据
|
||||
type Data struct {
|
||||
StepInfoList []struct {
|
||||
Timestamp int `json:"timestamp"`
|
||||
Step int `json:"step"`
|
||||
} `json:"stepInfoList"`
|
||||
}
|
||||
|
||||
// NewWeRun 实例化
|
||||
func NewWeRun(ctx *context.Context) *WeRun {
|
||||
return &WeRun{Context: ctx}
|
||||
}
|
||||
|
||||
// GetWeRunData 解密数据
|
||||
func (werun *WeRun) GetWeRunData(sessionKey, encryptedData, iv string) (*Data, error) {
|
||||
cipherText, err := encryptor.GetCipherText(sessionKey, encryptedData, iv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var weRunData Data
|
||||
err = json.Unmarshal(cipherText, &weRunData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &weRunData, nil
|
||||
}
|
||||
@@ -62,6 +62,11 @@ func (basic *Basic) GetQRTicket(tq *Request) (t *Ticket, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
if t.ErrMsg != "" {
|
||||
err = fmt.Errorf("get qr_ticket error : errcode=%v , errormsg=%v", t.ErrCode, t.ErrMsg)
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
52
officialaccount/basic/short_url.go
Normal file
52
officialaccount/basic/short_url.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package basic
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const (
|
||||
// 将一条长链接转成短链接
|
||||
// https://developers.weixin.qq.com/doc/offiaccount/Account_Management/URL_Shortener.html
|
||||
long2shortURL = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=%s"
|
||||
long2shortAction = "long2short"
|
||||
)
|
||||
|
||||
type (
|
||||
reqLong2ShortURL struct {
|
||||
Action string `json:"action"`
|
||||
LongURL string `json:"long_url"`
|
||||
}
|
||||
resplong2ShortURL struct {
|
||||
ShortURL string `json:"short_url"`
|
||||
util.CommonError
|
||||
}
|
||||
)
|
||||
|
||||
// Long2ShortURL 将一条长链接转成短链接
|
||||
func (basic *Basic) Long2ShortURL(longURL string) (shortURL string, err error) {
|
||||
var (
|
||||
req = &reqLong2ShortURL{
|
||||
Action: long2shortAction,
|
||||
LongURL: longURL,
|
||||
}
|
||||
resp = new(resplong2ShortURL)
|
||||
ac, uri string
|
||||
responseBytes []byte
|
||||
)
|
||||
ac, err = basic.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
uri = fmt.Sprintf(long2shortURL, ac)
|
||||
responseBytes, err = util.PostJSON(uri, req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = util.DecodeWithError(responseBytes, resp, long2shortAction); err != nil {
|
||||
return
|
||||
}
|
||||
shortURL = resp.ShortURL
|
||||
return
|
||||
}
|
||||
@@ -333,9 +333,11 @@ func (broadcast *Broadcast) chooseTagOrOpenID(user *User, req *sendRequest) (ret
|
||||
sendURL = sendURLByTag
|
||||
} else {
|
||||
if broadcast.preview {
|
||||
// 预览
|
||||
req.ToUser = user.OpenID
|
||||
sendURL = previewSendURL
|
||||
// 预览 默认发给第一个用户
|
||||
if len(user.OpenID) != 0 {
|
||||
req.ToUser = user.OpenID[0]
|
||||
sendURL = previewSendURL
|
||||
}
|
||||
} else {
|
||||
if user.TagID != 0 {
|
||||
req.Filter = map[string]interface{}{
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"github.com/silenceper/wechat/v2/cache"
|
||||
)
|
||||
|
||||
//Config config for 微信公众号
|
||||
// Config config for 微信公众号
|
||||
type Config struct {
|
||||
AppID string `json:"app_id"` //appid
|
||||
AppSecret string `json:"app_secret"` //appsecret
|
||||
|
||||
@@ -119,6 +119,9 @@ func (material *Material) AddNews(articles []*Article) (mediaID string, err erro
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if res.ErrCode != 0 {
|
||||
return "", fmt.Errorf("errcode=%d,errmsg=%s", res.ErrCode, res.ErrMsg)
|
||||
}
|
||||
mediaID = res.MediaID
|
||||
return
|
||||
}
|
||||
|
||||
@@ -13,47 +13,51 @@ type Button struct {
|
||||
}
|
||||
|
||||
//SetSubButton 设置二级菜单
|
||||
func (btn *Button) SetSubButton(name string, subButtons []*Button) {
|
||||
func (btn *Button) SetSubButton(name string, subButtons []*Button) *Button {
|
||||
btn.Name = name
|
||||
btn.SubButtons = subButtons
|
||||
btn.Type = ""
|
||||
btn.Key = ""
|
||||
btn.URL = ""
|
||||
btn.MediaID = ""
|
||||
return btn
|
||||
}
|
||||
|
||||
//SetClickButton btn 为click类型
|
||||
func (btn *Button) SetClickButton(name, key string) {
|
||||
func (btn *Button) SetClickButton(name, key string) *Button {
|
||||
btn.Type = "click"
|
||||
btn.Name = name
|
||||
btn.Key = key
|
||||
btn.URL = ""
|
||||
btn.MediaID = ""
|
||||
btn.SubButtons = nil
|
||||
return btn
|
||||
}
|
||||
|
||||
//SetViewButton view类型
|
||||
func (btn *Button) SetViewButton(name, url string) {
|
||||
func (btn *Button) SetViewButton(name, url string) *Button {
|
||||
btn.Type = "view"
|
||||
btn.Name = name
|
||||
btn.URL = url
|
||||
btn.Key = ""
|
||||
btn.MediaID = ""
|
||||
btn.SubButtons = nil
|
||||
return btn
|
||||
}
|
||||
|
||||
// SetScanCodePushButton 扫码推事件
|
||||
func (btn *Button) SetScanCodePushButton(name, key string) {
|
||||
//SetScanCodePushButton 扫码推事件
|
||||
func (btn *Button) SetScanCodePushButton(name, key string) *Button {
|
||||
btn.Type = "scancode_push"
|
||||
btn.Name = name
|
||||
btn.Key = key
|
||||
btn.URL = ""
|
||||
btn.MediaID = ""
|
||||
btn.SubButtons = nil
|
||||
return btn
|
||||
}
|
||||
|
||||
//SetScanCodeWaitMsgButton 设置 扫码推事件且弹出"消息接收中"提示框
|
||||
func (btn *Button) SetScanCodeWaitMsgButton(name, key string) {
|
||||
func (btn *Button) SetScanCodeWaitMsgButton(name, key string) *Button {
|
||||
btn.Type = "scancode_waitmsg"
|
||||
btn.Name = name
|
||||
btn.Key = key
|
||||
@@ -61,10 +65,11 @@ func (btn *Button) SetScanCodeWaitMsgButton(name, key string) {
|
||||
btn.URL = ""
|
||||
btn.MediaID = ""
|
||||
btn.SubButtons = nil
|
||||
return btn
|
||||
}
|
||||
|
||||
//SetPicSysPhotoButton 设置弹出系统拍照发图按钮
|
||||
func (btn *Button) SetPicSysPhotoButton(name, key string) {
|
||||
func (btn *Button) SetPicSysPhotoButton(name, key string) *Button {
|
||||
btn.Type = "pic_sysphoto"
|
||||
btn.Name = name
|
||||
btn.Key = key
|
||||
@@ -72,10 +77,11 @@ func (btn *Button) SetPicSysPhotoButton(name, key string) {
|
||||
btn.URL = ""
|
||||
btn.MediaID = ""
|
||||
btn.SubButtons = nil
|
||||
return btn
|
||||
}
|
||||
|
||||
//SetPicPhotoOrAlbumButton 设置弹出拍照或者相册发图类型按钮
|
||||
func (btn *Button) SetPicPhotoOrAlbumButton(name, key string) {
|
||||
func (btn *Button) SetPicPhotoOrAlbumButton(name, key string) *Button {
|
||||
btn.Type = "pic_photo_or_album"
|
||||
btn.Name = name
|
||||
btn.Key = key
|
||||
@@ -83,10 +89,11 @@ func (btn *Button) SetPicPhotoOrAlbumButton(name, key string) {
|
||||
btn.URL = ""
|
||||
btn.MediaID = ""
|
||||
btn.SubButtons = nil
|
||||
return btn
|
||||
}
|
||||
|
||||
// SetPicWeixinButton 设置弹出微信相册发图器类型按钮
|
||||
func (btn *Button) SetPicWeixinButton(name, key string) {
|
||||
//SetPicWeixinButton 设置弹出微信相册发图器类型按钮
|
||||
func (btn *Button) SetPicWeixinButton(name, key string) *Button {
|
||||
btn.Type = "pic_weixin"
|
||||
btn.Name = name
|
||||
btn.Key = key
|
||||
@@ -94,10 +101,11 @@ func (btn *Button) SetPicWeixinButton(name, key string) {
|
||||
btn.URL = ""
|
||||
btn.MediaID = ""
|
||||
btn.SubButtons = nil
|
||||
return btn
|
||||
}
|
||||
|
||||
// SetLocationSelectButton 设置 弹出地理位置选择器 类型按钮
|
||||
func (btn *Button) SetLocationSelectButton(name, key string) {
|
||||
//SetLocationSelectButton 设置 弹出地理位置选择器 类型按钮
|
||||
func (btn *Button) SetLocationSelectButton(name, key string) *Button {
|
||||
btn.Type = "location_select"
|
||||
btn.Name = name
|
||||
btn.Key = key
|
||||
@@ -105,10 +113,11 @@ func (btn *Button) SetLocationSelectButton(name, key string) {
|
||||
btn.URL = ""
|
||||
btn.MediaID = ""
|
||||
btn.SubButtons = nil
|
||||
return btn
|
||||
}
|
||||
|
||||
//SetMediaIDButton 设置 下发消息(除文本消息) 类型按钮
|
||||
func (btn *Button) SetMediaIDButton(name, mediaID string) {
|
||||
func (btn *Button) SetMediaIDButton(name, mediaID string) *Button {
|
||||
btn.Type = "media_id"
|
||||
btn.Name = name
|
||||
btn.MediaID = mediaID
|
||||
@@ -116,10 +125,11 @@ func (btn *Button) SetMediaIDButton(name, mediaID string) {
|
||||
btn.Key = ""
|
||||
btn.URL = ""
|
||||
btn.SubButtons = nil
|
||||
return btn
|
||||
}
|
||||
|
||||
//SetViewLimitedButton 设置 跳转图文消息URL 类型按钮
|
||||
func (btn *Button) SetViewLimitedButton(name, mediaID string) {
|
||||
func (btn *Button) SetViewLimitedButton(name, mediaID string) *Button {
|
||||
btn.Type = "view_limited"
|
||||
btn.Name = name
|
||||
btn.MediaID = mediaID
|
||||
@@ -127,10 +137,11 @@ func (btn *Button) SetViewLimitedButton(name, mediaID string) {
|
||||
btn.Key = ""
|
||||
btn.URL = ""
|
||||
btn.SubButtons = nil
|
||||
return btn
|
||||
}
|
||||
|
||||
//SetMiniprogramButton 设置 跳转小程序 类型按钮 (公众号后台必须已经关联小程序)
|
||||
func (btn *Button) SetMiniprogramButton(name, url, appID, pagePath string) {
|
||||
func (btn *Button) SetMiniprogramButton(name, url, appID, pagePath string) *Button {
|
||||
btn.Type = "miniprogram"
|
||||
btn.Name = name
|
||||
btn.URL = url
|
||||
@@ -140,4 +151,65 @@ func (btn *Button) SetMiniprogramButton(name, url, appID, pagePath string) {
|
||||
btn.Key = ""
|
||||
btn.MediaID = ""
|
||||
btn.SubButtons = nil
|
||||
return btn
|
||||
}
|
||||
|
||||
//NewSubButton 二级菜单
|
||||
func NewSubButton(name string, subButtons []*Button) *Button {
|
||||
return (&Button{}).SetSubButton(name, subButtons)
|
||||
}
|
||||
|
||||
//NewClickButton btn 为click类型
|
||||
func NewClickButton(name, key string) *Button {
|
||||
return (&Button{}).SetClickButton(name, key)
|
||||
}
|
||||
|
||||
//NewViewButton view类型
|
||||
func NewViewButton(name, url string) *Button {
|
||||
return (&Button{}).SetViewButton(name, url)
|
||||
}
|
||||
|
||||
//NewScanCodePushButton 扫码推事件
|
||||
func NewScanCodePushButton(name, key string) *Button {
|
||||
return (&Button{}).SetScanCodePushButton(name, key)
|
||||
}
|
||||
|
||||
//NewScanCodeWaitMsgButton 扫码推事件且弹出"消息接收中"提示框
|
||||
func NewScanCodeWaitMsgButton(name, key string) *Button {
|
||||
return (&Button{}).SetScanCodeWaitMsgButton(name, key)
|
||||
}
|
||||
|
||||
//NewPicSysPhotoButton 弹出系统拍照发图按钮
|
||||
func NewPicSysPhotoButton(name, key string) *Button {
|
||||
return (&Button{}).SetPicSysPhotoButton(name, key)
|
||||
}
|
||||
|
||||
//NewPicPhotoOrAlbumButton 弹出拍照或者相册发图类型按钮
|
||||
func NewPicPhotoOrAlbumButton(name, key string) *Button {
|
||||
return (&Button{}).SetPicPhotoOrAlbumButton(name, key)
|
||||
}
|
||||
|
||||
//NewPicWeixinButton 弹出微信相册发图器类型按钮
|
||||
func NewPicWeixinButton(name, key string) *Button {
|
||||
return (&Button{}).SetPicWeixinButton(name, key)
|
||||
}
|
||||
|
||||
//NewLocationSelectButton 弹出地理位置选择器 类型按钮
|
||||
func NewLocationSelectButton(name, key string) *Button {
|
||||
return (&Button{}).SetLocationSelectButton(name, key)
|
||||
}
|
||||
|
||||
//NewMediaIDButton 下发消息(除文本消息) 类型按钮
|
||||
func NewMediaIDButton(name, mediaID string) *Button {
|
||||
return (&Button{}).SetMediaIDButton(name, mediaID)
|
||||
}
|
||||
|
||||
//NewViewLimitedButton 跳转图文消息URL 类型按钮
|
||||
func NewViewLimitedButton(name, mediaID string) *Button {
|
||||
return (&Button{}).SetViewLimitedButton(name, mediaID)
|
||||
}
|
||||
|
||||
//NewMiniprogramButton 跳转小程序 类型按钮 (公众号后台必须已经关联小程序)
|
||||
func NewMiniprogramButton(name, url, appID, pagePath string) *Button {
|
||||
return (&Button{}).SetMiniprogramButton(name, url, appID, pagePath)
|
||||
}
|
||||
|
||||
28
officialaccount/menu/button_test.go
Normal file
28
officialaccount/menu/button_test.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package menu
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestNewButtonFun(t *testing.T) {
|
||||
buttons := []*Button{
|
||||
NewSubButton("1", []*Button{
|
||||
NewViewButton("1.1", "https://baidu.com"),
|
||||
NewViewButton("1.2", "https://baidu.com"),
|
||||
NewViewButton("1.3", "https://baidu.com"),
|
||||
}),
|
||||
NewSubButton("2", []*Button{
|
||||
NewViewButton("2.1", "https://baidu.com"),
|
||||
NewViewButton("2.2", "https://baidu.com"),
|
||||
NewViewButton("2.3", "https://baidu.com"),
|
||||
}),
|
||||
NewViewButton("3", "https://baidu.com"),
|
||||
}
|
||||
|
||||
data, err := json.Marshal(buttons)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, `[{"name":"1","sub_button":[{"type":"view","name":"1.1","url":"https://baidu.com"},{"type":"view","name":"1.2","url":"https://baidu.com"},{"type":"view","name":"1.3","url":"https://baidu.com"}]},{"name":"2","sub_button":[{"type":"view","name":"2.1","url":"https://baidu.com"},{"type":"view","name":"2.2","url":"https://baidu.com"},{"type":"view","name":"2.3","url":"https://baidu.com"}]},{"type":"view","name":"3","url":"https://baidu.com"}]`, string(data))
|
||||
}
|
||||
@@ -147,12 +147,12 @@ func (menu *Menu) SetMenuByJSON(jsonInfo string) error {
|
||||
|
||||
uri := fmt.Sprintf("%s?access_token=%s", menuCreateURL, accessToken)
|
||||
|
||||
response, err := util.PostJSON(uri, jsonInfo)
|
||||
response, err := util.HTTPPost(uri, jsonInfo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return util.DecodeWithCommonError(response, "SetMenu")
|
||||
return util.DecodeWithCommonError(response, "SetMenuByJSON")
|
||||
}
|
||||
|
||||
//GetMenu 获取菜单配置
|
||||
@@ -223,7 +223,7 @@ func (menu *Menu) AddConditionalByJSON(jsonInfo string) error {
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("%s?access_token=%s", menuAddConditionalURL, accessToken)
|
||||
response, err := util.PostJSON(uri, jsonInfo)
|
||||
response, err := util.HTTPPost(uri, jsonInfo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -69,6 +69,8 @@ const (
|
||||
EventLocationSelect = "location_select"
|
||||
//EventTemplateSendJobFinish 发送模板消息推送通知
|
||||
EventTemplateSendJobFinish = "TEMPLATESENDJOBFINISH"
|
||||
//EventMassSendJobFinish 群发消息推送通知
|
||||
EventMassSendJobFinish = "MASSSENDJOBFINISH"
|
||||
//EventWxaMediaCheck 异步校验图片/音频是否含有违法违规内容推送事件
|
||||
EventWxaMediaCheck = "wxa_media_check"
|
||||
)
|
||||
@@ -117,6 +119,10 @@ type MixMessage struct {
|
||||
MenuID string `xml:"MenuId"`
|
||||
Status string `xml:"Status"`
|
||||
SessionFrom string `xml:"SessionFrom"`
|
||||
TotalCount int64 `xml:"TotalCount"`
|
||||
FilterCount int64 `xml:"FilterCount"`
|
||||
SentCount int64 `xml:"SentCount"`
|
||||
ErrorCount int64 `xml:"ErrorCount"`
|
||||
|
||||
ScanCodeInfo struct {
|
||||
ScanType string `xml:"ScanType"`
|
||||
@@ -225,3 +231,8 @@ func (msg *CommonToken) SetCreateTime(createTime int64) {
|
||||
func (msg *CommonToken) SetMsgType(msgType MsgType) {
|
||||
msg.MsgType = msgType
|
||||
}
|
||||
|
||||
//GetOpenID get the FromUserName value
|
||||
func (msg *CommonToken) GetOpenID() string {
|
||||
return string(msg.FromUserName)
|
||||
}
|
||||
|
||||
93
officialaccount/message/subscribe.go
Normal file
93
officialaccount/message/subscribe.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/officialaccount/context"
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const (
|
||||
subscribeSendURL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend"
|
||||
subscribeTemplateListURL = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate"
|
||||
)
|
||||
|
||||
//Subscrib 订阅消息
|
||||
type Subscrib struct {
|
||||
*context.Context
|
||||
}
|
||||
|
||||
//NewSubscrib 实例化
|
||||
func NewSubscrib(context *context.Context) *Subscrib {
|
||||
tpl := new(Subscrib)
|
||||
tpl.Context = context
|
||||
return tpl
|
||||
}
|
||||
|
||||
//SubscribeMessage 发送的订阅消息内容
|
||||
type SubscribeMessage struct {
|
||||
ToUser string `json:"touser"` // 必须, 接受者OpenID
|
||||
TemplateID string `json:"template_id"` // 必须, 模版ID
|
||||
Page string `json:"page,omitempty"` // 可选, 跳转网页时填写
|
||||
Data map[string]*SubscribeDataItem `json:"data"` // 必须, 模板数据
|
||||
MiniProgram struct {
|
||||
AppID string `json:"appid"` //所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)
|
||||
PagePath string `json:"pagepath"` //所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar)
|
||||
} `json:"miniprogram"` //可选,跳转至小程序地址
|
||||
}
|
||||
|
||||
//SubscribeDataItem 模版内某个 .DATA 的值
|
||||
type SubscribeDataItem struct {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
//Send 发送订阅消息
|
||||
func (tpl *Subscrib) Send(msg *SubscribeMessage) (err error) {
|
||||
var accessToken string
|
||||
accessToken, err = tpl.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
uri := fmt.Sprintf("%s?access_token=%s", subscribeSendURL, accessToken)
|
||||
response, err := util.PostJSON(uri, msg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "SendSubscribMessage")
|
||||
}
|
||||
|
||||
// PrivateSubscribItem 私有订阅消息模板
|
||||
type PrivateSubscribItem struct {
|
||||
PriTmplID string `json:"priTmplId"` // 添加至帐号下的模板 id,发送订阅通知时所需
|
||||
Title string `json:"title"` //模版标题
|
||||
Content string `json:"content"` //模版内容
|
||||
Example string `json:"example"` //模板内容示例
|
||||
SubType int `json:"type"` //模版类型,2 为一次性订阅,3 为长期订阅
|
||||
}
|
||||
|
||||
type resPrivateSubscribList struct {
|
||||
util.CommonError
|
||||
SubscriptionList []*PrivateSubscribItem `json:"data"`
|
||||
}
|
||||
|
||||
//List 获取私有订阅消息模板列表
|
||||
func (tpl *Subscrib) List() (templateList []*PrivateSubscribItem, err error) {
|
||||
var accessToken string
|
||||
accessToken, err = tpl.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
uri := fmt.Sprintf("%s?access_token=%s", subscribeTemplateListURL, accessToken)
|
||||
var response []byte
|
||||
response, err = util.HTTPGet(uri)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var res resPrivateSubscribList
|
||||
err = util.DecodeWithError(response, &res, "ListSubscription")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
templateList = res.SubscriptionList
|
||||
return
|
||||
}
|
||||
@@ -15,7 +15,7 @@ const (
|
||||
webAppRedirectOauthURL = "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect"
|
||||
accessTokenURL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"
|
||||
refreshAccessTokenURL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s"
|
||||
userInfoURL = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"
|
||||
userInfoURL = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=%s"
|
||||
checkAccessTokenURL = "https://api.weixin.qq.com/sns/auth?access_token=%s&openid=%s"
|
||||
)
|
||||
|
||||
@@ -144,8 +144,11 @@ type UserInfo struct {
|
||||
}
|
||||
|
||||
//GetUserInfo 如果scope为 snsapi_userinfo 则可以通过此方法获取到用户基本信息
|
||||
func (oauth *Oauth) GetUserInfo(accessToken, openID string) (result UserInfo, err error) {
|
||||
urlStr := fmt.Sprintf(userInfoURL, accessToken, openID)
|
||||
func (oauth *Oauth) GetUserInfo(accessToken, openID, lang string) (result UserInfo, err error) {
|
||||
if lang == "" {
|
||||
lang = "zh_CN"
|
||||
}
|
||||
urlStr := fmt.Sprintf(userInfoURL, accessToken, openID, lang)
|
||||
var response []byte
|
||||
response, err = util.HTTPGet(urlStr)
|
||||
if err != nil {
|
||||
|
||||
287
officialaccount/ocr/ocr.go
Normal file
287
officialaccount/ocr/ocr.go
Normal file
@@ -0,0 +1,287 @@
|
||||
package ocr
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"github.com/silenceper/wechat/v2/officialaccount/context"
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const (
|
||||
ocrIDCardURL = "https://api.weixin.qq.com/cv/ocr/idcard"
|
||||
ocrBankCardURL = "https://api.weixin.qq.com/cv/ocr/bankcard"
|
||||
ocrDrivingURL = "https://api.weixin.qq.com/cv/ocr/driving"
|
||||
ocrDrivingLicenseURL = "https://api.weixin.qq.com/cv/ocr/drivinglicense"
|
||||
ocrBizLicenseURL = "https://api.weixin.qq.com/cv/ocr/bizlicense"
|
||||
ocrCommonURL = "https://api.weixin.qq.com/cv/ocr/comm"
|
||||
ocrPlateNumberURL = "https://api.weixin.qq.com/cv/ocr/platenum"
|
||||
)
|
||||
|
||||
//OCR struct
|
||||
type OCR struct {
|
||||
*context.Context
|
||||
}
|
||||
|
||||
//coordinate 坐标
|
||||
type coordinate struct {
|
||||
X int64 `json:"x,omitempty"`
|
||||
Y int64 `json:"y,omitempty"`
|
||||
}
|
||||
|
||||
//position 位置
|
||||
type position struct {
|
||||
LeftTop coordinate `json:"left_top"`
|
||||
RightTop coordinate `json:"right_top"`
|
||||
RightBottom coordinate `json:"right_bottom"`
|
||||
LeftBottom coordinate `json:"left_bottom"`
|
||||
}
|
||||
|
||||
//imageSize 图片尺寸
|
||||
type imageSize struct {
|
||||
Width int64 `json:"w,omitempty"`
|
||||
Height int64 `json:"h,omitempty"`
|
||||
}
|
||||
|
||||
//ResDriving 行驶证返回结果
|
||||
type ResDriving struct {
|
||||
util.CommonError
|
||||
|
||||
PlateNumber string `json:"plate_num,omitempty"`
|
||||
VehicleType string `json:"vehicle_type,omitempty"`
|
||||
Owner string `json:"owner,omitempty"`
|
||||
Address string `json:"addr,omitempty"`
|
||||
UseCharacter string `json:"use_character,omitempty"`
|
||||
Model string `json:"model,omitempty"`
|
||||
Vin string `json:"vin,omitempty"`
|
||||
EngineNumber string `json:"engine_num,omitempty"`
|
||||
RegisterDate string `json:"register_date,omitempty"`
|
||||
IssueDate string `json:"issue_date,omitempty"`
|
||||
PlateNumberB string `json:"plate_num_b,omitempty"`
|
||||
Record string `json:"record,omitempty"`
|
||||
PassengersNumber string `json:"passengers_num,omitempty"`
|
||||
TotalQuality string `json:"total_quality,omitempty"`
|
||||
PrepareQuality string `json:"prepare_quality,omitempty"`
|
||||
OverallSize string `json:"overall_size,omitempty"`
|
||||
CardPositionFront map[string]position `json:"card_position_front,omitempty"`
|
||||
CardPositionBack map[string]position `json:"card_position_back,omitempty"`
|
||||
ImageSize imageSize `json:"img_size,omitempty"`
|
||||
}
|
||||
|
||||
//ResIDCard 身份证返回结果
|
||||
type ResIDCard struct {
|
||||
util.CommonError
|
||||
|
||||
Type string `json:"type,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Address string `json:"addr,omitempty"`
|
||||
Gender string `json:"gender,omitempty"`
|
||||
Nationality string `json:"nationality,omitempty"`
|
||||
ValidDate string `json:"valid_date,omitempty"`
|
||||
}
|
||||
|
||||
//ResBankCard 银行卡返回结果
|
||||
type ResBankCard struct {
|
||||
util.CommonError
|
||||
|
||||
Number string `json:"number,omitempty"`
|
||||
}
|
||||
|
||||
//ResDrivingLicense 驾驶证返回结果
|
||||
type ResDrivingLicense struct {
|
||||
util.CommonError
|
||||
|
||||
IDNumber string `json:"id_num,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Sex string `json:"sex,omitempty"`
|
||||
Nationality string `json:"nationality,omitempty"`
|
||||
Address string `json:"address,omitempty"`
|
||||
Birthday string `json:"birth_date,omitempty"`
|
||||
IssueDate string `json:"issue_date,omitempty"`
|
||||
CarClass string `json:"car_class,omitempty"`
|
||||
ValidFrom string `json:"valid_from,omitempty"`
|
||||
ValidTo string `json:"valid_to,omitempty"`
|
||||
OfficialSeal string `json:"official_seal,omitempty"`
|
||||
}
|
||||
|
||||
//ResBizLicense 营业执照返回结果
|
||||
type ResBizLicense struct {
|
||||
util.CommonError
|
||||
|
||||
RegisterNumber string `json:"reg_num,omitempty"`
|
||||
Serial string `json:"serial,omitempty"`
|
||||
LegalRepresentative string `json:"legal_representative,omitempty"`
|
||||
EnterpriseName string `json:"enterprise_name,omitempty"`
|
||||
TypeOfOrganization string `json:"type_of_organization,omitempty"`
|
||||
Address string `json:"address,omitempty"`
|
||||
TypeOfEnterprise string `json:"type_of_enterprise,omitempty"`
|
||||
BusinessScope string `json:"business_scope,omitempty"`
|
||||
RegisteredCapital string `json:"registered_capital,omitempty"`
|
||||
PaidInCapital string `json:"paid_in_capital,omitempty"`
|
||||
ValidPeriod string `json:"valid_period,omitempty"`
|
||||
RegisterDate string `json:"registered_date,omitempty"`
|
||||
CertPosition map[string]position `json:"cert_position,omitempty"`
|
||||
ImageSize imageSize `json:"img_size,omitempty"`
|
||||
}
|
||||
|
||||
//ResCommon 公共印刷品返回结果
|
||||
type ResCommon struct {
|
||||
util.CommonError
|
||||
|
||||
Items []commonItem `json:"items,omitempty"`
|
||||
ImageSize imageSize `json:"img_size,omitempty"`
|
||||
}
|
||||
|
||||
//commonItem 公共元素
|
||||
type commonItem struct {
|
||||
Position position `json:"pos"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
//ResPlateNumber 车牌号返回结果
|
||||
type ResPlateNumber struct {
|
||||
util.CommonError
|
||||
|
||||
Number string `json:"number"`
|
||||
}
|
||||
|
||||
//NewOCR 实例
|
||||
func NewOCR(c *context.Context) *OCR {
|
||||
ocr := new(OCR)
|
||||
ocr.Context = c
|
||||
return ocr
|
||||
}
|
||||
|
||||
//IDCard 身份证OCR识别接口
|
||||
func (ocr *OCR) IDCard(path string) (ResIDCard ResIDCard, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrIDCardURL, url.QueryEscape(path), accessToken)
|
||||
|
||||
response, err := util.HTTPPost(uri, "")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = util.DecodeWithError(response, &ResIDCard, "OCRIDCard")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
//BankCard 银行卡OCR识别接口
|
||||
func (ocr *OCR) BankCard(path string) (ResBankCard ResBankCard, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrBankCardURL, url.QueryEscape(path), accessToken)
|
||||
|
||||
response, err := util.HTTPPost(uri, "")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = util.DecodeWithError(response, &ResBankCard, "OCRBankCard")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
//Driving 行驶证OCR识别接口
|
||||
func (ocr *OCR) Driving(path string) (ResDriving ResDriving, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrDrivingURL, url.QueryEscape(path), accessToken)
|
||||
|
||||
response, err := util.HTTPPost(uri, "")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = util.DecodeWithError(response, &ResDriving, "OCRDriving")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
//DrivingLicense 驾驶证OCR识别接口
|
||||
func (ocr *OCR) DrivingLicense(path string) (ResDrivingLicense ResDrivingLicense, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrDrivingLicenseURL, url.QueryEscape(path), accessToken)
|
||||
|
||||
response, err := util.HTTPPost(uri, "")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = util.DecodeWithError(response, &ResDrivingLicense, "OCRDrivingLicense")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
//BizLicense 营业执照OCR识别接口
|
||||
func (ocr *OCR) BizLicense(path string) (ResBizLicense ResBizLicense, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrBizLicenseURL, url.QueryEscape(path), accessToken)
|
||||
|
||||
response, err := util.HTTPPost(uri, "")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = util.DecodeWithError(response, &ResBizLicense, "OCRBizLicense")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
//Common 通用印刷体OCR识别接口
|
||||
func (ocr *OCR) Common(path string) (ResCommon ResCommon, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrCommonURL, url.QueryEscape(path), accessToken)
|
||||
|
||||
response, err := util.HTTPPost(uri, "")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = util.DecodeWithError(response, &ResCommon, "OCRCommon")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
//PlateNumber 车牌OCR识别接口
|
||||
func (ocr *OCR) PlateNumber(path string) (ResPlateNumber ResPlateNumber, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("%s?img_url=%s&access_token=%s", ocrPlateNumberURL, url.QueryEscape(path), accessToken)
|
||||
|
||||
response, err := util.HTTPPost(uri, "")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = util.DecodeWithError(response, &ResPlateNumber, "OCRPlateNumber")
|
||||
|
||||
return
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package officialaccount
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/silenceper/wechat/v2/officialaccount/ocr"
|
||||
|
||||
"github.com/silenceper/wechat/v2/officialaccount/datacube"
|
||||
|
||||
"github.com/silenceper/wechat/v2/credential"
|
||||
@@ -113,3 +115,8 @@ func (officialAccount *OfficialAccount) GetBroadcast() *broadcast.Broadcast {
|
||||
func (officialAccount *OfficialAccount) GetDataCube() *datacube.DataCube {
|
||||
return datacube.NewCube(officialAccount.ctx)
|
||||
}
|
||||
|
||||
//GetOCR OCR接口
|
||||
func (officialAccount *OfficialAccount) GetOCR() *ocr.OCR {
|
||||
return ocr.NewOCR(officialAccount.ctx)
|
||||
}
|
||||
|
||||
@@ -27,10 +27,10 @@ type Server struct {
|
||||
|
||||
openID string
|
||||
|
||||
messageHandler func(message.MixMessage) *message.Reply
|
||||
messageHandler func(*message.MixMessage) *message.Reply
|
||||
|
||||
RequestRawXMLMsg []byte
|
||||
RequestMsg message.MixMessage
|
||||
RequestMsg *message.MixMessage
|
||||
ResponseRawXMLMsg []byte
|
||||
ResponseMsg interface{}
|
||||
|
||||
@@ -105,7 +105,7 @@ func (srv *Server) handleRequest() (reply *message.Reply, err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
mixMessage, success := msg.(message.MixMessage)
|
||||
mixMessage, success := msg.(*message.MixMessage)
|
||||
if !success {
|
||||
err = errors.New("消息类型转换失败")
|
||||
}
|
||||
@@ -160,14 +160,14 @@ func (srv *Server) getMessage() (interface{}, error) {
|
||||
return srv.parseRequestMessage(rawXMLMsgBytes)
|
||||
}
|
||||
|
||||
func (srv *Server) parseRequestMessage(rawXMLMsgBytes []byte) (msg message.MixMessage, err error) {
|
||||
msg = message.MixMessage{}
|
||||
err = xml.Unmarshal(rawXMLMsgBytes, &msg)
|
||||
func (srv *Server) parseRequestMessage(rawXMLMsgBytes []byte) (msg *message.MixMessage, err error) {
|
||||
msg = &message.MixMessage{}
|
||||
err = xml.Unmarshal(rawXMLMsgBytes, msg)
|
||||
return
|
||||
}
|
||||
|
||||
//SetMessageHandler 设置用户自定义的回调方法
|
||||
func (srv *Server) SetMessageHandler(handler func(message.MixMessage) *message.Reply) {
|
||||
func (srv *Server) SetMessageHandler(handler func(*message.MixMessage) *message.Reply) {
|
||||
srv.messageHandler = handler
|
||||
}
|
||||
|
||||
|
||||
87
officialaccount/user/migrate.go
Normal file
87
officialaccount/user/migrate.go
Normal file
@@ -0,0 +1,87 @@
|
||||
//Package user migrate 用于微信公众号账号迁移,获取openID变化
|
||||
//参考文档:https://kf.qq.com/faq/1901177NrqMr190117nqYJze.html
|
||||
package user
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const (
|
||||
changeOpenIDURL = "https://api.weixin.qq.com/cgi-bin/changeopenid"
|
||||
)
|
||||
|
||||
// ChangeOpenIDResult OpenID迁移变化
|
||||
type ChangeOpenIDResult struct {
|
||||
OriOpenID string `json:"ori_openid"`
|
||||
NewOpenID string `json:"new_openid"`
|
||||
ErrMsg string `json:"err_msg,omitempty"`
|
||||
}
|
||||
|
||||
// ChangeOpenIDResultList OpenID迁移变化列表
|
||||
type ChangeOpenIDResultList struct {
|
||||
util.CommonError
|
||||
List []ChangeOpenIDResult `json:"result_list"`
|
||||
}
|
||||
|
||||
// ListChangeOpenIDs 返回指定OpenID变化列表
|
||||
// fromAppID 为老账号AppID
|
||||
// openIDs 为老账号的openID,openIDs限100个以内
|
||||
// AccessToken 为新账号的AccessToken
|
||||
func (user *User) ListChangeOpenIDs(fromAppID string, openIDs ...string) (list *ChangeOpenIDResultList, err error) {
|
||||
list = &ChangeOpenIDResultList{}
|
||||
//list.List = make([]ChangeOpenIDResult, 0)
|
||||
if len(openIDs) > 100 {
|
||||
err = errors.New("openIDs length must be lt 100")
|
||||
return
|
||||
}
|
||||
|
||||
if fromAppID == "" {
|
||||
err = errors.New("fromAppID is required")
|
||||
return
|
||||
}
|
||||
|
||||
accessToken, err := user.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("%s?access_token=%s", changeOpenIDURL, accessToken)
|
||||
var resp []byte
|
||||
var req struct {
|
||||
FromAppID string `json:"from_appid"`
|
||||
OpenidList []string `json:"openid_list"`
|
||||
}
|
||||
req.FromAppID = fromAppID
|
||||
req.OpenidList = append(req.OpenidList, openIDs...)
|
||||
resp, err = util.PostJSON(uri, req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = util.DecodeWithError(resp, list, "ListChangeOpenIDs")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListAllChangeOpenIDs 返回所有用户OpenID列表
|
||||
// fromAppID 为老账号AppID
|
||||
// openIDs 为老账号的openID
|
||||
// AccessToken 为新账号的AccessToken
|
||||
func (user *User) ListAllChangeOpenIDs(fromAppID string, openIDs ...string) (list []ChangeOpenIDResult, err error) {
|
||||
list = make([]ChangeOpenIDResult, 0)
|
||||
chunks := util.SliceChunk(openIDs, 100)
|
||||
for _, chunk := range chunks {
|
||||
result, err := user.ListChangeOpenIDs(fromAppID, chunk...)
|
||||
if err != nil {
|
||||
return list, err
|
||||
}
|
||||
list = append(list, result.List...)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -139,7 +139,7 @@ func (user *User) ListUserOpenIDs(nextOpenid ...string) (*OpenidList, error) {
|
||||
// ListAllUserOpenIDs 返回所有用户OpenID列表
|
||||
func (user *User) ListAllUserOpenIDs() ([]string, error) {
|
||||
nextOpenid := ""
|
||||
openids := []string{}
|
||||
openids := make([]string, 0)
|
||||
count := 0
|
||||
for {
|
||||
ul, err := user.ListUserOpenIDs(nextOpenid)
|
||||
|
||||
@@ -22,7 +22,7 @@ openPlatform := wc.GetOpenPlatform(cfg)
|
||||
// 传入request和responseWriter
|
||||
server := openPlatform.GetServer(req, rw)
|
||||
//设置接收消息的处理方法
|
||||
server.SetMessageHandler(func(msg message.MixMessage) *message.Reply {
|
||||
server.SetMessageHandler(func(msg *message.MixMessage) *message.Reply {
|
||||
if msg.InfoType == message.InfoTypeVerifyTicket {
|
||||
componentVerifyTicket, err := openPlatform.SetComponentAccessToken(msg.ComponentVerifyTicket)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package config
|
||||
|
||||
//Config config for pay
|
||||
// Config config for pay
|
||||
type Config struct {
|
||||
AppID string `json:"app_id"`
|
||||
MchID string `json:"mch_id"`
|
||||
|
||||
@@ -46,9 +46,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"`
|
||||
|
||||
77
pay/notify/refund.go
Normal file
77
pay/notify/refund.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
// reference: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_16&index=10
|
||||
|
||||
// RefundedResult 退款回调
|
||||
type RefundedResult struct {
|
||||
ReturnCode *string `xml:"return_code"`
|
||||
ReturnMsg *string `xml:"return_msg"`
|
||||
|
||||
AppID *string `xml:"appid"`
|
||||
MchID *string `xml:"mch_id"`
|
||||
NonceStr *string `xml:"nonce_str"`
|
||||
ReqInfo *string `xml:"req_info"`
|
||||
}
|
||||
|
||||
// RefundedReqInfo 退款结果(明文)
|
||||
type RefundedReqInfo struct {
|
||||
TransactionID *string `xml:"transaction_id"`
|
||||
OutTradeNO *string `xml:"out_trade_no"`
|
||||
RefundID *string `xml:"refund_id"`
|
||||
OutRefundNO *string `xml:"out_refund_no"`
|
||||
TotalFee *int `xml:"total_fee"`
|
||||
SettlementTotalFee *int `xml:"settlement_total_fee"`
|
||||
RefundFee *int `xml:"refund_fee"`
|
||||
SettlementRefundFee *int `xml:"settlement_refund_fee"`
|
||||
RefundStatus *string `xml:"refund_status"`
|
||||
SuccessTime *string `xml:"success_time"`
|
||||
RefundRecvAccount *string `xml:"refund_recv_account"`
|
||||
RefundAccount *string `xml:"refund_account"`
|
||||
RefundRequestSource *string `xml:"refund_request_source"`
|
||||
}
|
||||
|
||||
// RefundedResp 消息通知返回
|
||||
type RefundedResp struct {
|
||||
ReturnCode string `xml:"return_code"`
|
||||
ReturnMsg string `xml:"return_msg"`
|
||||
}
|
||||
|
||||
// DecryptReqInfo 对退款结果进行解密
|
||||
func (notify *Notify) DecryptReqInfo(result *RefundedResult) (*RefundedReqInfo, error) {
|
||||
var err error
|
||||
if result == nil || result.ReqInfo == nil {
|
||||
return nil, errors.New("empty refunded_result or req_info")
|
||||
}
|
||||
|
||||
base64Decode, err := base64.StdEncoding.DecodeString(*result.ReqInfo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
hash := md5.New()
|
||||
if _, err = hash.Write([]byte(notify.Key)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
md5APIKey := hex.EncodeToString(hash.Sum(nil))
|
||||
|
||||
data, err := util.AesECBDecrypt(base64Decode, []byte(md5APIKey))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
res := &RefundedReqInfo{}
|
||||
if err = xml.Unmarshal(data, res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
26
pay/notify/refund_test.go
Normal file
26
pay/notify/refund_test.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"testing"
|
||||
|
||||
"github.com/silenceper/wechat/v2/pay/config"
|
||||
)
|
||||
|
||||
func TestNotify_DecryptReqInfo(t *testing.T) {
|
||||
// data_source: https://studygolang.com/articles/11811
|
||||
notify := &Notify{Config: &config.Config{Key: "ziR0QKsTUfMOuochC9RfCdmfHECorQAP"}}
|
||||
info := "YYwp8C48th0wnQzTqeI+41pflB26v+smFj9z6h9RPBgxTyZyxc+4YNEz7QEgZNWj/6rIb2MfyWMZmCc41CfjKSssoSZPXxOhUayb6KvNSZ1p6frOX1PDWzhyruXK7ouNND+gDsG4yZ0XXzsL4/pYNwLLba/71QrnkJ/BHcByk4EXnglju5DLup9pJQSnTxjomI9Rxu57m9jg5lLQFxMWXyeASZJNvof0ulnHlWJswS4OxKOkmW7VEyKyLGV6npoOm03Qsx2wkRxLsSa9gPpg4hdaReeUqh1FMbm7aWjyrVYT/MEZWg98p4GomEIYvz34XfDncTezX4bf/ZiSLXt79aE1/YTZrYfymXeCrGjlbe0rg/T2ezJHAC870u2vsVbY1/KcE2A443N+DEnAziXlBQ1AeWq3Rqk/O6/TMM0lomzgctAOiAMg+bh5+Gu1ubA9O3E+vehULydD5qx2o6i3+qA9ORbH415NyRrQdeFq5vmCiRikp5xYptWiGZA0tkoaLKMPQ4ndE5gWHqiBbGPfULZWokI+QjjhhBmwgbd6J0VqpRorwOuzC/BHdkP72DCdNcm7IDUpggnzBIy0+seWIkcHEryKjge3YDHpJeQCqrAH0CgxXHDt1xtbQbST1VqFyuhPhUjDXMXrknrGPN/oE1t0rLRq+78cI+k8xe5E6seeUXQsEe8r3358mpcDYSmXWSXVZxK6er9EF98APqHwcndyEJD2YyCh/mMVhERuX+7kjlRXSiNUWa/Cv/XAKFQuvUYA5ea2eYWtPRHa4DpyuF1SNsaqVKfgqKXZrJHfAgslVpSVqUpX4zkKszHF4kwMZO3M7J1P94Mxa7Tm9mTOJePOoHPXeEB+m9rX6pSfoi3mJDQ5inJ+Vc4gOkg/Wd/lqiy6TTyP/dHDN6/v+AuJx5AXBo/2NDD3fWhHjkqEKIuARr2ClZt9ZRQO4HkXdZo7CN06sGCHk48Tg8PmxnxKcMZm7Aoquv5yMIM2gWSWIRJhwJ8cUpafIHc+GesDlbF6Zbt+/KXkafJAQq2RklEN+WvZ/zFz113EPgWPjp16TwBoziq96MMekvWKY/vdhjol8VFtGH9F61Oy1Xwf6DJtPw=="
|
||||
res, err := notify.DecryptReqInfo(&RefundedResult{ReqInfo: &info})
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
bytes, err := xml.Marshal(res)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
t.Log(string(bytes))
|
||||
}
|
||||
@@ -11,9 +11,12 @@ import (
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
//https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
|
||||
// https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
|
||||
var payGateway = "https://api.mch.weixin.qq.com/pay/unifiedorder"
|
||||
|
||||
// SUCCESS 表示支付成功
|
||||
const SUCCESS = "SUCCESS"
|
||||
|
||||
// Order struct extends context
|
||||
type Order struct {
|
||||
*config.Config
|
||||
@@ -25,7 +28,7 @@ func NewOrder(cfg *config.Config) *Order {
|
||||
return &order
|
||||
}
|
||||
|
||||
// Params was NEEDED when request unifiedorder
|
||||
// Params was NEEDED when request Unified order
|
||||
// 传入的参数,用于生成 prepay_id 的必需参数
|
||||
type Params struct {
|
||||
TotalFee string
|
||||
@@ -51,7 +54,7 @@ type Config struct {
|
||||
PaySign string `json:"paySign"`
|
||||
}
|
||||
|
||||
// PreOrder 是 unifie order 接口的返回
|
||||
// PreOrder 是 Unified order 接口的返回
|
||||
type PreOrder struct {
|
||||
ReturnCode string `xml:"return_code"`
|
||||
ReturnMsg string `xml:"return_msg"`
|
||||
@@ -70,14 +73,14 @@ type PreOrder struct {
|
||||
|
||||
// payRequest 接口请求参数
|
||||
type payRequest struct {
|
||||
AppID string `xml:"appid"`
|
||||
MchID string `xml:"mch_id"`
|
||||
DeviceInfo string `xml:"device_info,omitempty"`
|
||||
NonceStr string `xml:"nonce_str"`
|
||||
Sign string `xml:"sign"`
|
||||
SignType string `xml:"sign_type,omitempty"`
|
||||
Body string `xml:"body"`
|
||||
Detail string `xml:"detail,omitempty"`
|
||||
AppID string `xml:"appid"` // 公众账号ID
|
||||
MchID string `xml:"mch_id"` // 商户号
|
||||
DeviceInfo string `xml:"device_info,omitempty"` // 设备号
|
||||
NonceStr string `xml:"nonce_str"` // 随机字符串
|
||||
Sign string `xml:"sign"` // 签名
|
||||
SignType string `xml:"sign_type,omitempty"` // 签名类型
|
||||
Body string `xml:"body"` // 商品描述
|
||||
Detail string `xml:"detail,omitempty"` // 商品详情
|
||||
Attach string `xml:"attach,omitempty"` // 附加数据
|
||||
OutTradeNo string `xml:"out_trade_no"` // 商户订单号
|
||||
FeeType string `xml:"fee_type,omitempty"` // 标价币种
|
||||
@@ -89,7 +92,7 @@ type payRequest struct {
|
||||
NotifyURL string `xml:"notify_url"` // 通知地址
|
||||
TradeType string `xml:"trade_type"` // 交易类型
|
||||
ProductID string `xml:"product_id,omitempty"` // 商品ID
|
||||
LimitPay string `xml:"limit_pay,omitempty"` //
|
||||
LimitPay string `xml:"limit_pay,omitempty"` // 指定支付方式
|
||||
OpenID string `xml:"openid,omitempty"` // 用户标识
|
||||
SceneInfo string `xml:"scene_info,omitempty"` // 场景信息
|
||||
|
||||
@@ -190,9 +193,9 @@ func (o *Order) PrePayOrder(p *Params) (payOrder PreOrder, err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if payOrder.ReturnCode == "SUCCESS" {
|
||||
if payOrder.ReturnCode == SUCCESS {
|
||||
// pay success
|
||||
if payOrder.ResultCode == "SUCCESS" {
|
||||
if payOrder.ResultCode == SUCCESS {
|
||||
err = nil
|
||||
return
|
||||
}
|
||||
|
||||
82
pay/order/query.go
Normal file
82
pay/order/query.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
|
||||
"github.com/silenceper/wechat/v2/pay/notify"
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
var queryGateway = "https://api.mch.weixin.qq.com/pay/orderquery"
|
||||
|
||||
// QueryParams 传入的参数
|
||||
type QueryParams struct {
|
||||
OutTradeNo string // 商户订单号
|
||||
SignType string // 签名类型
|
||||
TransactionID string // 微信订单号
|
||||
}
|
||||
|
||||
// queryRequest 接口请求参数
|
||||
type queryRequest struct {
|
||||
AppID string `xml:"appid"` // 公众账号ID
|
||||
MchID string `xml:"mch_id"` // 商户号
|
||||
NonceStr string `xml:"nonce_str"` // 随机字符串
|
||||
Sign string `xml:"sign"` // 签名
|
||||
SignType string `xml:"sign_type,omitempty"` // 签名类型
|
||||
TransactionID string `xml:"transaction_id"` // 微信订单号
|
||||
OutTradeNo string `xml:"out_trade_no"` // 商户订单号
|
||||
}
|
||||
|
||||
// QueryOrder 查询订单
|
||||
func (o *Order) QueryOrder(p *QueryParams) (paidResult notify.PaidResult, err error) {
|
||||
nonceStr := util.RandomStr(32)
|
||||
// 签名类型
|
||||
if p.SignType == "" {
|
||||
p.SignType = "MD5"
|
||||
}
|
||||
|
||||
params := make(map[string]string)
|
||||
params["appid"] = o.AppID
|
||||
params["mch_id"] = o.MchID
|
||||
params["nonce_str"] = nonceStr
|
||||
params["out_trade_no"] = p.OutTradeNo
|
||||
params["sign_type"] = p.SignType
|
||||
params["transaction_id"] = p.TransactionID
|
||||
|
||||
sign, err := util.ParamSign(params, o.Key)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
request := queryRequest{
|
||||
AppID: o.AppID,
|
||||
MchID: o.MchID,
|
||||
NonceStr: nonceStr,
|
||||
Sign: sign,
|
||||
OutTradeNo: p.OutTradeNo,
|
||||
TransactionID: p.TransactionID,
|
||||
SignType: p.SignType,
|
||||
}
|
||||
|
||||
rawRet, err := util.PostXML(queryGateway, request)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = xml.Unmarshal(rawRet, &paidResult)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if *paidResult.ReturnCode == SUCCESS {
|
||||
// query success
|
||||
if *paidResult.ResultCode == SUCCESS {
|
||||
err = nil
|
||||
return
|
||||
}
|
||||
err = errors.New(*paidResult.ErrCode + *paidResult.ErrCodeDes)
|
||||
return
|
||||
}
|
||||
err = errors.New("[msg : xmlUnmarshalError] [rawReturn : " + string(rawRet) + "] [sign : " + sign + "]")
|
||||
return
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"github.com/silenceper/wechat/v2/pay/notify"
|
||||
"github.com/silenceper/wechat/v2/pay/order"
|
||||
"github.com/silenceper/wechat/v2/pay/refund"
|
||||
"github.com/silenceper/wechat/v2/pay/transfer"
|
||||
)
|
||||
|
||||
//Pay 微信支付相关API
|
||||
@@ -31,3 +32,8 @@ func (pay *Pay) GetNotify() *notify.Notify {
|
||||
func (pay *Pay) GetRefund() *refund.Refund {
|
||||
return refund.NewRefund(pay.cfg)
|
||||
}
|
||||
|
||||
// GetTransfer 付款
|
||||
func (pay *Pay) GetTransfer() *transfer.Transfer {
|
||||
return transfer.NewTransfer(pay.cfg)
|
||||
}
|
||||
|
||||
@@ -21,32 +21,36 @@ func NewRefund(cfg *config.Config) *Refund {
|
||||
return &refund
|
||||
}
|
||||
|
||||
//Params 调用参数
|
||||
// Params 调用参数
|
||||
type Params struct {
|
||||
TransactionID string
|
||||
OutRefundNo string
|
||||
OutTradeNo string
|
||||
TotalFee string
|
||||
RefundFee string
|
||||
RefundDesc string
|
||||
RootCa string //ca证书
|
||||
RootCa string // ca证书
|
||||
NotifyURL string
|
||||
SignType string
|
||||
}
|
||||
|
||||
//request 接口请求参数
|
||||
// request 接口请求参数
|
||||
type request struct {
|
||||
AppID string `xml:"appid"`
|
||||
MchID string `xml:"mch_id"`
|
||||
NonceStr string `xml:"nonce_str"`
|
||||
Sign string `xml:"sign"`
|
||||
SignType string `xml:"sign_type,omitempty"`
|
||||
TransactionID string `xml:"transaction_id"`
|
||||
TransactionID string `xml:"transaction_id,omitempty"`
|
||||
OutTradeNo string `xml:"out_trade_no,omitempty"`
|
||||
OutRefundNo string `xml:"out_refund_no"`
|
||||
TotalFee string `xml:"total_fee"`
|
||||
RefundFee string `xml:"refund_fee"`
|
||||
RefundDesc string `xml:"refund_desc,omitempty"`
|
||||
//NotifyUrl string `xml:"notify_url,omitempty"`
|
||||
NotifyURL string `xml:"notify_url,omitempty"`
|
||||
}
|
||||
|
||||
//Response 接口返回
|
||||
// Response 接口返回
|
||||
type Response struct {
|
||||
ReturnCode string `xml:"return_code"`
|
||||
ReturnMsg string `xml:"return_msg"`
|
||||
@@ -70,38 +74,35 @@ type Response struct {
|
||||
CashFeeType string `xml:"cash_fee_type,omitempty"`
|
||||
}
|
||||
|
||||
//Refund 退款申请
|
||||
// Refund 退款申请
|
||||
func (refund *Refund) Refund(p *Params) (rsp Response, err error) {
|
||||
nonceStr := util.RandomStr(32)
|
||||
param := make(map[string]string)
|
||||
param["appid"] = refund.AppID
|
||||
param["mch_id"] = refund.MchID
|
||||
param["nonce_str"] = nonceStr
|
||||
param["out_refund_no"] = p.OutRefundNo
|
||||
param["refund_desc"] = p.RefundDesc
|
||||
param["refund_fee"] = p.RefundFee
|
||||
param["total_fee"] = p.TotalFee
|
||||
param["sign_type"] = util.SignTypeMD5
|
||||
param["transaction_id"] = p.TransactionID
|
||||
param := refund.GetSignParam(p)
|
||||
|
||||
sign, err := util.ParamSign(param, refund.Key)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
request := request{
|
||||
AppID: refund.AppID,
|
||||
MchID: refund.MchID,
|
||||
NonceStr: nonceStr,
|
||||
Sign: sign,
|
||||
SignType: util.SignTypeMD5,
|
||||
TransactionID: p.TransactionID,
|
||||
OutRefundNo: p.OutRefundNo,
|
||||
TotalFee: p.TotalFee,
|
||||
RefundFee: p.RefundFee,
|
||||
RefundDesc: p.RefundDesc,
|
||||
req := request{
|
||||
AppID: param["appid"],
|
||||
MchID: param["mch_id"],
|
||||
NonceStr: param["nonce_str"],
|
||||
Sign: sign,
|
||||
SignType: param["sign_type"],
|
||||
OutRefundNo: param["out_refund_no"],
|
||||
TotalFee: param["total_fee"],
|
||||
RefundFee: param["refund_fee"],
|
||||
RefundDesc: param["refund_desc"],
|
||||
NotifyURL: param["notify_url"],
|
||||
}
|
||||
rawRet, err := util.PostXMLWithTLS(refundGateway, request, p.RootCa, refund.MchID)
|
||||
if p.OutTradeNo != "" {
|
||||
req.OutTradeNo = p.OutTradeNo
|
||||
}
|
||||
if p.TransactionID != "" {
|
||||
req.TransactionID = p.TransactionID
|
||||
}
|
||||
|
||||
rawRet, err := util.PostXMLWithTLS(refundGateway, req, p.RootCa, refund.MchID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -120,3 +121,31 @@ func (refund *Refund) Refund(p *Params) (rsp Response, err error) {
|
||||
err = fmt.Errorf("[msg : xmlUnmarshalError] [rawReturn : %s] [sign : %s]", string(rawRet), sign)
|
||||
return
|
||||
}
|
||||
|
||||
// GetSignParam 获取签名的参数
|
||||
func (refund *Refund) GetSignParam(p *Params) (param map[string]string) {
|
||||
nonceStr := util.RandomStr(32)
|
||||
param = make(map[string]string)
|
||||
param["appid"] = refund.AppID
|
||||
param["mch_id"] = refund.MchID
|
||||
param["nonce_str"] = nonceStr
|
||||
param["out_refund_no"] = p.OutRefundNo
|
||||
param["refund_desc"] = p.RefundDesc
|
||||
param["refund_fee"] = p.RefundFee
|
||||
param["total_fee"] = p.TotalFee
|
||||
|
||||
if p.SignType == "" {
|
||||
param["sign_type"] = util.SignTypeMD5
|
||||
}
|
||||
if p.OutTradeNo != "" {
|
||||
param["out_trade_no"] = p.OutTradeNo
|
||||
}
|
||||
if p.TransactionID != "" {
|
||||
param["transaction_id"] = p.TransactionID
|
||||
}
|
||||
if p.NotifyURL != "" {
|
||||
param["notify_url"] = p.NotifyURL
|
||||
}
|
||||
|
||||
return param
|
||||
}
|
||||
|
||||
138
pay/transfer/transfer_wallet.go
Normal file
138
pay/transfer/transfer_wallet.go
Normal file
@@ -0,0 +1,138 @@
|
||||
package transfer
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/silenceper/wechat/v2/pay/config"
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
// 付款到零钱
|
||||
// https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
|
||||
var walletTransferGateway = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"
|
||||
|
||||
// Transfer struct extends context
|
||||
type Transfer struct {
|
||||
*config.Config
|
||||
}
|
||||
|
||||
// NewTransfer return an instance of Transfer package
|
||||
func NewTransfer(cfg *config.Config) *Transfer {
|
||||
transfer := Transfer{cfg}
|
||||
return &transfer
|
||||
}
|
||||
|
||||
//Params 调用参数
|
||||
type Params struct {
|
||||
DeviceInfo string
|
||||
PartnerTradeNo string
|
||||
OpenID string
|
||||
CheckName bool
|
||||
ReUserName string
|
||||
Amount int
|
||||
Desc string
|
||||
SpbillCreateIP string
|
||||
RootCa string //ca证书
|
||||
}
|
||||
|
||||
//request 接口请求参数
|
||||
type request struct {
|
||||
AppID string `xml:"mch_appid"`
|
||||
MchID string `xml:"mchid"`
|
||||
NonceStr string `xml:"nonce_str"`
|
||||
Sign string `xml:"sign"`
|
||||
DeviceInfo string `xml:"device_info,omitempty"`
|
||||
PartnerTradeNo string `xml:"partner_trade_no"`
|
||||
OpenID string `xml:"openid"`
|
||||
CheckName string `xml:"check_name"`
|
||||
ReUserName string `xml:"re_user_name,omitempty"`
|
||||
Amount int `xml:"amount"`
|
||||
Desc string `xml:"desc"`
|
||||
SpbillCreateIP string `xml:"spbill_create_ip,omitempty"`
|
||||
}
|
||||
|
||||
//Response 接口返回
|
||||
type Response struct {
|
||||
ReturnCode string `xml:"return_code"`
|
||||
ReturnMsg string `xml:"return_msg"`
|
||||
AppID string `xml:"appid,omitempty"`
|
||||
MchID string `xml:"mch_id,omitempty"`
|
||||
DeviceInfo string `xml:"device_info,omitempty"`
|
||||
NonceStr string `xml:"nonce_str,omitempty"`
|
||||
ResultCode string `xml:"result_code,omitempty"`
|
||||
ErrCode string `xml:"err_code,omitempty"`
|
||||
ErrCodeDes string `xml:"err_code_des,omitempty"`
|
||||
PartnerTradeNo string `xml:"partner_trade_no"`
|
||||
PaymentNo string `xml:"payment_no"`
|
||||
PaymentTime string `xml:"payment_time"`
|
||||
}
|
||||
|
||||
//WalletTransfer 付款到零钱
|
||||
func (transfer *Transfer) WalletTransfer(p *Params) (rsp Response, err error) {
|
||||
nonceStr := util.RandomStr(32)
|
||||
param := make(map[string]string)
|
||||
param["mch_appid"] = transfer.AppID
|
||||
param["mchid"] = transfer.MchID
|
||||
param["nonce_str"] = nonceStr
|
||||
param["partner_trade_no"] = p.PartnerTradeNo
|
||||
param["openid"] = p.OpenID
|
||||
param["amount"] = strconv.Itoa(p.Amount)
|
||||
param["desc"] = p.Desc
|
||||
if p.DeviceInfo != "" {
|
||||
param["device_info"] = p.DeviceInfo
|
||||
}
|
||||
if p.CheckName {
|
||||
param["check_name"] = "FORCE_CHECK"
|
||||
param["re_user_name"] = p.ReUserName
|
||||
} else {
|
||||
param["check_name"] = "NO_CHECK"
|
||||
}
|
||||
if p.SpbillCreateIP != "" {
|
||||
param["spbill_create_ip"] = p.SpbillCreateIP
|
||||
}
|
||||
|
||||
sign, err := util.ParamSign(param, transfer.Key)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
req := request{
|
||||
AppID: transfer.AppID,
|
||||
MchID: transfer.MchID,
|
||||
NonceStr: nonceStr,
|
||||
Sign: sign,
|
||||
DeviceInfo: p.DeviceInfo,
|
||||
PartnerTradeNo: p.PartnerTradeNo,
|
||||
OpenID: p.OpenID,
|
||||
Amount: p.Amount,
|
||||
Desc: p.Desc,
|
||||
SpbillCreateIP: p.SpbillCreateIP,
|
||||
}
|
||||
if p.CheckName {
|
||||
req.CheckName = "FORCE_CHECK"
|
||||
req.ReUserName = p.ReUserName
|
||||
} else {
|
||||
req.CheckName = "NO_CHECK"
|
||||
}
|
||||
|
||||
rawRet, err := util.PostXMLWithTLS(walletTransferGateway, req, p.RootCa, transfer.MchID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = xml.Unmarshal(rawRet, &rsp)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if rsp.ReturnCode == "SUCCESS" {
|
||||
if rsp.ResultCode == "SUCCESS" {
|
||||
err = nil
|
||||
return
|
||||
}
|
||||
err = fmt.Errorf("transfer error, errcode=%s,errmsg=%s", rsp.ErrCode, rsp.ErrCodeDes)
|
||||
return
|
||||
}
|
||||
err = fmt.Errorf("[msg : xmlUnmarshalError] [rawReturn : %s] [sign : %s]", string(rawRet), sign)
|
||||
return
|
||||
}
|
||||
109
util/crypto.go
109
util/crypto.go
@@ -1,6 +1,7 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/hmac"
|
||||
@@ -20,7 +21,7 @@ const (
|
||||
SignTypeHMACSHA256 = `HMAC-SHA256`
|
||||
)
|
||||
|
||||
//EncryptMsg 加密消息
|
||||
// EncryptMsg 加密消息
|
||||
func EncryptMsg(random, rawXMLMsg []byte, appID, aesKey string) (encrtptMsg []byte, err error) {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
@@ -38,7 +39,7 @@ func EncryptMsg(random, rawXMLMsg []byte, appID, aesKey string) (encrtptMsg []by
|
||||
return
|
||||
}
|
||||
|
||||
//AESEncryptMsg ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]
|
||||
// AESEncryptMsg ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]
|
||||
//参考:github.com/chanxuehong/wechat.v2
|
||||
func AESEncryptMsg(random, rawXMLMsg []byte, appID string, aesKey []byte) (ciphertext []byte) {
|
||||
const (
|
||||
@@ -76,7 +77,7 @@ func AESEncryptMsg(random, rawXMLMsg []byte, appID string, aesKey []byte) (ciphe
|
||||
return
|
||||
}
|
||||
|
||||
//DecryptMsg 消息解密
|
||||
// DecryptMsg 消息解密
|
||||
func DecryptMsg(appID, encryptedMsg, aesKey string) (random, rawMsgXMLBytes []byte, err error) {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
@@ -227,3 +228,105 @@ func ParamSign(p map[string]string, key string) (string, error) {
|
||||
|
||||
return CalculateSign(str, signType, key)
|
||||
}
|
||||
|
||||
// ECB provides confidentiality by assigning a fixed ciphertext block to each plaintext block.
|
||||
// See NIST SP 800-38A, pp 08-09
|
||||
// reference: https://codereview.appspot.com/7860047/patch/23001/24001
|
||||
type ecb struct {
|
||||
b cipher.Block
|
||||
blockSize int
|
||||
}
|
||||
|
||||
func newECB(b cipher.Block) *ecb {
|
||||
return &ecb{
|
||||
b: b,
|
||||
blockSize: b.BlockSize(),
|
||||
}
|
||||
}
|
||||
|
||||
// ECBEncryptor -
|
||||
type ECBEncryptor ecb
|
||||
|
||||
// NewECBEncryptor returns a BlockMode which encrypts in electronic code book mode, using the given Block.
|
||||
func NewECBEncryptor(b cipher.Block) cipher.BlockMode {
|
||||
return (*ECBEncryptor)(newECB(b))
|
||||
}
|
||||
|
||||
// BlockSize implement BlockMode.BlockSize
|
||||
func (x *ECBEncryptor) BlockSize() int {
|
||||
return x.blockSize
|
||||
}
|
||||
|
||||
// CryptBlocks implement BlockMode.CryptBlocks
|
||||
func (x *ECBEncryptor) CryptBlocks(dst, src []byte) {
|
||||
if len(src)%x.blockSize != 0 {
|
||||
panic("crypto/cipher: input not full blocks")
|
||||
}
|
||||
if len(dst) < len(src) {
|
||||
panic("crypto/cipher: output smaller than input")
|
||||
}
|
||||
for len(src) > 0 {
|
||||
x.b.Encrypt(dst, src[:x.blockSize])
|
||||
src = src[x.blockSize:]
|
||||
dst = dst[x.blockSize:]
|
||||
}
|
||||
}
|
||||
|
||||
// ECBDecryptor -
|
||||
type ECBDecryptor ecb
|
||||
|
||||
// NewECBDecryptor returns a BlockMode which decrypts in electronic code book mode, using the given Block.
|
||||
func NewECBDecryptor(b cipher.Block) cipher.BlockMode {
|
||||
return (*ECBDecryptor)(newECB(b))
|
||||
}
|
||||
|
||||
// BlockSize implement BlockMode.BlockSize
|
||||
func (x *ECBDecryptor) BlockSize() int {
|
||||
return x.blockSize
|
||||
}
|
||||
|
||||
// CryptBlocks implement BlockMode.CryptBlocks
|
||||
func (x *ECBDecryptor) CryptBlocks(dst, src []byte) {
|
||||
if len(src)%x.blockSize != 0 {
|
||||
panic("crypto/cipher: input not full blocks")
|
||||
}
|
||||
if len(dst) < len(src) {
|
||||
panic("crypto/cipher: output smaller than input")
|
||||
}
|
||||
for len(src) > 0 {
|
||||
x.b.Decrypt(dst, src[:x.blockSize])
|
||||
src = src[x.blockSize:]
|
||||
dst = dst[x.blockSize:]
|
||||
}
|
||||
}
|
||||
|
||||
// AesECBDecrypt will decrypt data with PKCS5Padding
|
||||
func AesECBDecrypt(ciphertext []byte, aesKey []byte) ([]byte, error) {
|
||||
if len(ciphertext) < aes.BlockSize {
|
||||
return nil, errors.New("ciphertext too short")
|
||||
}
|
||||
// ECB mode always works in whole blocks.
|
||||
if len(ciphertext)%aes.BlockSize != 0 {
|
||||
return nil, errors.New("ciphertext is not a multiple of the block size")
|
||||
}
|
||||
block, err := aes.NewCipher(aesKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
NewECBDecryptor(block).CryptBlocks(ciphertext, ciphertext)
|
||||
return PKCS5UnPadding(ciphertext), nil
|
||||
}
|
||||
|
||||
// PKCS5Padding -
|
||||
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(ciphertext)%blockSize
|
||||
padText := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(ciphertext, padText...)
|
||||
}
|
||||
|
||||
// PKCS5UnPadding -
|
||||
func PKCS5UnPadding(origData []byte) []byte {
|
||||
length := len(origData)
|
||||
unPadding := int(origData[length-1])
|
||||
return origData[:(length - unPadding)]
|
||||
}
|
||||
|
||||
23
util/http.go
23
util/http.go
@@ -48,15 +48,14 @@ func HTTPPost(uri string, data string) ([]byte, error) {
|
||||
|
||||
//PostJSON post json 数据请求
|
||||
func PostJSON(uri string, obj interface{}) ([]byte, error) {
|
||||
jsonData, err := json.Marshal(obj)
|
||||
jsonBuf := new(bytes.Buffer)
|
||||
enc := json.NewEncoder(jsonBuf)
|
||||
enc.SetEscapeHTML(false)
|
||||
err := enc.Encode(obj)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
jsonData = bytes.Replace(jsonData, []byte("\\u003c"), []byte("<"), -1)
|
||||
jsonData = bytes.Replace(jsonData, []byte("\\u003e"), []byte(">"), -1)
|
||||
jsonData = bytes.Replace(jsonData, []byte("\\u0026"), []byte("&"), -1)
|
||||
body := bytes.NewBuffer(jsonData)
|
||||
response, err := http.Post(uri, "application/json;charset=utf-8", body)
|
||||
response, err := http.Post(uri, "application/json;charset=utf-8", jsonBuf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -70,17 +69,15 @@ func PostJSON(uri string, obj interface{}) ([]byte, error) {
|
||||
|
||||
// PostJSONWithRespContentType post json数据请求,且返回数据类型
|
||||
func PostJSONWithRespContentType(uri string, obj interface{}) ([]byte, string, error) {
|
||||
jsonData, err := json.Marshal(obj)
|
||||
jsonBuf := new(bytes.Buffer)
|
||||
enc := json.NewEncoder(jsonBuf)
|
||||
enc.SetEscapeHTML(false)
|
||||
err := enc.Encode(obj)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
jsonData = bytes.Replace(jsonData, []byte("\\u003c"), []byte("<"), -1)
|
||||
jsonData = bytes.Replace(jsonData, []byte("\\u003e"), []byte(">"), -1)
|
||||
jsonData = bytes.Replace(jsonData, []byte("\\u0026"), []byte("&"), -1)
|
||||
|
||||
body := bytes.NewBuffer(jsonData)
|
||||
response, err := http.Post(uri, "application/json;charset=utf-8", body)
|
||||
response, err := http.Post(uri, "application/json;charset=utf-8", jsonBuf)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
41
util/util.go
Normal file
41
util/util.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package util
|
||||
|
||||
//SliceChunk 用于将字符串切片分块
|
||||
func SliceChunk(src []string, chunkSize int) (chunks [][]string) {
|
||||
total := len(src)
|
||||
chunks = make([][]string, 0)
|
||||
if chunkSize < 1 {
|
||||
chunkSize = 1
|
||||
}
|
||||
if total == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
chunkNum := total / chunkSize
|
||||
if total%chunkSize != 0 {
|
||||
chunkNum++
|
||||
}
|
||||
|
||||
chunks = make([][]string, chunkNum)
|
||||
|
||||
for i := 0; i < chunkNum; i++ {
|
||||
for j := 0; j < chunkSize; j++ {
|
||||
offset := i*chunkSize + j
|
||||
if offset >= total {
|
||||
return
|
||||
}
|
||||
|
||||
if chunks[i] == nil {
|
||||
actualChunkSize := chunkSize
|
||||
if i == chunkNum-1 && total%chunkSize != 0 {
|
||||
actualChunkSize = total % chunkSize
|
||||
}
|
||||
chunks[i] = make([]string, actualChunkSize)
|
||||
}
|
||||
|
||||
chunks[i][j] = src[offset]
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
18
util/util_test.go
Normal file
18
util/util_test.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestSliceChunk(t *testing.T) {
|
||||
src1 := []string{"1", "2", "3", "4", "5"}
|
||||
assert.Equal(t, [][]string{{"1", "2"}, {"3", "4"}, {"5"}}, SliceChunk(src1, 2))
|
||||
assert.Equal(t, [][]string{{"1", "2", "3", "4", "5"}}, SliceChunk(src1, 5))
|
||||
assert.Equal(t, [][]string{{"1", "2", "3", "4", "5"}}, SliceChunk(src1, 6))
|
||||
assert.Equal(t, [][]string{{"1"}, {"2"}, {"3"}, {"4"}, {"5"}}, SliceChunk(src1, 1))
|
||||
assert.Equal(t, [][]string{{"1"}, {"2"}, {"3"}, {"4"}, {"5"}}, SliceChunk(src1, 0))
|
||||
assert.Equal(t, [][]string{{"1"}, {"2"}, {"3"}, {"4"}, {"5"}}, SliceChunk(src1, -100))
|
||||
assert.Equal(t, [][]string{}, SliceChunk(nil, 5))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
15
work/config/config.go
Normal file
15
work/config/config.go
Normal file
@@ -0,0 +1,15 @@
|
||||
// Package config 企业微信config配置
|
||||
package config
|
||||
|
||||
import (
|
||||
"github.com/silenceper/wechat/v2/cache"
|
||||
)
|
||||
|
||||
// Config 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 // 消息加密私钥,可以在企业微信管理端--管理工具--消息加密公钥查看对用公钥,私钥一般由自己保存
|
||||
}
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
260
work/msgaudit/client.go
Normal file
260
work/msgaudit/client.go
Normal file
@@ -0,0 +1,260 @@
|
||||
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"
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
"github.com/silenceper/wechat/v2/work/config"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 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))
|
||||
}
|
||||
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
|
||||
}
|
||||
39
work/work.go
Normal file
39
work/work.go
Normal file
@@ -0,0 +1,39 @@
|
||||
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/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)
|
||||
}
|
||||
Reference in New Issue
Block a user