mirror of
https://github.com/silenceper/wechat.git
synced 2026-02-07 22:22:28 +08:00
Compare commits
40 Commits
v2.0.0-alp
...
v2.0.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
69d0b94fdf | ||
|
|
c14c020a3c | ||
|
|
fe31f04640 | ||
|
|
2ccc15b050 | ||
|
|
3d7d60644f | ||
|
|
5d9705ddc8 | ||
|
|
63f2226974 | ||
|
|
3a1221e7ed | ||
|
|
6c06c05233 | ||
|
|
2af3f42055 | ||
|
|
c4cb394d80 | ||
|
|
681e86e3d4 | ||
|
|
6fe797765f | ||
|
|
74e965b207 | ||
|
|
0e23fa3fee | ||
|
|
351cf65621 | ||
|
|
f3e3564178 | ||
|
|
5e8e16444c | ||
|
|
880ab20a6b | ||
|
|
66369c9541 | ||
|
|
58092a21de | ||
|
|
01f83c20d5 | ||
|
|
972dec0406 | ||
|
|
b599e93c5b | ||
|
|
f77ee8dd2e | ||
|
|
c89d24990c | ||
|
|
e6a61a5ec7 | ||
|
|
4326efae54 | ||
|
|
5d3f4be9a2 | ||
|
|
9b5bb79a72 | ||
|
|
a4a388aef7 | ||
|
|
7a4230414d | ||
|
|
239fe1d758 | ||
|
|
3f7690cf24 | ||
|
|
2e94f61043 | ||
|
|
a3ce22df79 | ||
|
|
f9a2c15361 | ||
|
|
3360ee7752 | ||
|
|
9c0cde64e5 | ||
|
|
748fe17e72 |
20
.travis.yml
20
.travis.yml
@@ -1,20 +0,0 @@
|
|||||||
language: go
|
|
||||||
|
|
||||||
go:
|
|
||||||
- 1.13.x
|
|
||||||
- 1.12.x
|
|
||||||
- 1.11.x
|
|
||||||
- 1.10.x
|
|
||||||
|
|
||||||
services:
|
|
||||||
- memcached
|
|
||||||
- redis-server
|
|
||||||
|
|
||||||
before_script:
|
|
||||||
- GO_FILES=$(find . -iname '*.go' -type f | grep -v /vendor/)
|
|
||||||
- go get golang.org/x/lint/golint
|
|
||||||
|
|
||||||
script:
|
|
||||||
- go test -v -race ./...
|
|
||||||
- go vet ./...
|
|
||||||
- golint -set_exit_status $(go list ./...)
|
|
||||||
20
README.md
20
README.md
@@ -1,11 +1,17 @@
|
|||||||
# WeChat SDK for Go
|
# WeChat SDK for Go
|
||||||
[](https://travis-ci.org/silenceper/wechat)
|

|
||||||
[](https://goreportcard.com/report/github.com/silenceper/wechat)
|
[](https://goreportcard.com/report/github.com/silenceper/wechat)
|
||||||
[](http://godoc.org/github.com/silenceper/wechat)
|
[](https://pkg.go.dev/github.com/silenceper/wechat/v2?tab=doc)
|
||||||
|
|
||||||
使用Golang开发的微信SDK,简单、易用。
|
使用Golang开发的微信SDK,简单、易用。
|
||||||
|
>当前版本为2.0版本
|
||||||
|
|
||||||
|
|
||||||
|
## 文档 && 例子
|
||||||
|
[Wechat SDK 2.0 文档](http://silenceper.com/wechat)
|
||||||
|
|
||||||
|
[Wechat SDK 2.0 例子](https://github.com/gowechat/example)
|
||||||
|
|
||||||
## 快速开始
|
## 快速开始
|
||||||
|
|
||||||
以下是一个微信公众号处理消息接收以及回复的例子:
|
以下是一个微信公众号处理消息接收以及回复的例子:
|
||||||
@@ -44,10 +50,6 @@ server.Send()
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 文档
|
|
||||||
[Wechat SDK 2.0 文档](http://silenceper.com/wechat)
|
|
||||||
|
|
||||||
|
|
||||||
## 目录说明
|
## 目录说明
|
||||||
- officialaccount: 微信公众号API
|
- officialaccount: 微信公众号API
|
||||||
- miniprogram: 小程序API
|
- miniprogram: 小程序API
|
||||||
@@ -57,10 +59,14 @@ server.Send()
|
|||||||
- work:企业微信
|
- work:企业微信
|
||||||
- aispeech:智能对话
|
- aispeech:智能对话
|
||||||
|
|
||||||
## 如何贡献
|
## 贡献
|
||||||
- 提交issue,描述需要贡献的内容
|
- 提交issue,描述需要贡献的内容
|
||||||
- 完成更改后,提交PR
|
- 完成更改后,提交PR
|
||||||
|
|
||||||
|
感谢以下成员贡献.
|
||||||
|
<a href="https://github.com/silenceper/wechat/graphs/contributors"><img src="https://opencollective.com/gowechat/contributors.svg?width=890&button=false" /></a>
|
||||||
|
## 公众号
|
||||||
|

|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
16
cache/memcache_test.go
vendored
16
cache/memcache_test.go
vendored
@@ -3,6 +3,9 @@ package cache
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/bradfitz/gomemcache/memcache"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestMemcache(t *testing.T) {
|
func TestMemcache(t *testing.T) {
|
||||||
@@ -16,13 +19,22 @@ func TestMemcache(t *testing.T) {
|
|||||||
if !mem.IsExist("username") {
|
if !mem.IsExist("username") {
|
||||||
t.Error("IsExist Error")
|
t.Error("IsExist Error")
|
||||||
}
|
}
|
||||||
|
exists := mem.IsExist("unknown-key")
|
||||||
|
assert.Equal(t, false, exists)
|
||||||
|
|
||||||
name := mem.Get("username").(string)
|
name := mem.Get("username").(string)
|
||||||
if name != "silenceper" {
|
if name != "" {
|
||||||
t.Error("get Error")
|
if name != "silenceper" {
|
||||||
|
t.Error("get Error")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
data := mem.Get("unknown-key")
|
||||||
|
assert.Nil(t, data)
|
||||||
|
|
||||||
if err = mem.Delete("username"); err != nil {
|
if err = mem.Delete("username"); err != nil {
|
||||||
t.Errorf("delete Error , err=%v", err)
|
t.Errorf("delete Error , err=%v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
err = mem.Delete("unknown-key")
|
||||||
|
assert.Equal(t, memcache.ErrCacheMiss, err)
|
||||||
}
|
}
|
||||||
|
|||||||
7
cache/redis.go
vendored
7
cache/redis.go
vendored
@@ -19,7 +19,7 @@ type RedisOpts struct {
|
|||||||
Database int `yml:"database" json:"database"`
|
Database int `yml:"database" json:"database"`
|
||||||
MaxIdle int `yml:"max_idle" json:"max_idle"`
|
MaxIdle int `yml:"max_idle" json:"max_idle"`
|
||||||
MaxActive int `yml:"max_active" json:"max_active"`
|
MaxActive int `yml:"max_active" json:"max_active"`
|
||||||
IdleTimeout int32 `yml:"idle_timeout" json:"idle_timeout"` //second
|
IdleTimeout int `yml:"idle_timeout" json:"idle_timeout"` //second
|
||||||
}
|
}
|
||||||
|
|
||||||
//NewRedis 实例化
|
//NewRedis 实例化
|
||||||
@@ -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
|
||||||
|
|||||||
1
cache/redis_test.go
vendored
1
cache/redis_test.go
vendored
@@ -10,6 +10,7 @@ func TestRedis(t *testing.T) {
|
|||||||
Host: "127.0.0.1:6379",
|
Host: "127.0.0.1:6379",
|
||||||
}
|
}
|
||||||
redis := NewRedis(opts)
|
redis := NewRedis(opts)
|
||||||
|
redis.SetConn(redis.conn)
|
||||||
var err error
|
var err error
|
||||||
timeoutDuration := 1 * time.Second
|
timeoutDuration := 1 * time.Second
|
||||||
|
|
||||||
|
|||||||
6
credential/access_token.go
Normal file
6
credential/access_token.go
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
package credential
|
||||||
|
|
||||||
|
//AccessTokenHandle AccessToken 接口
|
||||||
|
type AccessTokenHandle interface {
|
||||||
|
GetAccessToken() (accessToken string, err error)
|
||||||
|
}
|
||||||
99
credential/default_access_token.go
Normal file
99
credential/default_access_token.go
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
package credential
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/cache"
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
//AccessTokenURL 获取access_token的接口
|
||||||
|
accessTokenURL = "https://api.weixin.qq.com/cgi-bin/token"
|
||||||
|
//CacheKeyOfficialAccountPrefix 微信公众号cache key前缀
|
||||||
|
CacheKeyOfficialAccountPrefix = "gowechat_officialaccount_"
|
||||||
|
//CacheKeyMiniProgramPrefix 小程序cache key前缀
|
||||||
|
CacheKeyMiniProgramPrefix = "gowechat_miniprogram_"
|
||||||
|
)
|
||||||
|
|
||||||
|
//DefaultAccessToken 默认AccessToken 获取
|
||||||
|
type DefaultAccessToken struct {
|
||||||
|
appID string
|
||||||
|
appSecret string
|
||||||
|
cacheKeyPrefix string
|
||||||
|
cache cache.Cache
|
||||||
|
accessTokenLock *sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewDefaultAccessToken new DefaultAccessToken
|
||||||
|
func NewDefaultAccessToken(appID, appSecret, cacheKeyPrefix string, cache cache.Cache) AccessTokenHandle {
|
||||||
|
if cache == nil {
|
||||||
|
panic("cache is ineed")
|
||||||
|
}
|
||||||
|
return &DefaultAccessToken{
|
||||||
|
appID: appID,
|
||||||
|
appSecret: appSecret,
|
||||||
|
cache: cache,
|
||||||
|
cacheKeyPrefix: cacheKeyPrefix,
|
||||||
|
accessTokenLock: new(sync.Mutex),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//ResAccessToken struct
|
||||||
|
type ResAccessToken struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
ExpiresIn int64 `json:"expires_in"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetAccessToken 获取access_token,先从cache中获取,没有则从服务端获取
|
||||||
|
func (ak *DefaultAccessToken) 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.appID)
|
||||||
|
val := ak.cache.Get(accessTokenCacheKey)
|
||||||
|
if val != nil {
|
||||||
|
accessToken = val.(string)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//cache失效,从微信服务器获取
|
||||||
|
var resAccessToken ResAccessToken
|
||||||
|
resAccessToken, err = GetTokenFromServer(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
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetTokenFromServer 强制从微信服务器获取token
|
||||||
|
func GetTokenFromServer(appID, appSecret string) (resAccessToken ResAccessToken, err error) {
|
||||||
|
url := fmt.Sprintf("%s?grant_type=client_credential&appid=%s&secret=%s", accessTokenURL, appID, appSecret)
|
||||||
|
var body []byte
|
||||||
|
body, err = util.HTTPGet(url)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = json.Unmarshal(body, &resAccessToken)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if resAccessToken.ErrMsg != "" {
|
||||||
|
err = fmt.Errorf("get access_token error : errcode=%v , errormsg=%v", resAccessToken.ErrCode, resAccessToken.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
18
credential/default_access_token_test.go
Normal file
18
credential/default_access_token_test.go
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
package credential
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"gopkg.in/h2non/gock.v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetTicketFromServer(t *testing.T) {
|
||||||
|
defer gock.Off()
|
||||||
|
gock.New(getTicketURL).Reply(200).JSON(&ResTicket{Ticket: "mock-ticket", ExpiresIn: 10})
|
||||||
|
ticket, err := GetTicketFromServer("arg-ak")
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Equal(t, int64(0), ticket.ErrCode)
|
||||||
|
assert.Equal(t, "mock-ticket", ticket.Ticket, "they should be equal")
|
||||||
|
assert.Equal(t, int64(10), ticket.ExpiresIn, "they should be equal")
|
||||||
|
}
|
||||||
80
credential/default_js_ticket.go
Normal file
80
credential/default_js_ticket.go
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
package credential
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/cache"
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
//获取ticket的url
|
||||||
|
const getTicketURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi"
|
||||||
|
|
||||||
|
//DefaultJsTicket 默认获取js ticket方法
|
||||||
|
type DefaultJsTicket struct {
|
||||||
|
appID string
|
||||||
|
cacheKeyPrefix string
|
||||||
|
cache cache.Cache
|
||||||
|
//jsAPITicket 读写锁 同一个AppID一个
|
||||||
|
jsAPITicketLock *sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewDefaultJsTicket new
|
||||||
|
func NewDefaultJsTicket(appID string, cacheKeyPrefix string, cache cache.Cache) JsTicketHandle {
|
||||||
|
return &DefaultJsTicket{
|
||||||
|
appID: appID,
|
||||||
|
cache: cache,
|
||||||
|
cacheKeyPrefix: cacheKeyPrefix,
|
||||||
|
jsAPITicketLock: new(sync.Mutex),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResTicket 请求jsapi_tikcet返回结果
|
||||||
|
type ResTicket struct {
|
||||||
|
util.CommonError
|
||||||
|
|
||||||
|
Ticket string `json:"ticket"`
|
||||||
|
ExpiresIn int64 `json:"expires_in"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetTicket 获取jsapi_ticket
|
||||||
|
func (js *DefaultJsTicket) GetTicket(accessToken string) (ticketStr string, err error) {
|
||||||
|
js.jsAPITicketLock.Lock()
|
||||||
|
defer js.jsAPITicketLock.Unlock()
|
||||||
|
|
||||||
|
//先从cache中取
|
||||||
|
jsAPITicketCacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", js.cacheKeyPrefix, js.appID)
|
||||||
|
val := js.cache.Get(jsAPITicketCacheKey)
|
||||||
|
if val != nil {
|
||||||
|
ticketStr = val.(string)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var ticket ResTicket
|
||||||
|
ticket, err = GetTicketFromServer(accessToken)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
expires := ticket.ExpiresIn - 1500
|
||||||
|
err = js.cache.Set(jsAPITicketCacheKey, ticket.Ticket, time.Duration(expires)*time.Second)
|
||||||
|
ticketStr = ticket.Ticket
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetTicketFromServer 从服务器中获取ticket
|
||||||
|
func GetTicketFromServer(accessToken string) (ticket ResTicket, err error) {
|
||||||
|
var response []byte
|
||||||
|
url := fmt.Sprintf(getTicketURL, accessToken)
|
||||||
|
response, err = util.HTTPGet(url)
|
||||||
|
err = json.Unmarshal(response, &ticket)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if ticket.ErrCode != 0 {
|
||||||
|
err = fmt.Errorf("getTicket Error : errcode=%d , errmsg=%s", ticket.ErrCode, ticket.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
7
credential/js_ticket.go
Normal file
7
credential/js_ticket.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package credential
|
||||||
|
|
||||||
|
//JsTicketHandle js ticket获取
|
||||||
|
type JsTicketHandle interface {
|
||||||
|
//GetTicket 获取ticket
|
||||||
|
GetTicket(accessToken string) (ticket string, err error)
|
||||||
|
}
|
||||||
2
go.mod
2
go.mod
@@ -8,5 +8,7 @@ require (
|
|||||||
github.com/gomodule/redigo v1.8.1
|
github.com/gomodule/redigo v1.8.1
|
||||||
github.com/sirupsen/logrus v1.6.0
|
github.com/sirupsen/logrus v1.6.0
|
||||||
github.com/spf13/cast v1.3.1
|
github.com/spf13/cast v1.3.1
|
||||||
|
github.com/stretchr/testify v1.5.1
|
||||||
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37
|
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37
|
||||||
|
gopkg.in/h2non/gock.v1 v1.0.15
|
||||||
)
|
)
|
||||||
|
|||||||
10
go.sum
10
go.sum
@@ -4,17 +4,25 @@ github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8
|
|||||||
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/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.1 h1:Abmo0bI7Xf0IhdIPc7HZQzZcShdnmxeoVuDDtIQp8N8=
|
||||||
github.com/gomodule/redigo v1.8.1/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0=
|
github.com/gomodule/redigo v1.8.1/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0=
|
||||||
|
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw=
|
||||||
|
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
|
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||||
|
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/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.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
|
||||||
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
||||||
|
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 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
|
||||||
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=
|
||||||
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-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw=
|
||||||
@@ -29,5 +37,7 @@ golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
|
|||||||
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 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/h2non/gock.v1 v1.0.15 h1:SzLqcIlb/fDfg7UvukMpNcWsu7sI5tWwL+KCATZqks0=
|
||||||
|
gopkg.in/h2non/gock.v1 v1.0.15/go.mod h1:sX4zAkdYX1TRGJ2JY156cFspQn4yRWn6p9EMdODlynE=
|
||||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
gopkg.in/yaml.v2 v2.2.2 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=
|
||||||
|
|||||||
@@ -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,15 +0,0 @@
|
|||||||
package basic
|
|
||||||
|
|
||||||
import "github.com/silenceper/wechat/v2/miniprogram/context"
|
|
||||||
|
|
||||||
//Basic struct
|
|
||||||
type Basic struct {
|
|
||||||
*context.Context
|
|
||||||
}
|
|
||||||
|
|
||||||
//NewBasic 实例
|
|
||||||
func NewBasic(context *context.Context) *Basic {
|
|
||||||
basic := new(Basic)
|
|
||||||
basic.Context = context
|
|
||||||
return basic
|
|
||||||
}
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
package context
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
//AccessTokenURL 获取access_token的接口
|
|
||||||
AccessTokenURL = "https://api.weixin.qq.com/cgi-bin/token"
|
|
||||||
//CacheKeyPrefix cache前缀
|
|
||||||
CacheKeyPrefix = "gowechat_miniprogram_"
|
|
||||||
)
|
|
||||||
|
|
||||||
//ResAccessToken struct
|
|
||||||
type ResAccessToken struct {
|
|
||||||
util.CommonError
|
|
||||||
|
|
||||||
AccessToken string `json:"access_token"`
|
|
||||||
ExpiresIn int64 `json:"expires_in"`
|
|
||||||
}
|
|
||||||
|
|
||||||
//GetAccessTokenFunc 获取 access token 的函数签名
|
|
||||||
type GetAccessTokenFunc func(ctx *Context) (accessToken string, err error)
|
|
||||||
|
|
||||||
//SetAccessTokenLock 设置读写锁(一个appID一个读写锁)
|
|
||||||
func (ctx *Context) SetAccessTokenLock(l *sync.RWMutex) {
|
|
||||||
ctx.accessTokenLock = l
|
|
||||||
}
|
|
||||||
|
|
||||||
//SetGetAccessTokenFunc 设置自定义获取accessToken的方式, 需要自己实现缓存
|
|
||||||
func (ctx *Context) SetGetAccessTokenFunc(f GetAccessTokenFunc) {
|
|
||||||
ctx.accessTokenFunc = f
|
|
||||||
}
|
|
||||||
|
|
||||||
//GetAccessToken 获取access_token
|
|
||||||
func (ctx *Context) GetAccessToken() (accessToken string, err error) {
|
|
||||||
ctx.accessTokenLock.Lock()
|
|
||||||
defer ctx.accessTokenLock.Unlock()
|
|
||||||
|
|
||||||
if ctx.accessTokenFunc != nil {
|
|
||||||
return ctx.accessTokenFunc(ctx)
|
|
||||||
}
|
|
||||||
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", CacheKeyPrefix, ctx.AppID)
|
|
||||||
val := ctx.Cache.Get(accessTokenCacheKey)
|
|
||||||
if val != nil {
|
|
||||||
accessToken = val.(string)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
//从微信服务器获取
|
|
||||||
var resAccessToken ResAccessToken
|
|
||||||
resAccessToken, err = ctx.GetAccessTokenFromServer()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
accessToken = resAccessToken.AccessToken
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
//GetAccessTokenFromServer 强制从微信服务器获取token
|
|
||||||
func (ctx *Context) GetAccessTokenFromServer() (resAccessToken ResAccessToken, err error) {
|
|
||||||
url := fmt.Sprintf("%s?grant_type=client_credential&appid=%s&secret=%s", AccessTokenURL, ctx.AppID, ctx.AppSecret)
|
|
||||||
var body []byte
|
|
||||||
body, err = util.HTTPGet(url)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
err = json.Unmarshal(body, &resAccessToken)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if resAccessToken.ErrMsg != "" {
|
|
||||||
err = fmt.Errorf("get access_token error : errcode=%v , errormsg=%v", resAccessToken.ErrCode, resAccessToken.ErrMsg)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", CacheKeyPrefix, ctx.AppID)
|
|
||||||
expires := resAccessToken.ExpiresIn - 1500
|
|
||||||
err = ctx.Cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
@@ -1,18 +1,12 @@
|
|||||||
package context
|
package context
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"sync"
|
"github.com/silenceper/wechat/v2/credential"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/config"
|
"github.com/silenceper/wechat/v2/miniprogram/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Context struct
|
// Context struct
|
||||||
type Context struct {
|
type Context struct {
|
||||||
*config.Config
|
*config.Config
|
||||||
|
credential.AccessTokenHandle
|
||||||
//accessTokenLock 读写锁 同一个AppID一个
|
|
||||||
accessTokenLock *sync.RWMutex
|
|
||||||
|
|
||||||
//accessTokenFunc 自定义获取 access token 的方法
|
|
||||||
accessTokenFunc GetAccessTokenFunc
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
package basic
|
package encryptor
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/aes"
|
"crypto/aes"
|
||||||
@@ -6,8 +6,23 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/miniprogram/context"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//Encryptor struct
|
||||||
|
type Encryptor struct {
|
||||||
|
*context.Context
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewEncryptor 实例
|
||||||
|
func NewEncryptor(context *context.Context) *Encryptor {
|
||||||
|
basic := new(Encryptor)
|
||||||
|
basic.Context = context
|
||||||
|
return basic
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// ErrAppIDNotMatch appid不匹配
|
// ErrAppIDNotMatch appid不匹配
|
||||||
ErrAppIDNotMatch = errors.New("app id not match")
|
ErrAppIDNotMatch = errors.New("app id not match")
|
||||||
@@ -19,8 +34,8 @@ var (
|
|||||||
ErrInvalidPKCS7Padding = errors.New("invalid padding on input")
|
ErrInvalidPKCS7Padding = errors.New("invalid padding on input")
|
||||||
)
|
)
|
||||||
|
|
||||||
// UserInfo 用户信息
|
// PlainData 用户信息/手机号信息
|
||||||
type UserInfo 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"`
|
||||||
@@ -30,18 +45,10 @@ type UserInfo struct {
|
|||||||
Country string `json:"country"`
|
Country string `json:"country"`
|
||||||
AvatarURL string `json:"avatarUrl"`
|
AvatarURL string `json:"avatarUrl"`
|
||||||
Language string `json:"language"`
|
Language string `json:"language"`
|
||||||
Watermark struct {
|
|
||||||
Timestamp int64 `json:"timestamp"`
|
|
||||||
AppID string `json:"appid"`
|
|
||||||
} `json:"watermark"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// PhoneInfo 用户手机号
|
|
||||||
type PhoneInfo struct {
|
|
||||||
PhoneNumber string `json:"phoneNumber"`
|
PhoneNumber string `json:"phoneNumber"`
|
||||||
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"`
|
||||||
@@ -96,35 +103,18 @@ func getCipherText(sessionKey, encryptedData, iv string) ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Decrypt 解密数据
|
// Decrypt 解密数据
|
||||||
func (basic *Basic) Decrypt(sessionKey, encryptedData, iv string) (*UserInfo, 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
|
||||||
}
|
}
|
||||||
var userInfo UserInfo
|
var plainData PlainData
|
||||||
err = json.Unmarshal(cipherText, &userInfo)
|
err = json.Unmarshal(cipherText, &plainData)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if userInfo.Watermark.AppID != basic.AppID {
|
if plainData.Watermark.AppID != encryptor.AppID {
|
||||||
return nil, ErrAppIDNotMatch
|
return nil, ErrAppIDNotMatch
|
||||||
}
|
}
|
||||||
return &userInfo, nil
|
return &plainData, nil
|
||||||
}
|
|
||||||
|
|
||||||
// DecryptPhone 解密数据(手机)
|
|
||||||
func (basic *Basic) DecryptPhone(sessionKey, encryptedData, iv string) (*PhoneInfo, error) {
|
|
||||||
cipherText, err := getCipherText(sessionKey, encryptedData, iv)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var phoneInfo PhoneInfo
|
|
||||||
err = json.Unmarshal(cipherText, &phoneInfo)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if phoneInfo.Watermark.AppID != basic.AppID {
|
|
||||||
return nil, ErrAppIDNotMatch
|
|
||||||
}
|
|
||||||
return &phoneInfo, nil
|
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
package miniprogram
|
package miniprogram
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"sync"
|
"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/basic"
|
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/config"
|
"github.com/silenceper/wechat/v2/miniprogram/config"
|
||||||
"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/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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -19,24 +19,27 @@ type MiniProgram struct {
|
|||||||
|
|
||||||
//NewMiniProgram 实例化小程序API
|
//NewMiniProgram 实例化小程序API
|
||||||
func NewMiniProgram(cfg *config.Config) *MiniProgram {
|
func NewMiniProgram(cfg *config.Config) *MiniProgram {
|
||||||
if cfg.Cache == nil {
|
defaultAkHandle := credential.NewDefaultAccessToken(cfg.AppID, cfg.AppSecret, credential.CacheKeyMiniProgramPrefix, cfg.Cache)
|
||||||
panic("cache未设置")
|
|
||||||
}
|
|
||||||
ctx := &context.Context{
|
ctx := &context.Context{
|
||||||
Config: cfg,
|
Config: cfg,
|
||||||
|
AccessTokenHandle: defaultAkHandle,
|
||||||
}
|
}
|
||||||
ctx.SetAccessTokenLock(new(sync.RWMutex))
|
|
||||||
return &MiniProgram{ctx}
|
return &MiniProgram{ctx}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//SetAccessTokenHandle 自定义access_token获取方式
|
||||||
|
func (miniProgram *MiniProgram) SetAccessTokenHandle(accessTokenHandle credential.AccessTokenHandle) {
|
||||||
|
miniProgram.ctx.AccessTokenHandle = accessTokenHandle
|
||||||
|
}
|
||||||
|
|
||||||
// GetContext get Context
|
// GetContext get Context
|
||||||
func (miniProgram *MiniProgram) GetContext() *context.Context {
|
func (miniProgram *MiniProgram) GetContext() *context.Context {
|
||||||
return miniProgram.ctx
|
return miniProgram.ctx
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetBasic 基础接口(小程序加解密)
|
// GetEncryptor 小程序加解密
|
||||||
func (miniProgram *MiniProgram) GetBasic() *basic.Basic {
|
func (miniProgram *MiniProgram) GetEncryptor() *encryptor.Encryptor {
|
||||||
return basic.NewBasic(miniProgram.ctx)
|
return encryptor.NewEncryptor(miniProgram.ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
//GetAuth 登录/用户信息相关接口
|
//GetAuth 登录/用户信息相关接口
|
||||||
@@ -58,3 +61,8 @@ 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)
|
||||||
|
}
|
||||||
|
|||||||
52
miniprogram/subscribe/subscribe.go
Normal file
52
miniprogram/subscribe/subscribe.go
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
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"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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 string `json:"value"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
|
||||||
|
return util.DecodeWithCommonError(response, "Send")
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
@@ -1,6 +1,21 @@
|
|||||||
package basic
|
package basic
|
||||||
|
|
||||||
import "github.com/silenceper/wechat/v2/officialaccount/context"
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/officialaccount/context"
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
//获取微信服务器IP地址
|
||||||
|
//文档:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_the_WeChat_server_IP_address.html
|
||||||
|
getCallbackIPURL = "https://api.weixin.qq.com/cgi-bin/getcallbackip"
|
||||||
|
getAPIDomainIPURL = "https://api.weixin.qq.com/cgi-bin/get_api_domain_ip"
|
||||||
|
|
||||||
|
//清理接口调用次数
|
||||||
|
clearQuotaURL = "https://api.weixin.qq.com/cgi-bin/clear_quota"
|
||||||
|
)
|
||||||
|
|
||||||
//Basic struct
|
//Basic struct
|
||||||
type Basic struct {
|
type Basic struct {
|
||||||
@@ -13,3 +28,57 @@ func NewBasic(context *context.Context) *Basic {
|
|||||||
basic.Context = context
|
basic.Context = context
|
||||||
return basic
|
return basic
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//IPListRes 获取微信服务器IP地址 返回结果
|
||||||
|
type IPListRes struct {
|
||||||
|
util.CommonError
|
||||||
|
IPList []string `json:"ip_list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetCallbackIP 获取微信callback IP地址
|
||||||
|
func (basic *Basic) GetCallbackIP() ([]string, error) {
|
||||||
|
ak, err := basic.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf("%s?access_token=%s", getCallbackIPURL, ak)
|
||||||
|
data, err := util.HTTPGet(url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ipListRes := &IPListRes{}
|
||||||
|
err = util.DecodeWithError(data, ipListRes, "GetCallbackIP")
|
||||||
|
return ipListRes.IPList, err
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetAPIDomainIP 获取微信API接口 IP地址
|
||||||
|
func (basic *Basic) GetAPIDomainIP() ([]string, error) {
|
||||||
|
ak, err := basic.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf("%s?access_token=%s", getAPIDomainIPURL, ak)
|
||||||
|
data, err := util.HTTPGet(url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ipListRes := &IPListRes{}
|
||||||
|
err = util.DecodeWithError(data, ipListRes, "GetAPIDomainIP")
|
||||||
|
return ipListRes.IPList, err
|
||||||
|
}
|
||||||
|
|
||||||
|
//ClearQuota 清理接口调用次数
|
||||||
|
func (basic *Basic) ClearQuota() error {
|
||||||
|
ak, err := basic.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf("%s?access_token=%s", clearQuotaURL, ak)
|
||||||
|
data, err := util.PostJSON(url, map[string]string{
|
||||||
|
"appid": basic.AppID,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return util.DecodeWithCommonError(data, "ClearQuota")
|
||||||
|
}
|
||||||
|
|||||||
279
officialaccount/broadcast/broadcast.go
Normal file
279
officialaccount/broadcast/broadcast.go
Normal file
@@ -0,0 +1,279 @@
|
|||||||
|
package broadcast
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/officialaccount/context"
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
sendURLByTag = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall"
|
||||||
|
sendURLByOpenID = "https://api.weixin.qq.com/cgi-bin/message/mass/send"
|
||||||
|
deleteSendURL ="https://api.weixin.qq.com/cgi-bin/message/mass/delete"
|
||||||
|
)
|
||||||
|
|
||||||
|
//MsgType 发送消息类型
|
||||||
|
type MsgType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
//MsgTypeNews 图文消息
|
||||||
|
MsgTypeNews MsgType = "mpnews"
|
||||||
|
//MsgTypeText 文本
|
||||||
|
MsgTypeText MsgType = "text"
|
||||||
|
//MsgTypeVoice 语音/音频
|
||||||
|
MsgTypeVoice MsgType = "voice"
|
||||||
|
//MsgTypeImage 图片
|
||||||
|
MsgTypeImage MsgType = "image"
|
||||||
|
//MsgTypeVideo 视频
|
||||||
|
MsgTypeVideo MsgType = "mpvideo"
|
||||||
|
//MsgTypeWxCard 卡券
|
||||||
|
MsgTypeWxCard MsgType = "wxcard"
|
||||||
|
)
|
||||||
|
|
||||||
|
//Broadcast 群发消息
|
||||||
|
type Broadcast struct {
|
||||||
|
*context.Context
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewBroadcast new
|
||||||
|
func NewBroadcast(ctx *context.Context) *Broadcast {
|
||||||
|
return &Broadcast{ctx}
|
||||||
|
}
|
||||||
|
|
||||||
|
//User 发送的用户
|
||||||
|
type User struct {
|
||||||
|
TagID int64
|
||||||
|
OpenID []string
|
||||||
|
}
|
||||||
|
|
||||||
|
//Result 群发返回结果
|
||||||
|
type Result struct {
|
||||||
|
util.CommonError
|
||||||
|
MsgID int64 `json:"msg_id"`
|
||||||
|
MsgDataID int64 `json:"msg_data_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//sendRequest 发送请求的数据
|
||||||
|
type sendRequest struct {
|
||||||
|
//根据tag获全部发送
|
||||||
|
Filter map[string]interface{} `json:"filter,omitempty"`
|
||||||
|
//根据OpenID发送
|
||||||
|
ToUser interface{} `json:"touser,omitempty"`
|
||||||
|
//发送文本
|
||||||
|
Text map[string]interface{} `json:"text,omitempty"`
|
||||||
|
//发送图文消息
|
||||||
|
Mpnews map[string]interface{} `json:"mpnews,omitempty"`
|
||||||
|
//发送语音
|
||||||
|
Voice map[string]interface{} `json:"voice,omitempty"`
|
||||||
|
//发送图片
|
||||||
|
Images *Image `json:"images,omitempty"`
|
||||||
|
//发送卡券
|
||||||
|
WxCard map[string]interface{} `json:"wxcard,omitempty"`
|
||||||
|
MsgType MsgType `json:"msgtype"`
|
||||||
|
SendIgnoreReprint int32 `json:"send_ignore_reprint,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//Image 发送图片
|
||||||
|
type Image struct{
|
||||||
|
MediaIDs []string `json:"media_ids"`
|
||||||
|
Recommend string `json:"recommend"`
|
||||||
|
NeedOpenComment int32 `json:"need_open_comment"`
|
||||||
|
OnlyFansCanComment int32 `json:"only_fans_can_comment"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//SendText 群发文本
|
||||||
|
//user 为nil,表示全员发送
|
||||||
|
//&User{TagID:2} 根据tag发送
|
||||||
|
//&User{OpenID:[]string("xxx","xxx")} 根据openid发送
|
||||||
|
func (broadcast *Broadcast) SendText(user *User, content string) (*Result, error) {
|
||||||
|
ak, err := broadcast.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req := &sendRequest{
|
||||||
|
ToUser: nil,
|
||||||
|
MsgType: MsgTypeText,
|
||||||
|
}
|
||||||
|
req.Text=map[string]interface{}{
|
||||||
|
"content":content,
|
||||||
|
}
|
||||||
|
req,sendURL:=broadcast.chooseTagOrOpenID(user,req)
|
||||||
|
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
||||||
|
data, err := util.PostJSON(url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
res := &Result{}
|
||||||
|
err = util.DecodeWithError(data, res, "SendText")
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
|
||||||
|
//SendNews 发送图文
|
||||||
|
func (broadcast *Broadcast) SendNews(user *User, mediaID string,ignoreReprint bool) (*Result, error) {
|
||||||
|
ak, err := broadcast.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req := &sendRequest{
|
||||||
|
ToUser: nil,
|
||||||
|
MsgType: MsgTypeNews,
|
||||||
|
}
|
||||||
|
if ignoreReprint{
|
||||||
|
req.SendIgnoreReprint=1
|
||||||
|
}
|
||||||
|
req.Mpnews=map[string]interface{}{
|
||||||
|
"media_id":mediaID,
|
||||||
|
}
|
||||||
|
req,sendURL:=broadcast.chooseTagOrOpenID(user,req)
|
||||||
|
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
||||||
|
data, err := util.PostJSON(url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
res := &Result{}
|
||||||
|
err = util.DecodeWithError(data, res, "SendNews")
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//SendVoice 发送语音
|
||||||
|
func (broadcast *Broadcast) SendVoice(user *User, mediaID string) (*Result, error) {
|
||||||
|
ak, err := broadcast.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req := &sendRequest{
|
||||||
|
ToUser: nil,
|
||||||
|
MsgType: MsgTypeVoice,
|
||||||
|
}
|
||||||
|
req.Voice=map[string]interface{}{
|
||||||
|
"media_id":mediaID,
|
||||||
|
}
|
||||||
|
req,sendURL:=broadcast.chooseTagOrOpenID(user,req)
|
||||||
|
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
||||||
|
data, err := util.PostJSON(url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
res := &Result{}
|
||||||
|
err = util.DecodeWithError(data, res, "SendVoice")
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
|
||||||
|
//SendImage 发送图片
|
||||||
|
func (broadcast *Broadcast) SendImage(user *User, images *Image) (*Result, error) {
|
||||||
|
ak, err := broadcast.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req := &sendRequest{
|
||||||
|
ToUser: nil,
|
||||||
|
MsgType: MsgTypeImage,
|
||||||
|
}
|
||||||
|
req.Images=images
|
||||||
|
req,sendURL:=broadcast.chooseTagOrOpenID(user,req)
|
||||||
|
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
||||||
|
data, err := util.PostJSON(url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
res := &Result{}
|
||||||
|
err = util.DecodeWithError(data, res, "SendImage")
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//SendVideo 发送视频
|
||||||
|
func (broadcast *Broadcast) SendVideo(user *User, mediaID string,title,description string) (*Result, error) {
|
||||||
|
ak, err := broadcast.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req := &sendRequest{
|
||||||
|
ToUser: nil,
|
||||||
|
MsgType: MsgTypeVideo,
|
||||||
|
}
|
||||||
|
req.Voice=map[string]interface{}{
|
||||||
|
"media_id":mediaID,
|
||||||
|
"title":title,
|
||||||
|
"description":description,
|
||||||
|
}
|
||||||
|
req,sendURL:=broadcast.chooseTagOrOpenID(user,req)
|
||||||
|
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
||||||
|
data, err := util.PostJSON(url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
res := &Result{}
|
||||||
|
err = util.DecodeWithError(data, res, "SendVideo")
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//SendWxCard 发送卡券
|
||||||
|
func (broadcast *Broadcast) SendWxCard(user *User, cardID string) (*Result, error) {
|
||||||
|
ak, err := broadcast.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req := &sendRequest{
|
||||||
|
ToUser: nil,
|
||||||
|
MsgType: MsgTypeWxCard,
|
||||||
|
}
|
||||||
|
req.WxCard=map[string]interface{}{
|
||||||
|
"card_id":cardID,
|
||||||
|
}
|
||||||
|
req,sendURL:=broadcast.chooseTagOrOpenID(user,req)
|
||||||
|
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
||||||
|
data, err := util.PostJSON(url, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
res := &Result{}
|
||||||
|
err = util.DecodeWithError(data, res, "SendWxCard")
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
//Delete 删除群发消息
|
||||||
|
func (broadcast *Broadcast) Delete(msgID int64 ,articleIDx int64) error {
|
||||||
|
ak, err := broadcast.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req := map[string]interface{}{
|
||||||
|
"msg_id": msgID,
|
||||||
|
"article_idx": articleIDx,
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf("%s?access_token=%s", deleteSendURL, ak)
|
||||||
|
data, err := util.PostJSON(url, req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return util.DecodeWithCommonError(data, "Delete")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//TODO 发送预览,群发消息状态,发送速度
|
||||||
|
|
||||||
|
func (broadcast *Broadcast) chooseTagOrOpenID(user *User,req *sendRequest)(ret *sendRequest,url string){
|
||||||
|
sendURL:=""
|
||||||
|
if user == nil {
|
||||||
|
req.Filter=map[string]interface{}{
|
||||||
|
"is_to_all":true,
|
||||||
|
}
|
||||||
|
sendURL=sendURLByTag
|
||||||
|
} 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return req,sendURL
|
||||||
|
}
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
package context
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
//AccessTokenURL 获取access_token的接口
|
|
||||||
AccessTokenURL = "https://api.weixin.qq.com/cgi-bin/token"
|
|
||||||
//CacheKeyPrefix 微信公众号cache key前缀
|
|
||||||
CacheKeyPrefix = "gowechat_officialaccount_"
|
|
||||||
)
|
|
||||||
|
|
||||||
//ResAccessToken struct
|
|
||||||
type ResAccessToken struct {
|
|
||||||
util.CommonError
|
|
||||||
|
|
||||||
AccessToken string `json:"access_token"`
|
|
||||||
ExpiresIn int64 `json:"expires_in"`
|
|
||||||
}
|
|
||||||
|
|
||||||
//GetAccessTokenFunc 获取 access token 的函数签名
|
|
||||||
type GetAccessTokenFunc func(ctx *Context) (accessToken string, err error)
|
|
||||||
|
|
||||||
//SetAccessTokenLock 设置读写锁(一个appID一个读写锁)
|
|
||||||
func (ctx *Context) SetAccessTokenLock(l *sync.RWMutex) {
|
|
||||||
ctx.accessTokenLock = l
|
|
||||||
}
|
|
||||||
|
|
||||||
//SetGetAccessTokenFunc 设置自定义获取accessToken的方式, 需要自己实现缓存
|
|
||||||
func (ctx *Context) SetGetAccessTokenFunc(f GetAccessTokenFunc) {
|
|
||||||
ctx.accessTokenFunc = f
|
|
||||||
}
|
|
||||||
|
|
||||||
//GetAccessToken 获取access_token
|
|
||||||
func (ctx *Context) GetAccessToken() (accessToken string, err error) {
|
|
||||||
ctx.accessTokenLock.Lock()
|
|
||||||
defer ctx.accessTokenLock.Unlock()
|
|
||||||
|
|
||||||
if ctx.accessTokenFunc != nil {
|
|
||||||
return ctx.accessTokenFunc(ctx)
|
|
||||||
}
|
|
||||||
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", CacheKeyPrefix, ctx.AppID)
|
|
||||||
val := ctx.Cache.Get(accessTokenCacheKey)
|
|
||||||
if val != nil {
|
|
||||||
accessToken = val.(string)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
//从微信服务器获取
|
|
||||||
var resAccessToken ResAccessToken
|
|
||||||
resAccessToken, err = ctx.GetAccessTokenFromServer()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
accessToken = resAccessToken.AccessToken
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
//GetAccessTokenFromServer 强制从微信服务器获取token
|
|
||||||
func (ctx *Context) GetAccessTokenFromServer() (resAccessToken ResAccessToken, err error) {
|
|
||||||
url := fmt.Sprintf("%s?grant_type=client_credential&appid=%s&secret=%s", AccessTokenURL, ctx.AppID, ctx.AppSecret)
|
|
||||||
var body []byte
|
|
||||||
body, err = util.HTTPGet(url)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
err = json.Unmarshal(body, &resAccessToken)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if resAccessToken.ErrMsg != "" {
|
|
||||||
err = fmt.Errorf("get access_token error : errcode=%v , errormsg=%v", resAccessToken.ErrCode, resAccessToken.ErrMsg)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", CacheKeyPrefix, ctx.AppID)
|
|
||||||
expires := resAccessToken.ExpiresIn - 1500
|
|
||||||
err = ctx.Cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
@@ -1,31 +1,12 @@
|
|||||||
package context
|
package context
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"sync"
|
"github.com/silenceper/wechat/v2/credential"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/officialaccount/config"
|
"github.com/silenceper/wechat/v2/officialaccount/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Context struct
|
// Context struct
|
||||||
type Context struct {
|
type Context struct {
|
||||||
*config.Config
|
*config.Config
|
||||||
|
credential.AccessTokenHandle
|
||||||
//accessTokenLock 读写锁 同一个AppID一个
|
|
||||||
accessTokenLock *sync.RWMutex
|
|
||||||
|
|
||||||
//jsAPITicket 读写锁 同一个AppID一个
|
|
||||||
jsAPITicketLock *sync.RWMutex
|
|
||||||
|
|
||||||
//accessTokenFunc 自定义获取 access token 的方法
|
|
||||||
accessTokenFunc GetAccessTokenFunc
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetJsAPITicketLock 设置jsAPITicket的lock
|
|
||||||
func (ctx *Context) SetJsAPITicketLock(lock *sync.RWMutex) {
|
|
||||||
ctx.jsAPITicketLock = lock
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetJsAPITicketLock 获取jsAPITicket 的lock
|
|
||||||
func (ctx *Context) GetJsAPITicketLock() *sync.RWMutex {
|
|
||||||
return ctx.jsAPITicketLock
|
|
||||||
}
|
}
|
||||||
|
|||||||
270
officialaccount/datacube/broadcast.go
Normal file
270
officialaccount/datacube/broadcast.go
Normal file
@@ -0,0 +1,270 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
82
officialaccount/datacube/interface.go
Normal file
82
officialaccount/datacube/interface.go
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
252
officialaccount/datacube/message.go
Normal file
252
officialaccount/datacube/message.go
Normal file
@@ -0,0 +1,252 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
306
officialaccount/datacube/publisher.go
Normal file
306
officialaccount/datacube/publisher.go
Normal file
@@ -0,0 +1,306 @@
|
|||||||
|
package datacube
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"github.com/silenceper/wechat/v2/util"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
//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
|
||||||
|
|
||||||
|
Base 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
|
||||||
|
|
||||||
|
Base 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
|
||||||
|
|
||||||
|
Base 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 = json.Unmarshal(response, &resPublisherAdPos)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if resPublisherAdPos.CommonError.ErrCode != 0 {
|
||||||
|
err = fmt.Errorf("GetPublisherAdPosGeneral Error , errcode=%d , errmsg=%s", resPublisherAdPos.CommonError.ErrCode, resPublisherAdPos.CommonError.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if resPublisherAdPos.BaseResp.Ret != 0 {
|
||||||
|
err = fmt.Errorf("GetPublisherAdPosGeneral Error , errcode=%d , errmsg=%s", resPublisherAdPos.BaseResp.Ret, resPublisherAdPos.BaseResp.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if resPublisherAdPos.Base.Ret != 0 {
|
||||||
|
err = fmt.Errorf("GetPublisherAdPosGeneral Error , errcode=%d , errmsg=%s", resPublisherAdPos.Base.Ret, resPublisherAdPos.Base.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 = json.Unmarshal(response, &resPublisherCps)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if resPublisherCps.CommonError.ErrCode != 0 {
|
||||||
|
err = fmt.Errorf("GetPublisherCpsGeneral Error , errcode=%d , errmsg=%s", resPublisherCps.CommonError.ErrCode, resPublisherCps.CommonError.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if resPublisherCps.BaseResp.Ret != 0 {
|
||||||
|
err = fmt.Errorf("GetPublisherCpsGeneral Error , errcode=%d , errmsg=%s", resPublisherCps.BaseResp.Ret, resPublisherCps.BaseResp.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if resPublisherCps.Base.Ret != 0 {
|
||||||
|
err = fmt.Errorf("GetPublisherCpsGeneral Error , errcode=%d , errmsg=%s", resPublisherCps.Base.Ret, resPublisherCps.Base.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 = json.Unmarshal(response, &resPublisherSettlement)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if resPublisherSettlement.CommonError.ErrCode != 0 {
|
||||||
|
err = fmt.Errorf("GetPublisherSettlement Error , errcode=%d , errmsg=%s", resPublisherSettlement.CommonError.ErrCode, resPublisherSettlement.CommonError.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if resPublisherSettlement.BaseResp.Ret != 0 {
|
||||||
|
err = fmt.Errorf("GetPublisherSettlement Error , errcode=%d , errmsg=%s", resPublisherSettlement.BaseResp.Ret, resPublisherSettlement.BaseResp.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if resPublisherSettlement.Base.Ret != 0 {
|
||||||
|
err = fmt.Errorf("GetPublisherSettlement Error , errcode=%d , errmsg=%s", resPublisherSettlement.Base.Ret, resPublisherSettlement.Base.ErrMsg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
77
officialaccount/datacube/user.go
Normal file
77
officialaccount/datacube/user.go
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -1,19 +1,17 @@
|
|||||||
package js
|
package js
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
|
||||||
|
|
||||||
|
"github.com/silenceper/wechat/v2/credential"
|
||||||
"github.com/silenceper/wechat/v2/officialaccount/context"
|
"github.com/silenceper/wechat/v2/officialaccount/context"
|
||||||
"github.com/silenceper/wechat/v2/util"
|
"github.com/silenceper/wechat/v2/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
const getTicketURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi"
|
|
||||||
|
|
||||||
// Js struct
|
// Js struct
|
||||||
type Js struct {
|
type Js struct {
|
||||||
*context.Context
|
*context.Context
|
||||||
|
credential.JsTicketHandle
|
||||||
}
|
}
|
||||||
|
|
||||||
// Config 返回给用户jssdk配置信息
|
// Config 返回给用户jssdk配置信息
|
||||||
@@ -24,27 +22,31 @@ type Config struct {
|
|||||||
Signature string `json:"signature"`
|
Signature string `json:"signature"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// resTicket 请求jsapi_tikcet返回结果
|
|
||||||
type resTicket struct {
|
|
||||||
util.CommonError
|
|
||||||
|
|
||||||
Ticket string `json:"ticket"`
|
|
||||||
ExpiresIn int64 `json:"expires_in"`
|
|
||||||
}
|
|
||||||
|
|
||||||
//NewJs init
|
//NewJs init
|
||||||
func NewJs(context *context.Context) *Js {
|
func NewJs(context *context.Context) *Js {
|
||||||
js := new(Js)
|
js := new(Js)
|
||||||
js.Context = context
|
js.Context = context
|
||||||
|
jsTicketHandle := credential.NewDefaultJsTicket(context.AppID, credential.CacheKeyOfficialAccountPrefix, context.Cache)
|
||||||
|
js.SetJsTicketHandle(jsTicketHandle)
|
||||||
return js
|
return js
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//SetJsTicketHandle 自定义js ticket取值方式
|
||||||
|
func (js *Js) SetJsTicketHandle(ticketHandle credential.JsTicketHandle) {
|
||||||
|
js.JsTicketHandle = ticketHandle
|
||||||
|
}
|
||||||
|
|
||||||
//GetConfig 获取jssdk需要的配置参数
|
//GetConfig 获取jssdk需要的配置参数
|
||||||
//uri 为当前网页地址
|
//uri 为当前网页地址
|
||||||
func (js *Js) GetConfig(uri string) (config *Config, err error) {
|
func (js *Js) GetConfig(uri string) (config *Config, err error) {
|
||||||
config = new(Config)
|
config = new(Config)
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = js.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
var ticketStr string
|
var ticketStr string
|
||||||
ticketStr, err = js.GetTicket()
|
ticketStr, err = js.GetTicket(accessToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -60,50 +62,3 @@ func (js *Js) GetConfig(uri string) (config *Config, err error) {
|
|||||||
config.Signature = sigStr
|
config.Signature = sigStr
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
//GetTicket 获取jsapi_ticket
|
|
||||||
func (js *Js) GetTicket() (ticketStr string, err error) {
|
|
||||||
js.GetJsAPITicketLock().Lock()
|
|
||||||
defer js.GetJsAPITicketLock().Unlock()
|
|
||||||
|
|
||||||
//先从cache中取
|
|
||||||
jsAPITicketCacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", context.CacheKeyPrefix, js.AppID)
|
|
||||||
val := js.Cache.Get(jsAPITicketCacheKey)
|
|
||||||
if val != nil {
|
|
||||||
ticketStr = val.(string)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var ticket resTicket
|
|
||||||
ticket, err = js.getTicketFromServer()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ticketStr = ticket.Ticket
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
//getTicketFromServer 强制从服务器中获取ticket
|
|
||||||
func (js *Js) getTicketFromServer() (ticket resTicket, err error) {
|
|
||||||
var accessToken string
|
|
||||||
accessToken, err = js.GetAccessToken()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var response []byte
|
|
||||||
url := fmt.Sprintf(getTicketURL, accessToken)
|
|
||||||
response, err = util.HTTPGet(url)
|
|
||||||
err = json.Unmarshal(response, &ticket)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if ticket.ErrCode != 0 {
|
|
||||||
err = fmt.Errorf("getTicket Error : errcode=%d , errmsg=%s", ticket.ErrCode, ticket.ErrMsg)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
jsAPITicketCacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", context.CacheKeyPrefix, js.AppID)
|
|
||||||
expires := ticket.ExpiresIn - 1500
|
|
||||||
err = js.Cache.Set(jsAPITicketCacheKey, ticket.Ticket, time.Duration(expires)*time.Second)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -14,8 +14,22 @@ const (
|
|||||||
addMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/add_material"
|
addMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/add_material"
|
||||||
delMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/del_material"
|
delMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/del_material"
|
||||||
getMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/get_material"
|
getMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/get_material"
|
||||||
|
batchGetMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//PermanentMaterialType 永久素材类型
|
||||||
|
type PermanentMaterialType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
//PermanentMaterialTypeImage 永久素材图片类型(image)
|
||||||
|
PermanentMaterialTypeImage PermanentMaterialType = "image"
|
||||||
|
//PermanentMaterialTypeVideo 永久素材视频类型(video)
|
||||||
|
PermanentMaterialTypeVideo PermanentMaterialType = "video"
|
||||||
|
//PermanentMaterialTypeVoice 永久素材语音类型 (voice)
|
||||||
|
PermanentMaterialTypeVoice PermanentMaterialType = "voice"
|
||||||
|
//PermanentMaterialTypeNews 永久素材图文类型(news)
|
||||||
|
PermanentMaterialTypeNews PermanentMaterialType = "news"
|
||||||
|
)
|
||||||
//Material 素材管理
|
//Material 素材管理
|
||||||
type Material struct {
|
type Material struct {
|
||||||
*context.Context
|
*context.Context
|
||||||
@@ -55,6 +69,9 @@ func (material *Material) GetNews(id string) ([]*Article, error) {
|
|||||||
}
|
}
|
||||||
req.MediaID = id
|
req.MediaID = id
|
||||||
responseBytes, err := util.PostJSON(uri, req)
|
responseBytes, err := util.PostJSON(uri, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
var res struct {
|
var res struct {
|
||||||
NewsItem []*Article `json:"news_item"`
|
NewsItem []*Article `json:"news_item"`
|
||||||
@@ -91,6 +108,9 @@ func (material *Material) AddNews(articles []*Article) (mediaID string, err erro
|
|||||||
|
|
||||||
uri := fmt.Sprintf("%s?access_token=%s", addNewsURL, accessToken)
|
uri := fmt.Sprintf("%s?access_token=%s", addNewsURL, accessToken)
|
||||||
responseBytes, err := util.PostJSON(uri, req)
|
responseBytes, err := util.PostJSON(uri, req)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
var res resArticles
|
var res resArticles
|
||||||
err = json.Unmarshal(responseBytes, &res)
|
err = json.Unmarshal(responseBytes, &res)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -112,6 +132,7 @@ type resAddMaterial struct {
|
|||||||
func (material *Material) AddMaterial(mediaType MediaType, filename string) (mediaID string, url string, err error) {
|
func (material *Material) AddMaterial(mediaType MediaType, filename string) (mediaID string, url string, err error) {
|
||||||
if mediaType == MediaTypeVideo {
|
if mediaType == MediaTypeVideo {
|
||||||
err = errors.New("永久视频素材上传使用 AddVideo 方法")
|
err = errors.New("永久视频素材上传使用 AddVideo 方法")
|
||||||
|
return
|
||||||
}
|
}
|
||||||
var accessToken string
|
var accessToken string
|
||||||
accessToken, err = material.GetAccessToken()
|
accessToken, err = material.GetAccessToken()
|
||||||
@@ -216,3 +237,59 @@ func (material *Material) DeleteMaterial(mediaID string) error {
|
|||||||
|
|
||||||
return util.DecodeWithCommonError(response, "DeleteMaterial")
|
return util.DecodeWithCommonError(response, "DeleteMaterial")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//ArticleList 永久素材列表
|
||||||
|
type ArticleList struct {
|
||||||
|
TotalCount int64 `json:"total_count"`
|
||||||
|
ItemCount int64 `json:"item_count"`
|
||||||
|
Item []ArticleListItem `json:"item"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ArticleListItem 用于ArticleList的item节点
|
||||||
|
type ArticleListItem struct {
|
||||||
|
MediaID string `json:"media_id"`
|
||||||
|
Content ArticleListContent `json:"content"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
UpdateTime int64 `json:"update_time"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//ArticleListContent 用于ArticleListItem的content节点
|
||||||
|
type ArticleListContent struct {
|
||||||
|
NewsItem []Article `json:"news_item"`
|
||||||
|
UpdateTime int64 `json:"update_time"`
|
||||||
|
CreateTime int64 `json:"create_time"`
|
||||||
|
}
|
||||||
|
|
||||||
|
//reqBatchGetMaterial BatchGetMaterial请求参数
|
||||||
|
type reqBatchGetMaterial struct {
|
||||||
|
Type PermanentMaterialType `json:"type"`
|
||||||
|
Count int64 `json:"count"`
|
||||||
|
Offset int64 `json:"offset"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchGetMaterial 批量获取永久素材
|
||||||
|
//reference:https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Get_materials_list.html
|
||||||
|
func (material *Material) BatchGetMaterial(permanentMaterialType PermanentMaterialType, offset, count int64) (list ArticleList, err error) {
|
||||||
|
var accessToken string
|
||||||
|
accessToken, err = material.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", batchGetMaterialURL, accessToken)
|
||||||
|
|
||||||
|
req := reqBatchGetMaterial{
|
||||||
|
Type: permanentMaterialType,
|
||||||
|
Offset: offset,
|
||||||
|
Count: count,
|
||||||
|
}
|
||||||
|
|
||||||
|
var response []byte
|
||||||
|
response, err = util.PostJSON(uri, req)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = util.DecodeWithError(response, &list, "BatchGetMaterial")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|||||||
@@ -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,6 +138,24 @@ func (menu *Menu) SetMenu(buttons []*Button) error {
|
|||||||
return util.DecodeWithCommonError(response, "SetMenu")
|
return util.DecodeWithCommonError(response, "SetMenu")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//SetMenuByJSON 设置按钮
|
||||||
|
func (menu *Menu) SetMenuByJSON(jsonInfo string) error {
|
||||||
|
accessToken, err := menu.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", menuCreateURL, accessToken)
|
||||||
|
|
||||||
|
response, err := util.PostJSON(uri, jsonInfo)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return util.DecodeWithCommonError(response, "SetMenu")
|
||||||
|
}
|
||||||
|
|
||||||
//GetMenu 获取菜单配置
|
//GetMenu 获取菜单配置
|
||||||
func (menu *Menu) GetMenu() (resMenu ResMenu, err error) {
|
func (menu *Menu) GetMenu() (resMenu ResMenu, err error) {
|
||||||
var accessToken string
|
var accessToken string
|
||||||
@@ -198,6 +216,23 @@ func (menu *Menu) AddConditional(buttons []*Button, matchRule *MatchRule) error
|
|||||||
return util.DecodeWithCommonError(response, "AddConditional")
|
return util.DecodeWithCommonError(response, "AddConditional")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//AddConditionalByJSON 添加个性化菜单
|
||||||
|
func (menu *Menu) AddConditionalByJSON(jsonInfo string) error {
|
||||||
|
accessToken, err := menu.GetAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := fmt.Sprintf("%s?access_token=%s", menuAddConditionalURL, accessToken)
|
||||||
|
response, err := util.PostJSON(uri, jsonInfo)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return util.DecodeWithCommonError(response, "AddConditional")
|
||||||
|
}
|
||||||
|
|
||||||
//DeleteConditional 删除个性化菜单
|
//DeleteConditional 删除个性化菜单
|
||||||
func (menu *Menu) DeleteConditional(menuID int64) error {
|
func (menu *Menu) DeleteConditional(menuID int64) error {
|
||||||
accessToken, err := menu.GetAccessToken()
|
accessToken, err := menu.GetAccessToken()
|
||||||
|
|||||||
@@ -89,20 +89,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"`
|
||||||
|
|||||||
@@ -24,13 +24,13 @@ func NewTemplate(context *context.Context) *Template {
|
|||||||
return tpl
|
return tpl
|
||||||
}
|
}
|
||||||
|
|
||||||
//Message 发送的模板消息内容
|
//TemplateMessage 发送的模板消息内容
|
||||||
type Message struct {
|
type TemplateMessage struct {
|
||||||
ToUser string `json:"touser"` // 必须, 接受者OpenID
|
ToUser string `json:"touser"` // 必须, 接受者OpenID
|
||||||
TemplateID string `json:"template_id"` // 必须, 模版ID
|
TemplateID string `json:"template_id"` // 必须, 模版ID
|
||||||
URL string `json:"url,omitempty"` // 可选, 用户点击后跳转的URL, 该URL必须处于开发者在公众平台网站中设置的域中
|
URL string `json:"url,omitempty"` // 可选, 用户点击后跳转的URL, 该URL必须处于开发者在公众平台网站中设置的域中
|
||||||
Color string `json:"color,omitempty"` // 可选, 整个消息的颜色, 可以不设置
|
Color string `json:"color,omitempty"` // 可选, 整个消息的颜色, 可以不设置
|
||||||
Data map[string]*DataItem `json:"data"` // 必须, 模板数据
|
Data map[string]*TemplateDataItem `json:"data"` // 必须, 模板数据
|
||||||
|
|
||||||
MiniProgram struct {
|
MiniProgram struct {
|
||||||
AppID string `json:"appid"` //所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)
|
AppID string `json:"appid"` //所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)
|
||||||
@@ -38,8 +38,8 @@ type Message struct {
|
|||||||
} `json:"miniprogram"` //可选,跳转至小程序地址
|
} `json:"miniprogram"` //可选,跳转至小程序地址
|
||||||
}
|
}
|
||||||
|
|
||||||
//DataItem 模版内某个 .DATA 的值
|
//TemplateDataItem 模版内某个 .DATA 的值
|
||||||
type DataItem struct {
|
type TemplateDataItem struct {
|
||||||
Value string `json:"value"`
|
Value string `json:"value"`
|
||||||
Color string `json:"color,omitempty"`
|
Color string `json:"color,omitempty"`
|
||||||
}
|
}
|
||||||
@@ -51,7 +51,7 @@ type resTemplateSend struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//Send 发送模板消息
|
//Send 发送模板消息
|
||||||
func (tpl *Template) Send(msg *Message) (msgID int64, err error) {
|
func (tpl *Template) Send(msg *TemplateMessage) (msgID int64, err error) {
|
||||||
var accessToken string
|
var accessToken string
|
||||||
accessToken, err = tpl.GetAccessToken()
|
accessToken, err = tpl.GetAccessToken()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
package officialaccount
|
package officialaccount
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/silenceper/wechat/v2/officialaccount/datacube"
|
||||||
"net/http"
|
"net/http"
|
||||||
"sync"
|
|
||||||
|
|
||||||
|
"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/config"
|
"github.com/silenceper/wechat/v2/officialaccount/config"
|
||||||
"github.com/silenceper/wechat/v2/officialaccount/context"
|
"github.com/silenceper/wechat/v2/officialaccount/context"
|
||||||
"github.com/silenceper/wechat/v2/officialaccount/device"
|
"github.com/silenceper/wechat/v2/officialaccount/device"
|
||||||
@@ -24,15 +26,17 @@ type OfficialAccount struct {
|
|||||||
|
|
||||||
//NewOfficialAccount 实例化公众号API
|
//NewOfficialAccount 实例化公众号API
|
||||||
func NewOfficialAccount(cfg *config.Config) *OfficialAccount {
|
func NewOfficialAccount(cfg *config.Config) *OfficialAccount {
|
||||||
//if cfg.Cache == nil {
|
defaultAkHandle := credential.NewDefaultAccessToken(cfg.AppID, cfg.AppSecret, credential.CacheKeyOfficialAccountPrefix, cfg.Cache)
|
||||||
// panic("cache未设置")
|
|
||||||
//}
|
|
||||||
ctx := &context.Context{
|
ctx := &context.Context{
|
||||||
Config: cfg,
|
Config: cfg,
|
||||||
|
AccessTokenHandle: defaultAkHandle,
|
||||||
}
|
}
|
||||||
ctx.SetAccessTokenLock(new(sync.RWMutex))
|
return &OfficialAccount{ctx: ctx}
|
||||||
ctx.SetJsAPITicketLock(new(sync.RWMutex))
|
}
|
||||||
return &OfficialAccount{ctx}
|
|
||||||
|
//SetAccessTokenHandle 自定义access_token获取方式
|
||||||
|
func (officialAccount *OfficialAccount) SetAccessTokenHandle(accessTokenHandle credential.AccessTokenHandle) {
|
||||||
|
officialAccount.ctx.AccessTokenHandle = accessTokenHandle
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetContext get Context
|
// GetContext get Context
|
||||||
@@ -50,7 +54,7 @@ func (officialAccount *OfficialAccount) GetMenu() *menu.Menu {
|
|||||||
return menu.NewMenu(officialAccount.ctx)
|
return menu.NewMenu(officialAccount.ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetServer 消息管理
|
// GetServer 消息管理:接收事件,被动回复消息管理
|
||||||
func (officialAccount *OfficialAccount) GetServer(req *http.Request, writer http.ResponseWriter) *server.Server {
|
func (officialAccount *OfficialAccount) GetServer(req *http.Request, writer http.ResponseWriter) *server.Server {
|
||||||
srv := server.NewServer(officialAccount.ctx)
|
srv := server.NewServer(officialAccount.ctx)
|
||||||
srv.Request = req
|
srv.Request = req
|
||||||
@@ -92,3 +96,14 @@ func (officialAccount *OfficialAccount) GetTemplate() *message.Template {
|
|||||||
func (officialAccount *OfficialAccount) GetDevice() *device.Device {
|
func (officialAccount *OfficialAccount) GetDevice() *device.Device {
|
||||||
return device.NewDevice(officialAccount.ctx)
|
return device.NewDevice(officialAccount.ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//GetBroadcast 群发消息
|
||||||
|
//TODO 待完善
|
||||||
|
func (officialAccount *OfficialAccount) GetBroadcast() *broadcast.Broadcast {
|
||||||
|
return broadcast.NewBroadcast(officialAccount.ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetDataCube 数据统计
|
||||||
|
func (officialAccount *OfficialAccount) GetDataCube() *datacube.DataCube {
|
||||||
|
return datacube.NewCube(officialAccount.ctx)
|
||||||
|
}
|
||||||
|
|||||||
@@ -29,10 +29,10 @@ type Server struct {
|
|||||||
|
|
||||||
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{}
|
||||||
|
|
||||||
isSafeMode bool
|
isSafeMode bool
|
||||||
random []byte
|
random []byte
|
||||||
@@ -71,7 +71,7 @@ func (srv *Server) Serve() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//debug print request msg
|
//debug print request msg
|
||||||
log.Debugf("request msg =%s", string(srv.requestRawXMLMsg))
|
log.Debugf("request msg =%s", string(srv.RequestRawXMLMsg))
|
||||||
|
|
||||||
return srv.buildResponse(response)
|
return srv.buildResponse(response)
|
||||||
}
|
}
|
||||||
@@ -109,7 +109,7 @@ func (srv *Server) handleRequest() (reply *message.Reply, err error) {
|
|||||||
if !success {
|
if !success {
|
||||||
err = errors.New("消息类型转换失败")
|
err = errors.New("消息类型转换失败")
|
||||||
}
|
}
|
||||||
srv.requestMsg = mixMessage
|
srv.RequestMsg = mixMessage
|
||||||
reply = srv.messageHandler(mixMessage)
|
reply = srv.messageHandler(mixMessage)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -155,7 +155,7 @@ func (srv *Server) getMessage() (interface{}, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
srv.requestRawXMLMsg = rawXMLMsgBytes
|
srv.RequestRawXMLMsg = rawXMLMsgBytes
|
||||||
|
|
||||||
return srv.parseRequestMessage(rawXMLMsgBytes)
|
return srv.parseRequestMessage(rawXMLMsgBytes)
|
||||||
}
|
}
|
||||||
@@ -204,10 +204,10 @@ func (srv *Server) buildResponse(reply *message.Reply) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
params := make([]reflect.Value, 1)
|
params := make([]reflect.Value, 1)
|
||||||
params[0] = reflect.ValueOf(srv.requestMsg.FromUserName)
|
params[0] = reflect.ValueOf(srv.RequestMsg.FromUserName)
|
||||||
value.MethodByName("SetToUserName").Call(params)
|
value.MethodByName("SetToUserName").Call(params)
|
||||||
|
|
||||||
params[0] = reflect.ValueOf(srv.requestMsg.ToUserName)
|
params[0] = reflect.ValueOf(srv.RequestMsg.ToUserName)
|
||||||
value.MethodByName("SetFromUserName").Call(params)
|
value.MethodByName("SetFromUserName").Call(params)
|
||||||
|
|
||||||
params[0] = reflect.ValueOf(msgType)
|
params[0] = reflect.ValueOf(msgType)
|
||||||
@@ -216,19 +216,19 @@ func (srv *Server) buildResponse(reply *message.Reply) (err error) {
|
|||||||
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
|
||||||
srv.responseRawXMLMsg, err = xml.Marshal(msgData)
|
srv.ResponseRawXMLMsg, err = xml.Marshal(msgData)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
//Send 将自定义的消息发送
|
//Send 将自定义的消息发送
|
||||||
func (srv *Server) Send() (err error) {
|
func (srv *Server) Send() (err error) {
|
||||||
replyMsg := srv.responseMsg
|
replyMsg := srv.ResponseMsg
|
||||||
log.Debugf("response msg =%+v", replyMsg)
|
log.Debugf("response msg =%+v", replyMsg)
|
||||||
if srv.isSafeMode {
|
if srv.isSafeMode {
|
||||||
//安全模式下对消息进行加密
|
//安全模式下对消息进行加密
|
||||||
var encryptedMsg []byte
|
var encryptedMsg []byte
|
||||||
encryptedMsg, err = util.EncryptMsg(srv.random, srv.responseRawXMLMsg, srv.AppID, srv.EncodingAESKey)
|
encryptedMsg, err = util.EncryptMsg(srv.random, srv.ResponseRawXMLMsg, srv.AppID, srv.EncodingAESKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ type Info struct {
|
|||||||
UnionID string `json:"unionid"`
|
UnionID string `json:"unionid"`
|
||||||
Remark string `json:"remark"`
|
Remark string `json:"remark"`
|
||||||
GroupID int32 `json:"groupid"`
|
GroupID int32 `json:"groupid"`
|
||||||
TagidList []int32 `json:"tagid_list"`
|
TagIDList []int32 `json:"tagid_list"`
|
||||||
SubscribeScene string `json:"subscribe_scene"`
|
SubscribeScene string `json:"subscribe_scene"`
|
||||||
QrScene int `json:"qr_scene"`
|
QrScene int `json:"qr_scene"`
|
||||||
QrSceneStr string `json:"qr_scene_str"`
|
QrSceneStr string `json:"qr_scene_str"`
|
||||||
|
|||||||
@@ -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,13 +17,10 @@ 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 {
|
||||||
@@ -52,4 +49,15 @@ if err != nil {
|
|||||||
}
|
}
|
||||||
//发送回复的消息
|
//发送回复的消息
|
||||||
server.Send()
|
server.Send()
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
### 待授权处理消息
|
||||||
|
```go
|
||||||
|
|
||||||
|
//授权的第三方公众号的appID
|
||||||
|
appID := "xxx"
|
||||||
|
openPlatform := wc.GetOpenPlatform(cfg)
|
||||||
|
openPlatform.GetOfficialAccount(appID)
|
||||||
|
|
||||||
```
|
```
|
||||||
34
openplatform/account/account.go
Normal file
34
openplatform/account/account.go
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
package account
|
||||||
|
|
||||||
|
import "github.com/silenceper/wechat/v2/openplatform/context"
|
||||||
|
|
||||||
|
//Account 开放平台张哈管理
|
||||||
|
//TODO 实现方法
|
||||||
|
type Account struct {
|
||||||
|
*context.Context
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewAccount new
|
||||||
|
func NewAccount(ctx *context.Context) *Account {
|
||||||
|
return &Account{ctx}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Create 创建开放平台帐号并绑定公众号/小程序
|
||||||
|
func (account *Account) Create(appID string) (string, error) {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
//Bind 将公众号/小程序绑定到开放平台帐号下
|
||||||
|
func (account *Account) Bind(appID string) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
//Unbind 将公众号/小程序从开放平台帐号下解绑
|
||||||
|
func (account *Account) Unbind(appID string, openAppID string) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
//Get 获取公众号/小程序所绑定的开放平台帐号
|
||||||
|
func (account *Account) Get(appID string) (string, error) {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
@@ -14,7 +14,10 @@ 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"
|
||||||
getComponentConfigURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_option?component_access_token=%s"
|
//TODO 获取授权方选项信息
|
||||||
|
getComponentConfigURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_option?component_access_token=%s"
|
||||||
|
//TODO 获取已授权的账号信息
|
||||||
|
getuthorizerListURL = "POST https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_list?component_access_token=%s"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ComponentAccessToken 第三方平台
|
// ComponentAccessToken 第三方平台
|
||||||
|
|||||||
@@ -48,5 +48,5 @@ func (basic *Basic) GetAccountBasicInfo() (*AccountBasicInfo, error) {
|
|||||||
|
|
||||||
//modify_domain设置服务器域名
|
//modify_domain设置服务器域名
|
||||||
//TODO
|
//TODO
|
||||||
//func (basic *Basic) modifyDomain() {
|
//func (encryptor *Basic) modifyDomain() {
|
||||||
//}
|
//}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
package officialaccount
|
package officialaccount
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/silenceper/wechat/v2/credential"
|
||||||
"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"
|
||||||
offContext "github.com/silenceper/wechat/v2/officialaccount/context"
|
|
||||||
opContext "github.com/silenceper/wechat/v2/openplatform/context"
|
opContext "github.com/silenceper/wechat/v2/openplatform/context"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -25,9 +25,25 @@ func NewOfficialAccount(opCtx *opContext.Context, appID string) *OfficialAccount
|
|||||||
Cache: opCtx.Cache,
|
Cache: opCtx.Cache,
|
||||||
})
|
})
|
||||||
//设置获取access_token的函数
|
//设置获取access_token的函数
|
||||||
officialAccount.GetContext().SetGetAccessTokenFunc(func(offCtx *offContext.Context) (accessToken string, err error) {
|
officialAccount.SetAccessTokenHandle(NewDefaultAuthrAccessToken(opCtx, appID))
|
||||||
// 获取授权方的access_token
|
|
||||||
return opCtx.GetAuthrAccessToken(appID)
|
|
||||||
})
|
|
||||||
return &OfficialAccount{appID: appID, OfficialAccount: officialAccount}
|
return &OfficialAccount{appID: appID, OfficialAccount: officialAccount}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//DefaultAuthrAccessToken 默认获取授权ak的方法
|
||||||
|
type DefaultAuthrAccessToken struct {
|
||||||
|
opCtx *opContext.Context
|
||||||
|
appID string
|
||||||
|
}
|
||||||
|
|
||||||
|
//NewDefaultAuthrAccessToken New
|
||||||
|
func NewDefaultAuthrAccessToken(opCtx *opContext.Context, appID string) credential.AccessTokenHandle {
|
||||||
|
return &DefaultAuthrAccessToken{
|
||||||
|
opCtx: opCtx,
|
||||||
|
appID: appID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetAccessToken 获取ak
|
||||||
|
func (ak *DefaultAuthrAccessToken) GetAccessToken() (string, error) {
|
||||||
|
return ak.opCtx.GetAuthrAccessToken(ak.appID)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
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/config"
|
"github.com/silenceper/wechat/v2/openplatform/config"
|
||||||
"github.com/silenceper/wechat/v2/openplatform/context"
|
"github.com/silenceper/wechat/v2/openplatform/context"
|
||||||
"github.com/silenceper/wechat/v2/openplatform/miniprogram"
|
"github.com/silenceper/wechat/v2/openplatform/miniprogram"
|
||||||
@@ -23,12 +27,24 @@ 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
//GetMiniProgram 小程序代理
|
//GetMiniProgram 小程序代理
|
||||||
func (openPlatform *OpenPlatform) GetMiniProgram(opCtx *context.Context, appID string) *miniprogram.MiniProgram {
|
func (openPlatform *OpenPlatform) GetMiniProgram(appID string) *miniprogram.MiniProgram {
|
||||||
return miniprogram.NewMiniProgram(opCtx, appID)
|
return miniprogram.NewMiniProgram(openPlatform.Context, appID)
|
||||||
|
}
|
||||||
|
|
||||||
|
//GetAccountManager 账号管理
|
||||||
|
//TODO
|
||||||
|
func (openPlatform *OpenPlatform) GetAccountManager() *account.Account {
|
||||||
|
return account.NewAccount(openPlatform.Context)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -85,8 +85,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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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"
|
||||||
@@ -96,13 +91,14 @@ type payRequest struct {
|
|||||||
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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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 +117,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
|
||||||
@@ -143,13 +138,13 @@ func (o *Order) PrePayOrder(p *Params) (payOrder PreOrder, err error) {
|
|||||||
notifyURL := o.NotifyURL
|
notifyURL := o.NotifyURL
|
||||||
// 签名类型
|
// 签名类型
|
||||||
if p.SignType == "" {
|
if p.SignType == "" {
|
||||||
p.SignType = "MD5"
|
p.SignType = util.SignTypeMD5
|
||||||
}
|
}
|
||||||
// 通知地址
|
// 通知地址
|
||||||
if p.NotifyURL != "" {
|
if p.NotifyURL != "" {
|
||||||
notifyURL = p.NotifyURL
|
notifyURL = p.NotifyURL
|
||||||
}
|
}
|
||||||
param := make(map[string]interface{})
|
param := make(map[string]string)
|
||||||
param["appid"] = o.AppID
|
param["appid"] = o.AppID
|
||||||
param["body"] = p.Body
|
param["body"] = p.Body
|
||||||
param["mch_id"] = o.MchID
|
param["mch_id"] = o.MchID
|
||||||
@@ -165,9 +160,10 @@ func (o *Order) PrePayOrder(p *Params) (payOrder PreOrder, err error) {
|
|||||||
param["goods_tag"] = p.GoodsTag
|
param["goods_tag"] = p.GoodsTag
|
||||||
param["notify_url"] = notifyURL
|
param["notify_url"] = notifyURL
|
||||||
|
|
||||||
bizKey := "&key=" + o.Key
|
sign, err := util.ParamSign(param, o.Key)
|
||||||
str := util.OrderParam(param, bizKey)
|
if err != nil {
|
||||||
sign := util.MD5Sum(str)
|
return
|
||||||
|
}
|
||||||
request := payRequest{
|
request := payRequest{
|
||||||
AppID: o.AppID,
|
AppID: o.AppID,
|
||||||
MchID: o.MchID,
|
MchID: o.MchID,
|
||||||
@@ -202,7 +198,7 @@ func (o *Order) PrePayOrder(p *Params) (payOrder PreOrder, err error) {
|
|||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ type Response struct {
|
|||||||
//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)
|
nonceStr := util.RandomStr(32)
|
||||||
param := make(map[string]interface{})
|
param := make(map[string]string)
|
||||||
param["appid"] = refund.AppID
|
param["appid"] = refund.AppID
|
||||||
param["mch_id"] = refund.MchID
|
param["mch_id"] = refund.MchID
|
||||||
param["nonce_str"] = nonceStr
|
param["nonce_str"] = nonceStr
|
||||||
@@ -81,18 +81,20 @@ func (refund *Refund) Refund(p *Params) (rsp Response, err error) {
|
|||||||
param["refund_desc"] = p.RefundDesc
|
param["refund_desc"] = p.RefundDesc
|
||||||
param["refund_fee"] = p.RefundFee
|
param["refund_fee"] = p.RefundFee
|
||||||
param["total_fee"] = p.TotalFee
|
param["total_fee"] = p.TotalFee
|
||||||
param["sign_type"] = "MD5"
|
param["sign_type"] = util.SignTypeMD5
|
||||||
param["transaction_id"] = p.TransactionID
|
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{
|
request := request{
|
||||||
AppID: refund.AppID,
|
AppID: refund.AppID,
|
||||||
MchID: refund.MchID,
|
MchID: refund.MchID,
|
||||||
NonceStr: nonceStr,
|
NonceStr: nonceStr,
|
||||||
Sign: sign,
|
Sign: sign,
|
||||||
SignType: "MD5",
|
SignType: util.SignTypeMD5,
|
||||||
TransactionID: p.TransactionID,
|
TransactionID: p.TransactionID,
|
||||||
OutRefundNo: p.OutRefundNo,
|
OutRefundNo: p.OutRefundNo,
|
||||||
TotalFee: p.TotalFee,
|
TotalFee: p.TotalFee,
|
||||||
@@ -115,7 +117,6 @@ 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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,23 @@
|
|||||||
package util
|
package util
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
|
||||||
"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"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 微信签名算法方式
|
||||||
|
const (
|
||||||
|
SignTypeMD5 = `MD5`
|
||||||
|
SignTypeHMACSHA256 = `HMAC-SHA256`
|
||||||
)
|
)
|
||||||
|
|
||||||
//EncryptMsg 加密消息
|
//EncryptMsg 加密消息
|
||||||
@@ -186,14 +195,35 @@ 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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user