mirror of
https://github.com/silenceper/wechat.git
synced 2026-02-04 12:52:27 +08:00
Compare commits
92 Commits
v2.0.0
...
v2.0.9-rc.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3afe499e70 | ||
|
|
beb2f9506d | ||
|
|
b535cd116a | ||
|
|
3cfa9e6c71 | ||
|
|
80d91d8316 | ||
|
|
c61154105b | ||
|
|
d392ff776b | ||
|
|
df82432f6c | ||
|
|
917f1817e5 | ||
|
|
6fdb986911 | ||
|
|
8ceabc2d0b | ||
|
|
fc1fc7e84e | ||
|
|
13611466f3 | ||
|
|
08008e1c86 | ||
|
|
01addecd53 | ||
|
|
4433fc18a6 | ||
|
|
e8c90848e4 | ||
|
|
6df8453378 | ||
|
|
2ff99d41dc | ||
|
|
b1144e3a38 | ||
|
|
51778fab8f | ||
|
|
6edaa7888a | ||
|
|
b27dca624f | ||
|
|
3f9aed72cd | ||
|
|
dc508f7341 | ||
|
|
1005807328 | ||
|
|
c1e4e2c9d0 | ||
|
|
c8522f1875 | ||
|
|
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 | ||
|
|
53b0f26688 | ||
|
|
430277c947 | ||
|
|
71e3ddaab3 | ||
|
|
0505969439 | ||
|
|
3014901b48 | ||
|
|
2e191c0a44 | ||
|
|
4c35924b8c | ||
|
|
ed508654a1 | ||
|
|
a18fe5b58a | ||
|
|
a6eb2eedc3 | ||
|
|
404d522d09 | ||
|
|
6f2bd492fc | ||
|
|
811d71c35b | ||
|
|
1fe872be66 | ||
|
|
ff38e6bac0 | ||
|
|
c956f416a5 | ||
|
|
5fea6d5965 | ||
|
|
a8763dd6c9 | ||
|
|
df9889d982 | ||
|
|
7fe7e21cb2 | ||
|
|
a5c6eb300d | ||
|
|
868b31cb3d | ||
|
|
b5c70cc206 | ||
|
|
69d0b94fdf | ||
|
|
c14c020a3c | ||
|
|
fe31f04640 | ||
|
|
2ccc15b050 | ||
|
|
3d7d60644f | ||
|
|
5d9705ddc8 | ||
|
|
63f2226974 | ||
|
|
3a1221e7ed | ||
|
|
6c06c05233 | ||
|
|
2af3f42055 | ||
|
|
c4cb394d80 | ||
|
|
681e86e3d4 |
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/
|
||||||
|
-->
|
||||||
|
**请描述您的问题**
|
||||||
42
.github/workflows/go.yml
vendored
42
.github/workflows/go.yml
vendored
@@ -2,49 +2,43 @@ name: Go
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ master,release-* ]
|
branches: [ master,release-*,v2 ]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ master,release-* ]
|
branches: [ master,release-*,v2 ]
|
||||||
|
|
||||||
jobs:
|
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:
|
build:
|
||||||
name: Build
|
name: Test
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
services:
|
services:
|
||||||
redis:
|
redis:
|
||||||
image: redis
|
image: redis
|
||||||
ports:
|
ports:
|
||||||
- 6379:6379
|
- 6379:6379
|
||||||
options: --entrypoint redis-server
|
options: --entrypoint redis-server
|
||||||
memcached:
|
memcached:
|
||||||
image: memcached
|
image: memcached
|
||||||
ports:
|
ports:
|
||||||
- 11211:11211
|
- 11211:11211
|
||||||
steps:
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
- name: Set up Go 1.x
|
- name: Set up Go 1.x
|
||||||
uses: actions/setup-go@v2
|
uses: actions/setup-go@v2
|
||||||
with:
|
with:
|
||||||
go-version: ^1.13
|
go-version: ^1.13
|
||||||
id: go
|
id: go
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Get dependencies
|
|
||||||
run: |
|
|
||||||
go get -v -t -d ./...
|
|
||||||
if [ -f Gopkg.toml ]; then
|
|
||||||
curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
|
|
||||||
dep ensure
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Lint Go Code
|
|
||||||
run: |
|
|
||||||
export PATH=$PATH:$(go env GOPATH)/bin # temporary fix. See https://github.com/actions/setup-go/issues/14
|
|
||||||
go get -u golang.org/x/lint/golint
|
|
||||||
go vet ./...
|
|
||||||
golint -set_exit_status $(go list ./...)
|
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: go test -v -race ./...
|
run: go test -v -race ./...
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -26,4 +26,5 @@ _testmain.go
|
|||||||
.vscode/
|
.vscode/
|
||||||
vendor
|
vendor
|
||||||
.idea/
|
.idea/
|
||||||
example/*
|
example/*
|
||||||
|
/test
|
||||||
|
|||||||
61
.golangci.yml
Normal file
61
.golangci.yml
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
linters:
|
||||||
|
# please, do not use `enable-all`: it's deprecated and will be removed soon.
|
||||||
|
# inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint
|
||||||
|
disable-all: true
|
||||||
|
enable:
|
||||||
|
- bodyclose
|
||||||
|
- deadcode
|
||||||
|
- depguard
|
||||||
|
- dogsled
|
||||||
|
- dupl
|
||||||
|
- errcheck
|
||||||
|
- funlen
|
||||||
|
- goconst
|
||||||
|
# - gocritic
|
||||||
|
- gocyclo
|
||||||
|
- gofmt
|
||||||
|
- goimports
|
||||||
|
- golint
|
||||||
|
- goprintffuncname
|
||||||
|
- gosimple
|
||||||
|
- govet
|
||||||
|
- ineffassign
|
||||||
|
- interfacer
|
||||||
|
- misspell
|
||||||
|
- nolintlint
|
||||||
|
- rowserrcheck
|
||||||
|
- scopelint
|
||||||
|
- staticcheck
|
||||||
|
- structcheck
|
||||||
|
- stylecheck
|
||||||
|
- typecheck
|
||||||
|
- unconvert
|
||||||
|
- unparam
|
||||||
|
- unused
|
||||||
|
- varcheck
|
||||||
|
- whitespace
|
||||||
|
|
||||||
|
issues:
|
||||||
|
# Excluding configuration per-path, per-linter, per-text and per-source
|
||||||
|
exclude-rules:
|
||||||
|
- path: _test\.go
|
||||||
|
linters:
|
||||||
|
- gomnd
|
||||||
|
|
||||||
|
# https://github.com/go-critic/go-critic/issues/926
|
||||||
|
- linters:
|
||||||
|
- gocritic
|
||||||
|
text: "unnecessaryDefer:"
|
||||||
|
|
||||||
|
linters-settings:
|
||||||
|
funlen:
|
||||||
|
lines: 66
|
||||||
|
statements: 40
|
||||||
|
|
||||||
|
issues:
|
||||||
|
include:
|
||||||
|
- EXC0002 # disable excluding of issues about comments from golint
|
||||||
|
exclude-rules:
|
||||||
|
- linters:
|
||||||
|
- stylecheck
|
||||||
|
text: "ST1000:"
|
||||||
15
README.md
15
README.md
@@ -1,18 +1,21 @@
|
|||||||
# WeChat SDK for Go
|
# WeChat SDK for Go
|
||||||

|

|
||||||
[](https://goreportcard.com/report/github.com/silenceper/wechat)
|
[](https://goreportcard.com/report/github.com/silenceper/wechat)
|
||||||
[](https://pkg.go.dev/github.com/silenceper/wechat/v2?tab=doc)
|
[](https://pkg.go.dev/github.com/silenceper/wechat/v2?tab=doc)
|
||||||
|
|
||||||
使用Golang开发的微信SDK,简单、易用。
|
使用Golang开发的微信SDK,简单、易用。
|
||||||
>当前版本为2.0版本
|
>当前版本为v2版本
|
||||||
|
|
||||||
|
|
||||||
## 文档 && 例子
|
## 文档 && 例子
|
||||||
[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)
|
[Wechat SDK 2.0 例子](https://github.com/gowechat/example)
|
||||||
|
|
||||||
## 快速开始
|
## 快速开始
|
||||||
|
```
|
||||||
|
import "github.com/silenceper/wechat/v2"
|
||||||
|
```
|
||||||
|
|
||||||
以下是一个微信公众号处理消息接收以及回复的例子:
|
以下是一个微信公众号处理消息接收以及回复的例子:
|
||||||
|
|
||||||
@@ -32,7 +35,7 @@ officialAccount := wc.GetOfficialAccount(cfg)
|
|||||||
// 传入request和responseWriter
|
// 传入request和responseWriter
|
||||||
server := officialAccount.GetServer(req, rw)
|
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)
|
text := message.NewText(msg.Content)
|
||||||
@@ -55,11 +58,11 @@ server.Send()
|
|||||||
- miniprogram: 小程序API
|
- miniprogram: 小程序API
|
||||||
- minigame:小游戏API
|
- minigame:小游戏API
|
||||||
- pay:微信支付API
|
- pay:微信支付API
|
||||||
- opernplatform:开放平台API
|
- openplatform:开放平台API
|
||||||
- work:企业微信
|
- work:企业微信
|
||||||
- aispeech:智能对话
|
- aispeech:智能对话
|
||||||
|
|
||||||
## 如何贡献
|
## 贡献
|
||||||
- 提交issue,描述需要贡献的内容
|
- 提交issue,描述需要贡献的内容
|
||||||
- 完成更改后,提交PR
|
- 完成更改后,提交PR
|
||||||
|
|
||||||
|
|||||||
2
cache/cache.go
vendored
2
cache/cache.go
vendored
@@ -2,7 +2,7 @@ package cache
|
|||||||
|
|
||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
//Cache interface
|
// Cache interface
|
||||||
type Cache interface {
|
type Cache interface {
|
||||||
Get(key string) interface{}
|
Get(key string) interface{}
|
||||||
Set(key string, val interface{}, timeout time.Duration) error
|
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"
|
"github.com/bradfitz/gomemcache/memcache"
|
||||||
)
|
)
|
||||||
|
|
||||||
//Memcache struct contains *memcache.Client
|
// Memcache struct contains *memcache.Client
|
||||||
type Memcache struct {
|
type Memcache struct {
|
||||||
conn *memcache.Client
|
conn *memcache.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
//NewMemcache create new memcache
|
// NewMemcache create new memcache
|
||||||
func NewMemcache(server ...string) *Memcache {
|
func NewMemcache(server ...string) *Memcache {
|
||||||
mc := memcache.New(server...)
|
mc := memcache.New(server...)
|
||||||
return &Memcache{mc}
|
return &Memcache{mc}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Get return cached value
|
// Get return cached value
|
||||||
func (mem *Memcache) Get(key string) interface{} {
|
func (mem *Memcache) Get(key string) interface{} {
|
||||||
var err error
|
var err error
|
||||||
var item *memcache.Item
|
var item *memcache.Item
|
||||||
@@ -40,7 +40,7 @@ func (mem *Memcache) IsExist(key string) bool {
|
|||||||
return true
|
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) {
|
func (mem *Memcache) Set(key string, val interface{}, timeout time.Duration) (err error) {
|
||||||
var data []byte
|
var data []byte
|
||||||
if data, err = json.Marshal(val); err != nil {
|
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)
|
return mem.conn.Set(item)
|
||||||
}
|
}
|
||||||
|
|
||||||
//Delete delete value in memcache.
|
// Delete delete value in memcache.
|
||||||
func (mem *Memcache) Delete(key string) error {
|
func (mem *Memcache) Delete(key string) error {
|
||||||
return mem.conn.Delete(key)
|
return mem.conn.Delete(key)
|
||||||
}
|
}
|
||||||
|
|||||||
6
cache/memory.go
vendored
6
cache/memory.go
vendored
@@ -62,13 +62,13 @@ func (mem *Memory) Set(key string, val interface{}, timeout time.Duration) (err
|
|||||||
|
|
||||||
//Delete delete value in memcache.
|
//Delete delete value in memcache.
|
||||||
func (mem *Memory) Delete(key string) error {
|
func (mem *Memory) Delete(key string) error {
|
||||||
return mem.deleteKey(key)
|
mem.deleteKey(key)
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// deleteKey
|
// deleteKey
|
||||||
func (mem *Memory) deleteKey(key string) error {
|
func (mem *Memory) deleteKey(key string) {
|
||||||
mem.Lock()
|
mem.Lock()
|
||||||
defer mem.Unlock()
|
defer mem.Unlock()
|
||||||
delete(mem.data, key)
|
delete(mem.data, key)
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
10
cache/redis.go
vendored
10
cache/redis.go
vendored
@@ -45,6 +45,11 @@ func NewRedis(opts *RedisOpts) *Redis {
|
|||||||
return &Redis{pool}
|
return &Redis{pool}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//SetRedisPool 设置redis连接池
|
||||||
|
func (r *Redis) SetRedisPool(pool *redis.Pool) {
|
||||||
|
r.conn = pool
|
||||||
|
}
|
||||||
|
|
||||||
//SetConn 设置conn
|
//SetConn 设置conn
|
||||||
func (r *Redis) SetConn(conn *redis.Pool) {
|
func (r *Redis) SetConn(conn *redis.Pool) {
|
||||||
r.conn = conn
|
r.conn = conn
|
||||||
@@ -90,10 +95,7 @@ func (r *Redis) IsExist(key string) bool {
|
|||||||
|
|
||||||
a, _ := conn.Do("EXISTS", key)
|
a, _ := conn.Do("EXISTS", key)
|
||||||
i := a.(int64)
|
i := a.(int64)
|
||||||
if i > 0 {
|
return i > 0
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//Delete 删除
|
//Delete 删除
|
||||||
|
|||||||
@@ -12,11 +12,15 @@ import (
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
//AccessTokenURL 获取access_token的接口
|
//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 微信公众号cache key前缀
|
||||||
CacheKeyOfficialAccountPrefix = "gowechat_officialaccount_"
|
CacheKeyOfficialAccountPrefix = "gowechat_officialaccount_"
|
||||||
//CacheKeyMiniProgramPrefix 小程序cache key前缀
|
//CacheKeyMiniProgramPrefix 小程序cache key前缀
|
||||||
CacheKeyMiniProgramPrefix = "gowechat_miniprogram_"
|
CacheKeyMiniProgramPrefix = "gowechat_miniprogram_"
|
||||||
|
//CacheKeyWorkPrefix 企业微信cache key前缀
|
||||||
|
CacheKeyWorkPrefix = "gowechat_work_"
|
||||||
)
|
)
|
||||||
|
|
||||||
//DefaultAccessToken 默认AccessToken 获取
|
//DefaultAccessToken 默认AccessToken 获取
|
||||||
@@ -52,11 +56,66 @@ type ResAccessToken struct {
|
|||||||
|
|
||||||
//GetAccessToken 获取access_token,先从cache中获取,没有则从服务端获取
|
//GetAccessToken 获取access_token,先从cache中获取,没有则从服务端获取
|
||||||
func (ak *DefaultAccessToken) GetAccessToken() (accessToken string, err error) {
|
func (ak *DefaultAccessToken) GetAccessToken() (accessToken string, err error) {
|
||||||
|
// 先从cache中取
|
||||||
|
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.appID)
|
||||||
|
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
|
||||||
|
return val.(string), nil
|
||||||
|
}
|
||||||
|
|
||||||
//加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
|
//加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
|
||||||
ak.accessTokenLock.Lock()
|
ak.accessTokenLock.Lock()
|
||||||
defer ak.accessTokenLock.Unlock()
|
defer ak.accessTokenLock.Unlock()
|
||||||
|
|
||||||
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.appID)
|
// 双检,防止重复从微信服务器获取
|
||||||
|
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
|
||||||
|
return val.(string), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
//cache失效,从微信服务器获取
|
||||||
|
var resAccessToken ResAccessToken
|
||||||
|
resAccessToken, err = GetTokenFromServer(fmt.Sprintf(accessTokenURL, ak.appID, ak.appSecret))
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
expires := resAccessToken.ExpiresIn - 1500
|
||||||
|
err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
accessToken = resAccessToken.AccessToken
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//WorkAccessToken 企业微信AccessToken 获取
|
||||||
|
type WorkAccessToken struct {
|
||||||
|
CorpID string
|
||||||
|
CorpSecret string
|
||||||
|
cacheKeyPrefix string
|
||||||
|
cache cache.Cache
|
||||||
|
accessTokenLock *sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewWorkAccessToken new WorkAccessToken
|
||||||
|
func NewWorkAccessToken(corpID, corpSecret, cacheKeyPrefix string, cache cache.Cache) AccessTokenHandle {
|
||||||
|
if cache == nil {
|
||||||
|
panic("cache the not exist")
|
||||||
|
}
|
||||||
|
return &WorkAccessToken{
|
||||||
|
CorpID: corpID,
|
||||||
|
CorpSecret: corpSecret,
|
||||||
|
cache: cache,
|
||||||
|
cacheKeyPrefix: cacheKeyPrefix,
|
||||||
|
accessTokenLock: new(sync.Mutex),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetAccessToken 企业微信获取access_token,先从cache中获取,没有则从服务端获取
|
||||||
|
func (ak *WorkAccessToken) GetAccessToken() (accessToken string, err error) {
|
||||||
|
//加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
|
||||||
|
ak.accessTokenLock.Lock()
|
||||||
|
defer ak.accessTokenLock.Unlock()
|
||||||
|
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.CorpID)
|
||||||
val := ak.cache.Get(accessTokenCacheKey)
|
val := ak.cache.Get(accessTokenCacheKey)
|
||||||
if val != nil {
|
if val != nil {
|
||||||
accessToken = val.(string)
|
accessToken = val.(string)
|
||||||
@@ -65,7 +124,7 @@ func (ak *DefaultAccessToken) GetAccessToken() (accessToken string, err error) {
|
|||||||
|
|
||||||
//cache失效,从微信服务器获取
|
//cache失效,从微信服务器获取
|
||||||
var resAccessToken ResAccessToken
|
var resAccessToken ResAccessToken
|
||||||
resAccessToken, err = GetTokenFromServer(ak.appID, ak.appSecret)
|
resAccessToken, err = GetTokenFromServer(fmt.Sprintf(workAccessTokenURL, ak.CorpID, ak.CorpSecret))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -80,8 +139,7 @@ func (ak *DefaultAccessToken) GetAccessToken() (accessToken string, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//GetTokenFromServer 强制从微信服务器获取token
|
//GetTokenFromServer 强制从微信服务器获取token
|
||||||
func GetTokenFromServer(appID, appSecret string) (resAccessToken ResAccessToken, err error) {
|
func GetTokenFromServer(url string) (resAccessToken ResAccessToken, err error) {
|
||||||
url := fmt.Sprintf("%s?grant_type=client_credential&appid=%s&secret=%s", accessTokenURL, appID, appSecret)
|
|
||||||
var body []byte
|
var body []byte
|
||||||
body, err = util.HTTPGet(url)
|
body, err = util.HTTPGet(url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -91,7 +149,7 @@ func GetTokenFromServer(appID, appSecret string) (resAccessToken ResAccessToken,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if resAccessToken.ErrMsg != "" {
|
if resAccessToken.ErrCode != 0 {
|
||||||
err = fmt.Errorf("get access_token error : errcode=%v , errormsg=%v", resAccessToken.ErrCode, resAccessToken.ErrMsg)
|
err = fmt.Errorf("get access_token error : errcode=%v , errormsg=%v", resAccessToken.ErrCode, resAccessToken.ErrMsg)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,16 +42,20 @@ type ResTicket struct {
|
|||||||
|
|
||||||
//GetTicket 获取jsapi_ticket
|
//GetTicket 获取jsapi_ticket
|
||||||
func (js *DefaultJsTicket) GetTicket(accessToken string) (ticketStr string, err error) {
|
func (js *DefaultJsTicket) GetTicket(accessToken string) (ticketStr string, err error) {
|
||||||
|
//先从cache中取
|
||||||
|
jsAPITicketCacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", js.cacheKeyPrefix, js.appID)
|
||||||
|
if val := js.cache.Get(jsAPITicketCacheKey); val != nil {
|
||||||
|
return val.(string), nil
|
||||||
|
}
|
||||||
|
|
||||||
js.jsAPITicketLock.Lock()
|
js.jsAPITicketLock.Lock()
|
||||||
defer js.jsAPITicketLock.Unlock()
|
defer js.jsAPITicketLock.Unlock()
|
||||||
|
|
||||||
//先从cache中取
|
// 双检,防止重复从微信服务器获取
|
||||||
jsAPITicketCacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", js.cacheKeyPrefix, js.appID)
|
if val := js.cache.Get(jsAPITicketCacheKey); val != nil {
|
||||||
val := js.cache.Get(jsAPITicketCacheKey)
|
return val.(string), nil
|
||||||
if val != nil {
|
|
||||||
ticketStr = val.(string)
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var ticket ResTicket
|
var ticket ResTicket
|
||||||
ticket, err = GetTicketFromServer(accessToken)
|
ticket, err = GetTicketFromServer(accessToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -68,6 +72,9 @@ func GetTicketFromServer(accessToken string) (ticket ResTicket, err error) {
|
|||||||
var response []byte
|
var response []byte
|
||||||
url := fmt.Sprintf(getTicketURL, accessToken)
|
url := fmt.Sprintf(getTicketURL, accessToken)
|
||||||
response, err = util.HTTPGet(url)
|
response, err = util.HTTPGet(url)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
err = json.Unmarshal(response, &ticket)
|
err = json.Unmarshal(response, &ticket)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
|
|||||||
12
go.mod
12
go.mod
@@ -5,10 +5,14 @@ go 1.14
|
|||||||
require (
|
require (
|
||||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b
|
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b
|
||||||
github.com/fatih/structs v1.1.0
|
github.com/fatih/structs v1.1.0
|
||||||
github.com/gomodule/redigo v1.8.1
|
github.com/gomodule/redigo v1.8.4
|
||||||
github.com/sirupsen/logrus v1.6.0
|
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/spf13/cast v1.3.1
|
||||||
github.com/stretchr/testify v1.5.1
|
github.com/stretchr/testify v1.7.0
|
||||||
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37
|
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
|
gopkg.in/h2non/gock.v1 v1.0.15
|
||||||
)
|
)
|
||||||
|
|||||||
40
go.sum
40
go.sum
@@ -1,41 +1,49 @@
|
|||||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b h1:L/QXpzIa3pOvUGt1D1lA5KjYhPBAN/3iWdP7xeFS9F0=
|
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/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.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 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
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 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
|
||||||
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
|
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.4 h1:Z5JUg94HMTR1XpwBaSH4vq3+PNSIykBLxMdglbw10gg=
|
||||||
github.com/gomodule/redigo v1.8.1/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0=
|
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 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw=
|
||||||
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI=
|
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/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
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 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4=
|
||||||
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms=
|
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/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.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
|
||||||
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
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 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
|
||||||
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
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/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.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
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-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-20210220033148-5ea612d1eb83 h1:/ZScEX8SfEmUGRHs0gxpqteO5nfNW6axyZbBdw9A12g=
|
||||||
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
|
|
||||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
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-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-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
|
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2 h1:46ULzRKLh1CwgRq2dC5SlBzEqqNCi8rreOZnNrbqcIY=
|
||||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
|
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=
|
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 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 h1:SzLqcIlb/fDfg7UvukMpNcWsu7sI5tWwL+KCATZqks0=
|
||||||
gopkg.in/h2non/gock.v1 v1.0.15/go.mod h1:sX4zAkdYX1TRGJ2JY156cFspQn4yRWn6p9EMdODlynE=
|
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.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=
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ func (analysis *Analysis) GetAnalysisDailySummary(beginDate, endDate string) (re
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fmt.Println(string(response))
|
|
||||||
err = json.Unmarshal(response, &result)
|
err = json.Unmarshal(response, &result)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
|
// Package config 小程序config配置
|
||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/silenceper/wechat/v2/cache"
|
"github.com/silenceper/wechat/v2/cache"
|
||||||
)
|
)
|
||||||
|
|
||||||
//Config config for 小程序
|
// Config config for 小程序
|
||||||
type Config struct {
|
type Config struct {
|
||||||
AppID string `json:"app_id"` //appid
|
AppID string `json:"app_id"` // appid
|
||||||
AppSecret string `json:"app_secret"` //appsecret
|
AppSecret string `json:"app_secret"` // appsecret
|
||||||
Cache cache.Cache
|
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")
|
||||||
|
}
|
||||||
@@ -22,7 +22,6 @@ func NewEncryptor(context *context.Context) *Encryptor {
|
|||||||
return basic
|
return basic
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// ErrAppIDNotMatch appid不匹配
|
// ErrAppIDNotMatch appid不匹配
|
||||||
ErrAppIDNotMatch = errors.New("app id not match")
|
ErrAppIDNotMatch = errors.New("app id not match")
|
||||||
@@ -36,19 +35,21 @@ var (
|
|||||||
|
|
||||||
// PlainData 用户信息/手机号信息
|
// PlainData 用户信息/手机号信息
|
||||||
type PlainData struct {
|
type PlainData struct {
|
||||||
OpenID string `json:"openId"`
|
OpenID string `json:"openId"`
|
||||||
UnionID string `json:"unionId"`
|
UnionID string `json:"unionId"`
|
||||||
NickName string `json:"nickName"`
|
NickName string `json:"nickName"`
|
||||||
Gender int `json:"gender"`
|
Gender int `json:"gender"`
|
||||||
City string `json:"city"`
|
City string `json:"city"`
|
||||||
Province string `json:"province"`
|
Province string `json:"province"`
|
||||||
Country string `json:"country"`
|
Country string `json:"country"`
|
||||||
AvatarURL string `json:"avatarUrl"`
|
AvatarURL string `json:"avatarUrl"`
|
||||||
Language string `json:"language"`
|
Language string `json:"language"`
|
||||||
PhoneNumber string `json:"phoneNumber"`
|
PhoneNumber string `json:"phoneNumber"`
|
||||||
|
OpenGID string `json:"openGId"`
|
||||||
|
MsgTicket string `json:"msgTicket"`
|
||||||
PurePhoneNumber string `json:"purePhoneNumber"`
|
PurePhoneNumber string `json:"purePhoneNumber"`
|
||||||
CountryCode string `json:"countryCode"`
|
CountryCode string `json:"countryCode"`
|
||||||
Watermark struct {
|
Watermark struct {
|
||||||
Timestamp int64 `json:"timestamp"`
|
Timestamp int64 `json:"timestamp"`
|
||||||
AppID string `json:"appid"`
|
AppID string `json:"appid"`
|
||||||
} `json:"watermark"`
|
} `json:"watermark"`
|
||||||
@@ -75,8 +76,8 @@ func pkcs7Unpad(data []byte, blockSize int) ([]byte, error) {
|
|||||||
return data[:len(data)-n], nil
|
return data[:len(data)-n], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// getCipherText returns slice of the cipher text
|
// GetCipherText returns slice of the cipher text
|
||||||
func getCipherText(sessionKey, encryptedData, iv string) ([]byte, error) {
|
func GetCipherText(sessionKey, encryptedData, iv string) ([]byte, error) {
|
||||||
aesKey, err := base64.StdEncoding.DecodeString(sessionKey)
|
aesKey, err := base64.StdEncoding.DecodeString(sessionKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -104,7 +105,7 @@ func getCipherText(sessionKey, encryptedData, iv string) ([]byte, error) {
|
|||||||
|
|
||||||
// Decrypt 解密数据
|
// Decrypt 解密数据
|
||||||
func (encryptor *Encryptor) Decrypt(sessionKey, encryptedData, iv string) (*PlainData, error) {
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
57
miniprogram/message/consts.go
Normal file
57
miniprogram/message/consts.go
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
package message
|
||||||
|
|
||||||
|
import "encoding/xml"
|
||||||
|
|
||||||
|
// MsgType 基本消息类型
|
||||||
|
type MsgType string
|
||||||
|
|
||||||
|
// EventType 事件类型
|
||||||
|
type EventType string
|
||||||
|
|
||||||
|
// InfoType 第三方平台授权事件类型
|
||||||
|
type InfoType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
//MsgTypeText 文本消息
|
||||||
|
MsgTypeText MsgType = "text"
|
||||||
|
//MsgTypeImage 图片消息
|
||||||
|
MsgTypeImage = "image"
|
||||||
|
//MsgTypeLink 图文链接
|
||||||
|
MsgTypeLink = "link"
|
||||||
|
//MsgTypeMiniProgramPage 小程序卡片
|
||||||
|
MsgTypeMiniProgramPage = "miniprogrampage"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CommonToken 消息中通用的结构
|
||||||
|
type CommonToken struct {
|
||||||
|
XMLName xml.Name `xml:"xml"`
|
||||||
|
ToUserName string `xml:"ToUserName"`
|
||||||
|
FromUserName string `xml:"FromUserName"`
|
||||||
|
CreateTime int64 `xml:"CreateTime"`
|
||||||
|
MsgType MsgType `xml:"MsgType"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MiniProgramMixMessage 小程序回调的消息结构
|
||||||
|
type MiniProgramMixMessage struct {
|
||||||
|
CommonToken
|
||||||
|
|
||||||
|
MsgID int64 `xml:"MsgId"`
|
||||||
|
|
||||||
|
// 文本消息
|
||||||
|
Content string `xml:"Content"`
|
||||||
|
|
||||||
|
// 图片消息
|
||||||
|
PicURL string `xml:"PicUrl"`
|
||||||
|
MediaID string `xml:"MediaId"`
|
||||||
|
|
||||||
|
// 小程序卡片消息
|
||||||
|
Title string `xml:"Title"`
|
||||||
|
AppID string `xml:"AppId"`
|
||||||
|
PagePath string `xml:"PagePath"`
|
||||||
|
ThumbURL string `xml:"ThumbUrl"`
|
||||||
|
ThumbMediaID string `xml:"ThumbMediaId"`
|
||||||
|
|
||||||
|
// 进入会话事件
|
||||||
|
Event string `xml:"Event"`
|
||||||
|
SessionFrom string `xml:"SessionFrom"`
|
||||||
|
}
|
||||||
124
miniprogram/message/customer_message.go
Normal file
124
miniprogram/message/customer_message.go
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
package message
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/miniprogram/context"
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
customerSendMessage = "https://api.weixin.qq.com/cgi-bin/message/custom/send"
|
||||||
|
)
|
||||||
|
|
||||||
|
//Manager 消息管理者,可以发送消息
|
||||||
|
type Manager struct {
|
||||||
|
*context.Context
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewCustomerMessageManager 实例化消息管理者
|
||||||
|
func NewCustomerMessageManager(context *context.Context) *Manager {
|
||||||
|
return &Manager{
|
||||||
|
context,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//MediaText 文本消息的文字
|
||||||
|
type MediaText struct {
|
||||||
|
Content string `json:"content"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//MediaResource 消息使用的临时素材id
|
||||||
|
type MediaResource struct {
|
||||||
|
MediaID string `json:"media_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//MediaMiniprogrampage 小程序卡片
|
||||||
|
type MediaMiniprogrampage struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
Appid string `json:"appid"`
|
||||||
|
Pagepath string `json:"pagepath"`
|
||||||
|
ThumbMediaID string `json:"thumb_media_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MediaLink 发送图文链接
|
||||||
|
type MediaLink struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
ThumbURL string `json:"thumb_url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//CustomerMessage 客服消息
|
||||||
|
type CustomerMessage struct {
|
||||||
|
ToUser string `json:"touser"` //接受者OpenID
|
||||||
|
Msgtype MsgType `json:"msgtype"` //客服消息类型
|
||||||
|
Text *MediaText `json:"text,omitempty"` //可选
|
||||||
|
Image *MediaResource `json:"image,omitempty"` //可选
|
||||||
|
Link *MediaLink `json:"link,omitempty"` //可选
|
||||||
|
Miniprogrampage *MediaMiniprogrampage `json:"miniprogrampage,omitempty"` //可选
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewCustomerTextMessage 文本消息结构体构造方法
|
||||||
|
func NewCustomerTextMessage(toUser, text string) *CustomerMessage {
|
||||||
|
return &CustomerMessage{
|
||||||
|
ToUser: toUser,
|
||||||
|
Msgtype: MsgTypeText,
|
||||||
|
Text: &MediaText{
|
||||||
|
Content: text,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewCustomerImgMessage 图片消息的构造方法
|
||||||
|
func NewCustomerImgMessage(toUser, mediaID string) *CustomerMessage {
|
||||||
|
return &CustomerMessage{
|
||||||
|
ToUser: toUser,
|
||||||
|
Msgtype: MsgTypeImage,
|
||||||
|
Image: &MediaResource{
|
||||||
|
MediaID: mediaID,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewCustomerLinkMessage 图文链接消息的构造方法
|
||||||
|
func NewCustomerLinkMessage(toUser, title, description, url, thumbURL string) *CustomerMessage {
|
||||||
|
return &CustomerMessage{
|
||||||
|
ToUser: toUser,
|
||||||
|
Msgtype: MsgTypeLink,
|
||||||
|
Link: &MediaLink{
|
||||||
|
Title: title,
|
||||||
|
Description: description,
|
||||||
|
URL: url,
|
||||||
|
ThumbURL: thumbURL,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewCustomerMiniprogrampageMessage 小程序卡片消息的构造方法
|
||||||
|
func NewCustomerMiniprogrampageMessage(toUser, title, pagepath, thumbMediaID string) *CustomerMessage {
|
||||||
|
return &CustomerMessage{
|
||||||
|
ToUser: toUser,
|
||||||
|
Msgtype: MsgTypeMiniProgramPage,
|
||||||
|
Miniprogrampage: &MediaMiniprogrampage{
|
||||||
|
Title: title,
|
||||||
|
Pagepath: pagepath,
|
||||||
|
ThumbMediaID: thumbMediaID,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Send 发送客服消息
|
||||||
|
func (manager *Manager) Send(msg *CustomerMessage) error {
|
||||||
|
accessToken, err := manager.Context.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", customerSendMessage, accessToken)
|
||||||
|
response, err := util.PostJSON(uri, msg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return util.DecodeWithCommonError(response, "SendCustomerMessage")
|
||||||
|
}
|
||||||
@@ -4,11 +4,15 @@ import (
|
|||||||
"github.com/silenceper/wechat/v2/credential"
|
"github.com/silenceper/wechat/v2/credential"
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/analysis"
|
"github.com/silenceper/wechat/v2/miniprogram/analysis"
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/auth"
|
"github.com/silenceper/wechat/v2/miniprogram/auth"
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/encryptor"
|
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/config"
|
"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/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/qrcode"
|
||||||
|
"github.com/silenceper/wechat/v2/miniprogram/subscribe"
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/tcb"
|
"github.com/silenceper/wechat/v2/miniprogram/tcb"
|
||||||
|
"github.com/silenceper/wechat/v2/miniprogram/werun"
|
||||||
)
|
)
|
||||||
|
|
||||||
//MiniProgram 微信小程序相关API
|
//MiniProgram 微信小程序相关API
|
||||||
@@ -60,3 +64,23 @@ func (miniProgram *MiniProgram) GetQRCode() *qrcode.QRCode {
|
|||||||
func (miniProgram *MiniProgram) GetTcb() *tcb.Tcb {
|
func (miniProgram *MiniProgram) GetTcb() *tcb.Tcb {
|
||||||
return tcb.NewTcb(miniProgram.ctx)
|
return tcb.NewTcb(miniProgram.ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//GetSubscribe 小程序订阅消息
|
||||||
|
func (miniProgram *MiniProgram) GetSubscribe() *subscribe.Subscribe {
|
||||||
|
return subscribe.NewSubscribe(miniProgram.ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCustomerMessage 客服消息接口
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|||||||
@@ -74,15 +74,13 @@ func (qrCode *QRCode) fetchCode(urlStr string, body interface{}) (response []byt
|
|||||||
err = fmt.Errorf("fetchCode error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
|
err = fmt.Errorf("fetchCode error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
} else if contentType == "image/jpeg" {
|
}
|
||||||
|
if contentType == "image/jpeg" {
|
||||||
// 返回文件
|
// 返回文件
|
||||||
return response, nil
|
return response, nil
|
||||||
} else {
|
|
||||||
err = fmt.Errorf("fetchCode error : unknown response content type - %v", contentType)
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
err = fmt.Errorf("fetchCode error : unknown response content type - %v", contentType)
|
||||||
return
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateWXAQRCode 获取小程序二维码,适用于需要的码数量较少的业务场景
|
// CreateWXAQRCode 获取小程序二维码,适用于需要的码数量较少的业务场景
|
||||||
|
|||||||
195
miniprogram/subscribe/subscribe.go
Normal file
195
miniprogram/subscribe/subscribe.go
Normal file
@@ -0,0 +1,195 @@
|
|||||||
|
package subscribe
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/miniprogram/context"
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
//发送订阅消息
|
||||||
|
//https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html
|
||||||
|
subscribeSendURL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send"
|
||||||
|
|
||||||
|
// 获取当前帐号下的个人模板列表
|
||||||
|
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.getTemplateList.html
|
||||||
|
getTemplateURL = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate"
|
||||||
|
|
||||||
|
// 添加订阅模板
|
||||||
|
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.addTemplate.html
|
||||||
|
addTemplateURL = "https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate"
|
||||||
|
|
||||||
|
// 删除私有模板
|
||||||
|
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.deleteTemplate.html
|
||||||
|
delTemplateURL = "https://api.weixin.qq.com/wxaapi/newtmpl/deltemplate"
|
||||||
|
|
||||||
|
// 统一服务消息
|
||||||
|
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/uniform-message/uniformMessage.send.html
|
||||||
|
uniformMessageSend = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Subscribe 订阅消息
|
||||||
|
type Subscribe struct {
|
||||||
|
*context.Context
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSubscribe 实例化
|
||||||
|
func NewSubscribe(ctx *context.Context) *Subscribe {
|
||||||
|
return &Subscribe{Context: ctx}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Message 订阅消息请求参数
|
||||||
|
type Message struct {
|
||||||
|
ToUser string `json:"touser"` //必选,接收者(用户)的 openid
|
||||||
|
TemplateID string `json:"template_id"` //必选,所需下发的订阅模板id
|
||||||
|
Page string `json:"page"` //可选,点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
|
||||||
|
Data map[string]*DataItem `json:"data"` //必选, 模板内容
|
||||||
|
MiniprogramState string `json:"miniprogram_state"` //可选,跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版
|
||||||
|
Lang string `json:"lang"` //入小程序查看”的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN
|
||||||
|
}
|
||||||
|
|
||||||
|
//DataItem 模版内某个 .DATA 的值
|
||||||
|
type DataItem struct {
|
||||||
|
Value interface{} `json:"value"`
|
||||||
|
Color string `json:"color"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//TemplateItem template item
|
||||||
|
type TemplateItem struct {
|
||||||
|
PriTmplID string `json:"priTmplId"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
Example string `json:"example"`
|
||||||
|
Type int64 `json:"type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//TemplateList template list
|
||||||
|
type TemplateList struct {
|
||||||
|
util.CommonError
|
||||||
|
Data []TemplateItem `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send 发送订阅消息
|
||||||
|
func (s *Subscribe) Send(msg *Message) (err error) {
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = s.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, "Send")
|
||||||
|
}
|
||||||
|
|
||||||
|
//ListTemplates 获取当前帐号下的个人模板列表
|
||||||
|
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.getTemplateList.html
|
||||||
|
func (s *Subscribe) ListTemplates() (*TemplateList, error) {
|
||||||
|
accessToken, err := s.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getTemplateURL, accessToken)
|
||||||
|
response, err := util.HTTPGet(uri)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
templateList := TemplateList{}
|
||||||
|
err = util.DecodeWithError(response, &templateList, "ListTemplates")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
|
||||||
|
type resSubscribeAdd struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
TemplateID string `json:"priTmplId"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add 添加订阅消息模板
|
||||||
|
func (s *Subscribe) Add(ShortID string, kidList []int, sceneDesc string) (templateID string, err error) {
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = s.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var msg = struct {
|
||||||
|
TemplateIDShort string `json:"tid"`
|
||||||
|
SceneDesc string `json:"sceneDesc"`
|
||||||
|
KidList []int `json:"kidList"`
|
||||||
|
}{TemplateIDShort: ShortID, SceneDesc: sceneDesc, KidList: kidList}
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", addTemplateURL, accessToken)
|
||||||
|
var response []byte
|
||||||
|
response, err = util.PostJSON(uri, msg)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var result resSubscribeAdd
|
||||||
|
err = util.DecodeWithError(response, &result, "AddSubscribe")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
templateID = result.TemplateID
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete 删除私有模板
|
||||||
|
func (s *Subscribe) Delete(templateID string) (err error) {
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = s.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var msg = struct {
|
||||||
|
TemplateID string `json:"priTmplId"`
|
||||||
|
}{TemplateID: templateID}
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", delTemplateURL, accessToken)
|
||||||
|
var response []byte
|
||||||
|
response, err = util.PostJSON(uri, msg)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return util.DecodeWithCommonError(response, "DeleteSubscribe")
|
||||||
|
}
|
||||||
@@ -29,4 +29,4 @@ if err != nil {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
更多使用方法参考[GODOC](https://godoc.org/github.com/silenceper/wechat/v2/tcb)
|
更多使用方法参考[PKG.DEV](https://pkg.go.dev/github.com/silenceper/wechat/v2/miniprogram/tcb)
|
||||||
@@ -130,5 +130,5 @@ func (tcb *Tcb) BatchDeleteFile(env string, fileIDList []string) (*BatchDeleteFi
|
|||||||
}
|
}
|
||||||
batchDeleteFileRes := &BatchDeleteFileRes{}
|
batchDeleteFileRes := &BatchDeleteFileRes{}
|
||||||
err = util.DecodeWithError(response, batchDeleteFileRes, "BatchDeleteFile")
|
err = util.DecodeWithError(response, batchDeleteFileRes, "BatchDeleteFile")
|
||||||
return batchDeleteFileRes, nil
|
return batchDeleteFileRes, err
|
||||||
}
|
}
|
||||||
|
|||||||
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if t.ErrMsg != "" {
|
||||||
|
err = fmt.Errorf("get qr_ticket error : errcode=%v , errormsg=%v", t.ErrCode, t.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
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
|
||||||
|
}
|
||||||
@@ -8,9 +8,13 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
sendURLByTag = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall"
|
sendURLByTag = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall"
|
||||||
sendURLByOpenID = "https://api.weixin.qq.com/cgi-bin/message/mass/send"
|
sendURLByOpenID = "https://api.weixin.qq.com/cgi-bin/message/mass/send"
|
||||||
deleteSendURL ="https://api.weixin.qq.com/cgi-bin/message/mass/delete"
|
deleteSendURL = "https://api.weixin.qq.com/cgi-bin/message/mass/delete"
|
||||||
|
previewSendURL = "https://api.weixin.qq.com/cgi-bin/message/mass/preview"
|
||||||
|
massStatusSendURL = "https://api.weixin.qq.com/cgi-bin/message/mass/get"
|
||||||
|
getSpeedSendURL = "https://api.weixin.qq.com/cgi-bin/message/mass/speed/get"
|
||||||
|
setSpeedSendURL = "https://api.weixin.qq.com/cgi-bin/message/mass/speed/set"
|
||||||
)
|
)
|
||||||
|
|
||||||
//MsgType 发送消息类型
|
//MsgType 发送消息类型
|
||||||
@@ -34,11 +38,12 @@ const (
|
|||||||
//Broadcast 群发消息
|
//Broadcast 群发消息
|
||||||
type Broadcast struct {
|
type Broadcast struct {
|
||||||
*context.Context
|
*context.Context
|
||||||
|
preview bool
|
||||||
}
|
}
|
||||||
|
|
||||||
//NewBroadcast new
|
//NewBroadcast new
|
||||||
func NewBroadcast(ctx *context.Context) *Broadcast {
|
func NewBroadcast(ctx *context.Context) *Broadcast {
|
||||||
return &Broadcast{ctx}
|
return &Broadcast{ctx, false}
|
||||||
}
|
}
|
||||||
|
|
||||||
//User 发送的用户
|
//User 发送的用户
|
||||||
@@ -50,8 +55,16 @@ type User struct {
|
|||||||
//Result 群发返回结果
|
//Result 群发返回结果
|
||||||
type Result struct {
|
type Result struct {
|
||||||
util.CommonError
|
util.CommonError
|
||||||
MsgID int64 `json:"msg_id"`
|
MsgID int64 `json:"msg_id"`
|
||||||
MsgDataID int64 `json:"msg_data_id"`
|
MsgDataID int64 `json:"msg_data_id"`
|
||||||
|
MsgStatus string `json:"msg_status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//SpeedResult 群发速度返回结果
|
||||||
|
type SpeedResult struct {
|
||||||
|
util.CommonError
|
||||||
|
Speed int64 `json:"speed"`
|
||||||
|
RealSpeed int64 `json:"realspeed"`
|
||||||
}
|
}
|
||||||
|
|
||||||
//sendRequest 发送请求的数据
|
//sendRequest 发送请求的数据
|
||||||
@@ -69,17 +82,17 @@ type sendRequest struct {
|
|||||||
//发送图片
|
//发送图片
|
||||||
Images *Image `json:"images,omitempty"`
|
Images *Image `json:"images,omitempty"`
|
||||||
//发送卡券
|
//发送卡券
|
||||||
WxCard map[string]interface{} `json:"wxcard,omitempty"`
|
WxCard map[string]interface{} `json:"wxcard,omitempty"`
|
||||||
MsgType MsgType `json:"msgtype"`
|
MsgType MsgType `json:"msgtype"`
|
||||||
SendIgnoreReprint int32 `json:"send_ignore_reprint,omitempty"`
|
SendIgnoreReprint int32 `json:"send_ignore_reprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
//Image 发送图片
|
//Image 发送图片
|
||||||
type Image struct{
|
type Image struct {
|
||||||
MediaIDs []string `json:"media_ids"`
|
MediaIDs []string `json:"media_ids"`
|
||||||
Recommend string `json:"recommend"`
|
Recommend string `json:"recommend"`
|
||||||
NeedOpenComment int32 `json:"need_open_comment"`
|
NeedOpenComment int32 `json:"need_open_comment"`
|
||||||
OnlyFansCanComment int32 `json:"only_fans_can_comment"`
|
OnlyFansCanComment int32 `json:"only_fans_can_comment"`
|
||||||
}
|
}
|
||||||
|
|
||||||
//SendText 群发文本
|
//SendText 群发文本
|
||||||
@@ -92,13 +105,13 @@ func (broadcast *Broadcast) SendText(user *User, content string) (*Result, error
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
req := &sendRequest{
|
req := &sendRequest{
|
||||||
ToUser: nil,
|
ToUser: nil,
|
||||||
MsgType: MsgTypeText,
|
MsgType: MsgTypeText,
|
||||||
}
|
}
|
||||||
req.Text=map[string]interface{}{
|
req.Text = map[string]interface{}{
|
||||||
"content":content,
|
"content": content,
|
||||||
}
|
}
|
||||||
req,sendURL:=broadcast.chooseTagOrOpenID(user,req)
|
req, sendURL := broadcast.chooseTagOrOpenID(user, req)
|
||||||
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
||||||
data, err := util.PostJSON(url, req)
|
data, err := util.PostJSON(url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -110,22 +123,22 @@ func (broadcast *Broadcast) SendText(user *User, content string) (*Result, error
|
|||||||
}
|
}
|
||||||
|
|
||||||
//SendNews 发送图文
|
//SendNews 发送图文
|
||||||
func (broadcast *Broadcast) SendNews(user *User, mediaID string,ignoreReprint bool) (*Result, error) {
|
func (broadcast *Broadcast) SendNews(user *User, mediaID string, ignoreReprint bool) (*Result, error) {
|
||||||
ak, err := broadcast.GetAccessToken()
|
ak, err := broadcast.GetAccessToken()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
req := &sendRequest{
|
req := &sendRequest{
|
||||||
ToUser: nil,
|
ToUser: nil,
|
||||||
MsgType: MsgTypeNews,
|
MsgType: MsgTypeNews,
|
||||||
}
|
}
|
||||||
if ignoreReprint{
|
if ignoreReprint {
|
||||||
req.SendIgnoreReprint=1
|
req.SendIgnoreReprint = 1
|
||||||
}
|
}
|
||||||
req.Mpnews=map[string]interface{}{
|
req.Mpnews = map[string]interface{}{
|
||||||
"media_id":mediaID,
|
"media_id": mediaID,
|
||||||
}
|
}
|
||||||
req,sendURL:=broadcast.chooseTagOrOpenID(user,req)
|
req, sendURL := broadcast.chooseTagOrOpenID(user, req)
|
||||||
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
||||||
data, err := util.PostJSON(url, req)
|
data, err := util.PostJSON(url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -136,7 +149,6 @@ func (broadcast *Broadcast) SendNews(user *User, mediaID string,ignoreReprint bo
|
|||||||
return res, err
|
return res, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//SendVoice 发送语音
|
//SendVoice 发送语音
|
||||||
func (broadcast *Broadcast) SendVoice(user *User, mediaID string) (*Result, error) {
|
func (broadcast *Broadcast) SendVoice(user *User, mediaID string) (*Result, error) {
|
||||||
ak, err := broadcast.GetAccessToken()
|
ak, err := broadcast.GetAccessToken()
|
||||||
@@ -144,13 +156,13 @@ func (broadcast *Broadcast) SendVoice(user *User, mediaID string) (*Result, erro
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
req := &sendRequest{
|
req := &sendRequest{
|
||||||
ToUser: nil,
|
ToUser: nil,
|
||||||
MsgType: MsgTypeVoice,
|
MsgType: MsgTypeVoice,
|
||||||
}
|
}
|
||||||
req.Voice=map[string]interface{}{
|
req.Voice = map[string]interface{}{
|
||||||
"media_id":mediaID,
|
"media_id": mediaID,
|
||||||
}
|
}
|
||||||
req,sendURL:=broadcast.chooseTagOrOpenID(user,req)
|
req, sendURL := broadcast.chooseTagOrOpenID(user, req)
|
||||||
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
||||||
data, err := util.PostJSON(url, req)
|
data, err := util.PostJSON(url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -168,11 +180,11 @@ func (broadcast *Broadcast) SendImage(user *User, images *Image) (*Result, error
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
req := &sendRequest{
|
req := &sendRequest{
|
||||||
ToUser: nil,
|
ToUser: nil,
|
||||||
MsgType: MsgTypeImage,
|
MsgType: MsgTypeImage,
|
||||||
}
|
}
|
||||||
req.Images=images
|
req.Images = images
|
||||||
req,sendURL:=broadcast.chooseTagOrOpenID(user,req)
|
req, sendURL := broadcast.chooseTagOrOpenID(user, req)
|
||||||
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
||||||
data, err := util.PostJSON(url, req)
|
data, err := util.PostJSON(url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -183,23 +195,22 @@ func (broadcast *Broadcast) SendImage(user *User, images *Image) (*Result, error
|
|||||||
return res, err
|
return res, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//SendVideo 发送视频
|
//SendVideo 发送视频
|
||||||
func (broadcast *Broadcast) SendVideo(user *User, mediaID string,title,description string) (*Result, error) {
|
func (broadcast *Broadcast) SendVideo(user *User, mediaID string, title, description string) (*Result, error) {
|
||||||
ak, err := broadcast.GetAccessToken()
|
ak, err := broadcast.GetAccessToken()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
req := &sendRequest{
|
req := &sendRequest{
|
||||||
ToUser: nil,
|
ToUser: nil,
|
||||||
MsgType: MsgTypeVideo,
|
MsgType: MsgTypeVideo,
|
||||||
}
|
}
|
||||||
req.Voice=map[string]interface{}{
|
req.Voice = map[string]interface{}{
|
||||||
"media_id":mediaID,
|
"media_id": mediaID,
|
||||||
"title":title,
|
"title": title,
|
||||||
"description":description,
|
"description": description,
|
||||||
}
|
}
|
||||||
req,sendURL:=broadcast.chooseTagOrOpenID(user,req)
|
req, sendURL := broadcast.chooseTagOrOpenID(user, req)
|
||||||
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
||||||
data, err := util.PostJSON(url, req)
|
data, err := util.PostJSON(url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -210,7 +221,6 @@ func (broadcast *Broadcast) SendVideo(user *User, mediaID string,title,descripti
|
|||||||
return res, err
|
return res, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//SendWxCard 发送卡券
|
//SendWxCard 发送卡券
|
||||||
func (broadcast *Broadcast) SendWxCard(user *User, cardID string) (*Result, error) {
|
func (broadcast *Broadcast) SendWxCard(user *User, cardID string) (*Result, error) {
|
||||||
ak, err := broadcast.GetAccessToken()
|
ak, err := broadcast.GetAccessToken()
|
||||||
@@ -218,13 +228,13 @@ func (broadcast *Broadcast) SendWxCard(user *User, cardID string) (*Result, erro
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
req := &sendRequest{
|
req := &sendRequest{
|
||||||
ToUser: nil,
|
ToUser: nil,
|
||||||
MsgType: MsgTypeWxCard,
|
MsgType: MsgTypeWxCard,
|
||||||
}
|
}
|
||||||
req.WxCard=map[string]interface{}{
|
req.WxCard = map[string]interface{}{
|
||||||
"card_id":cardID,
|
"card_id": cardID,
|
||||||
}
|
}
|
||||||
req,sendURL:=broadcast.chooseTagOrOpenID(user,req)
|
req, sendURL := broadcast.chooseTagOrOpenID(user, req)
|
||||||
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
||||||
data, err := util.PostJSON(url, req)
|
data, err := util.PostJSON(url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -234,11 +244,12 @@ func (broadcast *Broadcast) SendWxCard(user *User, cardID string) (*Result, erro
|
|||||||
err = util.DecodeWithError(data, res, "SendWxCard")
|
err = util.DecodeWithError(data, res, "SendWxCard")
|
||||||
return res, err
|
return res, err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Delete 删除群发消息
|
//Delete 删除群发消息
|
||||||
func (broadcast *Broadcast) Delete(msgID int64 ,articleIDx int64) error {
|
func (broadcast *Broadcast) Delete(msgID int64, articleIDx int64) error {
|
||||||
ak, err := broadcast.GetAccessToken()
|
ak, err := broadcast.GetAccessToken()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
req := map[string]interface{}{
|
req := map[string]interface{}{
|
||||||
"msg_id": msgID,
|
"msg_id": msgID,
|
||||||
@@ -247,33 +258,99 @@ func (broadcast *Broadcast) Delete(msgID int64 ,articleIDx int64) error {
|
|||||||
url := fmt.Sprintf("%s?access_token=%s", deleteSendURL, ak)
|
url := fmt.Sprintf("%s?access_token=%s", deleteSendURL, ak)
|
||||||
data, err := util.PostJSON(url, req)
|
data, err := util.PostJSON(url, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return util.DecodeWithCommonError(data, "Delete")
|
return util.DecodeWithCommonError(data, "Delete")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Preview 预览
|
||||||
|
func (broadcast *Broadcast) Preview() *Broadcast {
|
||||||
|
broadcast.preview = true
|
||||||
|
return broadcast
|
||||||
|
}
|
||||||
|
|
||||||
//TODO 发送预览,群发消息状态,发送速度
|
// GetMassStatus 获取群发状态
|
||||||
|
func (broadcast *Broadcast) GetMassStatus(msgID string) (*Result, error) {
|
||||||
|
ak, err := broadcast.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req := map[string]interface{}{
|
||||||
|
"msg_id": msgID,
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf("%s?access_token=%s", massStatusSendURL, ak)
|
||||||
|
data, err := util.PostJSON(url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
res := &Result{}
|
||||||
|
err = util.DecodeWithError(data, res, "GetMassStatus")
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
|
||||||
func (broadcast *Broadcast) chooseTagOrOpenID(user *User,req *sendRequest)(ret *sendRequest,url string){
|
// GetSpeed 获取群发速度
|
||||||
sendURL:=""
|
func (broadcast *Broadcast) GetSpeed() (*SpeedResult, error) {
|
||||||
|
ak, err := broadcast.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req := map[string]interface{}{}
|
||||||
|
url := fmt.Sprintf("%s?access_token=%s", getSpeedSendURL, ak)
|
||||||
|
data, err := util.PostJSON(url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
res := &SpeedResult{}
|
||||||
|
err = util.DecodeWithError(data, res, "GetSpeed")
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetSpeed 设置群发速度
|
||||||
|
func (broadcast *Broadcast) SetSpeed(speed int) (*SpeedResult, error) {
|
||||||
|
ak, err := broadcast.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req := map[string]interface{}{
|
||||||
|
"speed": speed,
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf("%s?access_token=%s", setSpeedSendURL, ak)
|
||||||
|
data, err := util.PostJSON(url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
res := &SpeedResult{}
|
||||||
|
err = util.DecodeWithError(data, res, "SetSpeed")
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (broadcast *Broadcast) chooseTagOrOpenID(user *User, req *sendRequest) (ret *sendRequest, url string) {
|
||||||
|
sendURL := ""
|
||||||
if user == nil {
|
if user == nil {
|
||||||
req.Filter=map[string]interface{}{
|
req.Filter = map[string]interface{}{
|
||||||
"is_to_all":true,
|
"is_to_all": true,
|
||||||
}
|
}
|
||||||
sendURL=sendURLByTag
|
sendURL = sendURLByTag
|
||||||
} else {
|
} else {
|
||||||
if user.TagID != 0 {
|
if broadcast.preview {
|
||||||
req.Filter=map[string]interface{}{
|
// 预览 默认发给第一个用户
|
||||||
"is_to_all":false,
|
if len(user.OpenID) != 0 {
|
||||||
"tag_id":user.TagID,
|
req.ToUser = user.OpenID[0]
|
||||||
|
sendURL = previewSendURL
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if user.TagID != 0 {
|
||||||
|
req.Filter = map[string]interface{}{
|
||||||
|
"is_to_all": false,
|
||||||
|
"tag_id": user.TagID,
|
||||||
|
}
|
||||||
|
sendURL = sendURLByTag
|
||||||
|
}
|
||||||
|
if len(user.OpenID) != 0 {
|
||||||
|
req.ToUser = user.OpenID
|
||||||
|
sendURL = sendURLByOpenID
|
||||||
}
|
}
|
||||||
sendURL=sendURLByTag
|
|
||||||
}
|
|
||||||
if len(user.OpenID) != 0 {
|
|
||||||
req.ToUser = user.OpenID
|
|
||||||
sendURL=sendURLByOpenID
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return req,sendURL
|
return req, sendURL
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"github.com/silenceper/wechat/v2/cache"
|
"github.com/silenceper/wechat/v2/cache"
|
||||||
)
|
)
|
||||||
|
|
||||||
//Config config for 微信公众号
|
// Config config for 微信公众号
|
||||||
type Config struct {
|
type Config struct {
|
||||||
AppID string `json:"app_id"` //appid
|
AppID string `json:"app_id"` //appid
|
||||||
AppSecret string `json:"app_secret"` //appsecret
|
AppSecret string `json:"app_secret"` //appsecret
|
||||||
|
|||||||
271
officialaccount/datacube/broadcast.go
Normal file
271
officialaccount/datacube/broadcast.go
Normal file
@@ -0,0 +1,271 @@
|
|||||||
|
package datacube
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
getArticleSummary = "https://api.weixin.qq.com/datacube/getarticlesummary"
|
||||||
|
getArticleTotal = "https://api.weixin.qq.com/datacube/getarticletotal"
|
||||||
|
getUserRead = "https://api.weixin.qq.com/datacube/getuserread"
|
||||||
|
getUserReadHour = "https://api.weixin.qq.com/datacube/getuserreadhour"
|
||||||
|
getUserShare = "https://api.weixin.qq.com/datacube/getusershare"
|
||||||
|
getUserShareHour = "https://api.weixin.qq.com/datacube/getusersharehour"
|
||||||
|
)
|
||||||
|
|
||||||
|
//ResArticleSummary 获取图文群发每日数据响应
|
||||||
|
type ResArticleSummary struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
MsgID string `json:"msgid"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
IntPageReadUser int `json:"int_page_read_user"`
|
||||||
|
IntPageReadCount int `json:"int_page_read_count"`
|
||||||
|
OriPageReadUser int `json:"ori_page_read_user"`
|
||||||
|
OriPageReadCount int `json:"ori_page_read_count"`
|
||||||
|
ShareUser int `json:"share_user"`
|
||||||
|
ShareCount int `json:"share_count"`
|
||||||
|
AddToFavUser int `json:"add_to_fav_user"`
|
||||||
|
AddToFavCount int `json:"add_to_fav_count"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResArticleTotal 获取图文群发总数据响应
|
||||||
|
type ResArticleTotal struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
MsgID string `json:"msgid"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Details []ArticleTotalDetails `json:"details"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ArticleTotalDetails 获取图文群发总数据响应文字详情
|
||||||
|
type ArticleTotalDetails struct {
|
||||||
|
StatDate string `json:"stat_date"`
|
||||||
|
TargetUser int `json:"target_user"`
|
||||||
|
IntPageReadUser int `json:"int_page_read_user"`
|
||||||
|
IntPageReadCount int `json:"int_page_read_count"`
|
||||||
|
OriPageReadUser int `json:"ori_page_read_user"`
|
||||||
|
OriPageReadCount int `json:"ori_page_read_count"`
|
||||||
|
ShareUser int `json:"share_user"`
|
||||||
|
ShareCount int `json:"share_count"`
|
||||||
|
AddToFavUser int `json:"add_to_fav_user"`
|
||||||
|
AddToFavCount int `json:"add_to_fav_count"`
|
||||||
|
IntPageFromSessionReadUser int `json:"int_page_from_session_read_user"`
|
||||||
|
IntPageFromSessionReadCount int `json:"int_page_from_session_read_count"`
|
||||||
|
IntPageFromHistMsgReadUser int `json:"int_page_from_hist_msg_read_user"`
|
||||||
|
IntPageFromHistMsgReadCount int `json:"int_page_from_hist_msg_read_count"`
|
||||||
|
IntPageFromFeedReadUser int `json:"int_page_from_feed_read_user"`
|
||||||
|
IntPageFromFeedReadCount int `json:"int_page_from_feed_read_count"`
|
||||||
|
IntPageFromFriendsReadUser int `json:"int_page_from_friends_read_user"`
|
||||||
|
IntPageFromFriendsReadCount int `json:"int_page_from_friends_read_count"`
|
||||||
|
IntPageFromOtherReadUser int `json:"int_page_from_other_read_user"`
|
||||||
|
IntPageFromOtherReadCount int `json:"int_page_from_other_read_count"`
|
||||||
|
FeedShareFromSessionUser int `json:"feed_share_from_session_user"`
|
||||||
|
FeedShareFromSessionCnt int `json:"feed_share_from_session_cnt"`
|
||||||
|
FeedShareFromFeedUser int `json:"feed_share_from_feed_user"`
|
||||||
|
FeedShareFromFeedCnt int `json:"feed_share_from_feed_cnt"`
|
||||||
|
FeedShareFromOtherUser int `json:"feed_share_from_other_user"`
|
||||||
|
FeedShareFromOtherCnt int `json:"feed_share_from_other_cnt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResUserRead 获取图文统计数据响应
|
||||||
|
type ResUserRead struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
UserSource int `json:"user_source"`
|
||||||
|
IntPageReadUser int `json:"int_page_read_user"`
|
||||||
|
IntPageReadCount int `json:"int_page_read_count"`
|
||||||
|
OriPageReadUser int `json:"ori_page_read_user"`
|
||||||
|
OriPageReadCount int `json:"ori_page_read_count"`
|
||||||
|
ShareUser int `json:"share_user"`
|
||||||
|
ShareCount int `json:"share_count"`
|
||||||
|
AddToFavUser int `json:"add_to_fav_user"`
|
||||||
|
AddToFavCount int `json:"add_to_fav_count"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResUserReadHour 获取图文统计分时数据
|
||||||
|
type ResUserReadHour struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
RefHour int `json:"ref_hour"`
|
||||||
|
UserSource int `json:"user_source"`
|
||||||
|
IntPageReadUser int `json:"int_page_read_user"`
|
||||||
|
IntPageReadCount int `json:"int_page_read_count"`
|
||||||
|
OriPageReadUser int `json:"ori_page_read_user"`
|
||||||
|
OriPageReadCount int `json:"ori_page_read_count"`
|
||||||
|
ShareUser int `json:"share_user"`
|
||||||
|
ShareCount int `json:"share_count"`
|
||||||
|
AddToFavUser int `json:"add_to_fav_user"`
|
||||||
|
AddToFavCount int `json:"add_to_fav_count"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResUserShare 获取图文分享转发数据
|
||||||
|
type ResUserShare struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
ShareScene int `json:"share_scene"`
|
||||||
|
ShareCount int `json:"share_count"`
|
||||||
|
ShareUser int `json:"share_user"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResUserShareHour 获取图文分享转发分时数据
|
||||||
|
type ResUserShareHour struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
RefHour int `json:"ref_hour"`
|
||||||
|
ShareScene int `json:"share_scene"`
|
||||||
|
ShareCount int `json:"share_count"`
|
||||||
|
ShareUser int `json:"share_user"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetArticleSummary 获取图文群发每日数据
|
||||||
|
func (cube *DataCube) GetArticleSummary(s string, e string) (resArticleSummary ResArticleSummary, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getArticleSummary, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resArticleSummary, "GetArticleSummary")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetArticleTotal 获取图文群发总数据
|
||||||
|
func (cube *DataCube) GetArticleTotal(s string, e string) (resArticleTotal ResArticleTotal, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getArticleTotal, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resArticleTotal, "GetArticleTotal")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetUserRead 获取图文统计数据
|
||||||
|
func (cube *DataCube) GetUserRead(s string, e string) (resUserRead ResUserRead, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getUserRead, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resUserRead, "GetUserRead")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetUserReadHour 获取图文统计分时数据
|
||||||
|
func (cube *DataCube) GetUserReadHour(s string, e string) (resUserReadHour ResUserReadHour, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getUserReadHour, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resUserReadHour, "GetUserReadHour")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetUserShare 获取图文分享转发数据
|
||||||
|
func (cube *DataCube) GetUserShare(s string, e string) (resUserShare ResUserShare, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getUserShare, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resUserShare, "GetUserShare")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetUserShareHour 获取图文分享转发分时数据
|
||||||
|
func (cube *DataCube) GetUserShareHour(s string, e string) (resUserShareHour ResUserShareHour, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getUserShareHour, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resUserShareHour, "GetUserShareHour")
|
||||||
|
return
|
||||||
|
}
|
||||||
22
officialaccount/datacube/datacube.go
Normal file
22
officialaccount/datacube/datacube.go
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package datacube
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/silenceper/wechat/v2/officialaccount/context"
|
||||||
|
)
|
||||||
|
|
||||||
|
type reqDate struct {
|
||||||
|
BeginDate string `json:"begin_date"`
|
||||||
|
EndDate string `json:"end_date"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//DataCube 数据统计
|
||||||
|
type DataCube struct {
|
||||||
|
*context.Context
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewCube 数据统计
|
||||||
|
func NewCube(context *context.Context) *DataCube {
|
||||||
|
dataCube := new(DataCube)
|
||||||
|
dataCube.Context = context
|
||||||
|
return dataCube
|
||||||
|
}
|
||||||
83
officialaccount/datacube/interface.go
Normal file
83
officialaccount/datacube/interface.go
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package datacube
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
getInterfaceSummary = "https://api.weixin.qq.com/datacube/getinterfacesummary"
|
||||||
|
getInterfaceSummaryHour = "https://api.weixin.qq.com/datacube/getinterfacesummaryhour"
|
||||||
|
)
|
||||||
|
|
||||||
|
//ResInterfaceSummary 接口分析数据响应
|
||||||
|
type ResInterfaceSummary struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
CallbackCount int `json:"callback_count"`
|
||||||
|
FailCount int `json:"fail_count"`
|
||||||
|
TotalTimeCost int `json:"total_time_cost"`
|
||||||
|
MaxTimeCost int `json:"max_time_cost"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResInterfaceSummaryHour 接口分析分时数据响应
|
||||||
|
type ResInterfaceSummaryHour struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
RefHour int `json:"ref_hour"`
|
||||||
|
CallbackCount int `json:"callback_count"`
|
||||||
|
FailCount int `json:"fail_count"`
|
||||||
|
TotalTimeCost int `json:"total_time_cost"`
|
||||||
|
MaxTimeCost int `json:"max_time_cost"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetInterfaceSummary 获取接口分析数据
|
||||||
|
func (cube *DataCube) GetInterfaceSummary(s string, e string) (resInterfaceSummary ResInterfaceSummary, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getInterfaceSummary, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resInterfaceSummary, "GetInterfaceSummary")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetInterfaceSummaryHour 获取接口分析分时数据
|
||||||
|
func (cube *DataCube) GetInterfaceSummaryHour(s string, e string) (resInterfaceSummaryHour ResInterfaceSummaryHour, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getInterfaceSummaryHour, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resInterfaceSummaryHour, "GetInterfaceSummaryHour")
|
||||||
|
return
|
||||||
|
}
|
||||||
253
officialaccount/datacube/message.go
Normal file
253
officialaccount/datacube/message.go
Normal file
@@ -0,0 +1,253 @@
|
|||||||
|
package datacube
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
getUpstreamMsg = "https://api.weixin.qq.com/datacube/getupstreammsg"
|
||||||
|
getUpstreamMsgHour = "https://api.weixin.qq.com/datacube/getupstreammsghour"
|
||||||
|
getUpstreamMsgWeek = "https://api.weixin.qq.com/datacube/getupstreammsgweek"
|
||||||
|
getUpstreamMsgMonth = "https://api.weixin.qq.com/datacube/getupstreammsgmonth"
|
||||||
|
getUpstreamMsgDist = "https://api.weixin.qq.com/datacube/getupstreammsgdist"
|
||||||
|
getUpstreamMsgDistWeek = "https://api.weixin.qq.com/datacube/getupstreammsgdistweek"
|
||||||
|
getUpstreamMsgDistMonth = "https://api.weixin.qq.com/datacube/getupstreammsgdistmonth"
|
||||||
|
)
|
||||||
|
|
||||||
|
//ResUpstreamMsg 获取消息发送概况数据响应
|
||||||
|
type ResUpstreamMsg struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
MsgType int `json:"msg_type"`
|
||||||
|
MsgUser int `json:"msg_user"`
|
||||||
|
MsgCount int `json:"msg_count"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResUpstreamMsgHour 获取消息分送分时数据响应
|
||||||
|
type ResUpstreamMsgHour struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
RefHour int `json:"ref_hour"`
|
||||||
|
MsgType int `json:"msg_type"`
|
||||||
|
MsgUser int `json:"msg_user"`
|
||||||
|
MsgCount int `json:"msg_count"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResUpstreamMsgWeek 获取消息发送周数据响应
|
||||||
|
type ResUpstreamMsgWeek struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
MsgType int `json:"msg_type"`
|
||||||
|
MsgUser int `json:"msg_user"`
|
||||||
|
MsgCount int `json:"msg_count"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResUpstreamMsgMonth 获取消息发送月数据响应
|
||||||
|
type ResUpstreamMsgMonth struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
MsgType int `json:"msg_type"`
|
||||||
|
MsgUser int `json:"msg_user"`
|
||||||
|
MsgCount int `json:"msg_count"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResUpstreamMsgDist 获取消息发送分布数据响应
|
||||||
|
type ResUpstreamMsgDist struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
CountInterval int `json:"count_interval"`
|
||||||
|
MsgUser int `json:"msg_user"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResUpstreamMsgDistWeek 获取消息发送分布周数据响应
|
||||||
|
type ResUpstreamMsgDistWeek struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
CountInterval int `json:"count_interval"`
|
||||||
|
MsgUser int `json:"msg_user"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResUpstreamMsgDistMonth 获取消息发送分布月数据响应
|
||||||
|
type ResUpstreamMsgDistMonth struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
CountInterval int `json:"count_interval"`
|
||||||
|
MsgUser int `json:"msg_user"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetUpstreamMsg 获取消息发送概况数据
|
||||||
|
func (cube *DataCube) GetUpstreamMsg(s string, e string) (resUpstreamMsg ResUpstreamMsg, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getUpstreamMsg, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resUpstreamMsg, "GetUpstreamMsg")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetUpstreamMsgHour 获取消息分送分时数据
|
||||||
|
func (cube *DataCube) GetUpstreamMsgHour(s string, e string) (resUpstreamMsgHour ResUpstreamMsgHour, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getUpstreamMsgHour, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resUpstreamMsgHour, "GetUpstreamMsgHour")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetUpstreamMsgWeek 获取消息发送周数据
|
||||||
|
func (cube *DataCube) GetUpstreamMsgWeek(s string, e string) (resUpstreamMsgWeek ResUpstreamMsgWeek, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getUpstreamMsgWeek, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resUpstreamMsgWeek, "GetUpstreamMsgWeek")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetUpstreamMsgMonth 获取消息发送月数据
|
||||||
|
func (cube *DataCube) GetUpstreamMsgMonth(s string, e string) (resUpstreamMsgMonth ResUpstreamMsgMonth, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getUpstreamMsgMonth, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resUpstreamMsgMonth, "GetUpstreamMsgMonth")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetUpstreamMsgDist 获取消息发送分布数据
|
||||||
|
func (cube *DataCube) GetUpstreamMsgDist(s string, e string) (resUpstreamMsgDist ResUpstreamMsgDist, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getUpstreamMsgDist, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resUpstreamMsgDist, "GetUpstreamMsgDist")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetUpstreamMsgDistWeek 获取消息发送分布周数据
|
||||||
|
func (cube *DataCube) GetUpstreamMsgDistWeek(s string, e string) (resUpstreamMsgDistWeek ResUpstreamMsgDistWeek, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getUpstreamMsgDistWeek, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resUpstreamMsgDistWeek, "GetUpstreamMsgDistWeek")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetUpstreamMsgDistMonth 获取消息发送分布月数据
|
||||||
|
func (cube *DataCube) GetUpstreamMsgDistMonth(s string, e string) (resUpstreamMsgDistMonth ResUpstreamMsgDistMonth, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getUpstreamMsgDistMonth, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resUpstreamMsgDistMonth, "GetUpstreamMsgDistMonth")
|
||||||
|
return
|
||||||
|
}
|
||||||
272
officialaccount/datacube/publisher.go
Normal file
272
officialaccount/datacube/publisher.go
Normal file
@@ -0,0 +1,272 @@
|
|||||||
|
package datacube
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
//AdSlot 广告位类型
|
||||||
|
type AdSlot string
|
||||||
|
|
||||||
|
const (
|
||||||
|
//SlotIDBizBottom 公众号底部广告
|
||||||
|
SlotIDBizBottom AdSlot = "SLOT_ID_BIZ_BOTTOM"
|
||||||
|
//SlotIDBizMidContext 公众号文中广告
|
||||||
|
SlotIDBizMidContext AdSlot = "SLOT_ID_BIZ_MID_CONTEXT"
|
||||||
|
//SlotIDBizVideoEnd 公众号视频后贴
|
||||||
|
SlotIDBizVideoEnd AdSlot = "SLOT_ID_BIZ_VIDEO_END"
|
||||||
|
//SlotIDBizSponsor 公众号互选广告
|
||||||
|
SlotIDBizSponsor AdSlot = "SLOT_ID_BIZ_SPONSOR"
|
||||||
|
//SlotIDBizCps 公众号返佣商品
|
||||||
|
SlotIDBizCps AdSlot = "SLOT_ID_BIZ_CPS"
|
||||||
|
//SlotIDWeappBanner 小程序banner
|
||||||
|
SlotIDWeappBanner AdSlot = "SLOT_ID_WEAPP_BANNER"
|
||||||
|
//SlotIDWeappRewardVideo 小程序激励视频
|
||||||
|
SlotIDWeappRewardVideo AdSlot = "SLOT_ID_WEAPP_REWARD_VIDEO"
|
||||||
|
//SlotIDWeappInterstitial 小程序插屏广告
|
||||||
|
SlotIDWeappInterstitial AdSlot = "SLOT_ID_WEAPP_INTERSTITIAL"
|
||||||
|
//SlotIDWeappVideoFeeds 小程序视频广告
|
||||||
|
SlotIDWeappVideoFeeds AdSlot = "SLOT_ID_WEAPP_VIDEO_FEEDS"
|
||||||
|
//SlotIDWeappVideoBegin 小程序视频前贴
|
||||||
|
SlotIDWeappVideoBegin AdSlot = "SLOT_ID_WEAPP_VIDEO_BEGIN"
|
||||||
|
//SlotIDWeappBox 小程序格子广告
|
||||||
|
SlotIDWeappBox AdSlot = "SLOT_ID_WEAPP_BOX"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
publisherURL = "https://api.weixin.qq.com/publisher/stat"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
actionPublisherAdPosGeneral = "publisher_adpos_general"
|
||||||
|
actionPublisherCpsGeneral = "publisher_cps_general"
|
||||||
|
actionPublisherSettlement = "publisher_settlement"
|
||||||
|
)
|
||||||
|
|
||||||
|
//BaseResp 错误信息
|
||||||
|
type BaseResp struct {
|
||||||
|
ErrMsg string `json:"err_msg"`
|
||||||
|
Ret int `json:"ret"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResPublisherAdPos 公众号分广告位数据响应
|
||||||
|
type ResPublisherAdPos struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
BaseResp BaseResp `json:"base_resp"`
|
||||||
|
List []ResAdPosList `json:"list"`
|
||||||
|
Summary ResAdPosSummary `json:"summary"`
|
||||||
|
TotalNum int `json:"total_num"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResAdPosList 公众号分广告位列表
|
||||||
|
type ResAdPosList struct {
|
||||||
|
SlotID int64 `json:"slot_id"`
|
||||||
|
AdSlot string `json:"ad_slot"`
|
||||||
|
Date string `json:"date"`
|
||||||
|
ReqSuccCount int `json:"req_succ_count"`
|
||||||
|
ExposureCount int `json:"exposure_count"`
|
||||||
|
ExposureRate float64 `json:"exposure_rate"`
|
||||||
|
ClickCount int `json:"click_count"`
|
||||||
|
ClickRate float64 `json:"click_rate"`
|
||||||
|
Income int `json:"income"`
|
||||||
|
Ecpm float64 `json:"ecpm"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResAdPosSummary 公众号分广告位概览
|
||||||
|
type ResAdPosSummary struct {
|
||||||
|
ReqSuccCount int `json:"req_succ_count"`
|
||||||
|
ExposureCount int `json:"exposure_count"`
|
||||||
|
ExposureRate float64 `json:"exposure_rate"`
|
||||||
|
ClickCount int `json:"click_count"`
|
||||||
|
ClickRate float64 `json:"click_rate"`
|
||||||
|
Income int `json:"income"`
|
||||||
|
Ecpm float64 `json:"ecpm"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResPublisherCps 公众号返佣商品数据响应
|
||||||
|
type ResPublisherCps struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
BaseResp BaseResp `json:"base_resp"`
|
||||||
|
List []ResCpsList `json:"list"`
|
||||||
|
Summary ResCpsSummary `json:"summary"`
|
||||||
|
TotalNum int `json:"total_num"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResCpsList 公众号返佣商品列表
|
||||||
|
type ResCpsList struct {
|
||||||
|
Date string `json:"date"`
|
||||||
|
ExposureCount int `json:"exposure_count"`
|
||||||
|
ClickCount int `json:"click_count"`
|
||||||
|
ClickRate float64 `json:"click_rate"`
|
||||||
|
OrderCount int `json:"order_count"`
|
||||||
|
OrderRate float64 `json:"order_rate"`
|
||||||
|
TotalFee int `json:"total_fee"`
|
||||||
|
TotalCommission int `json:"total_commission"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResCpsSummary 公众号返佣概览
|
||||||
|
type ResCpsSummary struct {
|
||||||
|
ExposureCount int `json:"exposure_count"`
|
||||||
|
ClickCount int `json:"click_count"`
|
||||||
|
ClickRate float64 `json:"click_rate"`
|
||||||
|
OrderCount int `json:"order_count"`
|
||||||
|
OrderRate float64 `json:"order_rate"`
|
||||||
|
TotalFee int `json:"total_fee"`
|
||||||
|
TotalCommission int `json:"total_commission"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResPublisherSettlement 公众号结算收入数据及结算主体信息响应
|
||||||
|
type ResPublisherSettlement struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
BaseResp BaseResp `json:"base_resp"`
|
||||||
|
Body string `json:"body"`
|
||||||
|
PenaltyAll int `json:"penalty_all"`
|
||||||
|
RevenueAll int64 `json:"revenue_all"`
|
||||||
|
SettledRevenueAll int64 `json:"settled_revenue_all"`
|
||||||
|
SettlementList []SettlementList `json:"settlement_list"`
|
||||||
|
TotalNum int `json:"total_num"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//SettlementList 结算单列表
|
||||||
|
type SettlementList struct {
|
||||||
|
Date string `json:"date"`
|
||||||
|
Zone string `json:"zone"`
|
||||||
|
Month string `json:"month"`
|
||||||
|
Order int `json:"order"`
|
||||||
|
SettStatus int `json:"sett_status"`
|
||||||
|
SettledRevenue int `json:"settled_revenue"`
|
||||||
|
SettNo string `json:"sett_no"`
|
||||||
|
MailSendCnt string `json:"mail_send_cnt"`
|
||||||
|
SlotRevenue []SlotRevenue `json:"slot_revenue"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//SlotRevenue 产生收入的广告
|
||||||
|
type SlotRevenue struct {
|
||||||
|
SlotID string `json:"slot_id"`
|
||||||
|
SlotSettledRevenue int `json:"slot_settled_revenue"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ParamsPublisher 拉取数据参数
|
||||||
|
type ParamsPublisher struct {
|
||||||
|
Action string `json:"action"`
|
||||||
|
StartDate string `json:"start_date"`
|
||||||
|
EndDate string `json:"end_date"`
|
||||||
|
Page int `json:"page"`
|
||||||
|
PageSize int `json:"page_size"`
|
||||||
|
AdSlot AdSlot `json:"ad_slot"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetchData 拉取统计数据
|
||||||
|
func (cube *DataCube) fetchData(params ParamsPublisher) (response []byte, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
v := url.Values{}
|
||||||
|
v.Add("action", params.Action)
|
||||||
|
v.Add("access_token", accessToken)
|
||||||
|
v.Add("page", strconv.Itoa(params.Page))
|
||||||
|
v.Add("page_size", strconv.Itoa(params.PageSize))
|
||||||
|
v.Add("start_date", params.StartDate)
|
||||||
|
v.Add("end_date", params.EndDate)
|
||||||
|
if params.AdSlot != "" {
|
||||||
|
v.Add("ad_slot", string(params.AdSlot))
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?%s", publisherURL, v.Encode())
|
||||||
|
|
||||||
|
response, err = util.HTTPGet(uri)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetPublisherAdPosGeneral 获取公众号分广告位数据
|
||||||
|
func (cube *DataCube) GetPublisherAdPosGeneral(startDate, endDate string, page, pageSize int, adSlot AdSlot) (resPublisherAdPos ResPublisherAdPos, err error) {
|
||||||
|
params := ParamsPublisher{
|
||||||
|
Action: actionPublisherAdPosGeneral,
|
||||||
|
StartDate: startDate,
|
||||||
|
EndDate: endDate,
|
||||||
|
Page: page,
|
||||||
|
PageSize: pageSize,
|
||||||
|
AdSlot: adSlot,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := cube.fetchData(params)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resPublisherAdPos, "GetPublisherAdPosGeneral")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if resPublisherAdPos.BaseResp.Ret != 0 {
|
||||||
|
err = fmt.Errorf("GetPublisherAdPosGeneral Error , errcode=%d , errmsg=%s", resPublisherAdPos.BaseResp.Ret, resPublisherAdPos.BaseResp.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetPublisherCpsGeneral 获取公众号返佣商品数据
|
||||||
|
func (cube *DataCube) GetPublisherCpsGeneral(startDate, endDate string, page, pageSize int) (resPublisherCps ResPublisherCps, err error) {
|
||||||
|
params := ParamsPublisher{
|
||||||
|
Action: actionPublisherCpsGeneral,
|
||||||
|
StartDate: startDate,
|
||||||
|
EndDate: endDate,
|
||||||
|
Page: page,
|
||||||
|
PageSize: pageSize,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := cube.fetchData(params)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resPublisherCps, "GetPublisherCpsGeneral")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if resPublisherCps.BaseResp.Ret != 0 {
|
||||||
|
err = fmt.Errorf("GetPublisherCpsGeneral Error , errcode=%d , errmsg=%s", resPublisherCps.BaseResp.Ret, resPublisherCps.BaseResp.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetPublisherSettlement 获取公众号结算收入数据及结算主体信息
|
||||||
|
func (cube *DataCube) GetPublisherSettlement(startDate, endDate string, page, pageSize int) (resPublisherSettlement ResPublisherSettlement, err error) {
|
||||||
|
params := ParamsPublisher{
|
||||||
|
Action: actionPublisherSettlement,
|
||||||
|
StartDate: startDate,
|
||||||
|
EndDate: endDate,
|
||||||
|
Page: page,
|
||||||
|
PageSize: pageSize,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := cube.fetchData(params)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resPublisherSettlement, "GetPublisherSettlement")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if resPublisherSettlement.BaseResp.Ret != 0 {
|
||||||
|
err = fmt.Errorf("GetPublisherSettlement Error , errcode=%d , errmsg=%s", resPublisherSettlement.BaseResp.Ret, resPublisherSettlement.BaseResp.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
78
officialaccount/datacube/user.go
Normal file
78
officialaccount/datacube/user.go
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
package datacube
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
getUserSummary = "https://api.weixin.qq.com/datacube/getusersummary"
|
||||||
|
getUserAccumulate = "https://api.weixin.qq.com/datacube/getusercumulate"
|
||||||
|
)
|
||||||
|
|
||||||
|
//ResUserSummary 获取用户增减数据响应
|
||||||
|
type ResUserSummary struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
UserSource int `json:"user_source"`
|
||||||
|
NewUser int `json:"new_user"`
|
||||||
|
CancelUser int `json:"cancel_user"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResUserAccumulate 获取累计用户数据响应
|
||||||
|
type ResUserAccumulate struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
List []struct {
|
||||||
|
RefDate string `json:"ref_date"`
|
||||||
|
CumulateUser int `json:"cumulate_user"`
|
||||||
|
} `json:"list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetUserSummary 获取用户增减数据
|
||||||
|
func (cube *DataCube) GetUserSummary(s string, e string) (resUserSummary ResUserSummary, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getUserSummary, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resUserSummary, "GetUserSummary")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetUserAccumulate 获取累计用户数据
|
||||||
|
func (cube *DataCube) GetUserAccumulate(s string, e string) (resUserAccumulate ResUserAccumulate, err error) {
|
||||||
|
accessToken, err := cube.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getUserAccumulate, accessToken)
|
||||||
|
reqDate := &reqDate{
|
||||||
|
BeginDate: s,
|
||||||
|
EndDate: e,
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, reqDate)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &resUserAccumulate, "GetUserAccumulate")
|
||||||
|
return
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
//Package device 设备相关接口
|
||||||
package device
|
package device
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -41,7 +42,7 @@ type ReqDevice struct {
|
|||||||
// ble – 3
|
// ble – 3
|
||||||
// wifi -- 4
|
// wifi -- 4
|
||||||
// 一个设备可以支持多种连接类型,用符号"|"做分割,客户端优先选择靠前的连接方式(优先级按|关系的排序依次降低),举例:
|
// 一个设备可以支持多种连接类型,用符号"|"做分割,客户端优先选择靠前的连接方式(优先级按|关系的排序依次降低),举例:
|
||||||
// 1:表示设备仅支持andiod classic bluetooth 1|2:表示设备支持andiod 和ios 两种classic bluetooth,但是客户端优先选择andriod classic bluetooth 协议,如果andriod classic bluetooth协议连接失败,再选择ios classic bluetooth协议进行连接
|
// 1:表示设备仅支持andiod classic bluetooth 1|2:表示设备支持android 和ios 两种classic bluetooth,但是客户端优先选择android classic bluetooth 协议,如果android classic bluetooth协议连接失败,再选择ios classic bluetooth协议进行连接
|
||||||
// (注:安卓平台不同时支持BLE和classic类型)
|
// (注:安卓平台不同时支持BLE和classic类型)
|
||||||
ConnectProtocol string `json:"connect_protocol"`
|
ConnectProtocol string `json:"connect_protocol"`
|
||||||
//auth及通信的加密key,第三方需要将key烧制在设备上(128bit),格式采用16进制串的方式(长度为32字节),不需要0X前缀,如: 1234567890ABCDEF1234567890ABCDEF
|
//auth及通信的加密key,第三方需要将key烧制在设备上(128bit),格式采用16进制串的方式(长度为32字节),不需要0X前缀,如: 1234567890ABCDEF1234567890ABCDEF
|
||||||
@@ -56,7 +57,7 @@ type ReqDevice struct {
|
|||||||
// 0:不加密的version
|
// 0:不加密的version
|
||||||
// 1:version 1
|
// 1:version 1
|
||||||
AuthVer string `json:"auth_ver"`
|
AuthVer string `json:"auth_ver"`
|
||||||
// 表示mac地址在厂商广播manufature data里含有mac地址的偏移,取值如下:
|
// 表示mac地址在厂商广播manufacture data里含有mac地址的偏移,取值如下:
|
||||||
// -1:在尾部、
|
// -1:在尾部、
|
||||||
// -2:表示不包含mac地址 其他:非法偏移
|
// -2:表示不包含mac地址 其他:非法偏移
|
||||||
ManuMacPos string `json:"manu_mac_pos"`
|
ManuMacPos string `json:"manu_mac_pos"`
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ func (d *Device) VerifyQRCode(ticket string) (res ResVerifyQRCode, err error) {
|
|||||||
req := map[string]interface{}{
|
req := map[string]interface{}{
|
||||||
"ticket": ticket,
|
"ticket": ticket,
|
||||||
}
|
}
|
||||||
fmt.Println(req)
|
|
||||||
var response []byte
|
var response []byte
|
||||||
if response, err = util.PostJSON(uri, req); err != nil {
|
if response, err = util.PostJSON(uri, req); err != nil {
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ func (js *Js) GetConfig(uri string) (config *Config, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
nonceStr := util.RandomStr(16)
|
nonceStr := util.RandomStr(16)
|
||||||
timestamp := util.GetCurrTs()
|
timestamp := util.GetCurrTS()
|
||||||
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
|
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
|
||||||
sigStr := util.Signature(str)
|
sigStr := util.Signature(str)
|
||||||
|
|
||||||
|
|||||||
@@ -10,10 +10,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
addNewsURL = "https://api.weixin.qq.com/cgi-bin/material/add_news"
|
addNewsURL = "https://api.weixin.qq.com/cgi-bin/material/add_news"
|
||||||
addMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/add_material"
|
updateNewsURL = "https://api.weixin.qq.com/cgi-bin/material/update_news"
|
||||||
delMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/del_material"
|
addMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/add_material"
|
||||||
getMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/get_material"
|
delMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/del_material"
|
||||||
|
getMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/get_material"
|
||||||
|
getMaterialCountURL = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount"
|
||||||
batchGetMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material"
|
batchGetMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -30,6 +32,7 @@ const (
|
|||||||
//PermanentMaterialTypeNews 永久素材图文类型(news)
|
//PermanentMaterialTypeNews 永久素材图文类型(news)
|
||||||
PermanentMaterialTypeNews PermanentMaterialType = "news"
|
PermanentMaterialTypeNews PermanentMaterialType = "news"
|
||||||
)
|
)
|
||||||
|
|
||||||
//Material 素材管理
|
//Material 素材管理
|
||||||
type Material struct {
|
type Material struct {
|
||||||
*context.Context
|
*context.Context
|
||||||
@@ -116,10 +119,39 @@ func (material *Material) AddNews(articles []*Article) (mediaID string, err erro
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if res.ErrCode != 0 {
|
||||||
|
return "", fmt.Errorf("errcode=%d,errmsg=%s", res.ErrCode, res.ErrMsg)
|
||||||
|
}
|
||||||
mediaID = res.MediaID
|
mediaID = res.MediaID
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//reqUpdateArticle 更新永久性图文素材请求信息
|
||||||
|
type reqUpdateArticle struct {
|
||||||
|
MediaID string `json:"media_id"`
|
||||||
|
Index int64 `json:"index"`
|
||||||
|
Articles *Article `json:"articles"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateNews 更新永久图文素材
|
||||||
|
func (material *Material) UpdateNews(article *Article, mediaID string, index int64) (err error) {
|
||||||
|
req := &reqUpdateArticle{mediaID, index, article}
|
||||||
|
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = material.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", updateNewsURL, accessToken)
|
||||||
|
var response []byte
|
||||||
|
response, err = util.PostJSON(uri, req)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return util.DecodeWithCommonError(response, "UpdateNews")
|
||||||
|
}
|
||||||
|
|
||||||
//resAddMaterial 永久性素材上传返回的结果
|
//resAddMaterial 永久性素材上传返回的结果
|
||||||
type resAddMaterial struct {
|
type resAddMaterial struct {
|
||||||
util.CommonError
|
util.CommonError
|
||||||
@@ -240,6 +272,7 @@ func (material *Material) DeleteMaterial(mediaID string) error {
|
|||||||
|
|
||||||
//ArticleList 永久素材列表
|
//ArticleList 永久素材列表
|
||||||
type ArticleList struct {
|
type ArticleList struct {
|
||||||
|
util.CommonError
|
||||||
TotalCount int64 `json:"total_count"`
|
TotalCount int64 `json:"total_count"`
|
||||||
ItemCount int64 `json:"item_count"`
|
ItemCount int64 `json:"item_count"`
|
||||||
Item []ArticleListItem `json:"item"`
|
Item []ArticleListItem `json:"item"`
|
||||||
@@ -293,3 +326,29 @@ func (material *Material) BatchGetMaterial(permanentMaterialType PermanentMateri
|
|||||||
err = util.DecodeWithError(response, &list, "BatchGetMaterial")
|
err = util.DecodeWithError(response, &list, "BatchGetMaterial")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ResMaterialCount 素材总数
|
||||||
|
type ResMaterialCount struct {
|
||||||
|
util.CommonError
|
||||||
|
VoiceCount int64 `json:"voice_count"` // 语音总数量
|
||||||
|
VideoCount int64 `json:"video_count"` // 视频总数量
|
||||||
|
ImageCount int64 `json:"image_count"` // 图片总数量
|
||||||
|
NewsCount int64 `json:"news_count"` // 图文总数量
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMaterialCount 获取素材总数.
|
||||||
|
func (material *Material) GetMaterialCount() (res ResMaterialCount, err error) {
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = material.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", getMaterialCountURL, accessToken)
|
||||||
|
var response []byte
|
||||||
|
response, err = util.HTTPGet(uri)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = util.DecodeWithError(response, &res, "GetMaterialCount")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,11 +14,11 @@ const (
|
|||||||
//MediaTypeImage 媒体文件:图片
|
//MediaTypeImage 媒体文件:图片
|
||||||
MediaTypeImage MediaType = "image"
|
MediaTypeImage MediaType = "image"
|
||||||
//MediaTypeVoice 媒体文件:声音
|
//MediaTypeVoice 媒体文件:声音
|
||||||
MediaTypeVoice = "voice"
|
MediaTypeVoice MediaType = "voice"
|
||||||
//MediaTypeVideo 媒体文件:视频
|
//MediaTypeVideo 媒体文件:视频
|
||||||
MediaTypeVideo = "video"
|
MediaTypeVideo MediaType = "video"
|
||||||
//MediaTypeThumb 媒体文件:缩略图
|
//MediaTypeThumb 媒体文件:缩略图
|
||||||
MediaTypeThumb = "thumb"
|
MediaTypeThumb MediaType = "thumb"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -106,5 +106,4 @@ func (material *Material) ImageUpload(filename string) (url string, err error) {
|
|||||||
}
|
}
|
||||||
url = image.URL
|
url = image.URL
|
||||||
return
|
return
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,47 +13,51 @@ type Button struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//SetSubButton 设置二级菜单
|
//SetSubButton 设置二级菜单
|
||||||
func (btn *Button) SetSubButton(name string, subButtons []*Button) {
|
func (btn *Button) SetSubButton(name string, subButtons []*Button) *Button {
|
||||||
btn.Name = name
|
btn.Name = name
|
||||||
btn.SubButtons = subButtons
|
btn.SubButtons = subButtons
|
||||||
btn.Type = ""
|
btn.Type = ""
|
||||||
btn.Key = ""
|
btn.Key = ""
|
||||||
btn.URL = ""
|
btn.URL = ""
|
||||||
btn.MediaID = ""
|
btn.MediaID = ""
|
||||||
|
return btn
|
||||||
}
|
}
|
||||||
|
|
||||||
//SetClickButton btn 为click类型
|
//SetClickButton btn 为click类型
|
||||||
func (btn *Button) SetClickButton(name, key string) {
|
func (btn *Button) SetClickButton(name, key string) *Button {
|
||||||
btn.Type = "click"
|
btn.Type = "click"
|
||||||
btn.Name = name
|
btn.Name = name
|
||||||
btn.Key = key
|
btn.Key = key
|
||||||
btn.URL = ""
|
btn.URL = ""
|
||||||
btn.MediaID = ""
|
btn.MediaID = ""
|
||||||
btn.SubButtons = nil
|
btn.SubButtons = nil
|
||||||
|
return btn
|
||||||
}
|
}
|
||||||
|
|
||||||
//SetViewButton view类型
|
//SetViewButton view类型
|
||||||
func (btn *Button) SetViewButton(name, url string) {
|
func (btn *Button) SetViewButton(name, url string) *Button {
|
||||||
btn.Type = "view"
|
btn.Type = "view"
|
||||||
btn.Name = name
|
btn.Name = name
|
||||||
btn.URL = url
|
btn.URL = url
|
||||||
btn.Key = ""
|
btn.Key = ""
|
||||||
btn.MediaID = ""
|
btn.MediaID = ""
|
||||||
btn.SubButtons = nil
|
btn.SubButtons = nil
|
||||||
|
return btn
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetScanCodePushButton 扫码推事件
|
//SetScanCodePushButton 扫码推事件
|
||||||
func (btn *Button) SetScanCodePushButton(name, key string) {
|
func (btn *Button) SetScanCodePushButton(name, key string) *Button {
|
||||||
btn.Type = "scancode_push"
|
btn.Type = "scancode_push"
|
||||||
btn.Name = name
|
btn.Name = name
|
||||||
btn.Key = key
|
btn.Key = key
|
||||||
btn.URL = ""
|
btn.URL = ""
|
||||||
btn.MediaID = ""
|
btn.MediaID = ""
|
||||||
btn.SubButtons = nil
|
btn.SubButtons = nil
|
||||||
|
return btn
|
||||||
}
|
}
|
||||||
|
|
||||||
//SetScanCodeWaitMsgButton 设置 扫码推事件且弹出"消息接收中"提示框
|
//SetScanCodeWaitMsgButton 设置 扫码推事件且弹出"消息接收中"提示框
|
||||||
func (btn *Button) SetScanCodeWaitMsgButton(name, key string) {
|
func (btn *Button) SetScanCodeWaitMsgButton(name, key string) *Button {
|
||||||
btn.Type = "scancode_waitmsg"
|
btn.Type = "scancode_waitmsg"
|
||||||
btn.Name = name
|
btn.Name = name
|
||||||
btn.Key = key
|
btn.Key = key
|
||||||
@@ -61,10 +65,11 @@ func (btn *Button) SetScanCodeWaitMsgButton(name, key string) {
|
|||||||
btn.URL = ""
|
btn.URL = ""
|
||||||
btn.MediaID = ""
|
btn.MediaID = ""
|
||||||
btn.SubButtons = nil
|
btn.SubButtons = nil
|
||||||
|
return btn
|
||||||
}
|
}
|
||||||
|
|
||||||
//SetPicSysPhotoButton 设置弹出系统拍照发图按钮
|
//SetPicSysPhotoButton 设置弹出系统拍照发图按钮
|
||||||
func (btn *Button) SetPicSysPhotoButton(name, key string) {
|
func (btn *Button) SetPicSysPhotoButton(name, key string) *Button {
|
||||||
btn.Type = "pic_sysphoto"
|
btn.Type = "pic_sysphoto"
|
||||||
btn.Name = name
|
btn.Name = name
|
||||||
btn.Key = key
|
btn.Key = key
|
||||||
@@ -72,10 +77,11 @@ func (btn *Button) SetPicSysPhotoButton(name, key string) {
|
|||||||
btn.URL = ""
|
btn.URL = ""
|
||||||
btn.MediaID = ""
|
btn.MediaID = ""
|
||||||
btn.SubButtons = nil
|
btn.SubButtons = nil
|
||||||
|
return btn
|
||||||
}
|
}
|
||||||
|
|
||||||
//SetPicPhotoOrAlbumButton 设置弹出拍照或者相册发图类型按钮
|
//SetPicPhotoOrAlbumButton 设置弹出拍照或者相册发图类型按钮
|
||||||
func (btn *Button) SetPicPhotoOrAlbumButton(name, key string) {
|
func (btn *Button) SetPicPhotoOrAlbumButton(name, key string) *Button {
|
||||||
btn.Type = "pic_photo_or_album"
|
btn.Type = "pic_photo_or_album"
|
||||||
btn.Name = name
|
btn.Name = name
|
||||||
btn.Key = key
|
btn.Key = key
|
||||||
@@ -83,10 +89,11 @@ func (btn *Button) SetPicPhotoOrAlbumButton(name, key string) {
|
|||||||
btn.URL = ""
|
btn.URL = ""
|
||||||
btn.MediaID = ""
|
btn.MediaID = ""
|
||||||
btn.SubButtons = nil
|
btn.SubButtons = nil
|
||||||
|
return btn
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetPicWeixinButton 设置弹出微信相册发图器类型按钮
|
//SetPicWeixinButton 设置弹出微信相册发图器类型按钮
|
||||||
func (btn *Button) SetPicWeixinButton(name, key string) {
|
func (btn *Button) SetPicWeixinButton(name, key string) *Button {
|
||||||
btn.Type = "pic_weixin"
|
btn.Type = "pic_weixin"
|
||||||
btn.Name = name
|
btn.Name = name
|
||||||
btn.Key = key
|
btn.Key = key
|
||||||
@@ -94,10 +101,11 @@ func (btn *Button) SetPicWeixinButton(name, key string) {
|
|||||||
btn.URL = ""
|
btn.URL = ""
|
||||||
btn.MediaID = ""
|
btn.MediaID = ""
|
||||||
btn.SubButtons = nil
|
btn.SubButtons = nil
|
||||||
|
return btn
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetLocationSelectButton 设置 弹出地理位置选择器 类型按钮
|
//SetLocationSelectButton 设置 弹出地理位置选择器 类型按钮
|
||||||
func (btn *Button) SetLocationSelectButton(name, key string) {
|
func (btn *Button) SetLocationSelectButton(name, key string) *Button {
|
||||||
btn.Type = "location_select"
|
btn.Type = "location_select"
|
||||||
btn.Name = name
|
btn.Name = name
|
||||||
btn.Key = key
|
btn.Key = key
|
||||||
@@ -105,10 +113,11 @@ func (btn *Button) SetLocationSelectButton(name, key string) {
|
|||||||
btn.URL = ""
|
btn.URL = ""
|
||||||
btn.MediaID = ""
|
btn.MediaID = ""
|
||||||
btn.SubButtons = nil
|
btn.SubButtons = nil
|
||||||
|
return btn
|
||||||
}
|
}
|
||||||
|
|
||||||
//SetMediaIDButton 设置 下发消息(除文本消息) 类型按钮
|
//SetMediaIDButton 设置 下发消息(除文本消息) 类型按钮
|
||||||
func (btn *Button) SetMediaIDButton(name, mediaID string) {
|
func (btn *Button) SetMediaIDButton(name, mediaID string) *Button {
|
||||||
btn.Type = "media_id"
|
btn.Type = "media_id"
|
||||||
btn.Name = name
|
btn.Name = name
|
||||||
btn.MediaID = mediaID
|
btn.MediaID = mediaID
|
||||||
@@ -116,10 +125,11 @@ func (btn *Button) SetMediaIDButton(name, mediaID string) {
|
|||||||
btn.Key = ""
|
btn.Key = ""
|
||||||
btn.URL = ""
|
btn.URL = ""
|
||||||
btn.SubButtons = nil
|
btn.SubButtons = nil
|
||||||
|
return btn
|
||||||
}
|
}
|
||||||
|
|
||||||
//SetViewLimitedButton 设置 跳转图文消息URL 类型按钮
|
//SetViewLimitedButton 设置 跳转图文消息URL 类型按钮
|
||||||
func (btn *Button) SetViewLimitedButton(name, mediaID string) {
|
func (btn *Button) SetViewLimitedButton(name, mediaID string) *Button {
|
||||||
btn.Type = "view_limited"
|
btn.Type = "view_limited"
|
||||||
btn.Name = name
|
btn.Name = name
|
||||||
btn.MediaID = mediaID
|
btn.MediaID = mediaID
|
||||||
@@ -127,10 +137,11 @@ func (btn *Button) SetViewLimitedButton(name, mediaID string) {
|
|||||||
btn.Key = ""
|
btn.Key = ""
|
||||||
btn.URL = ""
|
btn.URL = ""
|
||||||
btn.SubButtons = nil
|
btn.SubButtons = nil
|
||||||
|
return btn
|
||||||
}
|
}
|
||||||
|
|
||||||
//SetMiniprogramButton 设置 跳转小程序 类型按钮 (公众号后台必须已经关联小程序)
|
//SetMiniprogramButton 设置 跳转小程序 类型按钮 (公众号后台必须已经关联小程序)
|
||||||
func (btn *Button) SetMiniprogramButton(name, url, appID, pagePath string) {
|
func (btn *Button) SetMiniprogramButton(name, url, appID, pagePath string) *Button {
|
||||||
btn.Type = "miniprogram"
|
btn.Type = "miniprogram"
|
||||||
btn.Name = name
|
btn.Name = name
|
||||||
btn.URL = url
|
btn.URL = url
|
||||||
@@ -140,4 +151,65 @@ func (btn *Button) SetMiniprogramButton(name, url, appID, pagePath string) {
|
|||||||
btn.Key = ""
|
btn.Key = ""
|
||||||
btn.MediaID = ""
|
btn.MediaID = ""
|
||||||
btn.SubButtons = nil
|
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))
|
||||||
|
}
|
||||||
@@ -102,12 +102,12 @@ type ButtonNew struct {
|
|||||||
|
|
||||||
//MatchRule 个性化菜单规则
|
//MatchRule 个性化菜单规则
|
||||||
type MatchRule struct {
|
type MatchRule struct {
|
||||||
GroupID int32 `json:"group_id,omitempty"`
|
GroupID string `json:"group_id,omitempty"`
|
||||||
Sex int32 `json:"sex,omitempty"`
|
Sex string `json:"sex,omitempty"`
|
||||||
Country string `json:"country,omitempty"`
|
Country string `json:"country,omitempty"`
|
||||||
Province string `json:"province,omitempty"`
|
Province string `json:"province,omitempty"`
|
||||||
City string `json:"city,omitempty"`
|
City string `json:"city,omitempty"`
|
||||||
ClientPlatformType int32 `json:"client_platform_type,omitempty"`
|
ClientPlatformType string `json:"client_platform_type,omitempty"`
|
||||||
Language string `json:"language,omitempty"`
|
Language string `json:"language,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,7 +138,6 @@ func (menu *Menu) SetMenu(buttons []*Button) error {
|
|||||||
return util.DecodeWithCommonError(response, "SetMenu")
|
return util.DecodeWithCommonError(response, "SetMenu")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//SetMenuByJSON 设置按钮
|
//SetMenuByJSON 设置按钮
|
||||||
func (menu *Menu) SetMenuByJSON(jsonInfo string) error {
|
func (menu *Menu) SetMenuByJSON(jsonInfo string) error {
|
||||||
accessToken, err := menu.GetAccessToken()
|
accessToken, err := menu.GetAccessToken()
|
||||||
@@ -148,12 +147,12 @@ func (menu *Menu) SetMenuByJSON(jsonInfo string) error {
|
|||||||
|
|
||||||
uri := fmt.Sprintf("%s?access_token=%s", menuCreateURL, accessToken)
|
uri := fmt.Sprintf("%s?access_token=%s", menuCreateURL, accessToken)
|
||||||
|
|
||||||
response, err := util.PostJSON(uri, jsonInfo)
|
response, err := util.HTTPPost(uri, jsonInfo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return util.DecodeWithCommonError(response, "SetMenu")
|
return util.DecodeWithCommonError(response, "SetMenuByJSON")
|
||||||
}
|
}
|
||||||
|
|
||||||
//GetMenu 获取菜单配置
|
//GetMenu 获取菜单配置
|
||||||
@@ -216,7 +215,6 @@ func (menu *Menu) AddConditional(buttons []*Button, matchRule *MatchRule) error
|
|||||||
return util.DecodeWithCommonError(response, "AddConditional")
|
return util.DecodeWithCommonError(response, "AddConditional")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//AddConditionalByJSON 添加个性化菜单
|
//AddConditionalByJSON 添加个性化菜单
|
||||||
func (menu *Menu) AddConditionalByJSON(jsonInfo string) error {
|
func (menu *Menu) AddConditionalByJSON(jsonInfo string) error {
|
||||||
accessToken, err := menu.GetAccessToken()
|
accessToken, err := menu.GetAccessToken()
|
||||||
@@ -225,7 +223,7 @@ func (menu *Menu) AddConditionalByJSON(jsonInfo string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
uri := fmt.Sprintf("%s?access_token=%s", menuAddConditionalURL, accessToken)
|
uri := fmt.Sprintf("%s?access_token=%s", menuAddConditionalURL, accessToken)
|
||||||
response, err := util.PostJSON(uri, jsonInfo)
|
response, err := util.HTTPPost(uri, jsonInfo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,6 +73,20 @@ func NewCustomerVoiceMessage(toUser, mediaID string) *CustomerMessage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//NewCustomerMiniprogrampageMessage 小程序卡片消息的构造方法
|
||||||
|
func NewCustomerMiniprogrampageMessage(toUser, title, appID, pagePath, thumbMediaID string) *CustomerMessage {
|
||||||
|
return &CustomerMessage{
|
||||||
|
ToUser: toUser,
|
||||||
|
Msgtype: MsgTypeMiniprogrampage,
|
||||||
|
Miniprogrampage: &MediaMiniprogrampage{
|
||||||
|
Title: title,
|
||||||
|
AppID: appID,
|
||||||
|
Pagepath: pagePath,
|
||||||
|
ThumbMediaID: thumbMediaID,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
//MediaText 文本消息的文字
|
//MediaText 文本消息的文字
|
||||||
type MediaText struct {
|
type MediaText struct {
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
@@ -134,7 +148,7 @@ type MediaWxcard struct {
|
|||||||
//MediaMiniprogrampage 小程序消息
|
//MediaMiniprogrampage 小程序消息
|
||||||
type MediaMiniprogrampage struct {
|
type MediaMiniprogrampage struct {
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Appid string `json:"appid"`
|
AppID string `json:"appid"`
|
||||||
Pagepath string `json:"pagepath"`
|
Pagepath string `json:"pagepath"`
|
||||||
ThumbMediaID string `json:"thumb_media_id"`
|
ThumbMediaID string `json:"thumb_media_id"`
|
||||||
}
|
}
|
||||||
@@ -147,6 +161,9 @@ func (manager *Manager) Send(msg *CustomerMessage) error {
|
|||||||
}
|
}
|
||||||
uri := fmt.Sprintf("%s?access_token=%s", customerSendMessage, accessToken)
|
uri := fmt.Sprintf("%s?access_token=%s", customerSendMessage, accessToken)
|
||||||
response, err := util.PostJSON(uri, msg)
|
response, err := util.PostJSON(uri, msg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
var result util.CommonError
|
var result util.CommonError
|
||||||
err = json.Unmarshal(response, &result)
|
err = json.Unmarshal(response, &result)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ const (
|
|||||||
MsgTypeVoice = "voice"
|
MsgTypeVoice = "voice"
|
||||||
//MsgTypeVideo 表示视频消息
|
//MsgTypeVideo 表示视频消息
|
||||||
MsgTypeVideo = "video"
|
MsgTypeVideo = "video"
|
||||||
|
//MsgTypeMiniprogrampage 表示小程序卡片消息
|
||||||
|
MsgTypeMiniprogrampage = "miniprogrampage"
|
||||||
//MsgTypeShortVideo 表示短视频消息[限接收]
|
//MsgTypeShortVideo 表示短视频消息[限接收]
|
||||||
MsgTypeShortVideo = "shortvideo"
|
MsgTypeShortVideo = "shortvideo"
|
||||||
//MsgTypeLocation 表示坐标消息[限接收]
|
//MsgTypeLocation 表示坐标消息[限接收]
|
||||||
@@ -67,6 +69,8 @@ const (
|
|||||||
EventLocationSelect = "location_select"
|
EventLocationSelect = "location_select"
|
||||||
//EventTemplateSendJobFinish 发送模板消息推送通知
|
//EventTemplateSendJobFinish 发送模板消息推送通知
|
||||||
EventTemplateSendJobFinish = "TEMPLATESENDJOBFINISH"
|
EventTemplateSendJobFinish = "TEMPLATESENDJOBFINISH"
|
||||||
|
//EventMassSendJobFinish 群发消息推送通知
|
||||||
|
EventMassSendJobFinish = "MASSSENDJOBFINISH"
|
||||||
//EventWxaMediaCheck 异步校验图片/音频是否含有违法违规内容推送事件
|
//EventWxaMediaCheck 异步校验图片/音频是否含有违法违规内容推送事件
|
||||||
EventWxaMediaCheck = "wxa_media_check"
|
EventWxaMediaCheck = "wxa_media_check"
|
||||||
)
|
)
|
||||||
@@ -89,20 +93,21 @@ type MixMessage struct {
|
|||||||
CommonToken
|
CommonToken
|
||||||
|
|
||||||
//基本消息
|
//基本消息
|
||||||
MsgID int64 `xml:"MsgId"`
|
MsgID int64 `xml:"MsgId"` //其他消息推送过来是MsgId
|
||||||
Content string `xml:"Content"`
|
TemplateMsgID int64 `xml:"MsgID"` //模板消息推送成功的消息是MsgID
|
||||||
Recognition string `xml:"Recognition"`
|
Content string `xml:"Content"`
|
||||||
PicURL string `xml:"PicUrl"`
|
Recognition string `xml:"Recognition"`
|
||||||
MediaID string `xml:"MediaId"`
|
PicURL string `xml:"PicUrl"`
|
||||||
Format string `xml:"Format"`
|
MediaID string `xml:"MediaId"`
|
||||||
ThumbMediaID string `xml:"ThumbMediaId"`
|
Format string `xml:"Format"`
|
||||||
LocationX float64 `xml:"Location_X"`
|
ThumbMediaID string `xml:"ThumbMediaId"`
|
||||||
LocationY float64 `xml:"Location_Y"`
|
LocationX float64 `xml:"Location_X"`
|
||||||
Scale float64 `xml:"Scale"`
|
LocationY float64 `xml:"Location_Y"`
|
||||||
Label string `xml:"Label"`
|
Scale float64 `xml:"Scale"`
|
||||||
Title string `xml:"Title"`
|
Label string `xml:"Label"`
|
||||||
Description string `xml:"Description"`
|
Title string `xml:"Title"`
|
||||||
URL string `xml:"Url"`
|
Description string `xml:"Description"`
|
||||||
|
URL string `xml:"Url"`
|
||||||
|
|
||||||
//事件相关
|
//事件相关
|
||||||
Event EventType `xml:"Event"`
|
Event EventType `xml:"Event"`
|
||||||
@@ -114,6 +119,10 @@ type MixMessage struct {
|
|||||||
MenuID string `xml:"MenuId"`
|
MenuID string `xml:"MenuId"`
|
||||||
Status string `xml:"Status"`
|
Status string `xml:"Status"`
|
||||||
SessionFrom string `xml:"SessionFrom"`
|
SessionFrom string `xml:"SessionFrom"`
|
||||||
|
TotalCount int64 `xml:"TotalCount"`
|
||||||
|
FilterCount int64 `xml:"FilterCount"`
|
||||||
|
SentCount int64 `xml:"SentCount"`
|
||||||
|
ErrorCount int64 `xml:"ErrorCount"`
|
||||||
|
|
||||||
ScanCodeInfo struct {
|
ScanCodeInfo struct {
|
||||||
ScanType string `xml:"ScanType"`
|
ScanType string `xml:"ScanType"`
|
||||||
@@ -222,3 +231,8 @@ func (msg *CommonToken) SetCreateTime(createTime int64) {
|
|||||||
func (msg *CommonToken) SetMsgType(msgType MsgType) {
|
func (msg *CommonToken) SetMsgType(msgType MsgType) {
|
||||||
msg.MsgType = msgType
|
msg.MsgType = msgType
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//GetOpenID get the FromUserName value
|
||||||
|
func (msg *CommonToken) GetOpenID() string {
|
||||||
|
return string(msg.FromUserName)
|
||||||
|
}
|
||||||
|
|||||||
147
officialaccount/message/subscribe.go
Normal file
147
officialaccount/message/subscribe.go
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
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"
|
||||||
|
subscribeTemplateAddURL = "https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate"
|
||||||
|
subscribeTemplateDelURL = "https://api.weixin.qq.com/wxaapi/newtmpl/deltemplate"
|
||||||
|
)
|
||||||
|
|
||||||
|
//Subscribe 订阅消息
|
||||||
|
type Subscribe struct {
|
||||||
|
*context.Context
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewSubscribe 实例化
|
||||||
|
func NewSubscribe(context *context.Context) *Subscribe {
|
||||||
|
tpl := new(Subscribe)
|
||||||
|
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 *Subscribe) 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, "SendSubscribeMessage")
|
||||||
|
}
|
||||||
|
|
||||||
|
// PrivateSubscribeItem 私有订阅消息模板
|
||||||
|
type PrivateSubscribeItem 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 resPrivateSubscribeList struct {
|
||||||
|
util.CommonError
|
||||||
|
SubscriptionList []*PrivateSubscribeItem `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//List 获取私有订阅消息模板列表
|
||||||
|
func (tpl *Subscribe) List() (templateList []*PrivateSubscribeItem, 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 resPrivateSubscribeList
|
||||||
|
err = util.DecodeWithError(response, &res, "ListSubscribe")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
templateList = res.SubscriptionList
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type resSubscribeAdd struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
TemplateID string `json:"priTmplId"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add 添加订阅消息模板
|
||||||
|
func (tpl *Subscribe) Add(ShortID string, kidList []int, sceneDesc string) (templateID string, err error) {
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = tpl.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var msg = struct {
|
||||||
|
TemplateIDShort string `json:"tid"`
|
||||||
|
SceneDesc string `json:"sceneDesc"`
|
||||||
|
KidList []int `json:"kidList"`
|
||||||
|
}{TemplateIDShort: ShortID, SceneDesc: sceneDesc, KidList: kidList}
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", subscribeTemplateAddURL, accessToken)
|
||||||
|
var response []byte
|
||||||
|
response, err = util.PostJSON(uri, msg)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var result resSubscribeAdd
|
||||||
|
err = util.DecodeWithError(response, &result, "AddSubscribe")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
templateID = result.TemplateID
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete 删除私有模板
|
||||||
|
func (tpl *Subscribe) Delete(templateID string) (err error) {
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = tpl.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var msg = struct {
|
||||||
|
TemplateID string `json:"priTmplId"`
|
||||||
|
}{TemplateID: templateID}
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", subscribeTemplateDelURL, accessToken)
|
||||||
|
var response []byte
|
||||||
|
response, err = util.PostJSON(uri, msg)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return util.DecodeWithCommonError(response, "DeleteSubscribe")
|
||||||
|
}
|
||||||
@@ -10,6 +10,9 @@ import (
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
templateSendURL = "https://api.weixin.qq.com/cgi-bin/message/template/send"
|
templateSendURL = "https://api.weixin.qq.com/cgi-bin/message/template/send"
|
||||||
|
templateListURL = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template"
|
||||||
|
templateAddURL = "https://api.weixin.qq.com/cgi-bin/template/api_add_template"
|
||||||
|
templateDelURL = "https://api.weixin.qq.com/cgi-bin/template/del_private_template"
|
||||||
)
|
)
|
||||||
|
|
||||||
//Template 模板消息
|
//Template 模板消息
|
||||||
@@ -58,8 +61,11 @@ func (tpl *Template) Send(msg *TemplateMessage) (msgID int64, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
uri := fmt.Sprintf("%s?access_token=%s", templateSendURL, accessToken)
|
uri := fmt.Sprintf("%s?access_token=%s", templateSendURL, accessToken)
|
||||||
response, err := util.PostJSON(uri, msg)
|
var response []byte
|
||||||
|
response, err = util.PostJSON(uri, msg)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
var result resTemplateSend
|
var result resTemplateSend
|
||||||
err = json.Unmarshal(response, &result)
|
err = json.Unmarshal(response, &result)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -72,3 +78,93 @@ func (tpl *Template) Send(msg *TemplateMessage) (msgID int64, err error) {
|
|||||||
msgID = result.MsgID
|
msgID = result.MsgID
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TemplateItem 模板消息.
|
||||||
|
type TemplateItem struct {
|
||||||
|
TemplateID string `json:"template_id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
PrimaryIndustry string `json:"primary_industry"`
|
||||||
|
DeputyIndustry string `json:"deputy_industry"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
Example string `json:"example"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type resTemplateList struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
TemplateList []*TemplateItem `json:"template_list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//List 获取模板列表
|
||||||
|
func (tpl *Template) List() (templateList []*TemplateItem, err error) {
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = tpl.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", templateListURL, accessToken)
|
||||||
|
var response []byte
|
||||||
|
response, err = util.HTTPGet(uri)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var res resTemplateList
|
||||||
|
err = util.DecodeWithError(response, &res, "ListTemplate")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
templateList = res.TemplateList
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type resTemplateAdd struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
TemplateID string `json:"template_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add 添加模板.
|
||||||
|
func (tpl *Template) Add(shortID string) (templateID string, err error) {
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = tpl.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var msg = struct {
|
||||||
|
ShortID string `json:"template_id_short"`
|
||||||
|
}{ShortID: shortID}
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", templateAddURL, accessToken)
|
||||||
|
var response []byte
|
||||||
|
response, err = util.PostJSON(uri, msg)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var result resTemplateAdd
|
||||||
|
err = util.DecodeWithError(response, &result, "AddTemplate")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
templateID = result.TemplateID
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete 删除私有模板.
|
||||||
|
func (tpl *Template) Delete(templateID string) (err error) {
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = tpl.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var msg = struct {
|
||||||
|
TemplateID string `json:"template_id"`
|
||||||
|
}{TemplateID: templateID}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", templateDelURL, accessToken)
|
||||||
|
var response []byte
|
||||||
|
response, err = util.PostJSON(uri, msg)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return util.DecodeWithCommonError(response, "DeleteTemplate")
|
||||||
|
}
|
||||||
|
|||||||
@@ -13,11 +13,11 @@ type TransInfo struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//NewTransferCustomer 实例化
|
//NewTransferCustomer 实例化
|
||||||
func NewTransferCustomer(KfAccount string) *TransferCustomer {
|
func NewTransferCustomer(kfAccount string) *TransferCustomer {
|
||||||
tc := new(TransferCustomer)
|
tc := new(TransferCustomer)
|
||||||
if KfAccount != "" {
|
if kfAccount != "" {
|
||||||
transInfo := new(TransInfo)
|
transInfo := new(TransInfo)
|
||||||
transInfo.KfAccount = KfAccount
|
transInfo.KfAccount = kfAccount
|
||||||
tc.TransInfo = transInfo
|
tc.TransInfo = transInfo
|
||||||
}
|
}
|
||||||
return tc
|
return tc
|
||||||
|
|||||||
@@ -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"
|
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"
|
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"
|
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"
|
checkAccessTokenURL = "https://api.weixin.qq.com/sns/auth?access_token=%s&openid=%s"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -50,7 +50,7 @@ func (oauth *Oauth) Redirect(writer http.ResponseWriter, req *http.Request, redi
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
http.Redirect(writer, req, location, 302)
|
http.Redirect(writer, req, location, http.StatusFound)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,8 +144,11 @@ type UserInfo struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//GetUserInfo 如果scope为 snsapi_userinfo 则可以通过此方法获取到用户基本信息
|
//GetUserInfo 如果scope为 snsapi_userinfo 则可以通过此方法获取到用户基本信息
|
||||||
func (oauth *Oauth) GetUserInfo(accessToken, openID string) (result UserInfo, err error) {
|
func (oauth *Oauth) GetUserInfo(accessToken, openID, lang string) (result UserInfo, err error) {
|
||||||
urlStr := fmt.Sprintf(userInfoURL, accessToken, openID)
|
if lang == "" {
|
||||||
|
lang = "zh_CN"
|
||||||
|
}
|
||||||
|
urlStr := fmt.Sprintf(userInfoURL, accessToken, openID, lang)
|
||||||
var response []byte
|
var response []byte
|
||||||
response, err = util.HTTPGet(urlStr)
|
response, err = util.HTTPGet(urlStr)
|
||||||
if err != nil {
|
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,10 @@ package officialaccount
|
|||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/officialaccount/ocr"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/officialaccount/datacube"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/credential"
|
"github.com/silenceper/wechat/v2/credential"
|
||||||
"github.com/silenceper/wechat/v2/officialaccount/basic"
|
"github.com/silenceper/wechat/v2/officialaccount/basic"
|
||||||
"github.com/silenceper/wechat/v2/officialaccount/broadcast"
|
"github.com/silenceper/wechat/v2/officialaccount/broadcast"
|
||||||
@@ -91,6 +95,11 @@ func (officialAccount *OfficialAccount) GetTemplate() *message.Template {
|
|||||||
return message.NewTemplate(officialAccount.ctx)
|
return message.NewTemplate(officialAccount.ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetCustomerMessageManager 客服消息接口
|
||||||
|
func (officialAccount *OfficialAccount) GetCustomerMessageManager() *message.Manager {
|
||||||
|
return message.NewMessageManager(officialAccount.ctx)
|
||||||
|
}
|
||||||
|
|
||||||
// GetDevice 获取智能设备的实例
|
// GetDevice 获取智能设备的实例
|
||||||
func (officialAccount *OfficialAccount) GetDevice() *device.Device {
|
func (officialAccount *OfficialAccount) GetDevice() *device.Device {
|
||||||
return device.NewDevice(officialAccount.ctx)
|
return device.NewDevice(officialAccount.ctx)
|
||||||
@@ -101,3 +110,18 @@ func (officialAccount *OfficialAccount) GetDevice() *device.Device {
|
|||||||
func (officialAccount *OfficialAccount) GetBroadcast() *broadcast.Broadcast {
|
func (officialAccount *OfficialAccount) GetBroadcast() *broadcast.Broadcast {
|
||||||
return broadcast.NewBroadcast(officialAccount.ctx)
|
return broadcast.NewBroadcast(officialAccount.ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//GetDataCube 数据统计
|
||||||
|
func (officialAccount *OfficialAccount) GetDataCube() *datacube.DataCube {
|
||||||
|
return datacube.NewCube(officialAccount.ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetOCR OCR接口
|
||||||
|
func (officialAccount *OfficialAccount) GetOCR() *ocr.OCR {
|
||||||
|
return ocr.NewOCR(officialAccount.ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetSubscribe 公众号订阅消息
|
||||||
|
func (officialAccount *OfficialAccount) GetSubscribe() *message.Subscribe {
|
||||||
|
return message.NewSubscribe(officialAccount.ctx)
|
||||||
|
}
|
||||||
|
|||||||
@@ -27,10 +27,10 @@ type Server struct {
|
|||||||
|
|
||||||
openID string
|
openID string
|
||||||
|
|
||||||
messageHandler func(message.MixMessage) *message.Reply
|
messageHandler func(*message.MixMessage) *message.Reply
|
||||||
|
|
||||||
RequestRawXMLMsg []byte
|
RequestRawXMLMsg []byte
|
||||||
RequestMsg message.MixMessage
|
RequestMsg *message.MixMessage
|
||||||
ResponseRawXMLMsg []byte
|
ResponseRawXMLMsg []byte
|
||||||
ResponseMsg interface{}
|
ResponseMsg interface{}
|
||||||
|
|
||||||
@@ -105,7 +105,7 @@ func (srv *Server) handleRequest() (reply *message.Reply, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
mixMessage, success := msg.(message.MixMessage)
|
mixMessage, success := msg.(*message.MixMessage)
|
||||||
if !success {
|
if !success {
|
||||||
err = errors.New("消息类型转换失败")
|
err = errors.New("消息类型转换失败")
|
||||||
}
|
}
|
||||||
@@ -160,14 +160,14 @@ func (srv *Server) getMessage() (interface{}, error) {
|
|||||||
return srv.parseRequestMessage(rawXMLMsgBytes)
|
return srv.parseRequestMessage(rawXMLMsgBytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (srv *Server) parseRequestMessage(rawXMLMsgBytes []byte) (msg message.MixMessage, err error) {
|
func (srv *Server) parseRequestMessage(rawXMLMsgBytes []byte) (msg *message.MixMessage, err error) {
|
||||||
msg = message.MixMessage{}
|
msg = &message.MixMessage{}
|
||||||
err = xml.Unmarshal(rawXMLMsgBytes, &msg)
|
err = xml.Unmarshal(rawXMLMsgBytes, msg)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
//SetMessageHandler 设置用户自定义的回调方法
|
//SetMessageHandler 设置用户自定义的回调方法
|
||||||
func (srv *Server) SetMessageHandler(handler func(message.MixMessage) *message.Reply) {
|
func (srv *Server) SetMessageHandler(handler func(*message.MixMessage) *message.Reply) {
|
||||||
srv.messageHandler = handler
|
srv.messageHandler = handler
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,7 +199,7 @@ func (srv *Server) buildResponse(reply *message.Reply) (err error) {
|
|||||||
value := reflect.ValueOf(msgData)
|
value := reflect.ValueOf(msgData)
|
||||||
//msgData must be a ptr
|
//msgData must be a ptr
|
||||||
kind := value.Kind().String()
|
kind := value.Kind().String()
|
||||||
if "ptr" != kind {
|
if kind != "ptr" {
|
||||||
return message.ErrUnsupportReply
|
return message.ErrUnsupportReply
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,7 +213,7 @@ func (srv *Server) buildResponse(reply *message.Reply) (err error) {
|
|||||||
params[0] = reflect.ValueOf(msgType)
|
params[0] = reflect.ValueOf(msgType)
|
||||||
value.MethodByName("SetMsgType").Call(params)
|
value.MethodByName("SetMsgType").Call(params)
|
||||||
|
|
||||||
params[0] = reflect.ValueOf(util.GetCurrTs())
|
params[0] = reflect.ValueOf(util.GetCurrTS())
|
||||||
value.MethodByName("SetCreateTime").Call(params)
|
value.MethodByName("SetCreateTime").Call(params)
|
||||||
|
|
||||||
srv.ResponseMsg = msgData
|
srv.ResponseMsg = msgData
|
||||||
|
|||||||
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
|
||||||
|
}
|
||||||
241
officialaccount/user/tag.go
Normal file
241
officialaccount/user/tag.go
Normal file
@@ -0,0 +1,241 @@
|
|||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
tagCreateURL = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token=%s"
|
||||||
|
tagGetURL = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token=%s"
|
||||||
|
tagUpdateURL = "https://api.weixin.qq.com/cgi-bin/tags/update?access_token=%s"
|
||||||
|
tagDeleteURL = "https://api.weixin.qq.com/cgi-bin/tags/delete?access_token=%s"
|
||||||
|
tagUserListURL = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=%s"
|
||||||
|
tagBatchtaggingURL = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=%s"
|
||||||
|
tagBatchuntaggingURL = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token=%s"
|
||||||
|
tagUserTidListURL = "https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token=%s"
|
||||||
|
)
|
||||||
|
|
||||||
|
//TagInfo 标签信息
|
||||||
|
type TagInfo struct {
|
||||||
|
ID int32 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Count int64 `json:"count"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TagOpenIDList 标签用户列表
|
||||||
|
type TagOpenIDList struct {
|
||||||
|
Count int `json:"count"`
|
||||||
|
Data struct {
|
||||||
|
OpenIDs []string `json:"openid"`
|
||||||
|
} `json:"data"`
|
||||||
|
NextOpenID string `json:"next_openid"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//CreateTag 创建标签
|
||||||
|
func (user *User) CreateTag(tagName string) (tagInfo *TagInfo, err error) {
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = user.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
uri := fmt.Sprintf(tagCreateURL, accessToken)
|
||||||
|
var response []byte
|
||||||
|
var request struct {
|
||||||
|
Tag struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
} `json:"tag"`
|
||||||
|
}
|
||||||
|
request.Tag.Name = tagName
|
||||||
|
response, err = util.PostJSON(uri, &request)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var result struct {
|
||||||
|
util.CommonError
|
||||||
|
Tag *TagInfo `json:"tag"`
|
||||||
|
}
|
||||||
|
err = json.Unmarshal(response, &result)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if result.ErrCode != 0 {
|
||||||
|
err = fmt.Errorf("CreateTag Error , errcode=%d , errmsg=%s", result.ErrCode, result.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return result.Tag, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
//DeleteTag 删除标签
|
||||||
|
func (user *User) DeleteTag(tagID int32) (err error) {
|
||||||
|
accessToken, err := user.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf(tagDeleteURL, accessToken)
|
||||||
|
var request struct {
|
||||||
|
Tag struct {
|
||||||
|
ID int32 `json:"id"`
|
||||||
|
} `json:"tag"`
|
||||||
|
}
|
||||||
|
request.Tag.ID = tagID
|
||||||
|
resp, err := util.PostJSON(url, &request)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return util.DecodeWithCommonError(resp, "DeleteTag")
|
||||||
|
}
|
||||||
|
|
||||||
|
//UpdateTag 编辑标签
|
||||||
|
func (user *User) UpdateTag(tagID int32, tagName string) (err error) {
|
||||||
|
accessToken, err := user.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf(tagUpdateURL, accessToken)
|
||||||
|
var request struct {
|
||||||
|
Tag struct {
|
||||||
|
ID int32 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
} `json:"tag"`
|
||||||
|
}
|
||||||
|
request.Tag.ID = tagID
|
||||||
|
request.Tag.Name = tagName
|
||||||
|
resp, err := util.PostJSON(url, &request)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return util.DecodeWithCommonError(resp, "UpdateTag")
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetTag 获取公众号已创建的标签
|
||||||
|
func (user *User) GetTag() (tags []*TagInfo, err error) {
|
||||||
|
accessToken, err := user.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf(tagGetURL, accessToken)
|
||||||
|
response, err := util.HTTPGet(url)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var result struct {
|
||||||
|
util.CommonError
|
||||||
|
Tags []*TagInfo `json:"tags"`
|
||||||
|
}
|
||||||
|
err = json.Unmarshal(response, &result)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return result.Tags, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
//OpenIDListByTag 获取标签下粉丝列表
|
||||||
|
func (user *User) OpenIDListByTag(tagID int32, nextOpenID ...string) (userList *TagOpenIDList, err error) {
|
||||||
|
accessToken, err := user.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf(tagUserListURL, accessToken)
|
||||||
|
var request = struct {
|
||||||
|
ID int32 `json:"tagid"`
|
||||||
|
OpenID string `json:"next_openid"`
|
||||||
|
}{
|
||||||
|
ID: tagID,
|
||||||
|
}
|
||||||
|
if len(nextOpenID) > 0 {
|
||||||
|
request.OpenID = nextOpenID[0]
|
||||||
|
}
|
||||||
|
response, err := util.PostJSON(url, &request)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
userList = new(TagOpenIDList)
|
||||||
|
err = json.Unmarshal(response, &userList)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//BatchTag 批量为用户打标签
|
||||||
|
func (user *User) BatchTag(openIDList []string, tagID int32) (err error) {
|
||||||
|
accessToken, err := user.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(openIDList) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var request = struct {
|
||||||
|
OpenIDList []string `json:"openid_list"`
|
||||||
|
TagID int32 `json:"tagid"`
|
||||||
|
}{
|
||||||
|
OpenIDList: openIDList,
|
||||||
|
TagID: tagID,
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf(tagBatchtaggingURL, accessToken)
|
||||||
|
resp, err := util.PostJSON(url, &request)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return util.DecodeWithCommonError(resp, "BatchTag")
|
||||||
|
}
|
||||||
|
|
||||||
|
//BatchUntag 批量为用户取消标签
|
||||||
|
func (user *User) BatchUntag(openIDList []string, tagID int32) (err error) {
|
||||||
|
if len(openIDList) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
accessToken, err := user.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf(tagBatchuntaggingURL, accessToken)
|
||||||
|
var request = struct {
|
||||||
|
OpenIDList []string `json:"openid_list"`
|
||||||
|
TagID int32 `json:"tagid"`
|
||||||
|
}{
|
||||||
|
OpenIDList: openIDList,
|
||||||
|
TagID: tagID,
|
||||||
|
}
|
||||||
|
resp, err := util.PostJSON(url, &request)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return util.DecodeWithCommonError(resp, "BatchUntag")
|
||||||
|
}
|
||||||
|
|
||||||
|
//UserTidList 获取用户身上的标签列表
|
||||||
|
func (user *User) UserTidList(openID string) (tagIDList []int32, err error) {
|
||||||
|
accessToken, err := user.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf(tagUserTidListURL, accessToken)
|
||||||
|
var request = struct {
|
||||||
|
OpenID string `json:"openid"`
|
||||||
|
TagID int32 `json:"tagid"`
|
||||||
|
}{
|
||||||
|
OpenID: openID,
|
||||||
|
}
|
||||||
|
resp, err := util.PostJSON(url, &request)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var result struct {
|
||||||
|
util.CommonError
|
||||||
|
TagIDList []int32 `json:"tagid_list"`
|
||||||
|
}
|
||||||
|
err = json.Unmarshal(resp, &result)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if result.ErrCode != 0 {
|
||||||
|
err = fmt.Errorf("UserTidList Error , errcode=%d , errmsg=%s", result.ErrCode, result.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return result.TagIDList, nil
|
||||||
|
}
|
||||||
@@ -52,6 +52,8 @@ type Info struct {
|
|||||||
|
|
||||||
// OpenidList 用户列表
|
// OpenidList 用户列表
|
||||||
type OpenidList struct {
|
type OpenidList struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
Total int `json:"total"`
|
Total int `json:"total"`
|
||||||
Count int `json:"count"`
|
Count int `json:"count"`
|
||||||
Data struct {
|
Data struct {
|
||||||
@@ -124,19 +126,20 @@ func (user *User) ListUserOpenIDs(nextOpenid ...string) (*OpenidList, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
userlist := new(OpenidList)
|
userlist := OpenidList{}
|
||||||
err = json.Unmarshal(response, userlist)
|
|
||||||
|
err = util.DecodeWithError(response, &userlist, "ListUserOpenIDs")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return userlist, nil
|
return &userlist, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListAllUserOpenIDs 返回所有用户OpenID列表
|
// ListAllUserOpenIDs 返回所有用户OpenID列表
|
||||||
func (user *User) ListAllUserOpenIDs() ([]string, error) {
|
func (user *User) ListAllUserOpenIDs() ([]string, error) {
|
||||||
nextOpenid := ""
|
nextOpenid := ""
|
||||||
openids := []string{}
|
openids := make([]string, 0)
|
||||||
count := 0
|
count := 0
|
||||||
for {
|
for {
|
||||||
ul, err := user.ListUserOpenIDs(nextOpenid)
|
ul, err := user.ListUserOpenIDs(nextOpenid)
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
# 微信开放平台
|
# 微信开放平台
|
||||||
|
|
||||||
状态:开发中
|
|
||||||
|
|
||||||
[官方文档](https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/Third_party_platform_appid.html)
|
[官方文档](https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/Third_party_platform_appid.html)
|
||||||
|
|
||||||
## 快速入门
|
## 快速入门
|
||||||
|
|
||||||
|
### 服务端处理
|
||||||
```go
|
```go
|
||||||
wc := wechat.NewWechat()
|
wc := wechat.NewWechat()
|
||||||
memory := cache.NewMemory()
|
memory := cache.NewMemory()
|
||||||
@@ -17,15 +17,12 @@ cfg := &openplatform.Config{
|
|||||||
Cache: memory,
|
Cache: memory,
|
||||||
}
|
}
|
||||||
|
|
||||||
//授权的第三方公众号的appID
|
|
||||||
appID := "xxx"
|
|
||||||
openPlatform := wc.GetOpenPlatform(cfg)
|
|
||||||
officialAccount := openPlatform.GetOfficialAccount(appID)
|
|
||||||
|
|
||||||
|
openPlatform := wc.GetOpenPlatform(cfg)
|
||||||
// 传入request和responseWriter
|
// 传入request和responseWriter
|
||||||
server := officialAccount.GetServer(req, rw)
|
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 {
|
if msg.InfoType == message.InfoTypeVerifyTicket {
|
||||||
componentVerifyTicket, err := openPlatform.SetComponentAccessToken(msg.ComponentVerifyTicket)
|
componentVerifyTicket, err := openPlatform.SetComponentAccessToken(msg.ComponentVerifyTicket)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -52,4 +49,15 @@ if err != nil {
|
|||||||
}
|
}
|
||||||
//发送回复的消息
|
//发送回复的消息
|
||||||
server.Send()
|
server.Send()
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
### 待授权处理消息
|
||||||
|
```go
|
||||||
|
|
||||||
|
//授权的第三方公众号的appID
|
||||||
|
appID := "xxx"
|
||||||
|
openPlatform := wc.GetOpenPlatform(cfg)
|
||||||
|
openPlatform.GetOfficialAccount(appID)
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
|
//Package context 开放平台相关context
|
||||||
package context
|
package context
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net/url"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
"github.com/silenceper/wechat/v2/util"
|
||||||
@@ -14,10 +16,12 @@ const (
|
|||||||
queryAuthURL = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=%s"
|
queryAuthURL = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=%s"
|
||||||
refreshTokenURL = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=%s"
|
refreshTokenURL = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=%s"
|
||||||
getComponentInfoURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=%s"
|
getComponentInfoURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=%s"
|
||||||
|
componentLoginURL = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=%s&pre_auth_code=%s&redirect_uri=%s&auth_type=%d&biz_appid=%s"
|
||||||
|
bindComponentURL = "https://mp.weixin.qq.com/safe/bindcomponent?action=bindcomponent&auth_type=%d&no_scan=1&component_appid=%s&pre_auth_code=%s&redirect_uri=%s&biz_appid=%s#wechat_redirect"
|
||||||
//TODO 获取授权方选项信息
|
//TODO 获取授权方选项信息
|
||||||
getComponentConfigURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_option?component_access_token=%s"
|
//getComponentConfigURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_option?component_access_token=%s"
|
||||||
//TODO 获取已授权的账号信息
|
//TODO 获取已授权的账号信息
|
||||||
getuthorizerListURL = "POST https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_list?component_access_token=%s"
|
//getuthorizerListURL = "POST https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_list?component_access_token=%s"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ComponentAccessToken 第三方平台
|
// ComponentAccessToken 第三方平台
|
||||||
@@ -86,6 +90,24 @@ func (ctx *Context) GetPreCode() (string, error) {
|
|||||||
return ret.PreCode, nil
|
return ret.PreCode, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetComponentLoginPage 获取第三方公众号授权链接(扫码授权)
|
||||||
|
func (ctx *Context) GetComponentLoginPage(redirectURI string, authType int, bizAppID string) (string, error) {
|
||||||
|
code, err := ctx.GetPreCode()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(componentLoginURL, ctx.AppID, code, url.QueryEscape(redirectURI), authType, bizAppID), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetBindComponentURL 获取第三方公众号授权链接(链接跳转,适用移动端)
|
||||||
|
func (ctx *Context) GetBindComponentURL(redirectURI string, authType int, bizAppID string) (string, error) {
|
||||||
|
code, err := ctx.GetPreCode()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(bindComponentURL, authType, ctx.AppID, code, url.QueryEscape(redirectURI), bizAppID), nil
|
||||||
|
}
|
||||||
|
|
||||||
// ID 微信返回接口中各种类型字段
|
// ID 微信返回接口中各种类型字段
|
||||||
type ID struct {
|
type ID struct {
|
||||||
ID int `json:"id"`
|
ID int `json:"id"`
|
||||||
@@ -128,13 +150,17 @@ func (ctx *Context) QueryAuthCode(authCode string) (*AuthBaseInfo, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var ret struct {
|
var ret struct {
|
||||||
|
util.CommonError
|
||||||
Info *AuthBaseInfo `json:"authorization_info"`
|
Info *AuthBaseInfo `json:"authorization_info"`
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := json.Unmarshal(body, &ret); err != nil {
|
if err := json.Unmarshal(body, &ret); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if ret.ErrCode != 0 {
|
||||||
|
err = fmt.Errorf("QueryAuthCode error : errcode=%v , errmsg=%v", ret.ErrCode, ret.ErrMsg)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
return ret.Info, nil
|
return ret.Info, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
57
openplatform/officialaccount/js/js.go
Normal file
57
openplatform/officialaccount/js/js.go
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
package js
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/credential"
|
||||||
|
"github.com/silenceper/wechat/v2/officialaccount/context"
|
||||||
|
officialJs "github.com/silenceper/wechat/v2/officialaccount/js"
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Js wx jssdk
|
||||||
|
type Js struct {
|
||||||
|
*context.Context
|
||||||
|
credential.JsTicketHandle
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewJs init
|
||||||
|
func NewJs(context *context.Context, appID string) *Js {
|
||||||
|
js := new(Js)
|
||||||
|
js.Context = context
|
||||||
|
jsTicketHandle := credential.NewDefaultJsTicket(appID, credential.CacheKeyOfficialAccountPrefix, context.Cache)
|
||||||
|
js.SetJsTicketHandle(jsTicketHandle)
|
||||||
|
return js
|
||||||
|
}
|
||||||
|
|
||||||
|
//SetJsTicketHandle 自定义js ticket取值方式
|
||||||
|
func (js *Js) SetJsTicketHandle(ticketHandle credential.JsTicketHandle) {
|
||||||
|
js.JsTicketHandle = ticketHandle
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetConfig 第三方平台 - 获取jssdk需要的配置参数
|
||||||
|
//uri 为当前网页地址
|
||||||
|
func (js *Js) GetConfig(uri, appid string) (config *officialJs.Config, err error) {
|
||||||
|
config = new(officialJs.Config)
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = js.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var ticketStr string
|
||||||
|
ticketStr, err = js.GetTicket(accessToken)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
nonceStr := util.RandomStr(16)
|
||||||
|
timestamp := util.GetCurrTS()
|
||||||
|
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
|
||||||
|
sigStr := util.Signature(str)
|
||||||
|
|
||||||
|
config.AppID = appid
|
||||||
|
config.NonceStr = nonceStr
|
||||||
|
config.Timestamp = timestamp
|
||||||
|
config.Signature = sigStr
|
||||||
|
return
|
||||||
|
}
|
||||||
65
openplatform/officialaccount/oauth/oauth.go
Normal file
65
openplatform/officialaccount/oauth/oauth.go
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
package oauth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/officialaccount/context"
|
||||||
|
officialOauth "github.com/silenceper/wechat/v2/officialaccount/oauth"
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
platformRedirectOauthURL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s&component_appid=%s#wechat_redirect"
|
||||||
|
platformAccessTokenURL = "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=%s&code=%s&grant_type=authorization_code&component_appid=%s&component_access_token=%s"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Oauth 平台代发起oauth2网页授权
|
||||||
|
type Oauth struct {
|
||||||
|
*context.Context
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOauth 实例化平台代发起oauth2网页授权
|
||||||
|
func NewOauth(context *context.Context) *Oauth {
|
||||||
|
auth := new(Oauth)
|
||||||
|
auth.Context = context
|
||||||
|
return auth
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetRedirectURL 第三方平台 - 获取跳转的url地址
|
||||||
|
func (oauth *Oauth) GetRedirectURL(redirectURI, scope, state, appID string) (string, error) {
|
||||||
|
//url encode
|
||||||
|
urlStr := url.QueryEscape(redirectURI)
|
||||||
|
return fmt.Sprintf(platformRedirectOauthURL, appID, urlStr, scope, state, oauth.AppID), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
//Redirect 第三方平台 - 跳转到网页授权
|
||||||
|
func (oauth *Oauth) Redirect(writer http.ResponseWriter, req *http.Request, redirectURI, scope, state, appID string) error {
|
||||||
|
location, err := oauth.GetRedirectURL(redirectURI, scope, state, appID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
http.Redirect(writer, req, location, http.StatusFound)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUserAccessToken 第三方平台 - 通过网页授权的code 换取access_token(区别于context中的access_token)
|
||||||
|
func (oauth *Oauth) GetUserAccessToken(code, appID, componentAccessToken string) (result officialOauth.ResAccessToken, err error) {
|
||||||
|
urlStr := fmt.Sprintf(platformAccessTokenURL, appID, code, oauth.AppID, componentAccessToken)
|
||||||
|
var response []byte
|
||||||
|
response, err = util.HTTPGet(urlStr)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = json.Unmarshal(response, &result)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if result.ErrCode != 0 {
|
||||||
|
err = fmt.Errorf("GetUserAccessToken error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import (
|
|||||||
"github.com/silenceper/wechat/v2/officialaccount"
|
"github.com/silenceper/wechat/v2/officialaccount"
|
||||||
offConfig "github.com/silenceper/wechat/v2/officialaccount/config"
|
offConfig "github.com/silenceper/wechat/v2/officialaccount/config"
|
||||||
opContext "github.com/silenceper/wechat/v2/openplatform/context"
|
opContext "github.com/silenceper/wechat/v2/openplatform/context"
|
||||||
|
"github.com/silenceper/wechat/v2/openplatform/officialaccount/js"
|
||||||
|
"github.com/silenceper/wechat/v2/openplatform/officialaccount/oauth"
|
||||||
)
|
)
|
||||||
|
|
||||||
//OfficialAccount 代公众号实现业务
|
//OfficialAccount 代公众号实现业务
|
||||||
@@ -12,7 +14,6 @@ type OfficialAccount struct {
|
|||||||
//授权的公众号的appID
|
//授权的公众号的appID
|
||||||
appID string
|
appID string
|
||||||
*officialaccount.OfficialAccount
|
*officialaccount.OfficialAccount
|
||||||
opContext *opContext.Context
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//NewOfficialAccount 实例化
|
//NewOfficialAccount 实例化
|
||||||
@@ -29,6 +30,16 @@ func NewOfficialAccount(opCtx *opContext.Context, appID string) *OfficialAccount
|
|||||||
return &OfficialAccount{appID: appID, OfficialAccount: officialAccount}
|
return &OfficialAccount{appID: appID, OfficialAccount: officialAccount}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PlatformOauth 平台代发起oauth2网页授权
|
||||||
|
func (officialAccount *OfficialAccount) PlatformOauth() *oauth.Oauth {
|
||||||
|
return oauth.NewOauth(officialAccount.GetContext())
|
||||||
|
}
|
||||||
|
|
||||||
|
// PlatformJs 平台代获取js-sdk配置
|
||||||
|
func (officialAccount *OfficialAccount) PlatformJs() *js.Js {
|
||||||
|
return js.NewJs(officialAccount.GetContext(), officialAccount.appID)
|
||||||
|
}
|
||||||
|
|
||||||
//DefaultAuthrAccessToken 默认获取授权ak的方法
|
//DefaultAuthrAccessToken 默认获取授权ak的方法
|
||||||
type DefaultAuthrAccessToken struct {
|
type DefaultAuthrAccessToken struct {
|
||||||
opCtx *opContext.Context
|
opCtx *opContext.Context
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package openplatform
|
package openplatform
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/officialaccount/server"
|
||||||
"github.com/silenceper/wechat/v2/openplatform/account"
|
"github.com/silenceper/wechat/v2/openplatform/account"
|
||||||
"github.com/silenceper/wechat/v2/openplatform/config"
|
"github.com/silenceper/wechat/v2/openplatform/config"
|
||||||
"github.com/silenceper/wechat/v2/openplatform/context"
|
"github.com/silenceper/wechat/v2/openplatform/context"
|
||||||
@@ -24,6 +27,12 @@ func NewOpenPlatform(cfg *config.Config) *OpenPlatform {
|
|||||||
return &OpenPlatform{ctx}
|
return &OpenPlatform{ctx}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//GetServer get server
|
||||||
|
func (openPlatform *OpenPlatform) GetServer(req *http.Request, writer http.ResponseWriter) *server.Server {
|
||||||
|
off := officialaccount.NewOfficialAccount(openPlatform.Context, "")
|
||||||
|
return off.GetServer(req, writer)
|
||||||
|
}
|
||||||
|
|
||||||
//GetOfficialAccount 公众号代处理
|
//GetOfficialAccount 公众号代处理
|
||||||
func (openPlatform *OpenPlatform) GetOfficialAccount(appID string) *officialaccount.OfficialAccount {
|
func (openPlatform *OpenPlatform) GetOfficialAccount(appID string) *officialaccount.OfficialAccount {
|
||||||
return officialaccount.NewOfficialAccount(openPlatform.Context, appID)
|
return officialaccount.NewOfficialAccount(openPlatform.Context, appID)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
//Config config for pay
|
// Config config for pay
|
||||||
type Config struct {
|
type Config struct {
|
||||||
AppID string `json:"app_id"`
|
AppID string `json:"app_id"`
|
||||||
MchID string `json:"mch_id"`
|
MchID string `json:"mch_id"`
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ type PaidResult struct {
|
|||||||
OpenID *string `xml:"openid"`
|
OpenID *string `xml:"openid"`
|
||||||
IsSubscribe *string `xml:"is_subscribe"`
|
IsSubscribe *string `xml:"is_subscribe"`
|
||||||
TradeType *string `xml:"trade_type"`
|
TradeType *string `xml:"trade_type"`
|
||||||
|
TradeState *string `xml:"trade_state"`
|
||||||
BankType *string `xml:"bank_type"`
|
BankType *string `xml:"bank_type"`
|
||||||
TotalFee *int `xml:"total_fee"`
|
TotalFee *int `xml:"total_fee"`
|
||||||
SettlementTotalFee *int `xml:"settlement_total_fee"`
|
SettlementTotalFee *int `xml:"settlement_total_fee"`
|
||||||
@@ -46,9 +47,9 @@ type PaidResult struct {
|
|||||||
CouponID0 *string `xml:"coupon_id_0"`
|
CouponID0 *string `xml:"coupon_id_0"`
|
||||||
CouponID1 *string `xml:"coupon_id_1"`
|
CouponID1 *string `xml:"coupon_id_1"`
|
||||||
CouponID2 *string `xml:"coupon_id_2"`
|
CouponID2 *string `xml:"coupon_id_2"`
|
||||||
CouponFeed0 *string `xml:"coupon_fee_0"`
|
CouponFee0 *string `xml:"coupon_fee_0"`
|
||||||
CouponFeed1 *string `xml:"coupon_fee_1"`
|
CouponFee1 *string `xml:"coupon_fee_1"`
|
||||||
CouponFeed2 *string `xml:"coupon_fee_2"`
|
CouponFee2 *string `xml:"coupon_fee_2"`
|
||||||
|
|
||||||
TransactionID *string `xml:"transaction_id"`
|
TransactionID *string `xml:"transaction_id"`
|
||||||
OutTradeNo *string `xml:"out_trade_no"`
|
OutTradeNo *string `xml:"out_trade_no"`
|
||||||
@@ -85,8 +86,15 @@ func (notify *Notify) PaidVerifySign(notifyRes PaidResult) bool {
|
|||||||
// STEP3, 在键值对的最后加上key=API_KEY
|
// STEP3, 在键值对的最后加上key=API_KEY
|
||||||
signStrings = signStrings + "key=" + notify.Key
|
signStrings = signStrings + "key=" + notify.Key
|
||||||
|
|
||||||
// STEP4, 进行MD5签名并且将所有字符转为大写.
|
// STEP4, 根据SignType计算出签名
|
||||||
sign := util.MD5Sum(signStrings)
|
var signType string
|
||||||
|
if notifyRes.SignType != nil {
|
||||||
|
signType = *notifyRes.SignType
|
||||||
|
}
|
||||||
|
sign, err := util.CalculateSign(signStrings, signType, notify.Key)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
if sign != *notifyRes.Sign {
|
if sign != *notifyRes.Sign {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|||||||
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_accout"`
|
||||||
|
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))
|
||||||
|
}
|
||||||
196
pay/order/pay.go
196
pay/order/pay.go
@@ -1,13 +1,8 @@
|
|||||||
package order
|
package order
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/hmac"
|
|
||||||
"crypto/md5"
|
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/xml"
|
"encoding/xml"
|
||||||
"errors"
|
"errors"
|
||||||
"hash"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -16,9 +11,12 @@ import (
|
|||||||
"github.com/silenceper/wechat/v2/util"
|
"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"
|
var payGateway = "https://api.mch.weixin.qq.com/pay/unifiedorder"
|
||||||
|
|
||||||
|
// SUCCESS 表示支付成功
|
||||||
|
const SUCCESS = "SUCCESS"
|
||||||
|
|
||||||
// Order struct extends context
|
// Order struct extends context
|
||||||
type Order struct {
|
type Order struct {
|
||||||
*config.Config
|
*config.Config
|
||||||
@@ -30,13 +28,14 @@ func NewOrder(cfg *config.Config) *Order {
|
|||||||
return &order
|
return &order
|
||||||
}
|
}
|
||||||
|
|
||||||
// Params was NEEDED when request unifiedorder
|
// Params was NEEDED when request Unified order
|
||||||
// 传入的参数,用于生成 prepay_id 的必需参数
|
// 传入的参数,用于生成 prepay_id 的必需参数
|
||||||
type Params struct {
|
type Params struct {
|
||||||
TotalFee string
|
TotalFee string
|
||||||
CreateIP string
|
CreateIP string
|
||||||
Body string
|
Body string
|
||||||
OutTradeNo string
|
OutTradeNo string
|
||||||
|
TimeExpire string // 订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。
|
||||||
OpenID string
|
OpenID string
|
||||||
TradeType string
|
TradeType string
|
||||||
SignType string
|
SignType string
|
||||||
@@ -56,7 +55,18 @@ type Config struct {
|
|||||||
PaySign string `json:"paySign"`
|
PaySign string `json:"paySign"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// PreOrder 是 unifie order 接口的返回
|
// ConfigForApp 是传出用于 app sdk 用的参数
|
||||||
|
type ConfigForApp struct {
|
||||||
|
AppID string `json:"appid"`
|
||||||
|
MchID string `json:"partnerid"` // 微信支付分配的商户号
|
||||||
|
PrePayID string `json:"prepayid"`
|
||||||
|
Package string `json:"package"`
|
||||||
|
NonceStr string `json:"nonceStr"`
|
||||||
|
Timestamp string `json:"timestamp"`
|
||||||
|
Sign string `json:"sign"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PreOrder 是 Unified order 接口的返回
|
||||||
type PreOrder struct {
|
type PreOrder struct {
|
||||||
ReturnCode string `xml:"return_code"`
|
ReturnCode string `xml:"return_code"`
|
||||||
ReturnMsg string `xml:"return_msg"`
|
ReturnMsg string `xml:"return_msg"`
|
||||||
@@ -68,20 +78,21 @@ type PreOrder struct {
|
|||||||
TradeType string `xml:"trade_type,omitempty"`
|
TradeType string `xml:"trade_type,omitempty"`
|
||||||
PrePayID string `xml:"prepay_id,omitempty"`
|
PrePayID string `xml:"prepay_id,omitempty"`
|
||||||
CodeURL string `xml:"code_url,omitempty"`
|
CodeURL string `xml:"code_url,omitempty"`
|
||||||
|
MWebURL string `xml:"mweb_url,omitempty"`
|
||||||
ErrCode string `xml:"err_code,omitempty"`
|
ErrCode string `xml:"err_code,omitempty"`
|
||||||
ErrCodeDes string `xml:"err_code_des,omitempty"`
|
ErrCodeDes string `xml:"err_code_des,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// payRequest 接口请求参数
|
// payRequest 接口请求参数
|
||||||
type payRequest struct {
|
type payRequest struct {
|
||||||
AppID string `xml:"appid"`
|
AppID string `xml:"appid"` // 公众账号ID
|
||||||
MchID string `xml:"mch_id"`
|
MchID string `xml:"mch_id"` // 商户号
|
||||||
DeviceInfo string `xml:"device_info,omitempty"`
|
DeviceInfo string `xml:"device_info,omitempty"` // 设备号
|
||||||
NonceStr string `xml:"nonce_str"`
|
NonceStr string `xml:"nonce_str"` // 随机字符串
|
||||||
Sign string `xml:"sign"`
|
Sign string `xml:"sign"` // 签名
|
||||||
SignType string `xml:"sign_type,omitempty"`
|
SignType string `xml:"sign_type,omitempty"` // 签名类型
|
||||||
Body string `xml:"body"`
|
Body string `xml:"body"` // 商品描述
|
||||||
Detail string `xml:"detail,omitempty"`
|
Detail string `xml:"detail,omitempty"` // 商品详情
|
||||||
Attach string `xml:"attach,omitempty"` // 附加数据
|
Attach string `xml:"attach,omitempty"` // 附加数据
|
||||||
OutTradeNo string `xml:"out_trade_no"` // 商户订单号
|
OutTradeNo string `xml:"out_trade_no"` // 商户订单号
|
||||||
FeeType string `xml:"fee_type,omitempty"` // 标价币种
|
FeeType string `xml:"fee_type,omitempty"` // 标价币种
|
||||||
@@ -93,16 +104,38 @@ type payRequest struct {
|
|||||||
NotifyURL string `xml:"notify_url"` // 通知地址
|
NotifyURL string `xml:"notify_url"` // 通知地址
|
||||||
TradeType string `xml:"trade_type"` // 交易类型
|
TradeType string `xml:"trade_type"` // 交易类型
|
||||||
ProductID string `xml:"product_id,omitempty"` // 商品ID
|
ProductID string `xml:"product_id,omitempty"` // 商品ID
|
||||||
LimitPay string `xml:"limit_pay,omitempty"` //
|
LimitPay string `xml:"limit_pay,omitempty"` // 指定支付方式
|
||||||
OpenID string `xml:"openid,omitempty"` // 用户标识
|
OpenID string `xml:"openid,omitempty"` // 用户标识
|
||||||
SceneInfo string `xml:"scene_info,omitempty"` // 场景信息
|
SceneInfo string `xml:"scene_info,omitempty"` // 场景信息
|
||||||
|
|
||||||
|
XMLName struct{} `xml:"xml"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (req *payRequest) BridgePayRequest(p *Params, AppID, MchID, nonceStr, sign string) *payRequest {
|
||||||
|
request := payRequest{
|
||||||
|
AppID: AppID,
|
||||||
|
MchID: MchID,
|
||||||
|
NonceStr: nonceStr,
|
||||||
|
Sign: sign,
|
||||||
|
Body: p.Body,
|
||||||
|
OutTradeNo: p.OutTradeNo,
|
||||||
|
TotalFee: p.TotalFee,
|
||||||
|
SpbillCreateIP: p.CreateIP,
|
||||||
|
NotifyURL: p.NotifyURL,
|
||||||
|
TradeType: p.TradeType,
|
||||||
|
OpenID: p.OpenID,
|
||||||
|
SignType: p.SignType,
|
||||||
|
Detail: p.Detail,
|
||||||
|
Attach: p.Attach,
|
||||||
|
GoodsTag: p.GoodsTag,
|
||||||
|
}
|
||||||
|
return &request
|
||||||
}
|
}
|
||||||
|
|
||||||
// BridgeConfig get js bridge config
|
// BridgeConfig get js bridge config
|
||||||
func (o *Order) BridgeConfig(p *Params) (cfg Config, err error) {
|
func (o *Order) BridgeConfig(p *Params) (cfg Config, err error) {
|
||||||
var (
|
var (
|
||||||
buffer strings.Builder
|
buffer strings.Builder
|
||||||
h hash.Hash
|
|
||||||
timestamp = strconv.FormatInt(time.Now().Unix(), 10)
|
timestamp = strconv.FormatInt(time.Now().Unix(), 10)
|
||||||
)
|
)
|
||||||
order, err := o.PrePayOrder(p)
|
order, err := o.PrePayOrder(p)
|
||||||
@@ -121,14 +154,13 @@ func (o *Order) BridgeConfig(p *Params) (cfg Config, err error) {
|
|||||||
buffer.WriteString(timestamp)
|
buffer.WriteString(timestamp)
|
||||||
buffer.WriteString("&key=")
|
buffer.WriteString("&key=")
|
||||||
buffer.WriteString(o.Key)
|
buffer.WriteString(o.Key)
|
||||||
if p.SignType == "MD5" {
|
|
||||||
h = md5.New()
|
sign, err := util.CalculateSign(buffer.String(), p.SignType, o.Key)
|
||||||
} else {
|
if err != nil {
|
||||||
h = hmac.New(sha256.New, []byte(o.Key))
|
return
|
||||||
}
|
}
|
||||||
h.Write([]byte(buffer.String()))
|
|
||||||
// 签名
|
// 签名
|
||||||
cfg.PaySign = strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
|
cfg.PaySign = sign
|
||||||
cfg.NonceStr = order.NonceStr
|
cfg.NonceStr = order.NonceStr
|
||||||
cfg.Timestamp = timestamp
|
cfg.Timestamp = timestamp
|
||||||
cfg.PrePayID = order.PrePayID
|
cfg.PrePayID = order.PrePayID
|
||||||
@@ -137,53 +169,85 @@ func (o *Order) BridgeConfig(p *Params) (cfg Config, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BridgeAppConfig get app bridge config
|
||||||
|
func (o *Order) BridgeAppConfig(p *Params) (cfg ConfigForApp, err error) {
|
||||||
|
var (
|
||||||
|
timestamp string = strconv.FormatInt(time.Now().Unix(), 10)
|
||||||
|
noncestr string = util.RandomStr(32)
|
||||||
|
_package string = "Sign=WXPay"
|
||||||
|
)
|
||||||
|
order, err := o.PrePayOrder(p)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
result := map[string]string{
|
||||||
|
"appid": order.AppID,
|
||||||
|
"partnerid": order.MchID,
|
||||||
|
"prepayid": order.PrePayID,
|
||||||
|
"package": _package,
|
||||||
|
"noncestr": noncestr,
|
||||||
|
"timestamp": timestamp,
|
||||||
|
}
|
||||||
|
// 签名
|
||||||
|
sign, err := util.ParamSign(result, o.Key)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result["sign"] = sign
|
||||||
|
cfg = ConfigForApp{
|
||||||
|
AppID: result["appid"],
|
||||||
|
MchID: result["partnerid"],
|
||||||
|
PrePayID: result["prepayid"],
|
||||||
|
Package: result["package"],
|
||||||
|
NonceStr: result["noncestr"],
|
||||||
|
Timestamp: result["timestamp"],
|
||||||
|
Sign: result["sign"],
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// PrePayOrder return data for invoke wechat payment
|
// PrePayOrder return data for invoke wechat payment
|
||||||
func (o *Order) PrePayOrder(p *Params) (payOrder PreOrder, err error) {
|
func (o *Order) PrePayOrder(p *Params) (payOrder PreOrder, err error) {
|
||||||
nonceStr := util.RandomStr(32)
|
nonceStr := util.RandomStr(32)
|
||||||
notifyURL := o.NotifyURL
|
param := map[string]string{
|
||||||
// 签名类型
|
"appid": o.AppID,
|
||||||
if p.SignType == "" {
|
"body": p.Body,
|
||||||
p.SignType = "MD5"
|
"mch_id": o.MchID,
|
||||||
|
"nonce_str": nonceStr,
|
||||||
|
"out_trade_no": p.OutTradeNo,
|
||||||
|
"spbill_create_ip": p.CreateIP,
|
||||||
|
"total_fee": p.TotalFee,
|
||||||
|
"trade_type": p.TradeType,
|
||||||
|
"openid": p.OpenID,
|
||||||
|
"sign_type": p.SignType,
|
||||||
|
"detail": p.Detail,
|
||||||
|
"attach": p.Attach,
|
||||||
|
"goods_tag": p.GoodsTag,
|
||||||
}
|
}
|
||||||
|
// 签名类型
|
||||||
|
if param["sign_type"] == "" {
|
||||||
|
param["sign_type"] = util.SignTypeMD5
|
||||||
|
}
|
||||||
|
|
||||||
// 通知地址
|
// 通知地址
|
||||||
if p.NotifyURL != "" {
|
if p.NotifyURL != "" {
|
||||||
notifyURL = p.NotifyURL
|
param["notify_url"] = p.NotifyURL
|
||||||
}
|
}
|
||||||
param := make(map[string]interface{})
|
|
||||||
param["appid"] = o.AppID
|
|
||||||
param["body"] = p.Body
|
|
||||||
param["mch_id"] = o.MchID
|
|
||||||
param["nonce_str"] = nonceStr
|
|
||||||
param["out_trade_no"] = p.OutTradeNo
|
|
||||||
param["spbill_create_ip"] = p.CreateIP
|
|
||||||
param["total_fee"] = p.TotalFee
|
|
||||||
param["trade_type"] = p.TradeType
|
|
||||||
param["openid"] = p.OpenID
|
|
||||||
param["sign_type"] = p.SignType
|
|
||||||
param["detail"] = p.Detail
|
|
||||||
param["attach"] = p.Attach
|
|
||||||
param["goods_tag"] = p.GoodsTag
|
|
||||||
param["notify_url"] = notifyURL
|
|
||||||
|
|
||||||
bizKey := "&key=" + o.Key
|
if p.TimeExpire != "" {
|
||||||
str := util.OrderParam(param, bizKey)
|
// 如果有传入交易结束时间
|
||||||
sign := util.MD5Sum(str)
|
param["time_expire"] = p.TimeExpire
|
||||||
request := payRequest{
|
}
|
||||||
AppID: o.AppID,
|
|
||||||
MchID: o.MchID,
|
sign, err := util.ParamSign(param, o.Key)
|
||||||
NonceStr: nonceStr,
|
if err != nil {
|
||||||
Sign: sign,
|
return
|
||||||
Body: p.Body,
|
}
|
||||||
OutTradeNo: p.OutTradeNo,
|
request := new(payRequest).BridgePayRequest(p, o.AppID, o.MchID, nonceStr, sign)
|
||||||
TotalFee: p.TotalFee,
|
if len(p.TimeExpire) > 0 {
|
||||||
SpbillCreateIP: p.CreateIP,
|
// 如果有传入交易结束时间
|
||||||
NotifyURL: notifyURL,
|
request.TimeExpire = p.TimeExpire
|
||||||
TradeType: p.TradeType,
|
|
||||||
OpenID: p.OpenID,
|
|
||||||
SignType: p.SignType,
|
|
||||||
Detail: p.Detail,
|
|
||||||
Attach: p.Attach,
|
|
||||||
GoodsTag: p.GoodsTag,
|
|
||||||
}
|
}
|
||||||
rawRet, err := util.PostXML(payGateway, request)
|
rawRet, err := util.PostXML(payGateway, request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -193,16 +257,16 @@ func (o *Order) PrePayOrder(p *Params) (payOrder PreOrder, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if payOrder.ReturnCode == "SUCCESS" {
|
if payOrder.ReturnCode == SUCCESS {
|
||||||
// pay success
|
// pay success
|
||||||
if payOrder.ResultCode == "SUCCESS" {
|
if payOrder.ResultCode == SUCCESS {
|
||||||
err = nil
|
err = nil
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err = errors.New(payOrder.ErrCode + payOrder.ErrCodeDes)
|
err = errors.New(payOrder.ErrCode + payOrder.ErrCodeDes)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err = errors.New("[msg : xmlUnmarshalError] [rawReturn : " + string(rawRet) + "] [params : " + str + "] [sign : " + sign + "]")
|
err = errors.New("[msg : xmlUnmarshalError] [rawReturn : " + string(rawRet) + "] [sign : " + sign + "]")
|
||||||
return
|
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
|
||||||
|
}
|
||||||
12
pay/pay.go
12
pay/pay.go
@@ -4,6 +4,8 @@ import (
|
|||||||
"github.com/silenceper/wechat/v2/pay/config"
|
"github.com/silenceper/wechat/v2/pay/config"
|
||||||
"github.com/silenceper/wechat/v2/pay/notify"
|
"github.com/silenceper/wechat/v2/pay/notify"
|
||||||
"github.com/silenceper/wechat/v2/pay/order"
|
"github.com/silenceper/wechat/v2/pay/order"
|
||||||
|
"github.com/silenceper/wechat/v2/pay/refund"
|
||||||
|
"github.com/silenceper/wechat/v2/pay/transfer"
|
||||||
)
|
)
|
||||||
|
|
||||||
//Pay 微信支付相关API
|
//Pay 微信支付相关API
|
||||||
@@ -25,3 +27,13 @@ func (pay *Pay) GetOrder() *order.Order {
|
|||||||
func (pay *Pay) GetNotify() *notify.Notify {
|
func (pay *Pay) GetNotify() *notify.Notify {
|
||||||
return notify.NewNotify(pay.cfg)
|
return notify.NewNotify(pay.cfg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetRefund 退款
|
||||||
|
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
|
return &refund
|
||||||
}
|
}
|
||||||
|
|
||||||
//Params 调用参数
|
// Params 调用参数
|
||||||
type Params struct {
|
type Params struct {
|
||||||
TransactionID string
|
TransactionID string
|
||||||
OutRefundNo string
|
OutRefundNo string
|
||||||
|
OutTradeNo string
|
||||||
TotalFee string
|
TotalFee string
|
||||||
RefundFee string
|
RefundFee string
|
||||||
RefundDesc string
|
RefundDesc string
|
||||||
RootCa string //ca证书
|
RootCa string // ca证书
|
||||||
|
NotifyURL string
|
||||||
|
SignType string
|
||||||
}
|
}
|
||||||
|
|
||||||
//request 接口请求参数
|
// request 接口请求参数
|
||||||
type request struct {
|
type request struct {
|
||||||
AppID string `xml:"appid"`
|
AppID string `xml:"appid"`
|
||||||
MchID string `xml:"mch_id"`
|
MchID string `xml:"mch_id"`
|
||||||
NonceStr string `xml:"nonce_str"`
|
NonceStr string `xml:"nonce_str"`
|
||||||
Sign string `xml:"sign"`
|
Sign string `xml:"sign"`
|
||||||
SignType string `xml:"sign_type,omitempty"`
|
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"`
|
OutRefundNo string `xml:"out_refund_no"`
|
||||||
TotalFee string `xml:"total_fee"`
|
TotalFee string `xml:"total_fee"`
|
||||||
RefundFee string `xml:"refund_fee"`
|
RefundFee string `xml:"refund_fee"`
|
||||||
RefundDesc string `xml:"refund_desc,omitempty"`
|
RefundDesc string `xml:"refund_desc,omitempty"`
|
||||||
//NotifyUrl string `xml:"notify_url,omitempty"`
|
NotifyURL string `xml:"notify_url,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
//Response 接口返回
|
// Response 接口返回
|
||||||
type Response struct {
|
type Response struct {
|
||||||
ReturnCode string `xml:"return_code"`
|
ReturnCode string `xml:"return_code"`
|
||||||
ReturnMsg string `xml:"return_msg"`
|
ReturnMsg string `xml:"return_msg"`
|
||||||
@@ -70,36 +74,35 @@ type Response struct {
|
|||||||
CashFeeType string `xml:"cash_fee_type,omitempty"`
|
CashFeeType string `xml:"cash_fee_type,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
//Refund 退款申请
|
// Refund 退款申请
|
||||||
func (refund *Refund) Refund(p *Params) (rsp Response, err error) {
|
func (refund *Refund) Refund(p *Params) (rsp Response, err error) {
|
||||||
nonceStr := util.RandomStr(32)
|
param := refund.GetSignParam(p)
|
||||||
param := make(map[string]interface{})
|
|
||||||
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"] = "MD5"
|
|
||||||
param["transaction_id"] = p.TransactionID
|
|
||||||
|
|
||||||
bizKey := "&key=" + refund.Key
|
sign, err := util.ParamSign(param, refund.Key)
|
||||||
str := util.OrderParam(param, bizKey)
|
if err != nil {
|
||||||
sign := util.MD5Sum(str)
|
return
|
||||||
request := request{
|
|
||||||
AppID: refund.AppID,
|
|
||||||
MchID: refund.MchID,
|
|
||||||
NonceStr: nonceStr,
|
|
||||||
Sign: sign,
|
|
||||||
SignType: "MD5",
|
|
||||||
TransactionID: p.TransactionID,
|
|
||||||
OutRefundNo: p.OutRefundNo,
|
|
||||||
TotalFee: p.TotalFee,
|
|
||||||
RefundFee: p.RefundFee,
|
|
||||||
RefundDesc: p.RefundDesc,
|
|
||||||
}
|
}
|
||||||
rawRet, err := util.PostXMLWithTLS(refundGateway, request, p.RootCa, refund.MchID)
|
|
||||||
|
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"],
|
||||||
|
}
|
||||||
|
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 {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -115,7 +118,34 @@ func (refund *Refund) Refund(p *Params) (rsp Response, err error) {
|
|||||||
err = fmt.Errorf("refund error, errcode=%s,errmsg=%s", rsp.ErrCode, rsp.ErrCodeDes)
|
err = fmt.Errorf("refund error, errcode=%s,errmsg=%s", rsp.ErrCode, rsp.ErrCodeDes)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err = fmt.Errorf("[msg : xmlUnmarshalError] [rawReturn : %s] [params : %s] [sign : %s]",
|
err = fmt.Errorf("[msg : xmlUnmarshalError] [rawReturn : %s] [sign : %s]", string(rawRet), sign)
|
||||||
string(rawRet), str, sign)
|
|
||||||
return
|
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
|
||||||
|
}
|
||||||
163
util/crypto.go
163
util/crypto.go
@@ -1,17 +1,27 @@
|
|||||||
package util
|
package util
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
|
||||||
"bytes"
|
"bytes"
|
||||||
"crypto/aes"
|
"crypto/aes"
|
||||||
"crypto/cipher"
|
"crypto/cipher"
|
||||||
|
"crypto/hmac"
|
||||||
"crypto/md5"
|
"crypto/md5"
|
||||||
|
"crypto/sha256"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"hash"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
//EncryptMsg 加密消息
|
// 微信签名算法方式
|
||||||
|
const (
|
||||||
|
SignTypeMD5 = `MD5`
|
||||||
|
SignTypeHMACSHA256 = `HMAC-SHA256`
|
||||||
|
)
|
||||||
|
|
||||||
|
// EncryptMsg 加密消息
|
||||||
func EncryptMsg(random, rawXMLMsg []byte, appID, aesKey string) (encrtptMsg []byte, err error) {
|
func EncryptMsg(random, rawXMLMsg []byte, appID, aesKey string) (encrtptMsg []byte, err error) {
|
||||||
defer func() {
|
defer func() {
|
||||||
if e := recover(); e != nil {
|
if e := recover(); e != nil {
|
||||||
@@ -29,7 +39,7 @@ func EncryptMsg(random, rawXMLMsg []byte, appID, aesKey string) (encrtptMsg []by
|
|||||||
return
|
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
|
//参考:github.com/chanxuehong/wechat.v2
|
||||||
func AESEncryptMsg(random, rawXMLMsg []byte, appID string, aesKey []byte) (ciphertext []byte) {
|
func AESEncryptMsg(random, rawXMLMsg []byte, appID string, aesKey []byte) (ciphertext []byte) {
|
||||||
const (
|
const (
|
||||||
@@ -56,7 +66,7 @@ func AESEncryptMsg(random, rawXMLMsg []byte, appID string, aesKey []byte) (ciphe
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 加密
|
// 加密
|
||||||
block, err := aes.NewCipher(aesKey[:])
|
block, err := aes.NewCipher(aesKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
@@ -67,7 +77,7 @@ func AESEncryptMsg(random, rawXMLMsg []byte, appID string, aesKey []byte) (ciphe
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
//DecryptMsg 消息解密
|
// DecryptMsg 消息解密
|
||||||
func DecryptMsg(appID, encryptedMsg, aesKey string) (random, rawMsgXMLBytes []byte, err error) {
|
func DecryptMsg(appID, encryptedMsg, aesKey string) (random, rawMsgXMLBytes []byte, err error) {
|
||||||
defer func() {
|
defer func() {
|
||||||
if e := recover(); e != nil {
|
if e := recover(); e != nil {
|
||||||
@@ -186,14 +196,137 @@ func decodeNetworkByteOrder(orderBytes []byte) (n uint32) {
|
|||||||
uint32(orderBytes[3])
|
uint32(orderBytes[3])
|
||||||
}
|
}
|
||||||
|
|
||||||
// MD5Sum 计算 32 位长度的 MD5 sum
|
// CalculateSign 计算签名
|
||||||
func MD5Sum(txt string) (sum string) {
|
func CalculateSign(content, signType, key string) (string, error) {
|
||||||
h := md5.New()
|
var h hash.Hash
|
||||||
buf := bufio.NewWriterSize(h, 128)
|
if signType == SignTypeHMACSHA256 {
|
||||||
buf.WriteString(txt)
|
h = hmac.New(sha256.New, []byte(key))
|
||||||
buf.Flush()
|
} else {
|
||||||
sign := make([]byte, hex.EncodedLen(h.Size()))
|
h = md5.New()
|
||||||
hex.Encode(sign, h.Sum(nil))
|
}
|
||||||
sum = string(bytes.ToUpper(sign))
|
|
||||||
return
|
if _, err := h.Write([]byte(content)); err != nil {
|
||||||
|
return ``, err
|
||||||
|
}
|
||||||
|
return strings.ToUpper(hex.EncodeToString(h.Sum(nil))), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParamSign 计算所传参数的签名
|
||||||
|
func ParamSign(p map[string]string, key string) (string, error) {
|
||||||
|
bizKey := "&key=" + key
|
||||||
|
str := OrderParam(p, bizKey)
|
||||||
|
|
||||||
|
var signType string
|
||||||
|
switch p["sign_type"] {
|
||||||
|
case SignTypeMD5, SignTypeHMACSHA256:
|
||||||
|
signType = p["sign_type"]
|
||||||
|
case ``:
|
||||||
|
signType = SignTypeMD5
|
||||||
|
default:
|
||||||
|
return ``, errors.New(`invalid sign_type`)
|
||||||
|
}
|
||||||
|
|
||||||
|
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 数据请求
|
//PostJSON post json 数据请求
|
||||||
func PostJSON(uri string, obj interface{}) ([]byte, error) {
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
jsonData = bytes.Replace(jsonData, []byte("\\u003c"), []byte("<"), -1)
|
response, err := http.Post(uri, "application/json;charset=utf-8", jsonBuf)
|
||||||
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)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -70,17 +69,15 @@ func PostJSON(uri string, obj interface{}) ([]byte, error) {
|
|||||||
|
|
||||||
// PostJSONWithRespContentType post json数据请求,且返回数据类型
|
// PostJSONWithRespContentType post json数据请求,且返回数据类型
|
||||||
func PostJSONWithRespContentType(uri string, obj interface{}) ([]byte, string, error) {
|
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 {
|
if err != nil {
|
||||||
return nil, "", err
|
return nil, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
jsonData = bytes.Replace(jsonData, []byte("\\u003c"), []byte("<"), -1)
|
response, err := http.Post(uri, "application/json;charset=utf-8", jsonBuf)
|
||||||
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)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", err
|
return nil, "", err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,65 +3,31 @@ package util
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// OrderParam order params
|
// OrderParam order params
|
||||||
func OrderParam(source interface{}, bizKey string) (returnStr string) {
|
func OrderParam(p map[string]string, bizKey string) (returnStr string) {
|
||||||
switch v := source.(type) {
|
keys := make([]string, 0, len(p))
|
||||||
case map[string]string:
|
for k := range p {
|
||||||
keys := make([]string, 0, len(v))
|
if k == "sign" {
|
||||||
for k := range v {
|
continue
|
||||||
if k == "sign" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
keys = append(keys, k)
|
|
||||||
}
|
}
|
||||||
sort.Strings(keys)
|
keys = append(keys, k)
|
||||||
var buf bytes.Buffer
|
|
||||||
for _, k := range keys {
|
|
||||||
if v[k] == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if buf.Len() > 0 {
|
|
||||||
buf.WriteByte('&')
|
|
||||||
}
|
|
||||||
buf.WriteString(k)
|
|
||||||
buf.WriteByte('=')
|
|
||||||
buf.WriteString(v[k])
|
|
||||||
}
|
|
||||||
buf.WriteString(bizKey)
|
|
||||||
returnStr = buf.String()
|
|
||||||
case map[string]interface{}:
|
|
||||||
keys := make([]string, 0, len(v))
|
|
||||||
for k := range v {
|
|
||||||
if k == "sign" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
keys = append(keys, k)
|
|
||||||
}
|
|
||||||
sort.Strings(keys)
|
|
||||||
var buf bytes.Buffer
|
|
||||||
for _, k := range keys {
|
|
||||||
if v[k] == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if buf.Len() > 0 {
|
|
||||||
buf.WriteByte('&')
|
|
||||||
}
|
|
||||||
buf.WriteString(k)
|
|
||||||
buf.WriteByte('=')
|
|
||||||
switch vv := v[k].(type) {
|
|
||||||
case string:
|
|
||||||
buf.WriteString(vv)
|
|
||||||
case int:
|
|
||||||
buf.WriteString(strconv.FormatInt(int64(vv), 10))
|
|
||||||
default:
|
|
||||||
panic("params type not supported")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
buf.WriteString(bizKey)
|
|
||||||
returnStr = buf.String()
|
|
||||||
}
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
var buf bytes.Buffer
|
||||||
|
for _, k := range keys {
|
||||||
|
if p[k] == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if buf.Len() > 0 {
|
||||||
|
buf.WriteByte('&')
|
||||||
|
}
|
||||||
|
buf.WriteString(k)
|
||||||
|
buf.WriteByte('=')
|
||||||
|
buf.WriteString(p[k])
|
||||||
|
}
|
||||||
|
buf.WriteString(bizKey)
|
||||||
|
returnStr = buf.String()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
43
util/rsa.go
Normal file
43
util/rsa.go
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
package util
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/rsa"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/pem"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RSADecrypt 数据解密
|
||||||
|
func RSADecrypt(privateKey string, ciphertext []byte) ([]byte, error) {
|
||||||
|
block, _ := pem.Decode([]byte(privateKey))
|
||||||
|
if block == nil {
|
||||||
|
return nil, errors.New("PrivateKey format error")
|
||||||
|
}
|
||||||
|
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||||
|
if err != nil {
|
||||||
|
oldErr := err
|
||||||
|
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ParsePKCS1PrivateKey error: %s, ParsePKCS8PrivateKey error: %s", oldErr.Error(), err.Error())
|
||||||
|
}
|
||||||
|
switch t := key.(type) {
|
||||||
|
case *rsa.PrivateKey:
|
||||||
|
priv = key.(*rsa.PrivateKey)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("ParsePKCS1PrivateKey error: %s, ParsePKCS8PrivateKey error: Not supported privatekey format, should be *rsa.PrivateKey, got %T", oldErr.Error(), t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RSADecryptBase64 Base64解码后再次进行RSA解密
|
||||||
|
func RSADecryptBase64(privateKey string, cryptoText string) ([]byte, error) {
|
||||||
|
encryptedData, err := base64.StdEncoding.DecodeString(cryptoText)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return RSADecrypt(privateKey, encryptedData)
|
||||||
|
}
|
||||||
@@ -12,7 +12,7 @@ func Signature(params ...string) string {
|
|||||||
sort.Strings(params)
|
sort.Strings(params)
|
||||||
h := sha1.New()
|
h := sha1.New()
|
||||||
for _, s := range params {
|
for _, s := range params {
|
||||||
io.WriteString(h, s)
|
_, _ = io.WriteString(h, s)
|
||||||
}
|
}
|
||||||
return fmt.Sprintf("%x", h.Sum(nil))
|
return fmt.Sprintf("%x", h.Sum(nil))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ package util
|
|||||||
|
|
||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
//GetCurrTs return current timestamps
|
//GetCurrTS return current timestamps
|
||||||
func GetCurrTs() int64 {
|
func GetCurrTS() int64 {
|
||||||
return time.Now().Unix()
|
return time.Now().Unix()
|
||||||
}
|
}
|
||||||
|
|||||||
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,11 +12,12 @@ import (
|
|||||||
openConfig "github.com/silenceper/wechat/v2/openplatform/config"
|
openConfig "github.com/silenceper/wechat/v2/openplatform/config"
|
||||||
"github.com/silenceper/wechat/v2/pay"
|
"github.com/silenceper/wechat/v2/pay"
|
||||||
payConfig "github.com/silenceper/wechat/v2/pay/config"
|
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"
|
log "github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|
||||||
// Log as JSON instead of the default ASCII formatter.
|
// Log as JSON instead of the default ASCII formatter.
|
||||||
log.SetFormatter(&log.TextFormatter{})
|
log.SetFormatter(&log.TextFormatter{})
|
||||||
|
|
||||||
@@ -26,7 +27,6 @@ func init() {
|
|||||||
|
|
||||||
// Only log the warning severity or above.
|
// Only log the warning severity or above.
|
||||||
log.SetLevel(log.DebugLevel)
|
log.SetLevel(log.DebugLevel)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wechat struct
|
// Wechat struct
|
||||||
@@ -69,3 +69,8 @@ func (wc *Wechat) GetPay(cfg *payConfig.Config) *pay.Pay {
|
|||||||
func (wc *Wechat) GetOpenPlatform(cfg *openConfig.Config) *openplatform.OpenPlatform {
|
func (wc *Wechat) GetOpenPlatform(cfg *openConfig.Config) *openplatform.OpenPlatform {
|
||||||
return openplatform.NewOpenPlatform(cfg)
|
return openplatform.NewOpenPlatform(cfg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetWork 获取企业微信的实例
|
||||||
|
func (wc *Wechat) GetWork(cfg *workConfig.Config) *work.Work {
|
||||||
|
return work.NewWork(cfg)
|
||||||
|
}
|
||||||
|
|||||||
18
work/config/config.go
Normal file
18
work/config/config.go
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
// Package config 企业微信config配置
|
||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/silenceper/wechat/v2/cache"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config for 企业微信
|
||||||
|
type Config struct {
|
||||||
|
CorpID string `json:"corp_id"` // corp_id
|
||||||
|
CorpSecret string `json:"corp_secret"` // corp_secret,如果需要获取会话存档实例,当前参数请填写聊天内容存档的Secret,可以在企业微信管理端--管理工具--聊天内容存档查看
|
||||||
|
AgentID string `json:"agent_id"` // agent_id
|
||||||
|
Cache cache.Cache
|
||||||
|
RasPrivateKey string // 消息加密私钥,可以在企业微信管理端--管理工具--消息加密公钥查看对用公钥,私钥一般由自己保存
|
||||||
|
|
||||||
|
Token string `json:"token"` // 微信客服回调配置,用于生成签名校验回调请求的合法性
|
||||||
|
EncodingAESKey string `json:"encoding_aes_key"` // 微信客服回调p配置,用于解密回调消息内容对应的密文
|
||||||
|
}
|
||||||
12
work/context/context.go
Normal file
12
work/context/context.go
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
package context
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/silenceper/wechat/v2/credential"
|
||||||
|
"github.com/silenceper/wechat/v2/work/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Context struct
|
||||||
|
type Context struct {
|
||||||
|
*config.Config
|
||||||
|
credential.AccessTokenHandle
|
||||||
|
}
|
||||||
3
work/kf/README.md
Normal file
3
work/kf/README.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
### 微信客服SDK
|
||||||
|
|
||||||
|
相关文档正在梳理中...
|
||||||
189
work/kf/account.go
Normal file
189
work/kf/account.go
Normal file
@@ -0,0 +1,189 @@
|
|||||||
|
package kf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
//添加客服账号
|
||||||
|
accountAddAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/account/add?access_token=%s"
|
||||||
|
// 删除客服账号
|
||||||
|
accountDelAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/account/del?access_token=%s"
|
||||||
|
// 修改客服账号
|
||||||
|
accountUpdateAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/account/update?access_token=%s"
|
||||||
|
// 获取客服账号列表
|
||||||
|
accountListAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/account/list?access_token=%s"
|
||||||
|
//获取客服账号链接
|
||||||
|
addContactWayAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/add_contact_way?access_token=%s"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AccountAddOptions 添加客服账号请求参数
|
||||||
|
type AccountAddOptions struct {
|
||||||
|
Name string `json:"name"` // 客服帐号名称, 不多于16个字符
|
||||||
|
MediaID string `json:"media_id"` // 客服头像临时素材。可以调用上传临时素材接口获取, 不多于128个字节
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountAddSchema 添加客服账号响应内容
|
||||||
|
type AccountAddSchema struct {
|
||||||
|
util.CommonError
|
||||||
|
OpenKFID string `json:"open_kfid"` // 新创建的客服张号ID
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountAdd 添加客服账号
|
||||||
|
func (r *Client) AccountAdd(options AccountAddOptions) (info AccountAddSchema, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(accountAddAddr, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountDelOptions 删除客服账号请求参数
|
||||||
|
type AccountDelOptions struct {
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID, 不多于64字节
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountDel 删除客服账号
|
||||||
|
func (r *Client) AccountDel(options AccountDelOptions) (info util.CommonError, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(accountDelAddr, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountUpdateOptions 修改客服账号请求参数
|
||||||
|
type AccountUpdateOptions struct {
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID, 不多于64字节
|
||||||
|
Name string `json:"name"` // 客服帐号名称, 不多于16个字符
|
||||||
|
MediaID string `json:"media_id"` // 客服头像临时素材。可以调用上传临时素材接口获取, 不多于128个字节
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountUpdate 修复客服账号
|
||||||
|
func (r *Client) AccountUpdate(options AccountUpdateOptions) (info util.CommonError, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(accountUpdateAddr, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountInfoSchema 客服详情
|
||||||
|
type AccountInfoSchema struct {
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||||
|
Name string `json:"name"` // 客服帐号名称
|
||||||
|
Avatar string `json:"avatar"` // 客服头像URL
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountListSchema 获取客服账号列表响应内容
|
||||||
|
type AccountListSchema struct {
|
||||||
|
util.CommonError
|
||||||
|
AccountList []AccountInfoSchema `json:"account_list"` // 客服账号列表
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountList 获取客服账号列表
|
||||||
|
func (r *Client) AccountList() (info AccountListSchema, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.HTTPGet(fmt.Sprintf(accountListAddr, accessToken))
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddContactWayOptions 获取客服账号链接
|
||||||
|
// 1.若scene非空,返回的客服链接开发者可拼接scene_param=SCENE_PARAM参数使用,用户进入会话事件会将SCENE_PARAM原样返回。其中SCENE_PARAM需要urlencode,且长度不能超过128字节。
|
||||||
|
// 如 https://work.weixin.qq.com/kf/kfcbf8f8d07ac7215f?enc_scene=ENCGFSDF567DF&scene_param=a%3D1%26b%3D2
|
||||||
|
// 2.历史调用接口返回的客服链接(包含encScene=XXX参数),不支持scene_param参数。
|
||||||
|
// 3.返回的客服链接,不能修改或复制参数到其他链接使用。否则进入会话事件参数校验不通过,导致无法回调。
|
||||||
|
type AddContactWayOptions struct {
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID, 不多于64字节
|
||||||
|
Scene string `json:"scene"` // 场景值,字符串类型,由开发者自定义, 不多于32字节, 字符串取值范围(正则表达式):[0-9a-zA-Z_-]*
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddContactWaySchema 获取客服账号链接响应内容
|
||||||
|
type AddContactWaySchema struct {
|
||||||
|
util.CommonError
|
||||||
|
URL string `json:"url"` // 客服链接,开发者可将该链接嵌入到H5页面中,用户点击链接即可向对应的微信客服帐号发起咨询。开发者也可根据该url自行生成需要的二维码图片
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddContactWay 获取客服账号链接
|
||||||
|
func (r *Client) AddContactWay(options AddContactWayOptions) (info AddContactWaySchema, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(addContactWayAddr, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
96
work/kf/callback.go
Normal file
96
work/kf/callback.go
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
package kf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/xml"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SignatureOptions 微信服务器验证参数
|
||||||
|
type SignatureOptions struct {
|
||||||
|
Signature string `form:"msg_signature"`
|
||||||
|
TimeStamp string `form:"timestamp"`
|
||||||
|
Nonce string `form:"nonce"`
|
||||||
|
EchoStr string `form:"echostr"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyURL 验证请求参数是否合法并返回解密后的消息内容
|
||||||
|
// //Gin框架的使用示例
|
||||||
|
// r.GET("/v1/event/callback", func(c *gin.Context) {
|
||||||
|
// options := kf.SignatureOptions{}
|
||||||
|
// //获取回调的的校验参数
|
||||||
|
// if = c.ShouldBindQuery(&options); err != nil {
|
||||||
|
// c.String(http.StatusUnauthorized, "参数解析失败")
|
||||||
|
// }
|
||||||
|
// // 调用VerifyURL方法校验当前请求,如果合法则把解密后的内容作为响应返回给微信服务器
|
||||||
|
// echo, err := kfClient.VerifyURL(options)
|
||||||
|
// if err == nil {
|
||||||
|
// c.String(http.StatusOK, echo)
|
||||||
|
// } else {
|
||||||
|
// c.String(http.StatusUnauthorized, "非法请求来源")
|
||||||
|
// }
|
||||||
|
// })
|
||||||
|
func (r *Client) VerifyURL(options SignatureOptions) (string, error) {
|
||||||
|
if options.Signature != util.Signature(r.ctx.Token, options.TimeStamp, options.Nonce, options.EchoStr) {
|
||||||
|
return "", NewSDKErr(40015)
|
||||||
|
}
|
||||||
|
_, bData, err := util.DecryptMsg(r.corpID, options.EchoStr, r.encodingAESKey)
|
||||||
|
if err != nil {
|
||||||
|
return "", NewSDKErr(40016)
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(bData), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 原始回调消息内容
|
||||||
|
type callbackOriginMessage struct {
|
||||||
|
ToUserName string // 企业微信的CorpID,当为第三方套件回调事件时,CorpID的内容为suiteid
|
||||||
|
AgentID string // 接收的应用id,可在应用的设置页面获取
|
||||||
|
Encrypt string // 消息结构体加密后的字符串
|
||||||
|
}
|
||||||
|
|
||||||
|
// CallbackMessage 微信客服回调消息
|
||||||
|
type CallbackMessage struct {
|
||||||
|
ToUserName string `json:"to_user_name"` // 微信客服组件ID
|
||||||
|
CreateTime int `json:"create_time"` // 消息创建时间,unix时间戳
|
||||||
|
MsgType string `json:"msgtype"` // 消息的类型,此时固定为 event
|
||||||
|
Event string `json:"event"` // 事件的类型,此时固定为 kf_msg_or_event
|
||||||
|
Token string `json:"token"` // 调用拉取消息接口时,需要传此token,用于校验请求的合法性
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCallbackMessage 获取回调事件中的消息内容
|
||||||
|
// //Gin框架的使用示例
|
||||||
|
// r.POST("/v1/event/callback", func(c *gin.Context) {
|
||||||
|
// var (
|
||||||
|
// message kf.CallbackMessage
|
||||||
|
// body []byte
|
||||||
|
// )
|
||||||
|
// // 读取原始消息内容
|
||||||
|
// body, err = c.GetRawData()
|
||||||
|
// if err != nil {
|
||||||
|
// c.String(http.StatusInternalServerError, err.Error())
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// // 解析原始数据
|
||||||
|
// message, err = kfClient.GetCallbackMessage(body)
|
||||||
|
// if err != nil {
|
||||||
|
// c.String(http.StatusInternalServerError, "消息获取失败")
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// fmt.Println(message)
|
||||||
|
// c.String(200, "ok")
|
||||||
|
// })
|
||||||
|
func (r *Client) GetCallbackMessage(encryptedMsg []byte) (msg CallbackMessage, err error) {
|
||||||
|
var origin callbackOriginMessage
|
||||||
|
if err = xml.Unmarshal(encryptedMsg, &origin); err != nil {
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
_, bData, err := util.DecryptMsg(r.corpID, origin.Encrypt, r.encodingAESKey)
|
||||||
|
if err != nil {
|
||||||
|
return msg, NewSDKErr(40016)
|
||||||
|
}
|
||||||
|
if err = xml.Unmarshal(bData, &msg); err != nil {
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
43
work/kf/client.go
Normal file
43
work/kf/client.go
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
package kf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/silenceper/wechat/v2/cache"
|
||||||
|
"github.com/silenceper/wechat/v2/credential"
|
||||||
|
"github.com/silenceper/wechat/v2/work/config"
|
||||||
|
"github.com/silenceper/wechat/v2/work/context"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Client 微信客服实例
|
||||||
|
type Client struct {
|
||||||
|
corpID string // 企业ID:企业开通的每个微信客服,都对应唯一的企业ID,企业可在微信客服管理后台的企业信息处查看
|
||||||
|
secret string // Secret是微信客服用于校验开发者身份的访问密钥,企业成功注册微信客服后,可在「微信客服管理后台-开发配置」处获取
|
||||||
|
token string // 用于生成签名校验回调请求的合法性
|
||||||
|
encodingAESKey string // 回调消息加解密参数是AES密钥的Base64编码,用于解密回调消息内容对应的密文
|
||||||
|
cache cache.Cache
|
||||||
|
ctx *context.Context
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewClient 初始化微信客服实例
|
||||||
|
func NewClient(cfg *config.Config) (client *Client, err error) {
|
||||||
|
if cfg.Cache == nil {
|
||||||
|
return nil, NewSDKErr(50001)
|
||||||
|
}
|
||||||
|
|
||||||
|
//初始化 AccessToken Handle
|
||||||
|
defaultAkHandle := credential.NewWorkAccessToken(cfg.CorpID, cfg.CorpSecret, credential.CacheKeyWorkPrefix, cfg.Cache)
|
||||||
|
ctx := &context.Context{
|
||||||
|
Config: cfg,
|
||||||
|
AccessTokenHandle: defaultAkHandle,
|
||||||
|
}
|
||||||
|
|
||||||
|
client = &Client{
|
||||||
|
corpID: cfg.CorpID,
|
||||||
|
secret: cfg.CorpSecret,
|
||||||
|
token: cfg.Token,
|
||||||
|
encodingAESKey: cfg.EncodingAESKey,
|
||||||
|
cache: cfg.Cache,
|
||||||
|
ctx: ctx,
|
||||||
|
}
|
||||||
|
|
||||||
|
return client, nil
|
||||||
|
}
|
||||||
56
work/kf/customer.go
Normal file
56
work/kf/customer.go
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package kf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
customerBatchGetAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/customer/batchget?access_token=%s"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CustomerBatchGetOptions 客户基本信息获取请求参数
|
||||||
|
type CustomerBatchGetOptions struct {
|
||||||
|
ExternalUserIDList []string `json:"external_userid_list"` // external_userid列表
|
||||||
|
}
|
||||||
|
|
||||||
|
// CustomerSchema 微信客户基本资料
|
||||||
|
type CustomerSchema struct {
|
||||||
|
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||||
|
NickName string `json:"nickname"` // 微信昵称
|
||||||
|
Avatar string `json:"avatar"` // 微信头像。第三方不可获取
|
||||||
|
Gender int `json:"gender"` // 性别
|
||||||
|
UnionID string `json:"unionid"` // unionid,需要绑定微信开发者帐号才能获取到,查看绑定方法: https://open.work.weixin.qq.com/kf/doc/92512/93143/94769#%E5%A6%82%E4%BD%95%E8%8E%B7%E5%8F%96%E5%BE%AE%E4%BF%A1%E5%AE%A2%E6%88%B7%E7%9A%84unionid
|
||||||
|
}
|
||||||
|
|
||||||
|
// CustomerBatchGetSchema 获取客户基本信息响应内容
|
||||||
|
type CustomerBatchGetSchema struct {
|
||||||
|
util.CommonError
|
||||||
|
CustomerList []CustomerSchema `json:"customer_list"` // 微信客户信息列表
|
||||||
|
InvalidExternalUserID []string `json:"invalid_external_userid"` // 无效的微信客户ID
|
||||||
|
}
|
||||||
|
|
||||||
|
// CustomerBatchGet 客户基本信息获取
|
||||||
|
func (r *Client) CustomerBatchGet(options CustomerBatchGetOptions) (info CustomerBatchGetSchema, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(customerBatchGetAddr, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
91
work/kf/error.go
Normal file
91
work/kf/error.go
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
package kf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Error 错误
|
||||||
|
type Error string
|
||||||
|
|
||||||
|
const (
|
||||||
|
// SDKInitFailed 错误码:50001
|
||||||
|
SDKInitFailed Error = "SDK初始化失败"
|
||||||
|
// SDKCacheUnavailable 错误码:50002
|
||||||
|
SDKCacheUnavailable Error = "缓存无效"
|
||||||
|
// SDKUnknownError 错误码:50003
|
||||||
|
SDKUnknownError Error = "未知错误"
|
||||||
|
// SDKInvalidCredential 错误码:40001
|
||||||
|
SDKInvalidCredential Error = "不合法的secret参数"
|
||||||
|
// SDKInvalidCorpID 错误码:40013
|
||||||
|
SDKInvalidCorpID Error = "无效的 CorpID"
|
||||||
|
// SDKAccessTokenInvalid 错误码:40014
|
||||||
|
SDKAccessTokenInvalid Error = "AccessToken 无效"
|
||||||
|
// SDKValidateSignatureFailed 错误码:40015
|
||||||
|
SDKValidateSignatureFailed Error = "校验签名错误"
|
||||||
|
// SDKDecryptMSGFailed 错误码:40016
|
||||||
|
SDKDecryptMSGFailed Error = "消息解密失败"
|
||||||
|
// SDKAccessTokenMissing 错误码:41001
|
||||||
|
SDKAccessTokenMissing Error = "缺少AccessToken参数"
|
||||||
|
// SDKAccessTokenExpired 错误码:42001
|
||||||
|
SDKAccessTokenExpired Error = "AccessToken 已过期"
|
||||||
|
// SDKApiFreqOutOfLimit 错误码:45009
|
||||||
|
SDKApiFreqOutOfLimit Error = "接口请求次数超频"
|
||||||
|
// SDKApiForbidden 错误码:48002
|
||||||
|
SDKApiForbidden Error = "API 禁止调用"
|
||||||
|
// SDKInvalidOpenKFID 错误码:95000
|
||||||
|
SDKInvalidOpenKFID Error = "无效的 open_kfid"
|
||||||
|
// SDKOpenKFIDNotExist 错误码:95004
|
||||||
|
SDKOpenKFIDNotExist Error = "open_kfid 不存在"
|
||||||
|
// SDKWeWorkAlready 错误码:95011
|
||||||
|
SDKWeWorkAlready Error = "已在企业微信使用微信客服"
|
||||||
|
// SDKApiNotOpen 错误码:95017
|
||||||
|
SDKApiNotOpen Error = "API 功能没有被开启"
|
||||||
|
)
|
||||||
|
|
||||||
|
//Error 输出错误信息
|
||||||
|
func (r Error) Error() string {
|
||||||
|
return reflect.ValueOf(r).String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSDKErr 初始化SDK实例错误信息
|
||||||
|
func NewSDKErr(code int64, msgList ...string) Error {
|
||||||
|
switch code {
|
||||||
|
case 50001:
|
||||||
|
return SDKInitFailed
|
||||||
|
case 50002:
|
||||||
|
return SDKCacheUnavailable
|
||||||
|
case 40001:
|
||||||
|
return SDKInvalidCredential
|
||||||
|
case 41001:
|
||||||
|
return SDKAccessTokenMissing
|
||||||
|
case 42001:
|
||||||
|
return SDKAccessTokenExpired
|
||||||
|
case 40013:
|
||||||
|
return SDKInvalidCorpID
|
||||||
|
case 40014:
|
||||||
|
return SDKAccessTokenInvalid
|
||||||
|
case 40015:
|
||||||
|
return SDKValidateSignatureFailed
|
||||||
|
case 40016:
|
||||||
|
return SDKDecryptMSGFailed
|
||||||
|
case 45009:
|
||||||
|
return SDKApiFreqOutOfLimit
|
||||||
|
case 48002:
|
||||||
|
return SDKApiForbidden
|
||||||
|
case 95000:
|
||||||
|
return SDKInvalidOpenKFID
|
||||||
|
case 95004:
|
||||||
|
return SDKOpenKFIDNotExist
|
||||||
|
case 95011:
|
||||||
|
return SDKWeWorkAlready
|
||||||
|
case 95017:
|
||||||
|
return SDKApiNotOpen
|
||||||
|
default:
|
||||||
|
//返回未知的自定义错误
|
||||||
|
if len(msgList) > 0 {
|
||||||
|
return Error(strings.Join(msgList, ","))
|
||||||
|
}
|
||||||
|
return SDKUnknownError
|
||||||
|
}
|
||||||
|
}
|
||||||
42
work/kf/sendmsg.go
Normal file
42
work/kf/sendmsg.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package kf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
//发送消息
|
||||||
|
sendMsgAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg?access_token=%s"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SendMsgSchema 发送消息响应内容
|
||||||
|
type SendMsgSchema struct {
|
||||||
|
util.CommonError
|
||||||
|
MsgID string `json:"msgid"` // 消息ID。如果请求参数指定了msgid,则原样返回,否则系统自动生成并返回。不多于32字节, 字符串取值范围(正则表达式):[0-9a-zA-Z_-]*
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendMsg 获取消息
|
||||||
|
func (r *Client) SendMsg(options interface{}) (info SendMsgSchema, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(sendMsgAddr, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
127
work/kf/sendmsg/message.go
Normal file
127
work/kf/sendmsg/message.go
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
package sendmsg
|
||||||
|
|
||||||
|
// Message 发送消息
|
||||||
|
type Message struct {
|
||||||
|
ToUser string `json:"touser"` // 指定接收消息的客户UserID
|
||||||
|
OpenKFID string `json:"open_kfid"` // 指定发送消息的客服帐号ID
|
||||||
|
MsgID string `json:"msgid"` // 指定消息ID
|
||||||
|
}
|
||||||
|
|
||||||
|
// Text 发送文本消息
|
||||||
|
type Text struct {
|
||||||
|
Message
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:text
|
||||||
|
Text struct {
|
||||||
|
Content string `json:"content"` // 消息内容,最长不超过2048个字节
|
||||||
|
} `json:"text"` // 文本消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// Image 发送图片消息
|
||||||
|
type Image struct {
|
||||||
|
Message
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:image
|
||||||
|
Image struct {
|
||||||
|
MediaID string `json:"media_id"` // 图片文件id,可以调用上传临时素材接口获取
|
||||||
|
} `json:"image"` // 图片消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// Voice 发送语音消息
|
||||||
|
type Voice struct {
|
||||||
|
Message
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:voice
|
||||||
|
Voice struct {
|
||||||
|
MediaID string `json:"media_id"` // 语音文件id,可以调用上传临时素材接口获取
|
||||||
|
} `json:"voice"` // 语音消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// Video 发送视频消息
|
||||||
|
type Video struct {
|
||||||
|
Message
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:video
|
||||||
|
Video struct {
|
||||||
|
MediaID string `json:"media_id"` // 视频文件id,可以调用上传临时素材接口获取
|
||||||
|
} `json:"video"` // 视频消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// File 发送文件消息
|
||||||
|
type File struct {
|
||||||
|
Message
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:file
|
||||||
|
File struct {
|
||||||
|
MediaID string `json:"media_id"` // 文件id,可以调用上传临时素材接口获取
|
||||||
|
} `json:"file"` // 文件消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// Link 图文链接消息
|
||||||
|
type Link struct {
|
||||||
|
Message
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:link
|
||||||
|
Link struct {
|
||||||
|
Title string `json:"title"` // 标题,不超过128个字节,超过会自动截断
|
||||||
|
Desc string `json:"desc"` // 描述,不超过512个字节,超过会自动截断
|
||||||
|
URL string `json:"url"` // 点击后跳转的链接。 最长2048字节,请确保包含了协议头(http/https)
|
||||||
|
ThumbMediaID string `json:"thumb_media_id"` // 缩略图的media_id, 可以通过素材管理接口获得。此处thumb_media_id即上传接口返回的media_id
|
||||||
|
} `json:"link"` // 链接消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// MiniProgram 小程序消息
|
||||||
|
type MiniProgram struct {
|
||||||
|
Message
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:miniprogram
|
||||||
|
MiniProgram struct {
|
||||||
|
AppID string `json:"appid"` // 小程序appid,必须是关联到企业的小程序应用
|
||||||
|
Title string `json:"title"` // 小程序消息标题,最多64个字节,超过会自动截断
|
||||||
|
ThumbMediaID string `json:"thumb_media_id"` // 小程序消息封面的mediaid,封面图建议尺寸为520*416
|
||||||
|
PagePath string `json:"pagepath"` // 点击消息卡片后进入的小程序页面路径
|
||||||
|
} `json:"miniprogram"` // 小程序消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// Menu 发送菜单消息
|
||||||
|
type Menu struct {
|
||||||
|
Message
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:msgmenu
|
||||||
|
MsgMenu struct {
|
||||||
|
HeadContent string `json:"head_content"` // 消息内容,不多于1024字节
|
||||||
|
List []interface{} `json:"list"` // 菜单项配置
|
||||||
|
} `json:"msgmenu"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MenuClick 回复菜单
|
||||||
|
type MenuClick struct {
|
||||||
|
Type string `json:"type"` // 菜单类型: click 回复菜单
|
||||||
|
Click struct {
|
||||||
|
ID string `json:"id"` // 菜单ID, 不少于1字节, 不多于64字节
|
||||||
|
Content string `json:"content"` // 菜单显示内容, 不少于1字节, 不多于128字节
|
||||||
|
} `json:"click"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MenuView 超链接菜单
|
||||||
|
type MenuView struct {
|
||||||
|
Type string `json:"type"` // 菜单类型: view 超链接菜单
|
||||||
|
View struct {
|
||||||
|
URL string `json:"url"` // 点击后跳转的链接, 不少于1字节, 不多于2048字节
|
||||||
|
Content string `json:"content"` // 菜单显示内容, 不少于1字节, 不多于1024字节
|
||||||
|
} `json:"view"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MenuMiniProgram 小程序菜单
|
||||||
|
type MenuMiniProgram struct {
|
||||||
|
Type string `json:"type"` // 菜单类型: miniprogram 小程序菜单
|
||||||
|
MiniProgram struct {
|
||||||
|
AppID string `json:"appid"` // 小程序appid, 不少于1字节, 不多于32字节
|
||||||
|
PagePath string `json:"pagepath"` // 点击后进入的小程序页面, 不少于1字节, 不多于1024字节
|
||||||
|
Content string `json:"content"` // 菜单显示内容, 不少于1字节, 不多于1024字节
|
||||||
|
} `json:"miniprogram"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Location 地理位置消息
|
||||||
|
type Location struct {
|
||||||
|
Message
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:location
|
||||||
|
Location struct {
|
||||||
|
Latitude float32 `json:"latitude"` // 纬度, 浮点数,范围为90 ~ -90
|
||||||
|
Longitude float32 `json:"longitude"` // 经度, 浮点数,范围为180 ~ -180
|
||||||
|
Name string `json:"name"` // 位置名
|
||||||
|
Address string `json:"address"` // 地址详情说明
|
||||||
|
} `json:"location"`
|
||||||
|
}
|
||||||
1
work/kf/sendmsg/sendmsg.go
Normal file
1
work/kf/sendmsg/sendmsg.go
Normal file
@@ -0,0 +1 @@
|
|||||||
|
package sendmsg
|
||||||
110
work/kf/servicer.go
Normal file
110
work/kf/servicer.go
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
package kf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
//添加接待人员
|
||||||
|
receptionistAddAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/servicer/add?access_token=%s"
|
||||||
|
//删除接待人员
|
||||||
|
receptionistDelAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/servicer/del?access_token=%s"
|
||||||
|
//获取接待人员列表
|
||||||
|
receptionistListAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/servicer/list?access_token=%s&open_kfid=%s"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReceptionistOptions 添加接待人员请求参数
|
||||||
|
type ReceptionistOptions struct {
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||||
|
UserIDList []string `json:"userid_list"` // 接待人员userid列表
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReceptionistSchema 添加接待人员响应内容
|
||||||
|
type ReceptionistSchema struct {
|
||||||
|
util.CommonError
|
||||||
|
ResultList []struct {
|
||||||
|
UserID string `json:"userid"`
|
||||||
|
util.CommonError
|
||||||
|
} `json:"result_list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReceptionistAdd 添加接待人员
|
||||||
|
func (r *Client) ReceptionistAdd(options ReceptionistOptions) (info ReceptionistSchema, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(receptionistAddAddr, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReceptionistDel 删除接待人员
|
||||||
|
func (r *Client) ReceptionistDel(options ReceptionistOptions) (info ReceptionistSchema, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(receptionistDelAddr, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReceptionistListSchema 获取接待人员列表响应内容
|
||||||
|
type ReceptionistListSchema struct {
|
||||||
|
util.CommonError
|
||||||
|
ReceptionistList []struct {
|
||||||
|
UserID string `json:"userid"` // 接待人员的userid。第三方应用获取到的为密文userid,即open_userid
|
||||||
|
Status int `json:"status"` // 接待人员的接待状态。0:接待中,1:停止接待。第三方应用需具有“管理帐号、分配会话和收发消息”权限才可获取
|
||||||
|
} `json:"servicer_list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReceptionistList 获取接待人员列表
|
||||||
|
func (r *Client) ReceptionistList(kfID string) (info ReceptionistListSchema, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.HTTPGet(fmt.Sprintf(receptionistListAddr, accessToken, kfID))
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
88
work/kf/servicestate.go
Normal file
88
work/kf/servicestate.go
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
package kf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
//获取会话状态
|
||||||
|
serviceStateGetAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/service_state/get?access_token=%s"
|
||||||
|
// 变更会话状态
|
||||||
|
serviceStateTransAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/service_state/trans?access_token=%s"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ServiceStateGetOptions 获取会话状态请求参数
|
||||||
|
type ServiceStateGetOptions struct {
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||||
|
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServiceStateGetSchema 获取会话状态响应内容
|
||||||
|
type ServiceStateGetSchema struct {
|
||||||
|
util.CommonError
|
||||||
|
ServiceState int `json:"service_state"` // 当前的会话状态,状态定义参考概述中的表格
|
||||||
|
ServiceUserID string `json:"service_userid"` // 接待人员的userid,仅当state=3时有效
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServiceStateGet 获取会话状态
|
||||||
|
//0 未处理 新会话接入。可选择:1.直接用API自动回复消息。2.放进待接入池等待接待人员接待。3.指定接待人员进行接待
|
||||||
|
//1 由智能助手接待 可使用API回复消息。可选择转入待接入池或者指定接待人员处理。
|
||||||
|
//2 待接入池排队中 在待接入池中排队等待接待人员接入。可选择转为指定人员接待
|
||||||
|
//3 由人工接待 人工接待中。可选择结束会话
|
||||||
|
//4 已结束 会话已经结束或未开始。不允许变更会话状态,等待用户发起咨询
|
||||||
|
// 注:一个微信用户向一个客服帐号发起咨询后,在48h内,或主动结束会话前(包括接待人员手动结束,或企业通过API结束会话),都算是一次会话
|
||||||
|
func (r *Client) ServiceStateGet(options ServiceStateGetOptions) (info ServiceStateGetSchema, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(serviceStateGetAddr, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServiceStateTransOptions 变更会话状态请求参数
|
||||||
|
type ServiceStateTransOptions struct {
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||||
|
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||||
|
ServiceState int `json:"service_state"` // 变更的目标状态,状态定义和所允许的变更可参考概述中的流程图和表格
|
||||||
|
ServicerUserID string `json:"servicer_userid"` // 接待人员的userid,当state=3时要求必填,接待人员须处于“正在接待”中
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServiceStateTrans 变更会话状态
|
||||||
|
func (r *Client) ServiceStateTrans(options ServiceStateTransOptions) (info util.CommonError, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(serviceStateTransAddr, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
108
work/kf/syncmsg.go
Normal file
108
work/kf/syncmsg.go
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
package kf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
"github.com/silenceper/wechat/v2/work/kf/syncmsg"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
//获取消息
|
||||||
|
syncMsgAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/sync_msg?access_token=%s"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SyncMsgOptions 获取消息查询参数
|
||||||
|
type SyncMsgOptions struct {
|
||||||
|
Cursor string `json:"cursor"` // 上一次调用时返回的next_cursor,第一次拉取可以不填, 不多于64字节
|
||||||
|
Token string `json:"token"` // 回调事件返回的token字段,10分钟内有效;可不填,如果不填接口有严格的频率限制, 不多于128字节
|
||||||
|
Limit uint `json:"limit"` // 期望请求的数据量,默认值和最大值都为1000, 注意:可能会出现返回条数少于limit的情况,需结合返回的has_more字段判断是否继续请求。
|
||||||
|
}
|
||||||
|
|
||||||
|
// SyncMsgSchema 获取消息查询响应内容
|
||||||
|
type syncMsgSchema struct {
|
||||||
|
ErrCode int32 `json:"errcode"` // 返回码
|
||||||
|
ErrMsg string `json:"errmsg"` // 错误码描述
|
||||||
|
NextCursor string `json:"next_cursor"` // 下次调用带上该值,则从当前的位置继续往后拉,以实现增量拉取。强烈建议对改该字段入库保存,每次请求读取带上,请求结束后更新。避免因意外丢,导致必须从头开始拉取,引起消息延迟。
|
||||||
|
HasMore uint32 `json:"has_more"` // 是否还有更多数据。0-否;1-是。不能通过判断msg_list是否空来停止拉取,可能会出现has_more为1,而msg_list为空的情况
|
||||||
|
MsgList []map[string]interface{} `json:"msg_list"` // 消息列表
|
||||||
|
}
|
||||||
|
|
||||||
|
// SyncMsgSchema 获取消息查询响应内容
|
||||||
|
type SyncMsgSchema struct {
|
||||||
|
ErrCode int32 `json:"errcode"` // 返回码
|
||||||
|
ErrMsg string `json:"errmsg"` // 错误码描述
|
||||||
|
NextCursor string `json:"next_cursor"` // 下次调用带上该值则从该key值往后拉,用于增量拉取
|
||||||
|
HasMore uint32 `json:"has_more"` // 是否还有更多数据。0-否;1-是。不能通过判断msg_list是否空来停止拉取,可能会出现has_more为1,而msg_list为空的情况
|
||||||
|
MsgList []syncmsg.Message `json:"msg_list"` // 消息列表
|
||||||
|
}
|
||||||
|
|
||||||
|
// SyncMsg 获取消息
|
||||||
|
func (r *Client) SyncMsg(options SyncMsgOptions) (info SyncMsgSchema, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(syncMsgAddr, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
originInfo := syncMsgSchema{}
|
||||||
|
if err = json.Unmarshal(data, &originInfo); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if originInfo.ErrCode != 0 {
|
||||||
|
return info, errors.New(originInfo.ErrMsg)
|
||||||
|
}
|
||||||
|
msgList := make([]syncmsg.Message, 0)
|
||||||
|
if len(originInfo.MsgList) > 0 {
|
||||||
|
for _, msg := range originInfo.MsgList {
|
||||||
|
newMsg := syncmsg.Message{}
|
||||||
|
if val, ok := msg["msgid"].(string); ok {
|
||||||
|
newMsg.MsgID = val
|
||||||
|
}
|
||||||
|
if val, ok := msg["open_kfid"].(string); ok {
|
||||||
|
newMsg.OpenKFID = val
|
||||||
|
}
|
||||||
|
if val, ok := msg["external_userid"].(string); ok {
|
||||||
|
newMsg.ExternalUserID = val
|
||||||
|
}
|
||||||
|
if val, ok := msg["send_time"].(float64); ok {
|
||||||
|
newMsg.SendTime = uint64(val)
|
||||||
|
}
|
||||||
|
if val, ok := msg["origin"].(float64); ok {
|
||||||
|
newMsg.Origin = uint32(val)
|
||||||
|
}
|
||||||
|
|
||||||
|
if val, ok := msg["msgtype"].(string); ok {
|
||||||
|
newMsg.MsgType = val
|
||||||
|
}
|
||||||
|
if newMsg.MsgType == "event" {
|
||||||
|
if event, ok := msg["event"].(map[string]interface{}); ok {
|
||||||
|
if eType, ok := event["event_type"].(string); ok {
|
||||||
|
newMsg.EventType = eType
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
originData, err := json.Marshal(msg)
|
||||||
|
if err != nil {
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
newMsg.OriginData = originData
|
||||||
|
msgList = append(msgList, newMsg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SyncMsgSchema{
|
||||||
|
ErrCode: originInfo.ErrCode,
|
||||||
|
ErrMsg: originInfo.ErrMsg,
|
||||||
|
NextCursor: originInfo.NextCursor,
|
||||||
|
HasMore: originInfo.HasMore,
|
||||||
|
MsgList: msgList,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
162
work/kf/syncmsg/message.go
Normal file
162
work/kf/syncmsg/message.go
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
package syncmsg
|
||||||
|
|
||||||
|
// BaseMessage 接收消息
|
||||||
|
type BaseMessage struct {
|
||||||
|
MsgID string `json:"msgid"` // 消息ID
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID(msgtype为event,该字段不返回)
|
||||||
|
ExternalUserID string `json:"external_userid"` // 客户UserID(msgtype为event,该字段不返回)
|
||||||
|
ReceptionistUserID string `json:"servicer_userid"` // 接待客服userID
|
||||||
|
SendTime uint64 `json:"send_time"` // 消息发送时间
|
||||||
|
Origin uint32 `json:"origin"` // 消息来源。3-微信客户发送的消息 4-系统推送的事件消息 5-接待人员在企业微信客户端发送的消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// Text 文本消息
|
||||||
|
type Text struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:text
|
||||||
|
Text struct {
|
||||||
|
Content string `json:"content"` // 文本内容
|
||||||
|
MenuID string `json:"menu_id"` // 客户点击菜单消息,触发的回复消息中附带的菜单ID
|
||||||
|
} `json:"text"` // 文本消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// Image 图片消息
|
||||||
|
type Image struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:image
|
||||||
|
Image struct {
|
||||||
|
MediaID string `json:"media_id"` // 图片文件ID
|
||||||
|
} `json:"image"` // 图片消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// Voice 语音消息
|
||||||
|
type Voice struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:voice
|
||||||
|
Voice struct {
|
||||||
|
MediaID string `json:"media_id"` // 语音文件ID
|
||||||
|
} `json:"voice"` // 语音消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// Video 视频消息
|
||||||
|
type Video struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:video
|
||||||
|
Video struct {
|
||||||
|
MediaID string `json:"media_id"` // 文件ID
|
||||||
|
} `json:"video"` // 视频消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// File 文件消息
|
||||||
|
type File struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:file
|
||||||
|
File struct {
|
||||||
|
MediaID string `json:"media_id"` // 文件ID
|
||||||
|
} `json:"file"` // 文件消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// Location 地理位置消息
|
||||||
|
type Location struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:location
|
||||||
|
Location struct {
|
||||||
|
Latitude float32 `json:"latitude"` // 纬度
|
||||||
|
Longitude float32 `json:"longitude"` // 经度
|
||||||
|
Name string `json:"name"` // 位置名
|
||||||
|
Address string `json:"address"` // 地址详情说明
|
||||||
|
} `json:"location"` // 地理位置消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// Link 链接消息
|
||||||
|
type Link struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:link
|
||||||
|
Link struct {
|
||||||
|
Title string `json:"title"` // 标题
|
||||||
|
Desc string `json:"desc"` // 描述
|
||||||
|
URL string `json:"url"` // 点击后跳转的链接
|
||||||
|
PicURL string `json:"pic_url"` // 缩略图链接
|
||||||
|
} `json:"link"` // 链接消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// BusinessCard 名片消息
|
||||||
|
type BusinessCard struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:business_card
|
||||||
|
BusinessCard struct {
|
||||||
|
UserID string `json:"userid"` // 名片 userid
|
||||||
|
} `json:"business_card"` // 名片消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// MiniProgram 小程序消息
|
||||||
|
type MiniProgram struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:miniprogram
|
||||||
|
MiniProgram struct {
|
||||||
|
AppID string `json:"appid"` // 小程序appid,必须是关联到企业的小程序应用
|
||||||
|
Title string `json:"title"` // 小程序消息标题,最多64个字节,超过会自动截断
|
||||||
|
ThumbMediaID string `json:"thumb_media_id"` // 小程序消息封面的mediaid,封面图建议尺寸为520*416
|
||||||
|
PagePath string `json:"pagepath"` // 点击消息卡片后进入的小程序页面路径
|
||||||
|
} `json:"miniprogram"` // 小程序消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// EventMessage 事件消息
|
||||||
|
type EventMessage struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:event
|
||||||
|
Event struct {
|
||||||
|
EventType string `json:"event_type"` // 事件类型
|
||||||
|
} `json:"event"` // 事件消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnterSessionEvent 用户进入会话事件
|
||||||
|
type EnterSessionEvent struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:event
|
||||||
|
Event struct {
|
||||||
|
EventType string `json:"event_type"` // 事件类型。此处固定为:enter_session
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服账号ID
|
||||||
|
ExternalUserID string `json:"external_userid"` // 客户UserID
|
||||||
|
Scene string `json:"scene"` // 进入会话的场景值,获取客服帐号链接开发者自定义的场景值
|
||||||
|
SceneParam string `json:"scene_param"` // 进入会话的自定义参数,获取客服帐号链接返回的url,开发者按规范拼接的scene_param参数
|
||||||
|
} `json:"event"` // 事件消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgSendFailEvent 消息发送失败事件
|
||||||
|
type MsgSendFailEvent struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:event
|
||||||
|
Event struct {
|
||||||
|
EventType string `json:"event_type"` // 事件类型。此处固定为:msg_send_fail
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服账号ID
|
||||||
|
ExternalUserID string `json:"external_userid"` // 客户UserID
|
||||||
|
FailMsgID string `json:"fail_msgid"` // 发送失败的消息msgid
|
||||||
|
FailType uint32 `json:"fail_type"` // 失败类型。0-未知原因 1-客服账号已删除 2-应用已关闭 4-会话已过期,超过48小时 5-会话已关闭 6-超过5条限制 7-未绑定视频号 8-主体未验证 9-未绑定视频号且主体未验证 10-用户拒收
|
||||||
|
} `json:"event"` // 事件消息
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReceptionistStatusChangeEvent 客服人员接待状态变更事件
|
||||||
|
type ReceptionistStatusChangeEvent struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:event
|
||||||
|
Event struct {
|
||||||
|
EventType string `json:"event_type"` // 事件类型。此处固定为:servicer_status_change
|
||||||
|
ReceptionistUserID string `json:"servicer_userid"` // 客服人员userid
|
||||||
|
Status uint32 `json:"status"` // 状态类型。1-接待中 2-停止接待
|
||||||
|
} `json:"event"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SessionStatusChangeEvent 会话状态变更事件
|
||||||
|
type SessionStatusChangeEvent struct {
|
||||||
|
BaseMessage
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型,此时固定为:event
|
||||||
|
Event struct {
|
||||||
|
EventType string `json:"event_type"` // 事件类型。此处固定为:session_status_change
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服账号ID
|
||||||
|
ExternalUserID string `json:"external_userid"` // 客户UserID
|
||||||
|
ChangeType uint32 `json:"change_type"` // 变更类型。1-从接待池接入会话 2-转接会话 3-结束会话
|
||||||
|
OldReceptionistUserID string `json:"old_servicer_userid"` // 老的客服人员userid。仅change_type为2和3有值
|
||||||
|
NewReceptionistUserID string `json:"new_servicer_userid"` // 新的客服人员userid。仅change_type为1和2有值
|
||||||
|
} `json:"event"` // 事件消息
|
||||||
|
}
|
||||||
102
work/kf/syncmsg/syncmsg.go
Normal file
102
work/kf/syncmsg/syncmsg.go
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
package syncmsg
|
||||||
|
|
||||||
|
import "encoding/json"
|
||||||
|
|
||||||
|
// Message 同步的消息内容
|
||||||
|
type Message struct {
|
||||||
|
MsgID string `json:"msgid"` // 消息ID
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||||
|
ExternalUserID string `json:"external_userid"` // 客户UserID
|
||||||
|
SendTime uint64 `json:"send_time"` // 消息发送时间
|
||||||
|
Origin uint32 `json:"origin"` // 消息来源。3-客户回复的消息 4-系统推送的消 息
|
||||||
|
MsgType string `json:"msgtype"` // 消息类型
|
||||||
|
EventType string `json:"event_type"` // 事件类型
|
||||||
|
OriginData []byte `json:"origin_data"` // 原始数据内容
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetOriginMessage 获取原始消息
|
||||||
|
func (r Message) GetOriginMessage() (info []byte) {
|
||||||
|
return r.OriginData
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTextMessage 获取文本消息
|
||||||
|
func (r Message) GetTextMessage() (info Text, err error) {
|
||||||
|
err = json.Unmarshal(r.OriginData, &info)
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetImageMessage 获取图片消息
|
||||||
|
func (r Message) GetImageMessage() (info Image, err error) {
|
||||||
|
err = json.Unmarshal(r.OriginData, &info)
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetVoiceMessage 获取语音消息
|
||||||
|
func (r Message) GetVoiceMessage() (info Voice, err error) {
|
||||||
|
err = json.Unmarshal(r.OriginData, &info)
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetVideoMessage 获取视频消息
|
||||||
|
func (r Message) GetVideoMessage() (info Video, err error) {
|
||||||
|
err = json.Unmarshal(r.OriginData, &info)
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFileMessage 获取文件消息
|
||||||
|
func (r Message) GetFileMessage() (info File, err error) {
|
||||||
|
err = json.Unmarshal(r.OriginData, &info)
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLocationMessage 获取文件消息
|
||||||
|
func (r Message) GetLocationMessage() (info Location, err error) {
|
||||||
|
err = json.Unmarshal(r.OriginData, &info)
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLinkMessage 获取链接消息
|
||||||
|
func (r Message) GetLinkMessage() (info Link, err error) {
|
||||||
|
err = json.Unmarshal(r.OriginData, &info)
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetBusinessCardMessage 获取名片消息
|
||||||
|
func (r Message) GetBusinessCardMessage() (info BusinessCard, err error) {
|
||||||
|
err = json.Unmarshal(r.OriginData, &info)
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMiniProgramMessage 获取小程序消息
|
||||||
|
func (r Message) GetMiniProgramMessage() (info MiniProgram, err error) {
|
||||||
|
err = json.Unmarshal(r.OriginData, &info)
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetEnterSessionEvent 用户进入会话事件
|
||||||
|
func (r Message) GetEnterSessionEvent() (info EnterSessionEvent, err error) {
|
||||||
|
err = json.Unmarshal(r.OriginData, &info)
|
||||||
|
info.OpenKFID = info.Event.OpenKFID
|
||||||
|
info.ExternalUserID = info.Event.ExternalUserID
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMsgSendFailEvent 消息发送失败事件
|
||||||
|
func (r Message) GetMsgSendFailEvent() (info MsgSendFailEvent, err error) {
|
||||||
|
err = json.Unmarshal(r.OriginData, &info)
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetReceptionistStatusChangeEvent 客服人员接待状态变更事件
|
||||||
|
func (r Message) GetReceptionistStatusChangeEvent() (info ReceptionistStatusChangeEvent, err error) {
|
||||||
|
err = json.Unmarshal(r.OriginData, &info)
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetSessionStatusChangeEvent 会话状态变更事件
|
||||||
|
func (r Message) GetSessionStatusChangeEvent() (info SessionStatusChangeEvent, err error) {
|
||||||
|
err = json.Unmarshal(r.OriginData, &info)
|
||||||
|
info.OpenKFID = info.Event.OpenKFID
|
||||||
|
info.ExternalUserID = info.Event.ExternalUserID
|
||||||
|
return info, err
|
||||||
|
}
|
||||||
187
work/kf/upgrade.go
Normal file
187
work/kf/upgrade.go
Normal file
@@ -0,0 +1,187 @@
|
|||||||
|
package kf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
//获取配置的专员与客户群
|
||||||
|
upgradeServiceConfigAddr = "https://qyapi.weixin.qq.com/cgi-bin/kf/customer/get_upgrade_service_config?access_token=%s"
|
||||||
|
// 为客户升级为专员或客户群服务
|
||||||
|
upgradeService = "https://qyapi.weixin.qq.com/cgi-bin/kf/customer/upgrade_service?access_token=%s"
|
||||||
|
//为客户取消推荐
|
||||||
|
upgradeServiceCancel = "https://qyapi.weixin.qq.com/cgi-bin/kf/customer/cancel_upgrade_service?access_token=%s"
|
||||||
|
)
|
||||||
|
|
||||||
|
// UpgradeServiceConfigSchema 获取配置的专员与客户群
|
||||||
|
type UpgradeServiceConfigSchema struct {
|
||||||
|
util.CommonError
|
||||||
|
MemberRange struct {
|
||||||
|
UserIDList []string `json:"userid_list"` // 专员userid列表
|
||||||
|
DepartmentIDList []string `json:"department_id_list"` // 专员部门列表
|
||||||
|
} `json:"member_range"` // 专员服务配置范围
|
||||||
|
GroupChatRange struct {
|
||||||
|
ChatIDList []string `json:"chat_id_list"` // 客户群列表
|
||||||
|
} `json:"groupchat_range"` // 客户群配置范围
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpgradeServiceConfig 获取配置的专员与客户群
|
||||||
|
func (r *Client) UpgradeServiceConfig() (info UpgradeServiceConfigSchema, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.HTTPGet(fmt.Sprintf(upgradeServiceConfigAddr, accessToken))
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpgradeServiceOptions 为客户升级为专员或客户群服务请求参数
|
||||||
|
type UpgradeServiceOptions struct {
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||||
|
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||||
|
Type int `json:"type"` // 表示是升级到专员服务还是客户群服务。1:专员服务。2:客户群服务
|
||||||
|
Member struct {
|
||||||
|
UserID string `json:"userid"` // 服务专员的userid
|
||||||
|
Wording string `json:"wording"` // 推荐语
|
||||||
|
} `json:"member"` // 推荐的服务专员,type等于1时有效
|
||||||
|
GroupChat struct {
|
||||||
|
ChatID string `json:"chat_id"` // 客户群id
|
||||||
|
Wording string `json:"wording"` // 推荐语
|
||||||
|
} `json:"groupchat"` // 推荐的客户群,type等于2时有效
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpgradeService 为客户升级为专员或客户群服务
|
||||||
|
func (r *Client) UpgradeService(options UpgradeServiceOptions) (info util.CommonError, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(upgradeService, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpgradeMemberServiceOptions 为客户升级为专员服务请求参数
|
||||||
|
type UpgradeMemberServiceOptions struct {
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||||
|
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||||
|
Type int `json:"type"` // 表示是升级到专员服务还是客户群服务。1:专员服务
|
||||||
|
Member struct {
|
||||||
|
UserID string `json:"userid"` // 服务专员的userid
|
||||||
|
Wording string `json:"wording"` // 推荐语
|
||||||
|
} `json:"member"` // 推荐的服务专员,type等于1时有效
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpgradeMemberService 为客户升级为专员服务
|
||||||
|
func (r *Client) UpgradeMemberService(options UpgradeMemberServiceOptions) (info util.CommonError, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(upgradeService, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpgradeServiceGroupChatOptions 为客户升级为客户群服务请求参数
|
||||||
|
type UpgradeServiceGroupChatOptions struct {
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||||
|
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||||
|
Type int `json:"type"` // 表示是升级到专员服务还是客户群服务。2:客户群服务
|
||||||
|
GroupChat struct {
|
||||||
|
ChatID string `json:"chat_id"` // 客户群id
|
||||||
|
Wording string `json:"wording"` // 推荐语
|
||||||
|
} `json:"groupchat"` // 推荐的客户群,type等于2时有效
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpgradeGroupChatService 为客户升级为客户群服务
|
||||||
|
func (r *Client) UpgradeGroupChatService(options UpgradeServiceGroupChatOptions) (info util.CommonError, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(upgradeService, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpgradeServiceCancelOptions 为客户取消推荐
|
||||||
|
type UpgradeServiceCancelOptions struct {
|
||||||
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||||
|
ExternalUserID string `json:"external_userid"` // 微信客户的external_userid
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpgradeServiceCancel 为客户取消推荐
|
||||||
|
func (r *Client) UpgradeServiceCancel(options UpgradeServiceCancelOptions) (info util.CommonError, err error) {
|
||||||
|
var (
|
||||||
|
accessToken string
|
||||||
|
data []byte
|
||||||
|
)
|
||||||
|
accessToken, err = r.ctx.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err = util.PostJSON(fmt.Sprintf(upgradeServiceCancel, accessToken), options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(data, &info); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.ErrCode != 0 {
|
||||||
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
95
work/msgaudit/README.md
Normal file
95
work/msgaudit/README.md
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
企业微信会话存档SDK(基于企业微信C版官方SDK封装),暂时只支持在`linux`环境下使用当前SDK。
|
||||||
|
|
||||||
|
### 官方文档地址
|
||||||
|
https://open.work.weixin.qq.com/api/doc/90000/90135/91774
|
||||||
|
|
||||||
|
### 使用方式
|
||||||
|
|
||||||
|
1、安装 go module
|
||||||
|
> go get -u github.com/silenceper/wechat/v2
|
||||||
|
|
||||||
|
2、从 `github.com/silenceper/wechat/v2/work/msgaudit/lib` 文件夹下复制 `libWeWorkFinanceSdk_C.so` 动态库文件到系统动态链接库默认文件夹下,或者复制到任意文件夹并在当前文件夹下执行 `export LD_LIBRARY_PATH=$(pwd)`命令设置动态链接库检索地址后即可正常使用
|
||||||
|
|
||||||
|
### Example
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"github.com/silenceper/wechat/v2"
|
||||||
|
"github.com/silenceper/wechat/v2/work/msgaudit"
|
||||||
|
"github.com/silenceper/wechat/v2/work/config"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
//初始化客户端
|
||||||
|
wechatClient := wechat.NewWechat()
|
||||||
|
|
||||||
|
workClient := wechatClient.NewWork(&config.Config{
|
||||||
|
CorpID: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
|
||||||
|
CorpSecret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
|
||||||
|
RasPrivateKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
|
||||||
|
})
|
||||||
|
|
||||||
|
client, err := workClient.GetMsgAudit()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("SDK 初始化失败:%v \n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//同步消息
|
||||||
|
chatDataList, err := client.GetChatData(0, 100, "", "", 3)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("消息同步失败:%v \n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, chatData := range chatDataList {
|
||||||
|
//消息解密
|
||||||
|
chatInfo, err := client.DecryptData(chatData.EncryptRandomKey, chatData.EncryptChatMsg)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("消息解密失败:%v \n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if chatInfo.Type == "image" {
|
||||||
|
image, _ := chatInfo.GetImageMessage()
|
||||||
|
sdkfileid := image.Image.SdkFileId
|
||||||
|
|
||||||
|
isFinish := false
|
||||||
|
buffer := bytes.Buffer{}
|
||||||
|
for !isFinish {
|
||||||
|
//获取媒体数据
|
||||||
|
mediaData, err := client.GetMediaData("", sdkfileid, "", "", 5)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("媒体数据拉取失败:%v \n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
buffer.Write(mediaData.Data)
|
||||||
|
if mediaData.IsFinish {
|
||||||
|
isFinish = mediaData.IsFinish
|
||||||
|
}
|
||||||
|
}
|
||||||
|
filePath, _ := os.Getwd()
|
||||||
|
filePath = path.Join(filePath, "test.png")
|
||||||
|
err := ioutil.WriteFile(filePath, buffer.Bytes(), 0666)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("文件存储失败:%v \n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//释放SDK实例
|
||||||
|
client.Free()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
207
work/msgaudit/chat.go
Normal file
207
work/msgaudit/chat.go
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
package msgaudit
|
||||||
|
|
||||||
|
import "encoding/json"
|
||||||
|
|
||||||
|
// ChatDataResponse 会话存档消息响应数据
|
||||||
|
type ChatDataResponse struct {
|
||||||
|
Error
|
||||||
|
ChatDataList []ChatData `json:"chatdata,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsError 判断是否正确响应
|
||||||
|
func (c ChatDataResponse) IsError() bool {
|
||||||
|
return c.ErrCode != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatData 会话存档原始数据
|
||||||
|
type ChatData struct {
|
||||||
|
Seq uint64 `json:"seq,omitempty"` // 消息的seq值,标识消息的序号。再次拉取需要带上上次回包中最大的seq。Uint64类型,范围0-pow(2,64)-1
|
||||||
|
MsgID string `json:"msgid,omitempty"` // 消息id,消息的唯一标识,企业可以使用此字段进行消息去重。
|
||||||
|
PublickeyVer uint32 `json:"publickey_ver,omitempty"` // 加密此条消息使用的公钥版本号。
|
||||||
|
EncryptRandomKey string `json:"encrypt_random_key,omitempty"` // 使用publickey_ver指定版本的公钥进行非对称加密后base64加密的内容,需要业务方先base64 decode处理后,再使用指定版本的私钥进行解密,得出内容。
|
||||||
|
EncryptChatMsg string `json:"encrypt_chat_msg,omitempty"` // 消息密文。需要业务方使用将encrypt_random_key解密得到的内容,与encrypt_chat_msg,传入sdk接口DecryptData,得到消息明文。
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatMessage 会话存档消息
|
||||||
|
type ChatMessage struct {
|
||||||
|
ID string // 消息id,消息的唯一标识,企业可以使用此字段进行消息去重。
|
||||||
|
From string // 消息发送方id。同一企业内容为userid,非相同企业为external_userid。消息如果是机器人发出,也为external_userid。
|
||||||
|
ToList []string // 消息接收方列表,可能是多个,同一个企业内容为userid,非相同企业为external_userid。
|
||||||
|
Action string // 消息动作,目前有send(发送消息)/recall(撤回消息)/switch(切换企业日志)三种类型。
|
||||||
|
Type string // 消息类型
|
||||||
|
originData []byte // 原始消息对象
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetOriginMessage 获取消息原始数据
|
||||||
|
func (c ChatMessage) GetOriginMessage() (msg map[string]interface{}, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTextMessage 获取文本消息
|
||||||
|
func (c ChatMessage) GetTextMessage() (msg TextMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetImageMessage 获取图片消息
|
||||||
|
func (c ChatMessage) GetImageMessage() (msg ImageMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRevokeMessage 获取撤回消息
|
||||||
|
func (c ChatMessage) GetRevokeMessage() (msg RevokeMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAgreeMessage 获取同意会话聊天内容
|
||||||
|
func (c ChatMessage) GetAgreeMessage() (msg AgreeMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetVoiceMessage 获取语音消息
|
||||||
|
func (c ChatMessage) GetVoiceMessage() (msg VoiceMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetVideoMessage 获取视频消息
|
||||||
|
func (c ChatMessage) GetVideoMessage() (msg VideoMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCardMessage 获取名片消息
|
||||||
|
func (c ChatMessage) GetCardMessage() (msg CardMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLocationMessage 获取位置消息
|
||||||
|
func (c ChatMessage) GetLocationMessage() (msg LocationMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetEmotionMessage 获取表情消息
|
||||||
|
func (c ChatMessage) GetEmotionMessage() (msg EmotionMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFileMessage 获取文件消息
|
||||||
|
func (c ChatMessage) GetFileMessage() (msg FileMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLinkMessage 获取链接消息
|
||||||
|
func (c ChatMessage) GetLinkMessage() (msg LinkMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetWeappMessage 获取小程序消息
|
||||||
|
func (c ChatMessage) GetWeappMessage() (msg WeappMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetChatRecordMessage 获取会话记录消息
|
||||||
|
func (c ChatMessage) GetChatRecordMessage() (msg ChatRecordMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTodoMessage 获取待办消息
|
||||||
|
func (c ChatMessage) GetTodoMessage() (msg TodoMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetVoteMessage 获取投票消息
|
||||||
|
func (c ChatMessage) GetVoteMessage() (msg VoteMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCollectMessage 获取填表消息
|
||||||
|
func (c ChatMessage) GetCollectMessage() (msg CollectMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRedpacketMessage 获取红包消息
|
||||||
|
func (c ChatMessage) GetRedpacketMessage() (msg RedpacketMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMeetingMessage 获取会议邀请消息
|
||||||
|
func (c ChatMessage) GetMeetingMessage() (msg MeetingMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDocMessage 获取在线文档消息
|
||||||
|
func (c ChatMessage) GetDocMessage() (msg DocMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMarkdownMessage 获取MarkDown格式消息
|
||||||
|
func (c ChatMessage) GetMarkdownMessage() (msg MarkdownMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetNewsMessage 获取图文消息
|
||||||
|
func (c ChatMessage) GetNewsMessage() (msg NewsMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCalendarMessage 获取日程消息
|
||||||
|
func (c ChatMessage) GetCalendarMessage() (msg CalendarMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMixedMessage 获取混合消息
|
||||||
|
func (c ChatMessage) GetMixedMessage() (msg MixedMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMeetingVoiceCallMessage 获取音频存档消息
|
||||||
|
func (c ChatMessage) GetMeetingVoiceCallMessage() (msg MeetingVoiceCallMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetVoipDocShareMessage 获取音频共享消息
|
||||||
|
func (c ChatMessage) GetVoipDocShareMessage() (msg VoipDocShareMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetExternalRedPacketMessage 获取互通红包消息
|
||||||
|
func (c ChatMessage) GetExternalRedPacketMessage() (msg ExternalRedPacketMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetSphFeedMessage 获取视频号消息
|
||||||
|
func (c ChatMessage) GetSphFeedMessage() (msg SphFeedMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetSwitchMessage 获取切换企业日志
|
||||||
|
func (c ChatMessage) GetSwitchMessage() (msg SwitchMessage, err error) {
|
||||||
|
err = json.Unmarshal(c.originData, &msg)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user