mirror of
https://github.com/silenceper/wechat.git
synced 2026-02-23 13:42:25 +08:00
Compare commits
10 Commits
v2.1.9-rc.
...
f26a66ec9c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f26a66ec9c | ||
|
|
356fe3df44 | ||
|
|
9e54a6a27b | ||
|
|
ef4e3a0a3e | ||
|
|
12dfb7051a | ||
|
|
d214617446 | ||
|
|
b3e2d624d9 | ||
|
|
7371d1649f | ||
|
|
b1f31feff6 | ||
|
|
b39be7fca2 |
6
.github/ISSUE_TEMPLATE/bug.md
vendored
6
.github/ISSUE_TEMPLATE/bug.md
vendored
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: 报告 Bug
|
name: 报告Bug
|
||||||
about: 反馈 BUG 信息
|
about: 反馈BUG信息
|
||||||
title: "[BUG]"
|
title: "[BUG]"
|
||||||
labels: bug
|
labels: bug
|
||||||
assignees: ''
|
assignees: ''
|
||||||
@@ -18,4 +18,4 @@ assignees: ''
|
|||||||
|
|
||||||
|
|
||||||
**使用的版本**
|
**使用的版本**
|
||||||
- SDK 版本:[比如 v0.0.0]
|
- SDK版本: [比如 v0.0.0]
|
||||||
|
|||||||
8
.github/ISSUE_TEMPLATE/feature.md
vendored
8
.github/ISSUE_TEMPLATE/feature.md
vendored
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: API 需求
|
name: API需求
|
||||||
about: 待实现的 API 接口,SDK 的强大离不开社区的帮助,欢迎为项目贡献 PR
|
about: 待实现的API接口,SDK的强大离不开社区的帮助,欢迎为项目贡献PR
|
||||||
title: "[Feature]"
|
title: "[Feature]"
|
||||||
labels: enhancement
|
labels: enhancement
|
||||||
assignees: ''
|
assignees: ''
|
||||||
@@ -8,8 +8,8 @@ assignees: ''
|
|||||||
---
|
---
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
!!!SDK 的强大离不开社区的帮助,欢迎为本项目贡献 PR!!!
|
!!!SDK的强大离不开社区的帮助,欢迎为本项目贡献PR!!!
|
||||||
-->
|
-->
|
||||||
**你想要实现的模块或 API**
|
**你想要实现的模块或API**
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
6
.github/ISSUE_TEMPLATE/question.md
vendored
6
.github/ISSUE_TEMPLATE/question.md
vendored
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: 使用咨询
|
name: 使用咨询
|
||||||
about: 关于 SDK 使用相关的咨询,在使用前请先阅读官方微信文档
|
about: 关于SDK使用相关的咨询,在使用前请先阅读官方微信文档
|
||||||
title: "[咨询]"
|
title: "[咨询]"
|
||||||
labels: question
|
labels: question
|
||||||
assignees: ''
|
assignees: ''
|
||||||
@@ -9,7 +9,7 @@ assignees: ''
|
|||||||
|
|
||||||
<!--
|
<!--
|
||||||
重要:
|
重要:
|
||||||
1、在使用本 SDK 前请先阅读对应的官方微信 API 文档:https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html
|
1、在使用本SDK前请先阅读对应的官方微信API文档:https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html
|
||||||
2、本 SDK 部分接口文档:https://silenceper.com/wechat/
|
2、本SDK部分接口文档: https://silenceper.com/wechat/
|
||||||
-->
|
-->
|
||||||
**请描述您的问题**
|
**请描述您的问题**
|
||||||
|
|||||||
18
.github/workflows/go.yml
vendored
18
.github/workflows/go.yml
vendored
@@ -2,26 +2,26 @@ name: Go
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ master,release-*,v2,feature/**,fix/** ]
|
branches: [ master,release-*,v2,feature/** ]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ master,release-*,v2,feature/**,fix/** ]
|
branches: [ master,release-*,v2,feature/** ]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
golangci:
|
golangci:
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
go-version: [ '1.16','1.17','1.18','1.19','1.20','1.21.4' ]
|
go-version: [ '1.16','1.17','1.18','1.19','1.20','1.21' ]
|
||||||
name: golangci-lint
|
name: golangci-lint
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Setup Golang ${{ matrix.go-version }}
|
- name: Setup Golang ${{ matrix.go-version }}
|
||||||
uses: actions/setup-go@v5
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: ${{ matrix.go-version }}
|
go-version: ${{ matrix.go-version }}
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v3
|
||||||
- name: golangci-lint
|
- name: golangci-lint
|
||||||
uses: golangci/golangci-lint-action@v4
|
uses: golangci/golangci-lint-action@v3
|
||||||
with:
|
with:
|
||||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||||
version: v1.52.2
|
version: v1.52.2
|
||||||
@@ -42,12 +42,12 @@ jobs:
|
|||||||
# strategy set
|
# strategy set
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
go: [ '1.16','1.17','1.18','1.19','1.20','1.21','1.22' ]
|
go: [ '1.16','1.17','1.18','1.19','1.20','1.21' ]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v3
|
||||||
- name: Set up Go 1.x
|
- name: Set up Go 1.x
|
||||||
uses: actions/setup-go@v5
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: ${{ matrix.go }}
|
go-version: ${{ matrix.go }}
|
||||||
id: go
|
id: go
|
||||||
|
|||||||
2
cache/redis.go
vendored
2
cache/redis.go
vendored
@@ -16,7 +16,6 @@ type Redis struct {
|
|||||||
// RedisOpts redis 连接属性
|
// RedisOpts redis 连接属性
|
||||||
type RedisOpts struct {
|
type RedisOpts struct {
|
||||||
Host string `yml:"host" json:"host"`
|
Host string `yml:"host" json:"host"`
|
||||||
Username string `yaml:"username" json:"username"`
|
|
||||||
Password string `yml:"password" json:"password"`
|
Password string `yml:"password" json:"password"`
|
||||||
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"`
|
||||||
@@ -29,7 +28,6 @@ func NewRedis(ctx context.Context, opts *RedisOpts) *Redis {
|
|||||||
conn := redis.NewUniversalClient(&redis.UniversalOptions{
|
conn := redis.NewUniversalClient(&redis.UniversalOptions{
|
||||||
Addrs: []string{opts.Host},
|
Addrs: []string{opts.Host},
|
||||||
DB: opts.Database,
|
DB: opts.Database,
|
||||||
Username: opts.Username,
|
|
||||||
Password: opts.Password,
|
Password: opts.Password,
|
||||||
IdleTimeout: time.Second * time.Duration(opts.IdleTimeout),
|
IdleTimeout: time.Second * time.Duration(opts.IdleTimeout),
|
||||||
MinIdleConns: opts.MaxIdle,
|
MinIdleConns: opts.MaxIdle,
|
||||||
|
|||||||
@@ -7,16 +7,6 @@ type AccessTokenHandle interface {
|
|||||||
GetAccessToken() (accessToken string, err error)
|
GetAccessToken() (accessToken string, err error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// AccessTokenCompatibleHandle 同时实现 AccessTokenHandle 和 AccessTokenContextHandle
|
|
||||||
type AccessTokenCompatibleHandle struct {
|
|
||||||
AccessTokenHandle
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetAccessTokenContext 获取access_token,先从cache中获取,没有则从服务端获取
|
|
||||||
func (c AccessTokenCompatibleHandle) GetAccessTokenContext(_ context.Context) (accessToken string, err error) {
|
|
||||||
return c.GetAccessToken()
|
|
||||||
}
|
|
||||||
|
|
||||||
// AccessTokenContextHandle AccessToken 接口
|
// AccessTokenContextHandle AccessToken 接口
|
||||||
type AccessTokenContextHandle interface {
|
type AccessTokenContextHandle interface {
|
||||||
AccessTokenHandle
|
AccessTokenHandle
|
||||||
|
|||||||
@@ -66,11 +66,9 @@ func (ak *DefaultAccessToken) GetAccessToken() (accessToken string, err error) {
|
|||||||
func (ak *DefaultAccessToken) GetAccessTokenContext(ctx context.Context) (accessToken string, err error) {
|
func (ak *DefaultAccessToken) GetAccessTokenContext(ctx context.Context) (accessToken string, err error) {
|
||||||
// 先从cache中取
|
// 先从cache中取
|
||||||
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.appID)
|
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.appID)
|
||||||
|
val := ak.cache.Get(accessTokenCacheKey)
|
||||||
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
|
if accessToken = val.(string); accessToken != "" {
|
||||||
if accessToken = val.(string); accessToken != "" {
|
return
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
|
// 加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
|
||||||
@@ -78,10 +76,9 @@ func (ak *DefaultAccessToken) GetAccessTokenContext(ctx context.Context) (access
|
|||||||
defer ak.accessTokenLock.Unlock()
|
defer ak.accessTokenLock.Unlock()
|
||||||
|
|
||||||
// 双检,防止重复从微信服务器获取
|
// 双检,防止重复从微信服务器获取
|
||||||
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
|
val = ak.cache.Get(accessTokenCacheKey)
|
||||||
if accessToken = val.(string); accessToken != "" {
|
if accessToken = val.(string); accessToken != "" {
|
||||||
return
|
return
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// cache失效,从微信服务器获取
|
// cache失效,从微信服务器获取
|
||||||
@@ -90,9 +87,9 @@ func (ak *DefaultAccessToken) GetAccessTokenContext(ctx context.Context) (access
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
expires := resAccessToken.ExpiresIn - 1500
|
if err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(resAccessToken.ExpiresIn-1500)*time.Second); err != nil {
|
||||||
err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
|
return
|
||||||
|
}
|
||||||
accessToken = resAccessToken.AccessToken
|
accessToken = resAccessToken.AccessToken
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -101,11 +98,10 @@ func (ak *DefaultAccessToken) GetAccessTokenContext(ctx context.Context) (access
|
|||||||
// 不强制更新access_token,可用于不同环境不同服务而不需要分布式锁以及公用缓存,避免access_token争抢
|
// 不强制更新access_token,可用于不同环境不同服务而不需要分布式锁以及公用缓存,避免access_token争抢
|
||||||
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html
|
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html
|
||||||
type StableAccessToken struct {
|
type StableAccessToken struct {
|
||||||
appID string
|
appID string
|
||||||
appSecret string
|
appSecret string
|
||||||
cacheKeyPrefix string
|
cacheKeyPrefix string
|
||||||
cache cache.Cache
|
cache cache.Cache
|
||||||
accessTokenLock *sync.Mutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewStableAccessToken new StableAccessToken
|
// NewStableAccessToken new StableAccessToken
|
||||||
@@ -114,11 +110,10 @@ func NewStableAccessToken(appID, appSecret, cacheKeyPrefix string, cache cache.C
|
|||||||
panic("cache is need")
|
panic("cache is need")
|
||||||
}
|
}
|
||||||
return &StableAccessToken{
|
return &StableAccessToken{
|
||||||
appID: appID,
|
appID: appID,
|
||||||
appSecret: appSecret,
|
appSecret: appSecret,
|
||||||
cache: cache,
|
cache: cache,
|
||||||
cacheKeyPrefix: cacheKeyPrefix,
|
cacheKeyPrefix: cacheKeyPrefix,
|
||||||
accessTokenLock: new(sync.Mutex),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,20 +127,7 @@ func (ak *StableAccessToken) GetAccessTokenContext(ctx context.Context) (accessT
|
|||||||
// 先从cache中取
|
// 先从cache中取
|
||||||
accessTokenCacheKey := fmt.Sprintf("%s_stable_access_token_%s", ak.cacheKeyPrefix, ak.appID)
|
accessTokenCacheKey := fmt.Sprintf("%s_stable_access_token_%s", ak.cacheKeyPrefix, ak.appID)
|
||||||
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
|
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
|
||||||
if accessToken = val.(string); accessToken != "" {
|
return val.(string), nil
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
|
|
||||||
ak.accessTokenLock.Lock()
|
|
||||||
defer ak.accessTokenLock.Unlock()
|
|
||||||
|
|
||||||
// 双检,防止重复从微信服务器获取
|
|
||||||
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
|
|
||||||
if accessToken = val.(string); accessToken != "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// cache失效,从微信服务器获取
|
// cache失效,从微信服务器获取
|
||||||
@@ -156,7 +138,7 @@ func (ak *StableAccessToken) GetAccessTokenContext(ctx context.Context) (accessT
|
|||||||
}
|
}
|
||||||
|
|
||||||
expires := resAccessToken.ExpiresIn - 300
|
expires := resAccessToken.ExpiresIn - 300
|
||||||
err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
|
_ = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
|
||||||
|
|
||||||
accessToken = resAccessToken.AccessToken
|
accessToken = resAccessToken.AccessToken
|
||||||
return
|
return
|
||||||
@@ -189,27 +171,19 @@ func (ak *StableAccessToken) GetAccessTokenDirectly(ctx context.Context, forceRe
|
|||||||
type WorkAccessToken struct {
|
type WorkAccessToken struct {
|
||||||
CorpID string
|
CorpID string
|
||||||
CorpSecret string
|
CorpSecret string
|
||||||
AgentID string // 可选,用于区分不同应用
|
|
||||||
cacheKeyPrefix string
|
cacheKeyPrefix string
|
||||||
cache cache.Cache
|
cache cache.Cache
|
||||||
accessTokenLock *sync.Mutex
|
accessTokenLock *sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewWorkAccessToken new WorkAccessToken (保持向后兼容)
|
// NewWorkAccessToken new WorkAccessToken
|
||||||
func NewWorkAccessToken(corpID, corpSecret, agentID, cacheKeyPrefix string, cache cache.Cache) AccessTokenContextHandle {
|
func NewWorkAccessToken(corpID, corpSecret, cacheKeyPrefix string, cache cache.Cache) AccessTokenContextHandle {
|
||||||
// 调用新方法,保持兼容性
|
|
||||||
return NewWorkAccessTokenWithAgentID(corpID, corpSecret, agentID, cacheKeyPrefix, cache)
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewWorkAccessTokenWithAgentID new WorkAccessToken with agentID
|
|
||||||
func NewWorkAccessTokenWithAgentID(corpID, corpSecret, agentID, cacheKeyPrefix string, cache cache.Cache) AccessTokenContextHandle {
|
|
||||||
if cache == nil {
|
if cache == nil {
|
||||||
panic("cache is needed")
|
panic("cache the not exist")
|
||||||
}
|
}
|
||||||
return &WorkAccessToken{
|
return &WorkAccessToken{
|
||||||
CorpID: corpID,
|
CorpID: corpID,
|
||||||
CorpSecret: corpSecret,
|
CorpSecret: corpSecret,
|
||||||
AgentID: agentID,
|
|
||||||
cache: cache,
|
cache: cache,
|
||||||
cacheKeyPrefix: cacheKeyPrefix,
|
cacheKeyPrefix: cacheKeyPrefix,
|
||||||
accessTokenLock: new(sync.Mutex),
|
accessTokenLock: new(sync.Mutex),
|
||||||
@@ -226,18 +200,7 @@ func (ak *WorkAccessToken) GetAccessTokenContext(ctx context.Context) (accessTok
|
|||||||
// 加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
|
// 加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
|
||||||
ak.accessTokenLock.Lock()
|
ak.accessTokenLock.Lock()
|
||||||
defer ak.accessTokenLock.Unlock()
|
defer ak.accessTokenLock.Unlock()
|
||||||
|
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.CorpID)
|
||||||
// 构建缓存key
|
|
||||||
var accessTokenCacheKey string
|
|
||||||
|
|
||||||
if ak.AgentID != "" {
|
|
||||||
// 如果设置了AgentID,使用新的key格式
|
|
||||||
accessTokenCacheKey = fmt.Sprintf("%s_access_token_%s_%s", ak.cacheKeyPrefix, ak.CorpID, ak.AgentID)
|
|
||||||
} else {
|
|
||||||
// 兼容历史版本的key格式
|
|
||||||
accessTokenCacheKey = fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.CorpID)
|
|
||||||
}
|
|
||||||
|
|
||||||
val := ak.cache.Get(accessTokenCacheKey)
|
val := ak.cache.Get(accessTokenCacheKey)
|
||||||
if val != nil {
|
if val != nil {
|
||||||
accessToken = val.(string)
|
accessToken = val.(string)
|
||||||
@@ -256,7 +219,6 @@ func (ak *WorkAccessToken) GetAccessTokenContext(ctx context.Context) (accessTok
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
accessToken = resAccessToken.AccessToken
|
accessToken = resAccessToken.AccessToken
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package credential
|
package credential
|
||||||
|
|
||||||
import (
|
import (
|
||||||
context2 "context"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -43,16 +42,6 @@ type ResTicket struct {
|
|||||||
|
|
||||||
// GetTicket 获取jsapi_ticket
|
// GetTicket 获取jsapi_ticket
|
||||||
func (js *DefaultJsTicket) GetTicket(accessToken string) (ticketStr string, err error) {
|
func (js *DefaultJsTicket) GetTicket(accessToken string) (ticketStr string, err error) {
|
||||||
return js.GetTicketContext(context2.Background(), accessToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetTicketFromServer 从服务器中获取ticket
|
|
||||||
func GetTicketFromServer(accessToken string) (ticket ResTicket, err error) {
|
|
||||||
return GetTicketFromServerContext(context2.Background(), accessToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetTicketContext 获取jsapi_ticket
|
|
||||||
func (js *DefaultJsTicket) GetTicketContext(ctx context2.Context, accessToken string) (ticketStr string, err error) {
|
|
||||||
// 先从cache中取
|
// 先从cache中取
|
||||||
jsAPITicketCacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", js.cacheKeyPrefix, js.appID)
|
jsAPITicketCacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", js.cacheKeyPrefix, js.appID)
|
||||||
if val := js.cache.Get(jsAPITicketCacheKey); val != nil {
|
if val := js.cache.Get(jsAPITicketCacheKey); val != nil {
|
||||||
@@ -68,7 +57,7 @@ func (js *DefaultJsTicket) GetTicketContext(ctx context2.Context, accessToken st
|
|||||||
}
|
}
|
||||||
|
|
||||||
var ticket ResTicket
|
var ticket ResTicket
|
||||||
ticket, err = GetTicketFromServerContext(ctx, accessToken)
|
ticket, err = GetTicketFromServer(accessToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -78,11 +67,11 @@ func (js *DefaultJsTicket) GetTicketContext(ctx context2.Context, accessToken st
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetTicketFromServerContext 从服务器中获取ticket
|
// GetTicketFromServer 从服务器中获取ticket
|
||||||
func GetTicketFromServerContext(ctx context2.Context, accessToken string) (ticket ResTicket, err error) {
|
func GetTicketFromServer(accessToken string) (ticket ResTicket, err error) {
|
||||||
var response []byte
|
var response []byte
|
||||||
url := fmt.Sprintf(getTicketURL, accessToken)
|
url := fmt.Sprintf(getTicketURL, accessToken)
|
||||||
response, err = util.HTTPGetContext(ctx, url)
|
response, err = util.HTTPGet(url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
package credential
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"gopkg.in/h2non/gock.v1"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestGetTicketFromServerContext 测试 GetTicketFromServerContext 函数
|
|
||||||
func TestGetTicketFromServerContext(t *testing.T) {
|
|
||||||
defer gock.Off()
|
|
||||||
gock.New(fmt.Sprintf(getTicketURL, "arg-ak")).Reply(200).JSON(&ResTicket{Ticket: "mock-ticket", ExpiresIn: 10})
|
|
||||||
|
|
||||||
ticket, err := GetTicketFromServerContext(context.Background(), "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")
|
|
||||||
}
|
|
||||||
@@ -1,15 +1,7 @@
|
|||||||
package credential
|
package credential
|
||||||
|
|
||||||
import context2 "context"
|
|
||||||
|
|
||||||
// JsTicketHandle js ticket获取
|
// JsTicketHandle js ticket获取
|
||||||
type JsTicketHandle interface {
|
type JsTicketHandle interface {
|
||||||
// GetTicket 获取ticket
|
// GetTicket 获取ticket
|
||||||
GetTicket(accessToken string) (ticket string, err error)
|
GetTicket(accessToken string) (ticket string, err error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// JsTicketContextHandle js ticket获取
|
|
||||||
type JsTicketContextHandle interface {
|
|
||||||
JsTicketHandle
|
|
||||||
GetTicketContext(ctx context2.Context, accessToken string) (ticket string, err error)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,118 +0,0 @@
|
|||||||
package credential
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/cache"
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TicketType ticket类型
|
|
||||||
type TicketType int
|
|
||||||
|
|
||||||
const (
|
|
||||||
// TicketTypeCorpJs 企业jsapi ticket
|
|
||||||
TicketTypeCorpJs TicketType = iota
|
|
||||||
// TicketTypeAgentJs 应用jsapi ticket
|
|
||||||
TicketTypeAgentJs
|
|
||||||
)
|
|
||||||
|
|
||||||
// 企业微信相关的 ticket URL
|
|
||||||
const (
|
|
||||||
// 企业微信 jsapi ticket
|
|
||||||
getWorkJsTicketURL = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=%s"
|
|
||||||
// 企业微信应用 jsapi ticket
|
|
||||||
getWorkAgentJsTicketURL = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=%s&type=agent_config"
|
|
||||||
)
|
|
||||||
|
|
||||||
// WorkJsTicket 企业微信js ticket获取
|
|
||||||
type WorkJsTicket struct {
|
|
||||||
corpID string
|
|
||||||
agentID string
|
|
||||||
cacheKeyPrefix string
|
|
||||||
cache cache.Cache
|
|
||||||
jsAPITicketLock *sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewWorkJsTicket new WorkJsTicket
|
|
||||||
func NewWorkJsTicket(corpID, agentID, cacheKeyPrefix string, cache cache.Cache) *WorkJsTicket {
|
|
||||||
return &WorkJsTicket{
|
|
||||||
corpID: corpID,
|
|
||||||
agentID: agentID,
|
|
||||||
cache: cache,
|
|
||||||
cacheKeyPrefix: cacheKeyPrefix,
|
|
||||||
jsAPITicketLock: new(sync.Mutex),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetTicket 根据类型获取相应的jsapi_ticket
|
|
||||||
func (js *WorkJsTicket) GetTicket(accessToken string, ticketType TicketType) (ticketStr string, err error) {
|
|
||||||
var cacheKey string
|
|
||||||
switch ticketType {
|
|
||||||
case TicketTypeCorpJs:
|
|
||||||
cacheKey = fmt.Sprintf("%s_corp_jsapi_ticket_%s", js.cacheKeyPrefix, js.corpID)
|
|
||||||
case TicketTypeAgentJs:
|
|
||||||
if js.agentID == "" {
|
|
||||||
err = fmt.Errorf("agentID is empty")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
cacheKey = fmt.Sprintf("%s_agent_jsapi_ticket_%s_%s", js.cacheKeyPrefix, js.corpID, js.agentID)
|
|
||||||
default:
|
|
||||||
err = fmt.Errorf("unsupported ticket type: %v", ticketType)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if val := js.cache.Get(cacheKey); val != nil {
|
|
||||||
return val.(string), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
js.jsAPITicketLock.Lock()
|
|
||||||
defer js.jsAPITicketLock.Unlock()
|
|
||||||
|
|
||||||
// 双检,防止重复从微信服务器获取
|
|
||||||
if val := js.cache.Get(cacheKey); val != nil {
|
|
||||||
return val.(string), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var ticket ResTicket
|
|
||||||
ticket, err = js.getTicketFromServer(accessToken, ticketType)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
expires := ticket.ExpiresIn - 1500
|
|
||||||
err = js.cache.Set(cacheKey, ticket.Ticket, time.Duration(expires)*time.Second)
|
|
||||||
ticketStr = ticket.Ticket
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// getTicketFromServer 从服务器中获取ticket
|
|
||||||
func (js *WorkJsTicket) getTicketFromServer(accessToken string, ticketType TicketType) (ticket ResTicket, err error) {
|
|
||||||
var url string
|
|
||||||
switch ticketType {
|
|
||||||
case TicketTypeCorpJs:
|
|
||||||
url = fmt.Sprintf(getWorkJsTicketURL, accessToken)
|
|
||||||
case TicketTypeAgentJs:
|
|
||||||
url = fmt.Sprintf(getWorkAgentJsTicketURL, accessToken)
|
|
||||||
default:
|
|
||||||
err = fmt.Errorf("unsupported ticket type: %v", ticketType)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var response []byte
|
|
||||||
response, err = util.HTTPGet(url)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
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
|
|
||||||
}
|
|
||||||
@@ -90,12 +90,10 @@ host: https://qyapi.weixin.qq.com/
|
|||||||
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 | 贡献者 |
|
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 | 贡献者 |
|
||||||
|:---------:|------|:----------------------------------------| ---------- | ------------------------------- |----------|
|
|:---------:|------|:----------------------------------------| ---------- | ------------------------------- |----------|
|
||||||
| 获取子部门ID列表 | GET | /cgi-bin/department/simplelist | YES | (r *Client) DepartmentSimpleList| MARKWANG |
|
| 获取子部门ID列表 | GET | /cgi-bin/department/simplelist | YES | (r *Client) DepartmentSimpleList| MARKWANG |
|
||||||
| 获取部门列表 | GET | /cgi-bin/department/list | YES | (r *Client) DepartmentList| just5325, ourines |
|
|
||||||
| 获取部门成员 | GET | /cgi-bin/user/simplelist | YES | (r *Client) UserSimpleList | MARKWANG |
|
| 获取部门成员 | GET | /cgi-bin/user/simplelist | YES | (r *Client) UserSimpleList | MARKWANG |
|
||||||
| 获取成员ID列表 | Post | /cgi-bin/user/list_id | YES | (r *Client) UserListId | MARKWANG |
|
| 获取成员ID列表 | Post | /cgi-bin/user/list_id | YES | (r *Client) UserListId | MARKWANG |
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## 素材管理
|
## 素材管理
|
||||||
[官方文档](https://developer.work.weixin.qq.com/document/path/91054)
|
[官方文档](https://developer.work.weixin.qq.com/document/path/91054)
|
||||||
|
|
||||||
|
|||||||
@@ -2,12 +2,12 @@ package openapi
|
|||||||
|
|
||||||
import "github.com/silenceper/wechat/v2/util"
|
import "github.com/silenceper/wechat/v2/util"
|
||||||
|
|
||||||
// GetAPIQuotaParams 查询 API 调用额度参数
|
// GetAPIQuotaParams 查询API调用额度参数
|
||||||
type GetAPIQuotaParams struct {
|
type GetAPIQuotaParams struct {
|
||||||
CgiPath string `json:"cgi_path"` // api 的请求地址,例如"/cgi-bin/message/custom/send";不要前缀“https://api.weixin.qq.com” ,也不要漏了"/",否则都会 76003 的报错
|
CgiPath string `json:"cgi_path"` // api的请求地址,例如"/cgi-bin/message/custom/send";不要前缀“https://api.weixin.qq.com” ,也不要漏了"/",否则都会76003的报错
|
||||||
}
|
}
|
||||||
|
|
||||||
// APIQuota API 调用额度
|
// APIQuota API调用额度
|
||||||
type APIQuota struct {
|
type APIQuota struct {
|
||||||
util.CommonError
|
util.CommonError
|
||||||
Quota struct {
|
Quota struct {
|
||||||
@@ -17,20 +17,20 @@ type APIQuota struct {
|
|||||||
} `json:"quota"` // 详情
|
} `json:"quota"` // 详情
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetRidInfoParams 查询 rid 信息参数
|
// GetRidInfoParams 查询rid信息参数
|
||||||
type GetRidInfoParams struct {
|
type GetRidInfoParams struct {
|
||||||
Rid string `json:"rid"` // 调用接口报错返回的 rid
|
Rid string `json:"rid"` // 调用接口报错返回的rid
|
||||||
}
|
}
|
||||||
|
|
||||||
// RidInfo rid 信息
|
// RidInfo rid信息
|
||||||
type RidInfo struct {
|
type RidInfo struct {
|
||||||
util.CommonError
|
util.CommonError
|
||||||
Request struct {
|
Request struct {
|
||||||
InvokeTime int64 `json:"invoke_time"` // 发起请求的时间戳
|
InvokeTime int64 `json:"invoke_time"` // 发起请求的时间戳
|
||||||
CostInMs int64 `json:"cost_in_ms"` // 请求毫秒级耗时
|
CostInMs int64 `json:"cost_in_ms"` // 请求毫秒级耗时
|
||||||
RequestURL string `json:"request_url"` // 请求的 URL 参数
|
RequestURL string `json:"request_url"` // 请求的URL参数
|
||||||
RequestBody string `json:"request_body"` // post 请求的请求参数
|
RequestBody string `json:"request_body"` // post请求的请求参数
|
||||||
ResponseBody string `json:"response_body"` // 接口请求返回参数
|
ResponseBody string `json:"response_body"` // 接口请求返回参数
|
||||||
ClientIP string `json:"client_ip"` // 接口请求的客户端 ip
|
ClientIP string `json:"client_ip"` // 接口请求的客户端ip
|
||||||
} `json:"request"` // 该 rid 对应的请求详情
|
} `json:"request"` // 该rid对应的请求详情
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,22 +10,11 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// code2SessionURL 小程序登录
|
|
||||||
code2SessionURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
|
code2SessionURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
|
||||||
// checkEncryptedDataURL 检查加密信息
|
|
||||||
checkEncryptedDataURL = "https://api.weixin.qq.com/wxa/business/checkencryptedmsg?access_token=%s"
|
checkEncryptedDataURL = "https://api.weixin.qq.com/wxa/business/checkencryptedmsg?access_token=%s"
|
||||||
// getPhoneNumber 获取手机号
|
|
||||||
getPhoneNumber = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s"
|
getPhoneNumber = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s"
|
||||||
// checkSessionURL 检验登录态
|
|
||||||
checkSessionURL = "https://api.weixin.qq.com/wxa/checksession?access_token=%s&signature=%s&openid=%s&sig_method=hmac_sha256"
|
|
||||||
// resetUserSessionKeyURL 重置登录态
|
|
||||||
resetUserSessionKeyURL = "https://api.weixin.qq.com/wxa/resetusersessionkey?access_token=%s&signature=%s&openid=%s&sig_method=hmac_sha256"
|
|
||||||
// getPluginOpenPIDURL 获取插件用户openPID
|
|
||||||
getPluginOpenPIDURL = "https://api.weixin.qq.com/wxa/getpluginopenpid?access_token=%s"
|
|
||||||
// getPaidUnionIDURL 支付后获取 UnionID
|
|
||||||
getPaidUnionIDURL = "https://api.weixin.qq.com/wxa/getpaidunionid"
|
|
||||||
// getUserEncryptKeyURL 获取用户encryptKey
|
|
||||||
getUserEncryptKeyURL = "https://api.weixin.qq.com/wxa/business/getuserencryptkey?access_token=%s&signature=%s&openid=%s&sig_method=hmac_sha256"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Auth 登录/用户信息
|
// Auth 登录/用户信息
|
||||||
@@ -76,45 +65,9 @@ func (auth *Auth) Code2SessionContext(ctx context2.Context, jsCode string) (resu
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
type (
|
|
||||||
// GetPaidUnionIDRequest 支付后获取UnionID请求
|
|
||||||
GetPaidUnionIDRequest struct {
|
|
||||||
OpenID string `json:"openid"`
|
|
||||||
TransactionID string `json:"transaction_id,omitempty"`
|
|
||||||
MchID string `json:"mch_id,omitempty"`
|
|
||||||
OutTradeNo string `json:"out_trade_no,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPaidUnionIDResponse 支付后获取UnionID响应
|
|
||||||
GetPaidUnionIDResponse struct {
|
|
||||||
util.CommonError
|
|
||||||
UnionID string `json:"unionid"`
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// GetPaidUnionID 用户支付完成后,获取该用户的 UnionId,无需用户授权
|
// GetPaidUnionID 用户支付完成后,获取该用户的 UnionId,无需用户授权
|
||||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/basic-info/getPaidUnionid.html
|
func (auth *Auth) GetPaidUnionID() {
|
||||||
func (auth *Auth) GetPaidUnionID(req *GetPaidUnionIDRequest) (string, error) {
|
// TODO
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = auth.GetAccessToken(); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
var url string
|
|
||||||
if req.TransactionID != "" {
|
|
||||||
url = fmt.Sprintf("%s?access_token=%s&openid=%s&transaction_id=%s", getPaidUnionIDURL, accessToken, req.OpenID, req.TransactionID)
|
|
||||||
} else {
|
|
||||||
url = fmt.Sprintf("%s?access_token=%s&openid=%s&mch_id=%s&out_trade_no=%s", getPaidUnionIDURL, accessToken, req.OpenID, req.MchID, req.OutTradeNo)
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.HTTPGet(url); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
result := &GetPaidUnionIDResponse{}
|
|
||||||
err = util.DecodeWithError(response, result, "GetPaidUnionID")
|
|
||||||
return result.UnionID, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// CheckEncryptedData .检查加密信息是否由微信生成(当前只支持手机号加密数据),只能检测最近3天生成的加密数据
|
// CheckEncryptedData .检查加密信息是否由微信生成(当前只支持手机号加密数据),只能检测最近3天生成的加密数据
|
||||||
@@ -128,7 +81,7 @@ func (auth *Auth) CheckEncryptedDataContext(ctx context2.Context, encryptedMsgHa
|
|||||||
var (
|
var (
|
||||||
at string
|
at string
|
||||||
)
|
)
|
||||||
if at, err = auth.GetAccessTokenContext(ctx); err != nil {
|
if at, err = auth.GetAccessToken(); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,7 +120,7 @@ func (auth *Auth) GetPhoneNumberContext(ctx context2.Context, code string) (*Get
|
|||||||
at string
|
at string
|
||||||
err error
|
err error
|
||||||
)
|
)
|
||||||
if at, err = auth.GetAccessTokenContext(ctx); err != nil {
|
if at, err = auth.GetAccessToken(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
body := map[string]interface{}{
|
body := map[string]interface{}{
|
||||||
@@ -185,123 +138,13 @@ func (auth *Auth) GetPhoneNumberContext(ctx context2.Context, code string) (*Get
|
|||||||
}
|
}
|
||||||
|
|
||||||
var result GetPhoneNumberResponse
|
var result GetPhoneNumberResponse
|
||||||
err = util.DecodeWithError(response, &result, "phonenumber.getPhoneNumber")
|
if err = util.DecodeWithError(response, &result, "phonenumber.getPhoneNumber"); err != nil {
|
||||||
return &result, err
|
return nil, err
|
||||||
|
}
|
||||||
|
return &result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetPhoneNumber 小程序通过code获取用户手机号
|
// GetPhoneNumber 小程序通过code获取用户手机号
|
||||||
func (auth *Auth) GetPhoneNumber(code string) (*GetPhoneNumberResponse, error) {
|
func (auth *Auth) GetPhoneNumber(code string) (*GetPhoneNumberResponse, error) {
|
||||||
return auth.GetPhoneNumberContext(context2.Background(), code)
|
return auth.GetPhoneNumberContext(context2.Background(), code)
|
||||||
}
|
}
|
||||||
|
|
||||||
// CheckSession 检验登录态
|
|
||||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/checkSessionKey.html
|
|
||||||
func (auth *Auth) CheckSession(signature, openID string) error {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = auth.GetAccessToken(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.HTTPGet(fmt.Sprintf(checkSessionURL, accessToken, signature, openID)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithCommonError(response, "CheckSession")
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResetUserSessionKeyResponse 重置登录态响应
|
|
||||||
type ResetUserSessionKeyResponse struct {
|
|
||||||
util.CommonError
|
|
||||||
OpenID string `json:"openid"`
|
|
||||||
SessionKey string `json:"session_key"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResetUserSessionKey 重置登录态
|
|
||||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/ResetUserSessionKey.html
|
|
||||||
func (auth *Auth) ResetUserSessionKey(signature, openID string) (*ResetUserSessionKeyResponse, error) {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = auth.GetAccessToken(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.HTTPGet(fmt.Sprintf(resetUserSessionKeyURL, accessToken, signature, openID)); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result := &ResetUserSessionKeyResponse{}
|
|
||||||
err = util.DecodeWithError(response, result, "ResetUserSessionKey")
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|
||||||
type (
|
|
||||||
// GetPluginOpenPIDRequest 获取插件用户openPID请求
|
|
||||||
GetPluginOpenPIDRequest struct {
|
|
||||||
Code string `json:"code"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPluginOpenPIDResponse 获取插件用户openPID响应
|
|
||||||
GetPluginOpenPIDResponse struct {
|
|
||||||
util.CommonError
|
|
||||||
OpenPID string `json:"openpid"`
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// GetPluginOpenPID 获取插件用户openPID
|
|
||||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/basic-info/getPluginOpenPId.html
|
|
||||||
func (auth *Auth) GetPluginOpenPID(code string) (string, error) {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = auth.GetAccessToken(); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
req := &GetPluginOpenPIDRequest{
|
|
||||||
Code: code,
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(getPluginOpenPIDURL, accessToken), req); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
result := &GetPluginOpenPIDResponse{}
|
|
||||||
err = util.DecodeWithError(response, result, "GetPluginOpenPID")
|
|
||||||
return result.OpenPID, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUserEncryptKeyResponse 获取用户encryptKey响应
|
|
||||||
type GetUserEncryptKeyResponse struct {
|
|
||||||
util.CommonError
|
|
||||||
KeyInfoList []KeyInfo `json:"key_info_list"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// KeyInfo 用户最近三次的加密key
|
|
||||||
type KeyInfo struct {
|
|
||||||
EncryptKey string `json:"encrypt_key"`
|
|
||||||
Version int64 `json:"version"`
|
|
||||||
ExpireIn int64 `json:"expire_in"`
|
|
||||||
Iv string `json:"iv"`
|
|
||||||
CreateTime int64 `json:"create_time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUserEncryptKey 获取用户encryptKey
|
|
||||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/internet/getUserEncryptKey.html
|
|
||||||
func (auth *Auth) GetUserEncryptKey(signature, openID string) (*GetUserEncryptKeyResponse, error) {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = auth.GetAccessToken(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.HTTPGet(fmt.Sprintf(getUserEncryptKeyURL, accessToken, signature, openID)); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result := &GetUserEncryptKeyResponse{}
|
|
||||||
err = util.DecodeWithError(response, result, "GetUserEncryptKey")
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package business
|
package business
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
"github.com/silenceper/wechat/v2/util"
|
||||||
@@ -29,18 +28,13 @@ type PhoneInfo struct {
|
|||||||
|
|
||||||
// GetPhoneNumber code换取用户手机号。 每个code只能使用一次,code的有效期为5min
|
// GetPhoneNumber code换取用户手机号。 每个code只能使用一次,code的有效期为5min
|
||||||
func (business *Business) GetPhoneNumber(in *GetPhoneNumberRequest) (info PhoneInfo, err error) {
|
func (business *Business) GetPhoneNumber(in *GetPhoneNumberRequest) (info PhoneInfo, err error) {
|
||||||
return business.GetPhoneNumberWithContext(context.Background(), in)
|
accessToken, err := business.GetAccessToken()
|
||||||
}
|
|
||||||
|
|
||||||
// GetPhoneNumberWithContext 利用context将code换取用户手机号。 每个code只能使用一次,code的有效期为5min
|
|
||||||
func (business *Business) GetPhoneNumberWithContext(ctx context.Context, in *GetPhoneNumberRequest) (info PhoneInfo, err error) {
|
|
||||||
accessToken, err := business.GetAccessTokenContext(ctx)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
uri := fmt.Sprintf(getPhoneNumberURL, accessToken)
|
uri := fmt.Sprintf(getPhoneNumberURL, accessToken)
|
||||||
response, err := util.PostJSONContext(ctx, uri, in)
|
response, err := util.PostJSON(uri, in)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -51,5 +45,10 @@ func (business *Business) GetPhoneNumberWithContext(ctx context.Context, in *Get
|
|||||||
PhoneInfo PhoneInfo `json:"phone_info"`
|
PhoneInfo PhoneInfo `json:"phone_info"`
|
||||||
}
|
}
|
||||||
err = util.DecodeWithError(response, &resp, "business.GetPhoneNumber")
|
err = util.DecodeWithError(response, &resp, "business.GetPhoneNumber")
|
||||||
return resp.PhoneInfo, err
|
if nil != err {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
info = resp.PhoneInfo
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,5 +14,4 @@ type Config struct {
|
|||||||
Token string `json:"token"` // token
|
Token string `json:"token"` // token
|
||||||
EncodingAESKey string `json:"encoding_aes_key"` // EncodingAESKey
|
EncodingAESKey string `json:"encoding_aes_key"` // EncodingAESKey
|
||||||
Cache cache.Cache
|
Cache cache.Cache
|
||||||
UseStableAK bool // use the stable access_token
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,5 +8,5 @@ import (
|
|||||||
// Context struct
|
// Context struct
|
||||||
type Context struct {
|
type Context struct {
|
||||||
*config.Config
|
*config.Config
|
||||||
credential.AccessTokenContextHandle
|
credential.AccessTokenHandle
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,8 +9,6 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/tidwall/gjson"
|
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/context"
|
"github.com/silenceper/wechat/v2/miniprogram/context"
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/security"
|
"github.com/silenceper/wechat/v2/miniprogram/security"
|
||||||
"github.com/silenceper/wechat/v2/util"
|
"github.com/silenceper/wechat/v2/util"
|
||||||
@@ -205,96 +203,32 @@ func (receiver *PushReceiver) getEvent(dataType string, eventType EventType, dec
|
|||||||
return &pushData, err
|
return &pushData, err
|
||||||
case EventSubscribePopup:
|
case EventSubscribePopup:
|
||||||
// 用户操作订阅通知弹窗事件推送
|
// 用户操作订阅通知弹窗事件推送
|
||||||
return receiver.unmarshalSubscribePopup(dataType, decryptMsg)
|
var pushData PushDataSubscribePopup
|
||||||
|
err := receiver.unmarshal(dataType, decryptMsg, &pushData)
|
||||||
|
return &pushData, err
|
||||||
case EventSubscribeMsgChange:
|
case EventSubscribeMsgChange:
|
||||||
// 用户管理订阅通知事件推送
|
// 用户管理订阅通知事件推送
|
||||||
return receiver.unmarshalSubscribeMsgChange(dataType, decryptMsg)
|
var pushData PushDataSubscribeMsgChange
|
||||||
|
err := receiver.unmarshal(dataType, decryptMsg, &pushData)
|
||||||
|
return &pushData, err
|
||||||
case EventSubscribeMsgSent:
|
case EventSubscribeMsgSent:
|
||||||
// 用户发送订阅通知事件推送
|
// 用户发送订阅通知事件推送
|
||||||
return receiver.unmarshalSubscribeMsgSent(dataType, decryptMsg)
|
var pushData PushDataSubscribeMsgSent
|
||||||
|
err := receiver.unmarshal(dataType, decryptMsg, &pushData)
|
||||||
|
return &pushData, err
|
||||||
}
|
}
|
||||||
// 暂不支持其他事件类型,直接返回解密后的数据,由调用方处理
|
// 暂不支持其他事件类型,直接返回解密后的数据,由调用方处理
|
||||||
return decryptMsg, nil
|
return decryptMsg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// unmarshal 解析推送的数据
|
// unmarshal 解析推送的数据
|
||||||
func (receiver *PushReceiver) unmarshal(dataType string, decryptMsg []byte, pushData interface{}) error {
|
func (receiver *PushReceiver) unmarshal(dateType string, decryptMsg []byte, pushData interface{}) error {
|
||||||
if dataType == DataTypeXML {
|
if dateType == DataTypeXML {
|
||||||
return xml.Unmarshal(decryptMsg, pushData)
|
return xml.Unmarshal(decryptMsg, pushData)
|
||||||
}
|
}
|
||||||
return json.Unmarshal(decryptMsg, pushData)
|
return json.Unmarshal(decryptMsg, pushData)
|
||||||
}
|
}
|
||||||
|
|
||||||
// unmarshalSubscribePopup
|
|
||||||
func (receiver *PushReceiver) unmarshalSubscribePopup(dataType string, decryptMsg []byte) (PushData, error) {
|
|
||||||
var pushData PushDataSubscribePopup
|
|
||||||
err := receiver.unmarshal(dataType, decryptMsg, &pushData)
|
|
||||||
if err == nil {
|
|
||||||
listData := gjson.Get(string(decryptMsg), "List")
|
|
||||||
if listData.IsObject() {
|
|
||||||
listItem := SubscribeMsgPopupEventList{}
|
|
||||||
if parseErr := json.Unmarshal([]byte(listData.Raw), &listItem); parseErr != nil {
|
|
||||||
return &pushData, parseErr
|
|
||||||
}
|
|
||||||
pushData.SetSubscribeMsgPopupEvents([]SubscribeMsgPopupEventList{listItem})
|
|
||||||
} else if listData.IsArray() {
|
|
||||||
listItems := make([]SubscribeMsgPopupEventList, 0)
|
|
||||||
if parseErr := json.Unmarshal([]byte(listData.Raw), &listItems); parseErr != nil {
|
|
||||||
return &pushData, parseErr
|
|
||||||
}
|
|
||||||
pushData.SetSubscribeMsgPopupEvents(listItems)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &pushData, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// unmarshalSubscribeMsgChange 解析用户管理订阅通知事件推送
|
|
||||||
func (receiver *PushReceiver) unmarshalSubscribeMsgChange(dataType string, decryptMsg []byte) (PushData, error) {
|
|
||||||
var pushData PushDataSubscribeMsgChange
|
|
||||||
err := receiver.unmarshal(dataType, decryptMsg, &pushData)
|
|
||||||
if err == nil {
|
|
||||||
listData := gjson.Get(string(decryptMsg), "List")
|
|
||||||
if listData.IsObject() {
|
|
||||||
listItem := SubscribeMsgChangeList{}
|
|
||||||
if parseErr := json.Unmarshal([]byte(listData.Raw), &listItem); parseErr != nil {
|
|
||||||
return &pushData, parseErr
|
|
||||||
}
|
|
||||||
pushData.SetSubscribeMsgChangeEvents([]SubscribeMsgChangeList{listItem})
|
|
||||||
} else if listData.IsArray() {
|
|
||||||
listItems := make([]SubscribeMsgChangeList, 0)
|
|
||||||
if parseErr := json.Unmarshal([]byte(listData.Raw), &listItems); parseErr != nil {
|
|
||||||
return &pushData, parseErr
|
|
||||||
}
|
|
||||||
pushData.SetSubscribeMsgChangeEvents(listItems)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return &pushData, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// unmarshalSubscribeMsgSent 解析用户发送订阅通知事件推送
|
|
||||||
func (receiver *PushReceiver) unmarshalSubscribeMsgSent(dataType string, decryptMsg []byte) (PushData, error) {
|
|
||||||
var pushData PushDataSubscribeMsgSent
|
|
||||||
err := receiver.unmarshal(dataType, decryptMsg, &pushData)
|
|
||||||
if err == nil {
|
|
||||||
listData := gjson.Get(string(decryptMsg), "List")
|
|
||||||
if listData.IsObject() {
|
|
||||||
listItem := SubscribeMsgSentList{}
|
|
||||||
if parseErr := json.Unmarshal([]byte(listData.Raw), &listItem); parseErr != nil {
|
|
||||||
return &pushData, parseErr
|
|
||||||
}
|
|
||||||
pushData.SetSubscribeMsgSentEvents([]SubscribeMsgSentList{listItem})
|
|
||||||
} else if listData.IsArray() {
|
|
||||||
listItems := make([]SubscribeMsgSentList, 0)
|
|
||||||
if parseErr := json.Unmarshal([]byte(listData.Raw), &listItems); parseErr != nil {
|
|
||||||
return &pushData, parseErr
|
|
||||||
}
|
|
||||||
pushData.SetSubscribeMsgSentEvents(listItems)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return &pushData, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// DataReceived 接收到的数据
|
// DataReceived 接收到的数据
|
||||||
type DataReceived struct {
|
type DataReceived struct {
|
||||||
Encrypt string `json:"Encrypt" xml:"Encrypt"` // 加密的消息体
|
Encrypt string `json:"Encrypt" xml:"Encrypt"` // 加密的消息体
|
||||||
@@ -398,7 +332,7 @@ type PushDataSecVodUpload struct {
|
|||||||
|
|
||||||
// SecVodUploadEvent 短剧媒资上传完成事件
|
// SecVodUploadEvent 短剧媒资上传完成事件
|
||||||
type SecVodUploadEvent struct {
|
type SecVodUploadEvent struct {
|
||||||
MediaID int64 `json:"media_id" xml:"media_id"` // 媒资 id
|
MediaID string `json:"media_id" xml:"media_id"` // 媒资 id
|
||||||
SourceContext string `json:"source_context" xml:"source_context"` // 透传上传接口中开发者设置的值。
|
SourceContext string `json:"source_context" xml:"source_context"` // 透传上传接口中开发者设置的值。
|
||||||
ErrCode int `json:"errcode" xml:"errcode"` // 错误码,上传失败时该值非
|
ErrCode int `json:"errcode" xml:"errcode"` // 错误码,上传失败时该值非
|
||||||
ErrMsg string `json:"errmsg" xml:"errmsg"` // 错误提示
|
ErrMsg string `json:"errmsg" xml:"errmsg"` // 错误提示
|
||||||
@@ -412,7 +346,7 @@ type PushDataSecVodAudit struct {
|
|||||||
|
|
||||||
// SecVodAuditEvent 短剧媒资审核状态事件
|
// SecVodAuditEvent 短剧媒资审核状态事件
|
||||||
type SecVodAuditEvent struct {
|
type SecVodAuditEvent struct {
|
||||||
DramaID int64 `json:"drama_id" xml:"drama_id"` // 剧目 id
|
DramaID string `json:"drama_id" xml:"drama_id"` // 剧目 id
|
||||||
SourceContext string `json:"source_context" xml:"source_context"` // 透传上传接口中开发者设置的值
|
SourceContext string `json:"source_context" xml:"source_context"` // 透传上传接口中开发者设置的值
|
||||||
AuditDetail DramaAuditDetail `json:"audit_detail" xml:"audit_detail"` // 剧目审核结果,单独每一集的审核结果可以根据 drama_id 查询剧集详情得到
|
AuditDetail DramaAuditDetail `json:"audit_detail" xml:"audit_detail"` // 剧目审核结果,单独每一集的审核结果可以根据 drama_id 查询剧集详情得到
|
||||||
}
|
}
|
||||||
@@ -471,13 +405,12 @@ type CoinInfo struct {
|
|||||||
// PushDataSubscribePopup 用户操作订阅通知弹窗事件推送
|
// PushDataSubscribePopup 用户操作订阅通知弹窗事件推送
|
||||||
type PushDataSubscribePopup struct {
|
type PushDataSubscribePopup struct {
|
||||||
CommonPushData
|
CommonPushData
|
||||||
subscribeMsgPopupEventList []SubscribeMsgPopupEventList `json:"-"`
|
List []SubscribeMsgPopupEventList `xml:"SubscribeMsgPopupEvent>List" json:"List"`
|
||||||
SubscribeMsgPopupEvent SubscribeMsgPopupEvent `xml:"SubscribeMsgPopupEvent"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SubscribeMsgPopupEvent 用户操作订阅通知弹窗消息回调
|
// SubscribeMsgPopupEvent 用户操作订阅通知弹窗消息回调
|
||||||
type SubscribeMsgPopupEvent struct {
|
type SubscribeMsgPopupEvent struct {
|
||||||
List []SubscribeMsgPopupEventList `xml:"List"`
|
List []SubscribeMsgPopupEventList `xml:"List" json:"List"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SubscribeMsgPopupEventList 订阅消息事件列表
|
// SubscribeMsgPopupEventList 订阅消息事件列表
|
||||||
@@ -487,28 +420,10 @@ type SubscribeMsgPopupEventList struct {
|
|||||||
PopupScene string `xml:"PopupScene" json:"PopupScene"`
|
PopupScene string `xml:"PopupScene" json:"PopupScene"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetSubscribeMsgPopupEvents 设置订阅消息事件
|
|
||||||
func (s *PushDataSubscribePopup) SetSubscribeMsgPopupEvents(list []SubscribeMsgPopupEventList) {
|
|
||||||
s.subscribeMsgPopupEventList = list
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSubscribeMsgPopupEvents 获取订阅消息事件数据
|
|
||||||
func (s *PushDataSubscribePopup) GetSubscribeMsgPopupEvents() []SubscribeMsgPopupEventList {
|
|
||||||
if s.subscribeMsgPopupEventList != nil {
|
|
||||||
return s.subscribeMsgPopupEventList
|
|
||||||
}
|
|
||||||
|
|
||||||
if s.SubscribeMsgPopupEvent.List == nil || len(s.SubscribeMsgPopupEvent.List) < 1 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return s.SubscribeMsgPopupEvent.List
|
|
||||||
}
|
|
||||||
|
|
||||||
// PushDataSubscribeMsgChange 用户管理订阅通知事件推送
|
// PushDataSubscribeMsgChange 用户管理订阅通知事件推送
|
||||||
type PushDataSubscribeMsgChange struct {
|
type PushDataSubscribeMsgChange struct {
|
||||||
CommonPushData
|
CommonPushData
|
||||||
SubscribeMsgChangeEvent SubscribeMsgChangeEvent `xml:"SubscribeMsgChangeEvent"`
|
List []SubscribeMsgChangeList `xml:"SubscribeMsgChangeEvent>List" json:"List"`
|
||||||
subscribeMsgChangeList []SubscribeMsgChangeList `json:"-"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SubscribeMsgChangeEvent 用户管理订阅通知回调
|
// SubscribeMsgChangeEvent 用户管理订阅通知回调
|
||||||
@@ -522,58 +437,21 @@ type SubscribeMsgChangeList struct {
|
|||||||
SubscribeStatusString string `xml:"SubscribeStatusString" json:"SubscribeStatusString"`
|
SubscribeStatusString string `xml:"SubscribeStatusString" json:"SubscribeStatusString"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetSubscribeMsgChangeEvents 设置订阅消息事件
|
|
||||||
func (s *PushDataSubscribeMsgChange) SetSubscribeMsgChangeEvents(list []SubscribeMsgChangeList) {
|
|
||||||
s.subscribeMsgChangeList = list
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSubscribeMsgChangeEvents 获取订阅消息事件数据
|
|
||||||
func (s *PushDataSubscribeMsgChange) GetSubscribeMsgChangeEvents() []SubscribeMsgChangeList {
|
|
||||||
if s.subscribeMsgChangeList != nil {
|
|
||||||
return s.subscribeMsgChangeList
|
|
||||||
}
|
|
||||||
|
|
||||||
if s.SubscribeMsgChangeEvent.List == nil || len(s.SubscribeMsgChangeEvent.List) < 1 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return s.SubscribeMsgChangeEvent.List
|
|
||||||
}
|
|
||||||
|
|
||||||
// PushDataSubscribeMsgSent 用户发送订阅通知事件推送
|
// PushDataSubscribeMsgSent 用户发送订阅通知事件推送
|
||||||
type PushDataSubscribeMsgSent struct {
|
type PushDataSubscribeMsgSent struct {
|
||||||
CommonPushData
|
CommonPushData
|
||||||
SubscribeMsgSentEvent SubscribeMsgSentEvent `xml:"SubscribeMsgSentEvent"`
|
List []SubscribeMsgSentEventList `xml:"SubscribeMsgSentEvent>List" json:"List"`
|
||||||
subscribeMsgSentEventList []SubscribeMsgSentList `json:"-"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SubscribeMsgSentEvent 用户发送订阅通知回调
|
// SubscribeMsgSentEvent 用户发送订阅通知回调
|
||||||
type SubscribeMsgSentEvent struct {
|
type SubscribeMsgSentEvent struct {
|
||||||
List []SubscribeMsgSentList `xml:"List" json:"List"`
|
List []SubscribeMsgSentEventList `xml:"List" json:"List"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SubscribeMsgSentList 订阅消息事件列表
|
// SubscribeMsgSentEventList 订阅消息事件列表
|
||||||
type SubscribeMsgSentList struct {
|
type SubscribeMsgSentEventList struct {
|
||||||
TemplateID string `xml:"TemplateId" json:"TemplateId"`
|
TemplateID string `xml:"TemplateId" json:"TemplateId"`
|
||||||
MsgID string `xml:"MsgID" json:"MsgID"`
|
MsgID string `xml:"MsgID" json:"MsgID"`
|
||||||
ErrorCode int `xml:"ErrorCode" json:"ErrorCode"`
|
ErrorCode int `xml:"ErrorCode" json:"ErrorCode"`
|
||||||
ErrorStatus string `xml:"ErrorStatus" json:"ErrorStatus"`
|
ErrorStatus string `xml:"ErrorStatus" json:"ErrorStatus"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetSubscribeMsgSentEvents 设置订阅消息事件
|
|
||||||
func (s *PushDataSubscribeMsgSent) SetSubscribeMsgSentEvents(list []SubscribeMsgSentList) {
|
|
||||||
s.subscribeMsgSentEventList = list
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSubscribeMsgSentEvents 获取订阅消息事件数据
|
|
||||||
func (s *PushDataSubscribeMsgSent) GetSubscribeMsgSentEvents() []SubscribeMsgSentList {
|
|
||||||
if s.subscribeMsgSentEventList != nil {
|
|
||||||
return s.subscribeMsgSentEventList
|
|
||||||
}
|
|
||||||
|
|
||||||
if s.SubscribeMsgSentEvent.List == nil || len(s.SubscribeMsgSentEvent.List) < 1 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return s.SubscribeMsgSentEvent.List
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,102 +0,0 @@
|
|||||||
package message
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/context"
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// createActivityURL 创建activity_id
|
|
||||||
createActivityURL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/activityid/create?access_token=%s"
|
|
||||||
// SendUpdatableMsgURL 修改动态消息
|
|
||||||
setUpdatableMsgURL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/updatablemsg/send?access_token=%s"
|
|
||||||
)
|
|
||||||
|
|
||||||
// UpdatableTargetState 动态消息状态
|
|
||||||
type UpdatableTargetState int
|
|
||||||
|
|
||||||
const (
|
|
||||||
// TargetStateNotStarted 未开始
|
|
||||||
TargetStateNotStarted UpdatableTargetState = 0
|
|
||||||
// TargetStateStarted 已开始
|
|
||||||
TargetStateStarted UpdatableTargetState = 1
|
|
||||||
// TargetStateFinished 已结束
|
|
||||||
TargetStateFinished UpdatableTargetState = 2
|
|
||||||
)
|
|
||||||
|
|
||||||
// UpdatableMessage 动态消息
|
|
||||||
type UpdatableMessage struct {
|
|
||||||
*context.Context
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewUpdatableMessage 实例化
|
|
||||||
func NewUpdatableMessage(ctx *context.Context) *UpdatableMessage {
|
|
||||||
return &UpdatableMessage{
|
|
||||||
Context: ctx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateActivityID 创建activity_id
|
|
||||||
func (updatableMessage *UpdatableMessage) CreateActivityID() (res CreateActivityIDResponse, err error) {
|
|
||||||
accessToken, err := updatableMessage.GetAccessToken()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
uri := fmt.Sprintf(createActivityURL, accessToken)
|
|
||||||
response, err := util.HTTPGet(uri)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
err = util.DecodeWithError(response, &res, "CreateActivityID")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetUpdatableMsg 修改动态消息
|
|
||||||
func (updatableMessage *UpdatableMessage) SetUpdatableMsg(activityID string, targetState UpdatableTargetState, template UpdatableMsgTemplate) (err error) {
|
|
||||||
accessToken, err := updatableMessage.GetAccessToken()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
uri := fmt.Sprintf(setUpdatableMsgURL, accessToken)
|
|
||||||
data := SendUpdatableMsgReq{
|
|
||||||
ActivityID: activityID,
|
|
||||||
TargetState: targetState,
|
|
||||||
TemplateInfo: template,
|
|
||||||
}
|
|
||||||
|
|
||||||
response, err := util.PostJSON(uri, data)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return util.DecodeWithCommonError(response, "SendUpdatableMsg")
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateActivityIDResponse 创建activity_id 返回
|
|
||||||
type CreateActivityIDResponse struct {
|
|
||||||
util.CommonError
|
|
||||||
|
|
||||||
ActivityID string `json:"activity_id"`
|
|
||||||
ExpirationTime int64 `json:"expiration_time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdatableMsgTemplate 动态消息模板
|
|
||||||
type UpdatableMsgTemplate struct {
|
|
||||||
ParameterList []UpdatableMsgParameter `json:"parameter_list"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdatableMsgParameter 动态消息参数
|
|
||||||
type UpdatableMsgParameter struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Value string `json:"value"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendUpdatableMsgReq 修改动态消息参数
|
|
||||||
type SendUpdatableMsgReq struct {
|
|
||||||
ActivityID string `json:"activity_id"`
|
|
||||||
TemplateInfo UpdatableMsgTemplate `json:"template_info"`
|
|
||||||
TargetState UpdatableTargetState `json:"target_state"`
|
|
||||||
}
|
|
||||||
@@ -15,7 +15,6 @@ import (
|
|||||||
"github.com/silenceper/wechat/v2/miniprogram/order"
|
"github.com/silenceper/wechat/v2/miniprogram/order"
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/privacy"
|
"github.com/silenceper/wechat/v2/miniprogram/privacy"
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/qrcode"
|
"github.com/silenceper/wechat/v2/miniprogram/qrcode"
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/redpacketcover"
|
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/riskcontrol"
|
"github.com/silenceper/wechat/v2/miniprogram/riskcontrol"
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/security"
|
"github.com/silenceper/wechat/v2/miniprogram/security"
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/shortlink"
|
"github.com/silenceper/wechat/v2/miniprogram/shortlink"
|
||||||
@@ -34,30 +33,17 @@ type MiniProgram struct {
|
|||||||
|
|
||||||
// NewMiniProgram 实例化小程序 API
|
// NewMiniProgram 实例化小程序 API
|
||||||
func NewMiniProgram(cfg *config.Config) *MiniProgram {
|
func NewMiniProgram(cfg *config.Config) *MiniProgram {
|
||||||
var defaultAkHandle credential.AccessTokenContextHandle
|
defaultAkHandle := credential.NewDefaultAccessToken(cfg.AppID, cfg.AppSecret, credential.CacheKeyMiniProgramPrefix, cfg.Cache)
|
||||||
const cacheKeyPrefix = credential.CacheKeyMiniProgramPrefix
|
|
||||||
if cfg.UseStableAK {
|
|
||||||
defaultAkHandle = credential.NewStableAccessToken(cfg.AppID, cfg.AppSecret, cacheKeyPrefix, cfg.Cache)
|
|
||||||
} else {
|
|
||||||
defaultAkHandle = credential.NewDefaultAccessToken(cfg.AppID, cfg.AppSecret, cacheKeyPrefix, cfg.Cache)
|
|
||||||
}
|
|
||||||
ctx := &context.Context{
|
ctx := &context.Context{
|
||||||
Config: cfg,
|
Config: cfg,
|
||||||
AccessTokenContextHandle: defaultAkHandle,
|
AccessTokenHandle: defaultAkHandle,
|
||||||
}
|
}
|
||||||
return &MiniProgram{ctx}
|
return &MiniProgram{ctx}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetAccessTokenHandle 自定义 access_token 获取方式
|
// SetAccessTokenHandle 自定义 access_token 获取方式
|
||||||
func (miniProgram *MiniProgram) SetAccessTokenHandle(accessTokenHandle credential.AccessTokenHandle) {
|
func (miniProgram *MiniProgram) SetAccessTokenHandle(accessTokenHandle credential.AccessTokenHandle) {
|
||||||
miniProgram.ctx.AccessTokenContextHandle = credential.AccessTokenCompatibleHandle{
|
miniProgram.ctx.AccessTokenHandle = accessTokenHandle
|
||||||
AccessTokenHandle: accessTokenHandle,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetAccessTokenContextHandle 自定义 access_token 获取方式
|
|
||||||
func (miniProgram *MiniProgram) SetAccessTokenContextHandle(accessTokenContextHandle credential.AccessTokenContextHandle) {
|
|
||||||
miniProgram.ctx.AccessTokenContextHandle = accessTokenContextHandle
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetContext get Context
|
// GetContext get Context
|
||||||
@@ -169,13 +155,3 @@ func (miniProgram *MiniProgram) GetShipping() *order.Shipping {
|
|||||||
func (miniProgram *MiniProgram) GetMiniDrama() *minidrama.MiniDrama {
|
func (miniProgram *MiniProgram) GetMiniDrama() *minidrama.MiniDrama {
|
||||||
return minidrama.NewMiniDrama(miniProgram.ctx)
|
return minidrama.NewMiniDrama(miniProgram.ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetRedPacketCover 小程序微信红包封面 API
|
|
||||||
func (miniProgram *MiniProgram) GetRedPacketCover() *redpacketcover.RedPacketCover {
|
|
||||||
return redpacketcover.NewRedPacketCover(miniProgram.ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUpdatableMessage 小程序动态消息
|
|
||||||
func (miniProgram *MiniProgram) GetUpdatableMessage() *message.UpdatableMessage {
|
|
||||||
return message.NewUpdatableMessage(miniProgram.ctx)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -103,8 +103,11 @@ func (s *Privacy) GetPrivacySetting(privacyVer int) (GetPrivacySettingResponse,
|
|||||||
}
|
}
|
||||||
// 返回错误信息
|
// 返回错误信息
|
||||||
var result GetPrivacySettingResponse
|
var result GetPrivacySettingResponse
|
||||||
err = util.DecodeWithError(response, &result, "getprivacysetting")
|
if err = util.DecodeWithError(response, &result, "getprivacysetting"); err != nil {
|
||||||
return result, err
|
return GetPrivacySettingResponse{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetPrivacySetting 更新小程序权限配置
|
// SetPrivacySetting 更新小程序权限配置
|
||||||
@@ -127,7 +130,11 @@ func (s *Privacy) SetPrivacySetting(privacyVer int, ownerSetting OwnerSetting, s
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 返回错误信息
|
// 返回错误信息
|
||||||
return util.DecodeWithCommonError(response, "setprivacysetting")
|
if err = util.DecodeWithCommonError(response, "setprivacysetting"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// UploadPrivacyExtFileResponse 上传权限定义模板响应参数
|
// UploadPrivacyExtFileResponse 上传权限定义模板响应参数
|
||||||
@@ -152,6 +159,9 @@ func (s *Privacy) UploadPrivacyExtFile(fileData []byte) (UploadPrivacyExtFileRes
|
|||||||
|
|
||||||
// 返回错误信息
|
// 返回错误信息
|
||||||
var result UploadPrivacyExtFileResponse
|
var result UploadPrivacyExtFileResponse
|
||||||
err = util.DecodeWithError(response, &result, "setprivacysetting")
|
if err = util.DecodeWithError(response, &result, "setprivacysetting"); err != nil {
|
||||||
|
return UploadPrivacyExtFileResponse{}, err
|
||||||
|
}
|
||||||
|
|
||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,8 +54,6 @@ type QRCoder struct {
|
|||||||
IsHyaline bool `json:"is_hyaline,omitempty"`
|
IsHyaline bool `json:"is_hyaline,omitempty"`
|
||||||
// envVersion 要打开的小程序版本。正式版为 "release",体验版为 "trial",开发版为 "develop"
|
// envVersion 要打开的小程序版本。正式版为 "release",体验版为 "trial",开发版为 "develop"
|
||||||
EnvVersion string `json:"env_version,omitempty"`
|
EnvVersion string `json:"env_version,omitempty"`
|
||||||
// ShowSplashAd 控制通过该小程序码进入小程序是否展示封面广告1、默认为true,展示封面广告2、传入为false时,不展示封面广告
|
|
||||||
ShowSplashAd bool `json:"show_splash_ad,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// fetchCode 请求并返回二维码二进制数据
|
// fetchCode 请求并返回二维码二进制数据
|
||||||
|
|||||||
@@ -1,59 +0,0 @@
|
|||||||
package redpacketcover
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/context"
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
getRedPacketCoverURL = "https://api.weixin.qq.com/redpacketcover/wxapp/cover_url/get_by_token?access_token=%s"
|
|
||||||
)
|
|
||||||
|
|
||||||
// RedPacketCover struct
|
|
||||||
type RedPacketCover struct {
|
|
||||||
*context.Context
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewRedPacketCover 实例
|
|
||||||
func NewRedPacketCover(context *context.Context) *RedPacketCover {
|
|
||||||
redPacketCover := new(RedPacketCover)
|
|
||||||
redPacketCover.Context = context
|
|
||||||
return redPacketCover
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetRedPacketCoverRequest 获取微信红包封面参数
|
|
||||||
type GetRedPacketCoverRequest struct {
|
|
||||||
// openid 可领取用户的openid
|
|
||||||
OpenID string `json:"openid"`
|
|
||||||
// ctoken 在红包封面平台获取发放ctoken(需要指定可以发放的appid)
|
|
||||||
CToken string `json:"ctoken"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetRedPacketCoverResp 获取微信红包封面
|
|
||||||
type GetRedPacketCoverResp struct {
|
|
||||||
util.CommonError
|
|
||||||
Data struct {
|
|
||||||
URL string `json:"url"`
|
|
||||||
} `json:"data"` // 唯一请求标识
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetRedPacketCoverURL 获得指定用户可以领取的红包封面链接。获取参数ctoken参考微信红包封面开放平台
|
|
||||||
// 文档地址: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/red-packet-cover/getRedPacketCoverUrl.html
|
|
||||||
func (cover *RedPacketCover) GetRedPacketCoverURL(coderParams GetRedPacketCoverRequest) (res GetRedPacketCoverResp, err error) {
|
|
||||||
accessToken, err := cover.GetAccessToken()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
uri := fmt.Sprintf(getRedPacketCoverURL, accessToken)
|
|
||||||
response, err := util.PostJSON(uri, coderParams)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 使用通用方法返回错误
|
|
||||||
err = util.DecodeWithError(response, &res, "GetRedPacketCoverURL")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
@@ -51,7 +51,12 @@ func (security *Security) MediaCheckAsyncV1(in *MediaCheckAsyncV1Request) (trace
|
|||||||
TraceID string `json:"trace_id"`
|
TraceID string `json:"trace_id"`
|
||||||
}
|
}
|
||||||
err = util.DecodeWithError(response, &res, "MediaCheckAsyncV1")
|
err = util.DecodeWithError(response, &res, "MediaCheckAsyncV1")
|
||||||
return res.TraceID, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
traceID = res.TraceID
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// MediaCheckAsyncRequest 图片/音频异步校验请求参数
|
// MediaCheckAsyncRequest 图片/音频异步校验请求参数
|
||||||
@@ -88,7 +93,12 @@ func (security *Security) MediaCheckAsync(in *MediaCheckAsyncRequest) (traceID s
|
|||||||
TraceID string `json:"trace_id"`
|
TraceID string `json:"trace_id"`
|
||||||
}
|
}
|
||||||
err = util.DecodeWithError(response, &res, "MediaCheckAsync")
|
err = util.DecodeWithError(response, &res, "MediaCheckAsync")
|
||||||
return res.TraceID, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
traceID = res.TraceID
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// ImageCheckV1 校验一张图片是否含有违法违规内容(同步)
|
// ImageCheckV1 校验一张图片是否含有违法违规内容(同步)
|
||||||
|
|||||||
@@ -60,7 +60,11 @@ func (shortLink *ShortLink) generate(shortLinkParams ShortLinker) (string, error
|
|||||||
// 使用通用方法返回错误
|
// 使用通用方法返回错误
|
||||||
var res resShortLinker
|
var res resShortLinker
|
||||||
err = util.DecodeWithError(response, &res, "GenerateShortLink")
|
err = util.DecodeWithError(response, &res, "GenerateShortLink")
|
||||||
return res.Link, err
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.Link, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GenerateShortLinkPermanent 生成永久 shortLink
|
// GenerateShortLinkPermanent 生成永久 shortLink
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package subscribe
|
package subscribe
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/context"
|
"github.com/silenceper/wechat/v2/miniprogram/context"
|
||||||
@@ -71,13 +70,6 @@ type TemplateList struct {
|
|||||||
Data []TemplateItem `json:"data"`
|
Data []TemplateItem `json:"data"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// resTemplateSend 发送获取 msg id
|
|
||||||
type resTemplateSend struct {
|
|
||||||
util.CommonError
|
|
||||||
|
|
||||||
MsgID int64 `json:"msgid"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send 发送订阅消息
|
// Send 发送订阅消息
|
||||||
func (s *Subscribe) Send(msg *Message) (err error) {
|
func (s *Subscribe) Send(msg *Message) (err error) {
|
||||||
var accessToken string
|
var accessToken string
|
||||||
@@ -93,33 +85,6 @@ func (s *Subscribe) Send(msg *Message) (err error) {
|
|||||||
return util.DecodeWithCommonError(response, "Send")
|
return util.DecodeWithCommonError(response, "Send")
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendGetMsgID 发送订阅消息返回 msgid
|
|
||||||
func (s *Subscribe) SendGetMsgID(msg *Message) (msgID int64, err error) {
|
|
||||||
var accessToken string
|
|
||||||
accessToken, err = s.GetAccessToken()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
uri := fmt.Sprintf("%s?access_token=%s", subscribeSendURL, accessToken)
|
|
||||||
response, err := util.PostJSON(uri, msg)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var result resTemplateSend
|
|
||||||
if err = json.Unmarshal(response, &result); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if result.ErrCode != 0 {
|
|
||||||
err = fmt.Errorf("template msg send error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
msgID = result.MsgID
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListTemplates 获取当前帐号下的个人模板列表
|
// ListTemplates 获取当前帐号下的个人模板列表
|
||||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.getTemplateList.html
|
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.getTemplateList.html
|
||||||
func (s *Subscribe) ListTemplates() (*TemplateList, error) {
|
func (s *Subscribe) ListTemplates() (*TemplateList, error) {
|
||||||
@@ -203,7 +168,11 @@ func (s *Subscribe) Add(ShortID string, kidList []int, sceneDesc string) (templa
|
|||||||
}
|
}
|
||||||
var result resSubscribeAdd
|
var result resSubscribeAdd
|
||||||
err = util.DecodeWithError(response, &result, "AddSubscribe")
|
err = util.DecodeWithError(response, &result, "AddSubscribe")
|
||||||
return result.TemplateID, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
templateID = result.TemplateID
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete 删除私有模板
|
// Delete 删除私有模板
|
||||||
|
|||||||
@@ -65,5 +65,8 @@ func (u *URLLink) Generate(params *ULParams) (string, error) {
|
|||||||
}
|
}
|
||||||
var resp ULResult
|
var resp ULResult
|
||||||
err = util.DecodeWithError(response, &resp, "URLLink.Generate")
|
err = util.DecodeWithError(response, &resp, "URLLink.Generate")
|
||||||
return resp.URLLink, err
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return resp.URLLink, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ type SchemeInfo struct {
|
|||||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-scheme/urlscheme.query.html#参数
|
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-scheme/urlscheme.query.html#参数
|
||||||
type resQueryScheme struct {
|
type resQueryScheme struct {
|
||||||
// 通用错误
|
// 通用错误
|
||||||
util.CommonError
|
*util.CommonError
|
||||||
// scheme 配置
|
// scheme 配置
|
||||||
SchemeInfo SchemeInfo `json:"scheme_info"`
|
SchemeInfo SchemeInfo `json:"scheme_info"`
|
||||||
// 访问该链接的openid,没有用户访问过则为空字符串
|
// 访问该链接的openid,没有用户访问过则为空字符串
|
||||||
@@ -62,5 +62,9 @@ func (u *URLScheme) QueryScheme(querySchemeParams QueryScheme) (schemeInfo Schem
|
|||||||
// 使用通用方法返回错误
|
// 使用通用方法返回错误
|
||||||
var res resQueryScheme
|
var res resQueryScheme
|
||||||
err = util.DecodeWithError(response, &res, "QueryScheme")
|
err = util.DecodeWithError(response, &res, "QueryScheme")
|
||||||
return res.SchemeInfo, res.VisitOpenid, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.SchemeInfo, res.VisitOpenid, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,7 +54,6 @@ type USParams struct {
|
|||||||
ExpireType TExpireType `json:"expire_type"`
|
ExpireType TExpireType `json:"expire_type"`
|
||||||
ExpireTime int64 `json:"expire_time"`
|
ExpireTime int64 `json:"expire_time"`
|
||||||
ExpireInterval int `json:"expire_interval"`
|
ExpireInterval int `json:"expire_interval"`
|
||||||
IsExpire bool `json:"is_expire,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// USResult 返回的结果
|
// USResult 返回的结果
|
||||||
@@ -79,5 +78,8 @@ func (u *URLScheme) Generate(params *USParams) (string, error) {
|
|||||||
}
|
}
|
||||||
var resp USResult
|
var resp USResult
|
||||||
err = util.DecodeWithError(response, &resp, "URLScheme.Generate")
|
err = util.DecodeWithError(response, &resp, "URLScheme.Generate")
|
||||||
return resp.OpenLink, err
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return resp.OpenLink, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,6 +44,9 @@ func (basic *Basic) Long2ShortURL(longURL string) (shortURL string, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err = util.DecodeWithError(responseBytes, resp, long2shortAction)
|
if err = util.DecodeWithError(responseBytes, resp, long2shortAction); err != nil {
|
||||||
return resp.ShortURL, err
|
return
|
||||||
|
}
|
||||||
|
shortURL = resp.ShortURL
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,10 +79,6 @@ type sendRequest struct {
|
|||||||
Mpnews map[string]interface{} `json:"mpnews,omitempty"`
|
Mpnews map[string]interface{} `json:"mpnews,omitempty"`
|
||||||
// 发送语音
|
// 发送语音
|
||||||
Voice map[string]interface{} `json:"voice,omitempty"`
|
Voice map[string]interface{} `json:"voice,omitempty"`
|
||||||
// 发送视频
|
|
||||||
Mpvideo map[string]interface{} `json:"mpvideo,omitempty"`
|
|
||||||
// 发送图片-预览使用
|
|
||||||
Image map[string]interface{} `json:"image,omitempty"`
|
|
||||||
// 发送图片
|
// 发送图片
|
||||||
Images *Image `json:"images,omitempty"`
|
Images *Image `json:"images,omitempty"`
|
||||||
// 发送卡券
|
// 发送卡券
|
||||||
@@ -187,13 +183,7 @@ func (broadcast *Broadcast) SendImage(user *User, images *Image) (*Result, error
|
|||||||
ToUser: nil,
|
ToUser: nil,
|
||||||
MsgType: MsgTypeImage,
|
MsgType: MsgTypeImage,
|
||||||
}
|
}
|
||||||
if broadcast.preview {
|
req.Images = images
|
||||||
req.Image = map[string]interface{}{
|
|
||||||
"media_id": images.MediaIDs[0],
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
req.Images = images
|
|
||||||
}
|
|
||||||
req, sendURL := broadcast.chooseTagOrOpenID(user, req)
|
req, sendURL := broadcast.chooseTagOrOpenID(user, req)
|
||||||
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
url := fmt.Sprintf("%s?access_token=%s", sendURL, ak)
|
||||||
data, err := util.PostJSON(url, req)
|
data, err := util.PostJSON(url, req)
|
||||||
@@ -215,7 +205,7 @@ func (broadcast *Broadcast) SendVideo(user *User, mediaID string, title, descrip
|
|||||||
ToUser: nil,
|
ToUser: nil,
|
||||||
MsgType: MsgTypeVideo,
|
MsgType: MsgTypeVideo,
|
||||||
}
|
}
|
||||||
req.Mpvideo = map[string]interface{}{
|
req.Voice = map[string]interface{}{
|
||||||
"media_id": mediaID,
|
"media_id": mediaID,
|
||||||
"title": title,
|
"title": title,
|
||||||
"description": description,
|
"description": description,
|
||||||
|
|||||||
@@ -11,5 +11,4 @@ type Config struct {
|
|||||||
Token string `json:"token"` // token
|
Token string `json:"token"` // token
|
||||||
EncodingAESKey string `json:"encoding_aes_key"` // EncodingAESKey
|
EncodingAESKey string `json:"encoding_aes_key"` // EncodingAESKey
|
||||||
Cache cache.Cache
|
Cache cache.Cache
|
||||||
UseStableAK bool // use the stable access_token
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,7 +72,11 @@ func (csm *Manager) List() (customerServiceList []*KeFuInfo, err error) {
|
|||||||
}
|
}
|
||||||
var res resKeFuList
|
var res resKeFuList
|
||||||
err = util.DecodeWithError(response, &res, "ListCustomerService")
|
err = util.DecodeWithError(response, &res, "ListCustomerService")
|
||||||
return res.KfList, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
customerServiceList = res.KfList
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// KeFuOnlineInfo 客服在线信息
|
// KeFuOnlineInfo 客服在线信息
|
||||||
@@ -103,7 +107,11 @@ func (csm *Manager) OnlineList() (customerServiceOnlineList []*KeFuOnlineInfo, e
|
|||||||
}
|
}
|
||||||
var res resKeFuOnlineList
|
var res resKeFuOnlineList
|
||||||
err = util.DecodeWithError(response, &res, "ListOnlineCustomerService")
|
err = util.DecodeWithError(response, &res, "ListOnlineCustomerService")
|
||||||
return res.KfOnlineList, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
customerServiceOnlineList = res.KfOnlineList
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add 添加客服账号
|
// Add 添加客服账号
|
||||||
|
|||||||
@@ -183,6 +183,9 @@ func (cube *DataCube) fetchData(params ParamsPublisher) (response []byte, err er
|
|||||||
uri := fmt.Sprintf("%s?%s", publisherURL, v.Encode())
|
uri := fmt.Sprintf("%s?%s", publisherURL, v.Encode())
|
||||||
|
|
||||||
response, err = util.HTTPGet(uri)
|
response, err = util.HTTPGet(uri)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -64,7 +64,11 @@ func (draft *Draft) AddDraft(articles []*Article) (mediaID string, err error) {
|
|||||||
MediaID string `json:"media_id"`
|
MediaID string `json:"media_id"`
|
||||||
}
|
}
|
||||||
err = util.DecodeWithError(response, &res, "AddDraft")
|
err = util.DecodeWithError(response, &res, "AddDraft")
|
||||||
return res.MediaID, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
mediaID = res.MediaID
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDraft 获取草稿
|
// GetDraft 获取草稿
|
||||||
@@ -90,7 +94,12 @@ func (draft *Draft) GetDraft(mediaID string) (articles []*Article, err error) {
|
|||||||
NewsItem []*Article `json:"news_item"`
|
NewsItem []*Article `json:"news_item"`
|
||||||
}
|
}
|
||||||
err = util.DecodeWithError(response, &res, "GetDraft")
|
err = util.DecodeWithError(response, &res, "GetDraft")
|
||||||
return res.NewsItem, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
articles = res.NewsItem
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteDraft 删除草稿
|
// DeleteDraft 删除草稿
|
||||||
@@ -163,7 +172,12 @@ func (draft *Draft) CountDraft() (total uint, err error) {
|
|||||||
Total uint `json:"total_count"`
|
Total uint `json:"total_count"`
|
||||||
}
|
}
|
||||||
err = util.DecodeWithError(response, &res, "CountDraft")
|
err = util.DecodeWithError(response, &res, "CountDraft")
|
||||||
return res.Total, err
|
if nil != err {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
total = res.Total
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// ArticleList 草稿列表
|
// ArticleList 草稿列表
|
||||||
|
|||||||
@@ -73,7 +73,12 @@ func (freePublish *FreePublish) Publish(mediaID string) (publishID int64, err er
|
|||||||
PublishID int64 `json:"publish_id"`
|
PublishID int64 `json:"publish_id"`
|
||||||
}
|
}
|
||||||
err = util.DecodeWithError(response, &res, "SubmitFreePublish")
|
err = util.DecodeWithError(response, &res, "SubmitFreePublish")
|
||||||
return res.PublishID, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
publishID = res.PublishID
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// PublishStatusList 发布任务状态列表
|
// PublishStatusList 发布任务状态列表
|
||||||
@@ -186,7 +191,12 @@ func (freePublish *FreePublish) First(articleID string) (list []Article, err err
|
|||||||
NewsItem []Article `json:"news_item"`
|
NewsItem []Article `json:"news_item"`
|
||||||
}
|
}
|
||||||
err = util.DecodeWithError(response, &res, "FirstFreePublish")
|
err = util.DecodeWithError(response, &res, "FirstFreePublish")
|
||||||
return res.NewsItem, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
list = res.NewsItem
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// ArticleList 发布列表
|
// ArticleList 发布列表
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package js
|
package js
|
||||||
|
|
||||||
import (
|
import (
|
||||||
context2 "context"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/credential"
|
"github.com/silenceper/wechat/v2/credential"
|
||||||
@@ -40,31 +39,14 @@ func (js *Js) SetJsTicketHandle(ticketHandle credential.JsTicketHandle) {
|
|||||||
// 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) {
|
||||||
return js.GetConfigContext(context2.Background(), uri)
|
config = new(Config)
|
||||||
}
|
|
||||||
|
|
||||||
// GetConfigContext 新方法,允许传入上下文,避免协程泄漏
|
|
||||||
func (js *Js) GetConfigContext(ctx context2.Context, uri string) (config *Config, err error) {
|
|
||||||
var accessToken string
|
var accessToken string
|
||||||
// 类型断言,如果断言成功,调用安全的 GetAccessTokenContext 方法
|
accessToken, err = js.GetAccessToken()
|
||||||
if ctxHandle, ok := js.Context.AccessTokenHandle.(credential.AccessTokenContextHandle); ok {
|
|
||||||
accessToken, err = ctxHandle.GetAccessTokenContext(ctx)
|
|
||||||
} else {
|
|
||||||
// 如果没有实现 AccessTokenContextHandle 接口,调用旧的 GetAccessToken 方法
|
|
||||||
accessToken, err = js.Context.GetAccessToken()
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var ticketStr string
|
var ticketStr string
|
||||||
// 类型断言 jsTicket
|
ticketStr, err = js.GetTicket(accessToken)
|
||||||
if ticketCtxHandle, ok := js.JsTicketHandle.(credential.JsTicketContextHandle); ok {
|
|
||||||
ticketStr, err = ticketCtxHandle.GetTicketContext(ctx, accessToken)
|
|
||||||
} else {
|
|
||||||
// 如果没有实现 JsTicketContextHandle 接口,调用旧的 GetTicket 方法
|
|
||||||
ticketStr, err = js.GetTicket(accessToken)
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -74,7 +56,6 @@ func (js *Js) GetConfigContext(ctx context2.Context, uri string) (config *Config
|
|||||||
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
|
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
|
||||||
sigStr := util.Signature(str)
|
sigStr := util.Signature(str)
|
||||||
|
|
||||||
config = new(Config)
|
|
||||||
config.AppID = js.AppID
|
config.AppID = js.AppID
|
||||||
config.NonceStr = nonceStr
|
config.NonceStr = nonceStr
|
||||||
config.Timestamp = timestamp
|
config.Timestamp = timestamp
|
||||||
|
|||||||
@@ -4,9 +4,6 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"path"
|
|
||||||
|
|
||||||
"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"
|
||||||
@@ -163,8 +160,8 @@ type resAddMaterial struct {
|
|||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddMaterialFromReader 上传永久性素材(处理视频需要单独上传),从 io.Reader 中读取
|
// AddMaterial 上传永久性素材(处理视频需要单独上传)
|
||||||
func (material *Material) AddMaterialFromReader(mediaType MediaType, filePath string, reader io.Reader) (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
|
return
|
||||||
@@ -176,10 +173,8 @@ func (material *Material) AddMaterialFromReader(mediaType MediaType, filePath st
|
|||||||
}
|
}
|
||||||
|
|
||||||
uri := fmt.Sprintf("%s?access_token=%s&type=%s", addMaterialURL, accessToken, mediaType)
|
uri := fmt.Sprintf("%s?access_token=%s&type=%s", addMaterialURL, accessToken, mediaType)
|
||||||
// 获取文件名
|
|
||||||
filename := path.Base(filePath)
|
|
||||||
var response []byte
|
var response []byte
|
||||||
response, err = util.PostFileFromReader("media", filePath, filename, uri, reader)
|
response, err = util.PostFile("media", filename, uri)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -197,24 +192,13 @@ func (material *Material) AddMaterialFromReader(mediaType MediaType, filePath st
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddMaterial 上传永久性素材(处理视频需要单独上传)
|
|
||||||
func (material *Material) AddMaterial(mediaType MediaType, filename string) (mediaID string, url string, err error) {
|
|
||||||
f, err := os.Open(filename)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer func() { _ = f.Close() }()
|
|
||||||
|
|
||||||
return material.AddMaterialFromReader(mediaType, filename, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
type reqVideo struct {
|
type reqVideo struct {
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Introduction string `json:"introduction"`
|
Introduction string `json:"introduction"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddVideoFromReader 永久视频素材文件上传,从 io.Reader 中读取
|
// AddVideo 永久视频素材文件上传
|
||||||
func (material *Material) AddVideoFromReader(filePath, title, introduction string, reader io.Reader) (mediaID string, url string, err error) {
|
func (material *Material) AddVideo(filename, title, introduction string) (mediaID string, url string, err error) {
|
||||||
var accessToken string
|
var accessToken string
|
||||||
accessToken, err = material.GetAccessToken()
|
accessToken, err = material.GetAccessToken()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -232,19 +216,16 @@ func (material *Material) AddVideoFromReader(filePath, title, introduction strin
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fileName := path.Base(filePath)
|
|
||||||
fields := []util.MultipartFormField{
|
fields := []util.MultipartFormField{
|
||||||
{
|
{
|
||||||
IsFile: true,
|
IsFile: true,
|
||||||
Fieldname: "media",
|
Fieldname: "media",
|
||||||
FilePath: filePath,
|
Filename: filename,
|
||||||
Filename: fileName,
|
|
||||||
FileReader: reader,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
IsFile: false,
|
IsFile: false,
|
||||||
Fieldname: "description",
|
Fieldname: "description",
|
||||||
Filename: fileName,
|
|
||||||
Value: fieldValue,
|
Value: fieldValue,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -269,17 +250,6 @@ func (material *Material) AddVideoFromReader(filePath, title, introduction strin
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddVideo 永久视频素材文件上传
|
|
||||||
func (material *Material) AddVideo(directory, title, introduction string) (mediaID string, url string, err error) {
|
|
||||||
f, err := os.Open(directory)
|
|
||||||
if err != nil {
|
|
||||||
return "", "", err
|
|
||||||
}
|
|
||||||
defer func() { _ = f.Close() }()
|
|
||||||
|
|
||||||
return material.AddVideoFromReader(directory, title, introduction, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
type reqDeleteMaterial struct {
|
type reqDeleteMaterial struct {
|
||||||
MediaID string `json:"media_id"`
|
MediaID string `json:"media_id"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package material
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
"github.com/silenceper/wechat/v2/util"
|
||||||
)
|
)
|
||||||
@@ -63,38 +62,6 @@ func (material *Material) MediaUpload(mediaType MediaType, filename string) (med
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// MediaUploadFromReader 临时素材上传
|
|
||||||
func (material *Material) MediaUploadFromReader(mediaType MediaType, filename string, reader io.Reader) (media Media, err error) {
|
|
||||||
var accessToken string
|
|
||||||
accessToken, err = material.GetAccessToken()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
uri := fmt.Sprintf("%s?access_token=%s&type=%s", mediaUploadURL, accessToken, mediaType)
|
|
||||||
|
|
||||||
var byteData []byte
|
|
||||||
byteData, err = io.ReadAll(reader)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var response []byte
|
|
||||||
response, err = util.PostFileByStream("media", filename, uri, byteData)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
err = json.Unmarshal(response, &media)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if media.ErrCode != 0 {
|
|
||||||
err = fmt.Errorf("MediaUpload error : errcode=%v , errmsg=%v", media.ErrCode, media.ErrMsg)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetMediaURL 返回临时素材的下载地址供用户自己处理
|
// GetMediaURL 返回临时素材的下载地址供用户自己处理
|
||||||
// NOTICE: URL 不可公开,因为含access_token 需要立即另存文件
|
// NOTICE: URL 不可公开,因为含access_token 需要立即另存文件
|
||||||
func (material *Material) GetMediaURL(mediaID string) (mediaURL string, err error) {
|
func (material *Material) GetMediaURL(mediaID string) (mediaURL string, err error) {
|
||||||
|
|||||||
@@ -27,15 +27,15 @@ const (
|
|||||||
MsgTypeVideo MsgType = "video"
|
MsgTypeVideo MsgType = "video"
|
||||||
// MsgTypeMiniprogrampage 表示小程序卡片消息
|
// MsgTypeMiniprogrampage 表示小程序卡片消息
|
||||||
MsgTypeMiniprogrampage MsgType = "miniprogrampage"
|
MsgTypeMiniprogrampage MsgType = "miniprogrampage"
|
||||||
// MsgTypeShortVideo 表示短视频消息 [限接收]
|
// MsgTypeShortVideo 表示短视频消息[限接收]
|
||||||
MsgTypeShortVideo MsgType = "shortvideo"
|
MsgTypeShortVideo MsgType = "shortvideo"
|
||||||
// MsgTypeLocation 表示坐标消息 [限接收]
|
// MsgTypeLocation 表示坐标消息[限接收]
|
||||||
MsgTypeLocation MsgType = "location"
|
MsgTypeLocation MsgType = "location"
|
||||||
// MsgTypeLink 表示链接消息 [限接收]
|
// MsgTypeLink 表示链接消息[限接收]
|
||||||
MsgTypeLink MsgType = "link"
|
MsgTypeLink MsgType = "link"
|
||||||
// MsgTypeMusic 表示音乐消息 [限回复]
|
// MsgTypeMusic 表示音乐消息[限回复]
|
||||||
MsgTypeMusic MsgType = "music"
|
MsgTypeMusic MsgType = "music"
|
||||||
// MsgTypeNews 表示图文消息 [限回复]
|
// MsgTypeNews 表示图文消息[限回复]
|
||||||
MsgTypeNews MsgType = "news"
|
MsgTypeNews MsgType = "news"
|
||||||
// MsgTypeTransfer 表示消息消息转发到客服
|
// MsgTypeTransfer 表示消息消息转发到客服
|
||||||
MsgTypeTransfer MsgType = "transfer_customer_service"
|
MsgTypeTransfer MsgType = "transfer_customer_service"
|
||||||
@@ -91,7 +91,7 @@ const (
|
|||||||
const (
|
const (
|
||||||
// 微信开放平台需要用到
|
// 微信开放平台需要用到
|
||||||
|
|
||||||
// InfoTypeVerifyTicket 返回 ticket
|
// InfoTypeVerifyTicket 返回ticket
|
||||||
InfoTypeVerifyTicket InfoType = "component_verify_ticket"
|
InfoTypeVerifyTicket InfoType = "component_verify_ticket"
|
||||||
// InfoTypeAuthorized 授权
|
// InfoTypeAuthorized 授权
|
||||||
InfoTypeAuthorized InfoType = "authorized"
|
InfoTypeAuthorized InfoType = "authorized"
|
||||||
@@ -108,8 +108,8 @@ type MixMessage struct {
|
|||||||
CommonToken
|
CommonToken
|
||||||
|
|
||||||
// 基本消息
|
// 基本消息
|
||||||
MsgID int64 `xml:"MsgId"` // 其他消息推送过来是 MsgId
|
MsgID int64 `xml:"MsgId"` // 其他消息推送过来是MsgId
|
||||||
TemplateMsgID int64 `xml:"MsgID"` // 模板消息推送成功的消息是 MsgID
|
TemplateMsgID int64 `xml:"MsgID"` // 模板消息推送成功的消息是MsgID
|
||||||
Content string `xml:"Content"`
|
Content string `xml:"Content"`
|
||||||
Recognition string `xml:"Recognition"`
|
Recognition string `xml:"Recognition"`
|
||||||
PicURL string `xml:"PicUrl"`
|
PicURL string `xml:"PicUrl"`
|
||||||
@@ -166,17 +166,17 @@ type MixMessage struct {
|
|||||||
|
|
||||||
// 事件相关:发布能力
|
// 事件相关:发布能力
|
||||||
PublishEventInfo struct {
|
PublishEventInfo struct {
|
||||||
PublishID int64 `xml:"publish_id"` // 发布任务 id
|
PublishID int64 `xml:"publish_id"` // 发布任务id
|
||||||
PublishStatus freepublish.PublishStatus `xml:"publish_status"` // 发布状态
|
PublishStatus freepublish.PublishStatus `xml:"publish_status"` // 发布状态
|
||||||
ArticleID string `xml:"article_id"` // 当发布状态为 0 时(即成功)时,返回图文的 article_id,可用于“客服消息”场景
|
ArticleID string `xml:"article_id"` // 当发布状态为0时(即成功)时,返回图文的 article_id,可用于“客服消息”场景
|
||||||
ArticleDetail struct {
|
ArticleDetail struct {
|
||||||
Count uint `xml:"count"` // 文章数量
|
Count uint `xml:"count"` // 文章数量
|
||||||
Item []struct {
|
Item []struct {
|
||||||
Index uint `xml:"idx"` // 文章对应的编号
|
Index uint `xml:"idx"` // 文章对应的编号
|
||||||
ArticleURL string `xml:"article_url"` // 图文的永久链接
|
ArticleURL string `xml:"article_url"` // 图文的永久链接
|
||||||
} `xml:"item"`
|
} `xml:"item"`
|
||||||
} `xml:"article_detail"` // 当发布状态为 0 时(即成功)时,返回内容
|
} `xml:"article_detail"` // 当发布状态为0时(即成功)时,返回内容
|
||||||
FailIndex []uint `xml:"fail_idx"` // 当发布状态为 2 或 4 时,返回不通过的文章编号,第一篇为 1;其他发布状态则为空
|
FailIndex []uint `xml:"fail_idx"` // 当发布状态为2或4时,返回不通过的文章编号,第一篇为 1;其他发布状态则为空
|
||||||
} `xml:"PublishEventInfo"`
|
} `xml:"PublishEventInfo"`
|
||||||
|
|
||||||
// 第三方平台相关
|
// 第三方平台相关
|
||||||
@@ -222,19 +222,19 @@ type MixMessage struct {
|
|||||||
TraceID string `xml:"trace_id"`
|
TraceID string `xml:"trace_id"`
|
||||||
StatusCode int `xml:"status_code"`
|
StatusCode int `xml:"status_code"`
|
||||||
|
|
||||||
// 小程序名称审核结果事件推送
|
//小程序名称审核结果事件推送
|
||||||
Ret int32 `xml:"ret"` // 审核结果 2:失败,3:成功
|
Ret int32 `xml:"ret"` //审核结果 2:失败,3:成功
|
||||||
NickName string `xml:"nickname"` // 小程序昵称
|
NickName string `xml:"nickname"` //小程序昵称
|
||||||
|
|
||||||
// 设备相关
|
// 设备相关
|
||||||
device.MsgDevice
|
device.MsgDevice
|
||||||
|
|
||||||
// 小程序审核通知
|
//小程序审核通知
|
||||||
SuccTime int `xml:"SuccTime"` // 审核成功时的时间戳
|
SuccTime int `xml:"SuccTime"` //审核成功时的时间戳
|
||||||
FailTime int `xml:"FailTime"` // 审核不通过的时间戳
|
FailTime int `xml:"FailTime"` //审核不通过的时间戳
|
||||||
DelayTime int `xml:"DelayTime"` // 审核延后时的时间戳
|
DelayTime int `xml:"DelayTime"` //审核延后时的时间戳
|
||||||
Reason string `xml:"Reason"` // 审核不通过的原因
|
Reason string `xml:"Reason"` //审核不通过的原因
|
||||||
ScreenShot string `xml:"ScreenShot"` // 审核不通过的截图示例。用 | 分隔的 media_id 的列表,可通过获取永久素材接口拉取截图内容
|
ScreenShot string `xml:"ScreenShot"` //审核不通过的截图示例。用 | 分隔的 media_id 的列表,可通过获取永久素材接口拉取截图内容
|
||||||
}
|
}
|
||||||
|
|
||||||
// SubscribeMsgPopupEvent 订阅通知事件推送的消息体
|
// SubscribeMsgPopupEvent 订阅通知事件推送的消息体
|
||||||
@@ -282,7 +282,7 @@ type ResponseEncryptedXMLMsg struct {
|
|||||||
Nonce string `xml:"Nonce" json:"Nonce"`
|
Nonce string `xml:"Nonce" json:"Nonce"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// CDATA 使用该类型,在序列化为 xml 文本时文本会被解析器忽略
|
// CDATA 使用该类型,在序列化为 xml 文本时文本会被解析器忽略
|
||||||
type CDATA string
|
type CDATA string
|
||||||
|
|
||||||
// MarshalXML 实现自己的序列化方法
|
// MarshalXML 实现自己的序列化方法
|
||||||
|
|||||||
@@ -90,7 +90,11 @@ func (tpl *Subscribe) List() (templateList []*PrivateSubscribeItem, err error) {
|
|||||||
}
|
}
|
||||||
var res resPrivateSubscribeList
|
var res resPrivateSubscribeList
|
||||||
err = util.DecodeWithError(response, &res, "ListSubscribe")
|
err = util.DecodeWithError(response, &res, "ListSubscribe")
|
||||||
return res.SubscriptionList, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
templateList = res.SubscriptionList
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
type resSubscribeAdd struct {
|
type resSubscribeAdd struct {
|
||||||
@@ -119,7 +123,11 @@ func (tpl *Subscribe) Add(ShortID string, kidList []int, sceneDesc string) (temp
|
|||||||
}
|
}
|
||||||
var result resSubscribeAdd
|
var result resSubscribeAdd
|
||||||
err = util.DecodeWithError(response, &result, "AddSubscribe")
|
err = util.DecodeWithError(response, &result, "AddSubscribe")
|
||||||
return result.TemplateID, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
templateID = result.TemplateID
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete 删除私有模板
|
// Delete 删除私有模板
|
||||||
@@ -167,7 +175,11 @@ func (tpl *Subscribe) GetCategory() (categoryList []*PublicTemplateCategory, err
|
|||||||
}
|
}
|
||||||
var result resSubscribeCategoryList
|
var result resSubscribeCategoryList
|
||||||
err = util.DecodeWithError(response, &result, "GetCategory")
|
err = util.DecodeWithError(response, &result, "GetCategory")
|
||||||
return result.CategoryList, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
categoryList = result.CategoryList
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// PublicTemplateKeyWords 模板中的关键词
|
// PublicTemplateKeyWords 模板中的关键词
|
||||||
@@ -198,7 +210,11 @@ func (tpl *Subscribe) GetPubTplKeyWordsByID(titleID string) (keyWordsList []*Pub
|
|||||||
}
|
}
|
||||||
var result resPublicTemplateKeyWordsList
|
var result resPublicTemplateKeyWordsList
|
||||||
err = util.DecodeWithError(response, &result, "GetPublicTemplateKeyWords")
|
err = util.DecodeWithError(response, &result, "GetPublicTemplateKeyWords")
|
||||||
return result.KeyWordsList, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
keyWordsList = result.KeyWordsList
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// PublicTemplateTitle 类目下的公共模板
|
// PublicTemplateTitle 类目下的公共模板
|
||||||
@@ -230,5 +246,10 @@ func (tpl *Subscribe) GetPublicTemplateTitleList(ids string, start int, limit in
|
|||||||
}
|
}
|
||||||
var result resPublicTemplateTitleList
|
var result resPublicTemplateTitleList
|
||||||
err = util.DecodeWithError(response, &result, "GetPublicTemplateTitle")
|
err = util.DecodeWithError(response, &result, "GetPublicTemplateTitle")
|
||||||
return result.Count, result.TemplateTitleList, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
count = result.Count
|
||||||
|
templateTitleList = result.TemplateTitleList
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,15 +61,15 @@ func (tpl *Template) Send(msg *TemplateMessage) (msgID int64, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var (
|
uri := fmt.Sprintf("%s?access_token=%s", templateSendURL, accessToken)
|
||||||
uri = fmt.Sprintf("%s?access_token=%s", templateSendURL, accessToken)
|
var response []byte
|
||||||
response []byte
|
response, err = util.PostJSON(uri, msg)
|
||||||
)
|
if err != nil {
|
||||||
if response, err = util.PostJSON(uri, msg); err != nil {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var result resTemplateSend
|
var result resTemplateSend
|
||||||
if err = json.Unmarshal(response, &result); err != nil {
|
err = json.Unmarshal(response, &result)
|
||||||
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if result.ErrCode != 0 {
|
if result.ErrCode != 0 {
|
||||||
@@ -103,16 +103,19 @@ func (tpl *Template) List() (templateList []*TemplateItem, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var (
|
uri := fmt.Sprintf("%s?access_token=%s", templateListURL, accessToken)
|
||||||
uri = fmt.Sprintf("%s?access_token=%s", templateListURL, accessToken)
|
var response []byte
|
||||||
response []byte
|
response, err = util.HTTPGet(uri)
|
||||||
)
|
if err != nil {
|
||||||
if response, err = util.HTTPGet(uri); err != nil {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var res resTemplateList
|
var res resTemplateList
|
||||||
err = util.DecodeWithError(response, &res, "ListTemplate")
|
err = util.DecodeWithError(response, &res, "ListTemplate")
|
||||||
return res.TemplateList, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
templateList = res.TemplateList
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
type resTemplateAdd struct {
|
type resTemplateAdd struct {
|
||||||
@@ -122,26 +125,29 @@ type resTemplateAdd struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add 添加模板.
|
// Add 添加模板.
|
||||||
func (tpl *Template) Add(shortID string, keyNameList []string) (templateID string, err error) {
|
func (tpl *Template) Add(shortID string) (templateID string, err error) {
|
||||||
var accessToken string
|
var accessToken string
|
||||||
accessToken, err = tpl.GetAccessToken()
|
accessToken, err = tpl.GetAccessToken()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var (
|
var msg = struct {
|
||||||
msg = struct {
|
ShortID string `json:"template_id_short"`
|
||||||
ShortID string `json:"template_id_short"`
|
}{ShortID: shortID}
|
||||||
KeyNameList []string `json:"keyword_name_list"`
|
uri := fmt.Sprintf("%s?access_token=%s", templateAddURL, accessToken)
|
||||||
}{ShortID: shortID, KeyNameList: keyNameList}
|
var response []byte
|
||||||
uri = fmt.Sprintf("%s?access_token=%s", templateAddURL, accessToken)
|
response, err = util.PostJSON(uri, msg)
|
||||||
response []byte
|
if err != nil {
|
||||||
)
|
|
||||||
if response, err = util.PostJSON(uri, msg); err != nil {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var result resTemplateAdd
|
var result resTemplateAdd
|
||||||
err = util.DecodeWithError(response, &result, "AddTemplate")
|
err = util.DecodeWithError(response, &result, "AddTemplate")
|
||||||
return result.TemplateID, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
templateID = result.TemplateID
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete 删除私有模板.
|
// Delete 删除私有模板.
|
||||||
@@ -151,14 +157,14 @@ func (tpl *Template) Delete(templateID string) (err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var (
|
var msg = struct {
|
||||||
msg = struct {
|
TemplateID string `json:"template_id"`
|
||||||
TemplateID string `json:"template_id"`
|
}{TemplateID: templateID}
|
||||||
}{TemplateID: templateID}
|
|
||||||
uri = fmt.Sprintf("%s?access_token=%s", templateDelURL, accessToken)
|
uri := fmt.Sprintf("%s?access_token=%s", templateDelURL, accessToken)
|
||||||
response []byte
|
var response []byte
|
||||||
)
|
response, err = util.PostJSON(uri, msg)
|
||||||
if response, err = util.PostJSON(uri, msg); err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
return util.DecodeWithCommonError(response, "DeleteTemplate")
|
return util.DecodeWithCommonError(response, "DeleteTemplate")
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package oauth
|
package oauth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
ctx2 "context"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -74,28 +73,11 @@ type ResAccessToken struct {
|
|||||||
UnionID string `json:"unionid"`
|
UnionID string `json:"unionid"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetUserInfoByCodeContext 通过网页授权的code 换取用户的信息
|
|
||||||
func (oauth *Oauth) GetUserInfoByCodeContext(ctx ctx2.Context, code string) (result UserInfo, err error) {
|
|
||||||
var (
|
|
||||||
token ResAccessToken
|
|
||||||
)
|
|
||||||
if token, err = oauth.GetUserAccessTokenContext(ctx, code); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
return oauth.GetUserInfoContext(ctx, token.AccessToken, token.OpenID, "")
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUserAccessToken 通过网页授权的code 换取access_token(区别于context中的access_token)
|
// GetUserAccessToken 通过网页授权的code 换取access_token(区别于context中的access_token)
|
||||||
func (oauth *Oauth) GetUserAccessToken(code string) (result ResAccessToken, err error) {
|
func (oauth *Oauth) GetUserAccessToken(code string) (result ResAccessToken, err error) {
|
||||||
return oauth.GetUserAccessTokenContext(ctx2.Background(), code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUserAccessTokenContext 通过网页授权的code 换取access_token(区别于context中的access_token) with context
|
|
||||||
func (oauth *Oauth) GetUserAccessTokenContext(ctx ctx2.Context, code string) (result ResAccessToken, err error) {
|
|
||||||
urlStr := fmt.Sprintf(accessTokenURL, oauth.AppID, oauth.AppSecret, code)
|
urlStr := fmt.Sprintf(accessTokenURL, oauth.AppID, oauth.AppSecret, code)
|
||||||
var response []byte
|
var response []byte
|
||||||
response, err = util.HTTPGetContext(ctx, urlStr)
|
response, err = util.HTTPGet(urlStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -112,14 +94,9 @@ func (oauth *Oauth) GetUserAccessTokenContext(ctx ctx2.Context, code string) (re
|
|||||||
|
|
||||||
// RefreshAccessToken 刷新access_token
|
// RefreshAccessToken 刷新access_token
|
||||||
func (oauth *Oauth) RefreshAccessToken(refreshToken string) (result ResAccessToken, err error) {
|
func (oauth *Oauth) RefreshAccessToken(refreshToken string) (result ResAccessToken, err error) {
|
||||||
return oauth.RefreshAccessTokenContext(ctx2.Background(), refreshToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
// RefreshAccessTokenContext 刷新access_token with context
|
|
||||||
func (oauth *Oauth) RefreshAccessTokenContext(ctx ctx2.Context, refreshToken string) (result ResAccessToken, err error) {
|
|
||||||
urlStr := fmt.Sprintf(refreshAccessTokenURL, oauth.AppID, refreshToken)
|
urlStr := fmt.Sprintf(refreshAccessTokenURL, oauth.AppID, refreshToken)
|
||||||
var response []byte
|
var response []byte
|
||||||
response, err = util.HTTPGetContext(ctx, urlStr)
|
response, err = util.HTTPGet(urlStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -136,14 +113,9 @@ func (oauth *Oauth) RefreshAccessTokenContext(ctx ctx2.Context, refreshToken str
|
|||||||
|
|
||||||
// CheckAccessToken 检验access_token是否有效
|
// CheckAccessToken 检验access_token是否有效
|
||||||
func (oauth *Oauth) CheckAccessToken(accessToken, openID string) (b bool, err error) {
|
func (oauth *Oauth) CheckAccessToken(accessToken, openID string) (b bool, err error) {
|
||||||
return oauth.CheckAccessTokenContext(ctx2.Background(), accessToken, openID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CheckAccessTokenContext 检验access_token是否有效 with context
|
|
||||||
func (oauth *Oauth) CheckAccessTokenContext(ctx ctx2.Context, accessToken, openID string) (b bool, err error) {
|
|
||||||
urlStr := fmt.Sprintf(checkAccessTokenURL, accessToken, openID)
|
urlStr := fmt.Sprintf(checkAccessTokenURL, accessToken, openID)
|
||||||
var response []byte
|
var response []byte
|
||||||
response, err = util.HTTPGetContext(ctx, urlStr)
|
response, err = util.HTTPGet(urlStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -177,17 +149,12 @@ type UserInfo struct {
|
|||||||
|
|
||||||
// GetUserInfo 如果scope为 snsapi_userinfo 则可以通过此方法获取到用户基本信息
|
// GetUserInfo 如果scope为 snsapi_userinfo 则可以通过此方法获取到用户基本信息
|
||||||
func (oauth *Oauth) GetUserInfo(accessToken, openID, lang string) (result UserInfo, err error) {
|
func (oauth *Oauth) GetUserInfo(accessToken, openID, lang string) (result UserInfo, err error) {
|
||||||
return oauth.GetUserInfoContext(ctx2.Background(), accessToken, openID, lang)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUserInfoContext 如果scope为 snsapi_userinfo 则可以通过此方法获取到用户基本信息 with context
|
|
||||||
func (oauth *Oauth) GetUserInfoContext(ctx ctx2.Context, accessToken, openID, lang string) (result UserInfo, err error) {
|
|
||||||
if lang == "" {
|
if lang == "" {
|
||||||
lang = "zh_CN"
|
lang = "zh_CN"
|
||||||
}
|
}
|
||||||
urlStr := fmt.Sprintf(userInfoURL, accessToken, openID, lang)
|
urlStr := fmt.Sprintf(userInfoURL, accessToken, openID, lang)
|
||||||
var response []byte
|
var response []byte
|
||||||
response, err = util.HTTPGetContext(ctx, urlStr)
|
response, err = util.HTTPGet(urlStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,13 +49,7 @@ type OfficialAccount struct {
|
|||||||
|
|
||||||
// NewOfficialAccount 实例化公众号API
|
// NewOfficialAccount 实例化公众号API
|
||||||
func NewOfficialAccount(cfg *config.Config) *OfficialAccount {
|
func NewOfficialAccount(cfg *config.Config) *OfficialAccount {
|
||||||
var defaultAkHandle credential.AccessTokenContextHandle
|
defaultAkHandle := credential.NewDefaultAccessToken(cfg.AppID, cfg.AppSecret, credential.CacheKeyOfficialAccountPrefix, cfg.Cache)
|
||||||
const cacheKeyPrefix = credential.CacheKeyOfficialAccountPrefix
|
|
||||||
if cfg.UseStableAK {
|
|
||||||
defaultAkHandle = credential.NewStableAccessToken(cfg.AppID, cfg.AppSecret, cacheKeyPrefix, cfg.Cache)
|
|
||||||
} else {
|
|
||||||
defaultAkHandle = credential.NewDefaultAccessToken(cfg.AppID, cfg.AppSecret, cacheKeyPrefix, cfg.Cache)
|
|
||||||
}
|
|
||||||
ctx := &context.Context{
|
ctx := &context.Context{
|
||||||
Config: cfg,
|
Config: cfg,
|
||||||
AccessTokenHandle: defaultAkHandle,
|
AccessTokenHandle: defaultAkHandle,
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ func (srv *Server) Serve() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// 非安全模式下,请求处理方法返回为 nil 则直接回复 success 给微信服务器
|
// 非安全模式下,请求处理方法返回为nil则直接回复success给微信服务器
|
||||||
if response == nil && !srv.isSafeMode {
|
if response == nil && !srv.isSafeMode {
|
||||||
srv.String("success")
|
srv.String("success")
|
||||||
return nil
|
return nil
|
||||||
@@ -198,7 +198,7 @@ func (srv *Server) parseRequestMessage(rawXMLMsgBytes []byte) (msg *message.MixM
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// nonstandard json, 目前小程序订阅消息返回数据格式不标准,订阅消息模板单个 List 返回是对象,多个 List 返回是数组。
|
// nonstandard json, 目前小程序订阅消息返回数据格式不标准,订阅消息模板单个List返回是对象,多个List返回是数组。
|
||||||
if msg.MsgType == message.MsgTypeEvent {
|
if msg.MsgType == message.MsgTypeEvent {
|
||||||
listData := gjson.Get(string(rawXMLMsgBytes), "List")
|
listData := gjson.Get(string(rawXMLMsgBytes), "List")
|
||||||
if listData.IsObject() {
|
if listData.IsObject() {
|
||||||
@@ -284,7 +284,7 @@ func (srv *Server) Send() (err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// TODO 如果获取不到 timestamp nonce 则自己生成
|
// TODO 如果获取不到timestamp nonce 则自己生成
|
||||||
timestamp := srv.timestamp
|
timestamp := srv.timestamp
|
||||||
timestampStr := strconv.FormatInt(timestamp, 10)
|
timestampStr := strconv.FormatInt(timestamp, 10)
|
||||||
msgSignature := util.Signature(srv.Token, timestampStr, srv.nonce, string(encryptedMsg))
|
msgSignature := util.Signature(srv.Token, timestampStr, srv.nonce, string(encryptedMsg))
|
||||||
|
|||||||
@@ -62,6 +62,10 @@ func (user *User) ListChangeOpenIDs(fromAppID string, openIDs ...string) (list *
|
|||||||
}
|
}
|
||||||
|
|
||||||
err = util.DecodeWithError(resp, list, "ListChangeOpenIDs")
|
err = util.DecodeWithError(resp, list, "ListChangeOpenIDs")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -126,7 +126,10 @@ func (user *User) GetTag() (tags []*TagInfo, err error) {
|
|||||||
Tags []*TagInfo `json:"tags"`
|
Tags []*TagInfo `json:"tags"`
|
||||||
}
|
}
|
||||||
err = json.Unmarshal(response, &result)
|
err = json.Unmarshal(response, &result)
|
||||||
return result.Tags, err
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return result.Tags, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// OpenIDListByTag 获取标签下粉丝列表
|
// OpenIDListByTag 获取标签下粉丝列表
|
||||||
@@ -151,6 +154,9 @@ func (user *User) OpenIDListByTag(tagID int32, nextOpenID ...string) (userList *
|
|||||||
}
|
}
|
||||||
userList = new(TagOpenIDList)
|
userList = new(TagOpenIDList)
|
||||||
err = json.Unmarshal(response, &userList)
|
err = json.Unmarshal(response, &userList)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ package account
|
|||||||
|
|
||||||
import "github.com/silenceper/wechat/v2/openplatform/context"
|
import "github.com/silenceper/wechat/v2/openplatform/context"
|
||||||
|
|
||||||
// Account 开放平台帐号管理
|
// Account 开放平台张哈管理
|
||||||
// TODO 实现方法
|
// TODO 实现方法
|
||||||
type Account struct {
|
type Account struct {
|
||||||
*context.Context
|
*context.Context
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ const (
|
|||||||
getComponentInfoURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=%s"
|
getComponentInfoURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=%s"
|
||||||
componentLoginURL = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=%s&pre_auth_code=%s&redirect_uri=%s&auth_type=%d&biz_appid=%s"
|
componentLoginURL = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=%s&pre_auth_code=%s&redirect_uri=%s&auth_type=%d&biz_appid=%s"
|
||||||
bindComponentURL = "https://mp.weixin.qq.com/safe/bindcomponent?action=bindcomponent&auth_type=%d&no_scan=1&component_appid=%s&pre_auth_code=%s&redirect_uri=%s&biz_appid=%s#wechat_redirect"
|
bindComponentURL = "https://mp.weixin.qq.com/safe/bindcomponent?action=bindcomponent&auth_type=%d&no_scan=1&component_appid=%s&pre_auth_code=%s&redirect_uri=%s&biz_appid=%s#wechat_redirect"
|
||||||
bindComponentURLV2 = "https://open.weixin.qq.com/wxaopen/safe/bindcomponent?action=bindcomponent&auth_type=%d&no_scan=1&component_appid=%s&pre_auth_code=%s&redirect_uri=%s&biz_appid=%s#wechat_redirect"
|
|
||||||
// TODO 获取授权方选项信息
|
// TODO 获取授权方选项信息
|
||||||
// getComponentConfigURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_option?component_access_token=%s"
|
// getComponentConfigURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_option?component_access_token=%s"
|
||||||
// TODO 获取已授权的账号信息
|
// TODO 获取已授权的账号信息
|
||||||
@@ -101,8 +100,11 @@ func (ctx *Context) GetPreCodeContext(stdCtx context.Context) (string, error) {
|
|||||||
var ret struct {
|
var ret struct {
|
||||||
PreCode string `json:"pre_auth_code"`
|
PreCode string `json:"pre_auth_code"`
|
||||||
}
|
}
|
||||||
err = json.Unmarshal(body, &ret)
|
if err := json.Unmarshal(body, &ret); err != nil {
|
||||||
return ret.PreCode, err
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret.PreCode, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetPreCode 获取预授权码
|
// GetPreCode 获取预授权码
|
||||||
@@ -138,20 +140,6 @@ func (ctx *Context) GetBindComponentURL(redirectURI string, authType int, bizApp
|
|||||||
return ctx.GetBindComponentURLContext(context.Background(), redirectURI, authType, bizAppID)
|
return ctx.GetBindComponentURLContext(context.Background(), redirectURI, authType, bizAppID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetBindComponentURLV2Context 获取新版本第三方公众号授权链接(链接跳转,适用移动端)
|
|
||||||
func (ctx *Context) GetBindComponentURLV2Context(stdCtx context.Context, redirectURI string, authType int, bizAppID string) (string, error) {
|
|
||||||
code, err := ctx.GetPreCodeContext(stdCtx)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return fmt.Sprintf(bindComponentURLV2, authType, ctx.AppID, code, url.QueryEscape(redirectURI), bizAppID), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetBindComponentURLV2 获取新版本第三方公众号授权链接(链接跳转,适用移动端)
|
|
||||||
func (ctx *Context) GetBindComponentURLV2(redirectURI string, authType int, bizAppID string) (string, error) {
|
|
||||||
return ctx.GetBindComponentURLContext(context.Background(), redirectURI, authType, bizAppID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ID 微信返回接口中各种类型字段
|
// ID 微信返回接口中各种类型字段
|
||||||
type ID struct {
|
type ID struct {
|
||||||
ID int `json:"id"`
|
ID int `json:"id"`
|
||||||
@@ -240,10 +228,6 @@ func (ctx *Context) RefreshAuthrTokenContext(stdCtx context.Context, appid, refr
|
|||||||
if err := cache.SetContext(stdCtx, ctx.Cache, authrTokenKey, ret.AccessToken, time.Second*time.Duration(ret.ExpiresIn-30)); err != nil {
|
if err := cache.SetContext(stdCtx, ctx.Cache, authrTokenKey, ret.AccessToken, time.Second*time.Duration(ret.ExpiresIn-30)); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
refreshTokenKey := "authorizer_refresh_token_" + appid
|
|
||||||
if err := cache.SetContext(stdCtx, ctx.Cache, refreshTokenKey, ret.RefreshToken, 10*365*24*60*60*time.Second); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return ret, nil
|
return ret, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -257,18 +241,8 @@ func (ctx *Context) GetAuthrAccessTokenContext(stdCtx context.Context, appid str
|
|||||||
authrTokenKey := "authorizer_access_token_" + appid
|
authrTokenKey := "authorizer_access_token_" + appid
|
||||||
val := cache.GetContext(stdCtx, ctx.Cache, authrTokenKey)
|
val := cache.GetContext(stdCtx, ctx.Cache, authrTokenKey)
|
||||||
if val == nil {
|
if val == nil {
|
||||||
refreshTokenKey := "authorizer_refresh_token_" + appid
|
return "", fmt.Errorf("cannot get authorizer %s access token", appid)
|
||||||
val := cache.GetContext(stdCtx, ctx.Cache, refreshTokenKey)
|
|
||||||
if val == nil {
|
|
||||||
return "", fmt.Errorf("cannot get authorizer %s refresh token", appid)
|
|
||||||
}
|
|
||||||
token, err := ctx.RefreshAuthrTokenContext(stdCtx, appid, val.(string))
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return token.AccessToken, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return val.(string), nil
|
return val.(string), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,12 +9,6 @@ import (
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
getAccountBasicInfoURL = "https://api.weixin.qq.com/cgi-bin/account/getaccountbasicinfo"
|
getAccountBasicInfoURL = "https://api.weixin.qq.com/cgi-bin/account/getaccountbasicinfo"
|
||||||
checkNickNameURL = "https://api.weixin.qq.com/cgi-bin/wxverify/checkwxverifynickname"
|
|
||||||
setNickNameURL = "https://api.weixin.qq.com/wxa/setnickname"
|
|
||||||
setSignatureURL = "https://api.weixin.qq.com/cgi-bin/account/modifysignature"
|
|
||||||
setHeadImageURL = "https://api.weixin.qq.com/cgi-bin/account/modifyheadimage"
|
|
||||||
getSearchStatusURL = "https://api.weixin.qq.com/wxa/getwxasearchstatus"
|
|
||||||
setSearchStatusURL = "https://api.weixin.qq.com/wxa/changewxasearchstatus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Basic 基础信息设置
|
// Basic 基础信息设置
|
||||||
@@ -57,181 +51,3 @@ func (basic *Basic) GetAccountBasicInfo() (*AccountBasicInfo, error) {
|
|||||||
// TODO
|
// TODO
|
||||||
// func (encryptor *Basic) modifyDomain() {
|
// func (encryptor *Basic) modifyDomain() {
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// CheckNickNameResp 小程序名称检测结果
|
|
||||||
type CheckNickNameResp struct {
|
|
||||||
util.CommonError
|
|
||||||
HitCondition bool `json:"hit_condition"` // 是否命中关键字策略。若命中,可以选填关键字材料
|
|
||||||
Wording string `json:"wording"` // 命中关键字的说明描述
|
|
||||||
}
|
|
||||||
|
|
||||||
// CheckNickName 检测微信认证的名称是否符合规则
|
|
||||||
// ref: https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/basic-info-management/checkNickName.html
|
|
||||||
func (basic *Basic) CheckNickName(nickname string) (*CheckNickNameResp, error) {
|
|
||||||
ak, err := basic.GetAuthrAccessToken(basic.AppID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
url := fmt.Sprintf("%s?access_token=%s", checkNickNameURL, ak)
|
|
||||||
data, err := util.PostJSON(url, map[string]string{
|
|
||||||
"nick_name": nickname,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
res := &CheckNickNameResp{}
|
|
||||||
err = util.DecodeWithError(data, res, "CheckNickName")
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetNickNameResp 设置小程序名称结果
|
|
||||||
type SetNickNameResp struct {
|
|
||||||
util.CommonError
|
|
||||||
AuditID int64 `json:"audit_id"` // 审核单Id,通过用于查询改名审核状态
|
|
||||||
Wording string `json:"wording"` // 材料说明
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetNickNameParam 设置小程序名称参数
|
|
||||||
type SetNickNameParam struct {
|
|
||||||
NickName string `json:"nick_name"` // 昵称,不支持包含“小程序”关键字的昵称
|
|
||||||
IDCard string `json:"id_card,omitempty"` // 身份证照片 mediaid,个人号必填
|
|
||||||
License string `json:"license,omitempty"` // 组织机构代码证或营业执照 mediaid,组织号必填
|
|
||||||
NameingOtherStuff1 string `json:"naming_other_stuff_1,omitempty"` // 其他证明材料 mediaid,选填
|
|
||||||
NameingOtherStuff2 string `json:"naming_other_stuff_2,omitempty"` // 其他证明材料 mediaid,选填
|
|
||||||
NameingOtherStuff3 string `json:"naming_other_stuff_3,omitempty"` // 其他证明材料 mediaid,选填
|
|
||||||
NameingOtherStuff4 string `json:"naming_other_stuff_4,omitempty"` // 其他证明材料 mediaid,选填
|
|
||||||
NameingOtherStuff5 string `json:"naming_other_stuff_5,omitempty"` // 其他证明材料 mediaid,选填
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetNickName 设置小程序名称
|
|
||||||
func (basic *Basic) SetNickName(nickname string) (*SetNickNameResp, error) {
|
|
||||||
return basic.SetNickNameFull(&SetNickNameParam{
|
|
||||||
NickName: nickname,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetNickNameFull 设置小程序名称
|
|
||||||
// ref: https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/basic-info-management/setNickName.html
|
|
||||||
func (basic *Basic) SetNickNameFull(param *SetNickNameParam) (*SetNickNameResp, error) {
|
|
||||||
ak, err := basic.GetAuthrAccessToken(basic.AppID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
url := fmt.Sprintf("%s?access_token=%s", setNickNameURL, ak)
|
|
||||||
data, err := util.PostJSON(url, param)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
res := &SetNickNameResp{}
|
|
||||||
err = util.DecodeWithError(data, res, "SetNickName")
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetSignatureResp 小程序功能介绍修改结果
|
|
||||||
type SetSignatureResp struct {
|
|
||||||
util.CommonError
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetSignature 小程序修改功能介绍
|
|
||||||
// ref: https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/basic-info-management/setSignature.html
|
|
||||||
func (basic *Basic) SetSignature(signature string) error {
|
|
||||||
ak, err := basic.GetAuthrAccessToken(basic.AppID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
url := fmt.Sprintf("%s?access_token=%s", setSignatureURL, ak)
|
|
||||||
data, err := util.PostJSON(url, map[string]string{
|
|
||||||
"signature": signature,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithError(data, &SetSignatureResp{}, "SetSignature")
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSearchStatusResp 查询小程序当前是否可被搜索
|
|
||||||
type GetSearchStatusResp struct {
|
|
||||||
util.CommonError
|
|
||||||
Status int `json:"status"` // 1 表示不可搜索,0 表示可搜索
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSearchStatus 查询小程序当前是否可被搜索
|
|
||||||
// ref: https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/basic-info-management/getSearchStatus.html
|
|
||||||
func (basic *Basic) GetSearchStatus(signature string) (*GetSearchStatusResp, error) {
|
|
||||||
ak, err := basic.GetAuthrAccessToken(basic.AppID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
url := fmt.Sprintf("%s?access_token=%s", getSearchStatusURL, ak)
|
|
||||||
data, err := util.HTTPGet(url)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
res := &GetSearchStatusResp{}
|
|
||||||
err = util.DecodeWithError(data, res, "GetSearchStatus")
|
|
||||||
return res, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetSearchStatusResp 小程序是否可被搜索修改结果
|
|
||||||
type SetSearchStatusResp struct {
|
|
||||||
util.CommonError
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetSearchStatus 修改小程序是否可被搜索
|
|
||||||
// status: 1 表示不可搜索,0 表示可搜索
|
|
||||||
// ref: https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/basic-info-management/setSearchStatus.html
|
|
||||||
func (basic *Basic) SetSearchStatus(status int) error {
|
|
||||||
ak, err := basic.GetAuthrAccessToken(basic.AppID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
url := fmt.Sprintf("%s?access_token=%s", setSearchStatusURL, ak)
|
|
||||||
data, err := util.PostJSON(url, map[string]int{
|
|
||||||
"status": status,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithError(data, &SetSearchStatusResp{}, "SetSearchStatus")
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetHeadImageResp 小程序头像修改结果
|
|
||||||
type SetHeadImageResp struct {
|
|
||||||
util.CommonError
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetHeadImageParam 小程序头像修改参数
|
|
||||||
type SetHeadImageParam struct {
|
|
||||||
HeadImageMediaID string `json:"head_img_media_id"` // 头像素材 media_id
|
|
||||||
X1 string `json:"x1"` // 裁剪框左上角 x 坐标(取值范围:[0, 1])
|
|
||||||
Y1 string `json:"y1"` // 裁剪框左上角 y 坐标(取值范围:[0, 1])
|
|
||||||
X2 string `json:"x2"` // 裁剪框右下角 x 坐标(取值范围:[0, 1])
|
|
||||||
Y2 string `json:"y2"` // 裁剪框右下角 y 坐标(取值范围:[0, 1])
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetHeadImage 修改小程序头像
|
|
||||||
func (basic *Basic) SetHeadImage(imgMediaID string) error {
|
|
||||||
return basic.SetHeadImageFull(&SetHeadImageParam{
|
|
||||||
HeadImageMediaID: imgMediaID,
|
|
||||||
X1: "0",
|
|
||||||
Y1: "0",
|
|
||||||
X2: "1",
|
|
||||||
Y2: "1",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetHeadImageFull 修改小程序头像
|
|
||||||
// 新增临时素材: https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/New_temporary_materials.html
|
|
||||||
// ref: https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/basic-info-management/setHeadImage.html
|
|
||||||
func (basic *Basic) SetHeadImageFull(param *SetHeadImageParam) error {
|
|
||||||
ak, err := basic.GetAuthrAccessToken(basic.AppID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
url := fmt.Sprintf("%s?access_token=%s", setHeadImageURL, ak)
|
|
||||||
data, err := util.PostJSON(url, param)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithError(data, &SetHeadImageResp{}, "account/setheadimage")
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package miniprogram
|
package miniprogram
|
||||||
|
|
||||||
import (
|
import (
|
||||||
originalContext "context"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/credential"
|
"github.com/silenceper/wechat/v2/credential"
|
||||||
@@ -38,22 +37,6 @@ func (miniProgram *MiniProgram) GetAccessToken() (string, error) {
|
|||||||
return akRes.AccessToken, nil
|
return akRes.AccessToken, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetAccessTokenContext 利用ctx获取ak
|
|
||||||
func (miniProgram *MiniProgram) GetAccessTokenContext(ctx originalContext.Context) (string, error) {
|
|
||||||
ak, akErr := miniProgram.openContext.GetAuthrAccessTokenContext(ctx, miniProgram.AppID)
|
|
||||||
if akErr == nil {
|
|
||||||
return ak, nil
|
|
||||||
}
|
|
||||||
if miniProgram.authorizerRefreshToken == "" {
|
|
||||||
return "", fmt.Errorf("please set the authorizer_refresh_token first")
|
|
||||||
}
|
|
||||||
akRes, akResErr := miniProgram.GetComponent().RefreshAuthrTokenContext(ctx, miniProgram.AppID, miniProgram.authorizerRefreshToken)
|
|
||||||
if akResErr != nil {
|
|
||||||
return "", akResErr
|
|
||||||
}
|
|
||||||
return akRes.AccessToken, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetAuthorizerRefreshToken 设置代执操作业务授权账号authorizer_refresh_token
|
// SetAuthorizerRefreshToken 设置代执操作业务授权账号authorizer_refresh_token
|
||||||
func (miniProgram *MiniProgram) SetAuthorizerRefreshToken(authorizerRefreshToken string) *MiniProgram {
|
func (miniProgram *MiniProgram) SetAuthorizerRefreshToken(authorizerRefreshToken string) *MiniProgram {
|
||||||
miniProgram.authorizerRefreshToken = authorizerRefreshToken
|
miniProgram.authorizerRefreshToken = authorizerRefreshToken
|
||||||
@@ -85,7 +68,7 @@ func (miniProgram *MiniProgram) GetBasic() *basic.Basic {
|
|||||||
// GetURLLink 小程序URL Link接口 调用前需确认已调用 SetAuthorizerRefreshToken 避免由于缓存中 authorizer_access_token 过期执行中断
|
// GetURLLink 小程序URL Link接口 调用前需确认已调用 SetAuthorizerRefreshToken 避免由于缓存中 authorizer_access_token 过期执行中断
|
||||||
func (miniProgram *MiniProgram) GetURLLink() *urllink.URLLink {
|
func (miniProgram *MiniProgram) GetURLLink() *urllink.URLLink {
|
||||||
return urllink.NewURLLink(&miniContext.Context{
|
return urllink.NewURLLink(&miniContext.Context{
|
||||||
AccessTokenContextHandle: miniProgram,
|
AccessTokenHandle: miniProgram,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package js
|
package js
|
||||||
|
|
||||||
import (
|
import (
|
||||||
context2 "context"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/credential"
|
"github.com/silenceper/wechat/v2/credential"
|
||||||
@@ -33,31 +32,14 @@ func (js *Js) SetJsTicketHandle(ticketHandle credential.JsTicketHandle) {
|
|||||||
// GetConfig 第三方平台 - 获取jssdk需要的配置参数
|
// GetConfig 第三方平台 - 获取jssdk需要的配置参数
|
||||||
// uri 为当前网页地址
|
// uri 为当前网页地址
|
||||||
func (js *Js) GetConfig(uri, appid string) (config *officialJs.Config, err error) {
|
func (js *Js) GetConfig(uri, appid string) (config *officialJs.Config, err error) {
|
||||||
return js.GetConfigContext(context2.Background(), uri, appid)
|
config = new(officialJs.Config)
|
||||||
}
|
|
||||||
|
|
||||||
// GetConfigContext 新方法,允许传入上下文,避免协程泄漏
|
|
||||||
func (js *Js) GetConfigContext(ctx context2.Context, uri, appid string) (config *officialJs.Config, err error) {
|
|
||||||
var accessToken string
|
var accessToken string
|
||||||
// 类型断言,如果断言成功,调用安全的 GetAccessTokenContext 方法
|
accessToken, err = js.GetAccessToken()
|
||||||
if ctxHandle, ok := js.Context.AccessTokenHandle.(credential.AccessTokenContextHandle); ok {
|
|
||||||
accessToken, err = ctxHandle.GetAccessTokenContext(ctx)
|
|
||||||
} else {
|
|
||||||
// 如果没有实现 AccessTokenContextHandle 接口,调用旧的 GetAccessToken 方法
|
|
||||||
accessToken, err = js.Context.GetAccessToken()
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var ticketStr string
|
var ticketStr string
|
||||||
// 类型断言 jsTicket
|
ticketStr, err = js.GetTicket(accessToken)
|
||||||
if ticketCtxHandle, ok := js.JsTicketHandle.(credential.JsTicketContextHandle); ok {
|
|
||||||
ticketStr, err = ticketCtxHandle.GetTicketContext(ctx, accessToken)
|
|
||||||
} else {
|
|
||||||
// 如果没有实现 JsTicketContextHandle 接口,调用旧的 GetTicket 方法
|
|
||||||
ticketStr, err = js.GetTicket(accessToken)
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -67,7 +49,6 @@ func (js *Js) GetConfigContext(ctx context2.Context, uri, appid string) (config
|
|||||||
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
|
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
|
||||||
sigStr := util.Signature(str)
|
sigStr := util.Signature(str)
|
||||||
|
|
||||||
config = new(officialJs.Config)
|
|
||||||
config.AppID = appid
|
config.AppID = appid
|
||||||
config.NonceStr = nonceStr
|
config.NonceStr = nonceStr
|
||||||
config.Timestamp = timestamp
|
config.Timestamp = timestamp
|
||||||
|
|||||||
@@ -1,147 +0,0 @@
|
|||||||
// 验证 js.GetConfigContext 是否能正确传递上下文到 HTTP 请求,确保上下文正确传播,防止在获取 JSSDK 配置时发生协程泄露。
|
|
||||||
package js
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
context2 "context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/cache"
|
|
||||||
"github.com/silenceper/wechat/v2/credential"
|
|
||||||
"github.com/silenceper/wechat/v2/officialaccount/config"
|
|
||||||
"github.com/silenceper/wechat/v2/officialaccount/context"
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
|
||||||
)
|
|
||||||
|
|
||||||
// mockAccessTokenHandle 模拟 AccessTokenHandle
|
|
||||||
type mockAccessTokenHandle struct{}
|
|
||||||
|
|
||||||
func (m *mockAccessTokenHandle) GetAccessToken() (string, error) {
|
|
||||||
return "mock-access-token", nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockAccessTokenHandle) GetAccessTokenContext(_ context2.Context) (string, error) {
|
|
||||||
return "mock-access-token", nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// contextCheckingRoundTripper 自定义 RoundTripper 用于检查 context
|
|
||||||
type contextCheckingRoundTripper struct {
|
|
||||||
originalCtx context2.Context
|
|
||||||
t *testing.T
|
|
||||||
key interface{}
|
|
||||||
expectedVal interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rt *contextCheckingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
||||||
// 获取请求中的 context
|
|
||||||
reqCtx := req.Context()
|
|
||||||
|
|
||||||
// 打印 context 比较结果
|
|
||||||
rt.t.Logf("比较上下文的内存地址:\n")
|
|
||||||
if reqCtx == rt.originalCtx {
|
|
||||||
rt.t.Logf("上下文具有相同的内存地址。原始上下文: %p, 请求上下文: %p\n", rt.originalCtx, reqCtx)
|
|
||||||
} else {
|
|
||||||
rt.t.Logf("上下文具有不同的内存地址。原始上下文: %p, 请求上下文: %p\n", rt.originalCtx, reqCtx)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查 context 中的键值对
|
|
||||||
if rt.key != nil {
|
|
||||||
value := reqCtx.Value(rt.key)
|
|
||||||
rt.t.Logf("检查请求上下文中的键 %v:\n", rt.key)
|
|
||||||
if value != rt.expectedVal {
|
|
||||||
rt.t.Errorf("上下文键 %v 的值不匹配: 预期 %v, 实际 %v\n", rt.key, rt.expectedVal, value)
|
|
||||||
} else {
|
|
||||||
rt.t.Logf("上下文键 %v 的值匹配: 预期 %v, 实际 %v\n", rt.key, rt.expectedVal, value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查上下文是否已取消
|
|
||||||
select {
|
|
||||||
case <-reqCtx.Done():
|
|
||||||
return nil, reqCtx.Err() // 返回上下文取消错误
|
|
||||||
default:
|
|
||||||
// 返回模拟的 HTTP 响应,包含有效的 JSON
|
|
||||||
responseBody := `{"ticket":"mock-ticket","expires_in":7200}`
|
|
||||||
response := &http.Response{
|
|
||||||
Status: "200 OK",
|
|
||||||
StatusCode: http.StatusOK,
|
|
||||||
Proto: "HTTP/1.1",
|
|
||||||
ProtoMajor: 1,
|
|
||||||
ProtoMinor: 1,
|
|
||||||
Body: io.NopCloser(bytes.NewReader([]byte(responseBody))),
|
|
||||||
ContentLength: int64(len(responseBody)),
|
|
||||||
Header: make(http.Header),
|
|
||||||
}
|
|
||||||
response.Header.Set("Content-Type", "application/json")
|
|
||||||
return response, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// contextKey 定义自定义上下文键类型,避免使用内置 string 类型
|
|
||||||
type contextKey string
|
|
||||||
|
|
||||||
// setupJsInstance 初始化 Js 实例和 HTTP 客户端
|
|
||||||
func setupJsInstance(t *testing.T, ctx context2.Context, key, val interface{}) (*Js, func()) {
|
|
||||||
cfg := &config.Config{
|
|
||||||
AppID: "test-app-id",
|
|
||||||
AppSecret: "test-app-secret",
|
|
||||||
Cache: cache.NewMemory(),
|
|
||||||
}
|
|
||||||
cacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", credential.CacheKeyOfficialAccountPrefix, cfg.AppID)
|
|
||||||
if err := cfg.Cache.Delete(cacheKey); err != nil {
|
|
||||||
t.Fatalf("清除缓存失败: %v", err)
|
|
||||||
}
|
|
||||||
t.Log("清除 jsapi_ticket 的缓存:", cacheKey)
|
|
||||||
|
|
||||||
ctxHandle := &context.Context{Config: cfg, AccessTokenHandle: &mockAccessTokenHandle{}}
|
|
||||||
jsInstance := NewJs(ctxHandle, cfg.AppID)
|
|
||||||
jsInstance.SetJsTicketHandle(credential.NewDefaultJsTicket(cfg.AppID, credential.CacheKeyOfficialAccountPrefix, cfg.Cache))
|
|
||||||
|
|
||||||
originalClient := util.DefaultHTTPClient
|
|
||||||
util.DefaultHTTPClient = &http.Client{
|
|
||||||
Transport: &contextCheckingRoundTripper{originalCtx: ctx, t: t, key: key, expectedVal: val},
|
|
||||||
}
|
|
||||||
return jsInstance, func() { util.DefaultHTTPClient = originalClient }
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestGetConfigContext 测试GetConfigContext的上下文传递和取消行为。
|
|
||||||
func TestGetConfigContext(t *testing.T) {
|
|
||||||
t.Run("ContextPassing", func(t *testing.T) {
|
|
||||||
ctxKey := contextKey("testKey111") // 使用自定义类型 contextKey
|
|
||||||
ctxValue := "testValue222"
|
|
||||||
ctx := context2.WithValue(context2.Background(), ctxKey, ctxValue)
|
|
||||||
t.Logf("创建的测试上下文: %p, 添加的键值对: %v=%v\n", ctx, ctxKey, ctxValue)
|
|
||||||
|
|
||||||
jsInstance, cleanup := setupJsInstance(t, ctx, ctxKey, ctxValue)
|
|
||||||
defer cleanup()
|
|
||||||
t.Log("调用 GetConfigContext")
|
|
||||||
config2, err := jsInstance.GetConfigContext(ctx, "https://www.baidu.com", "test-app-id")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("GetConfigContext 失败: %v", err)
|
|
||||||
}
|
|
||||||
if config2.AppID != "test-app-id" {
|
|
||||||
t.Errorf("预期 AppID 为 %s,实际为 %s", "test-app-id", config2.AppID)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("ContextCancellation", func(t *testing.T) {
|
|
||||||
ctx, cancel := context2.WithCancel(context2.Background())
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
jsInstance, cleanup := setupJsInstance(t, ctx, nil, nil)
|
|
||||||
defer cleanup()
|
|
||||||
|
|
||||||
cancel()
|
|
||||||
t.Log("调用 GetConfigContext(已取消上下文)")
|
|
||||||
_, err := jsInstance.GetConfigContext(ctx, "https://www.baidu.com", "test-app-id")
|
|
||||||
if err == nil {
|
|
||||||
t.Error("预期上下文取消错误,但 GetConfigContext 未返回错误")
|
|
||||||
} else if !errors.Is(err, context2.Canceled) {
|
|
||||||
t.Errorf("预期错误为 context.Canceled,实际为: %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
122
util/http.go
122
util/http.go
@@ -17,19 +17,6 @@ import (
|
|||||||
"golang.org/x/crypto/pkcs12"
|
"golang.org/x/crypto/pkcs12"
|
||||||
)
|
)
|
||||||
|
|
||||||
// URIModifier URI修改器
|
|
||||||
type URIModifier func(uri string) string
|
|
||||||
|
|
||||||
var uriModifier URIModifier
|
|
||||||
|
|
||||||
// DefaultHTTPClient 默认httpClient
|
|
||||||
var DefaultHTTPClient = http.DefaultClient
|
|
||||||
|
|
||||||
// SetURIModifier 设置URI修改器
|
|
||||||
func SetURIModifier(fn URIModifier) {
|
|
||||||
uriModifier = fn
|
|
||||||
}
|
|
||||||
|
|
||||||
// HTTPGet get 请求
|
// HTTPGet get 请求
|
||||||
func HTTPGet(uri string) ([]byte, error) {
|
func HTTPGet(uri string) ([]byte, error) {
|
||||||
return HTTPGetContext(context.Background(), uri)
|
return HTTPGetContext(context.Background(), uri)
|
||||||
@@ -37,14 +24,11 @@ func HTTPGet(uri string) ([]byte, error) {
|
|||||||
|
|
||||||
// HTTPGetContext get 请求
|
// HTTPGetContext get 请求
|
||||||
func HTTPGetContext(ctx context.Context, uri string) ([]byte, error) {
|
func HTTPGetContext(ctx context.Context, uri string) ([]byte, error) {
|
||||||
if uriModifier != nil {
|
|
||||||
uri = uriModifier(uri)
|
|
||||||
}
|
|
||||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
|
request, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
response, err := DefaultHTTPClient.Do(request)
|
response, err := http.DefaultClient.Do(request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -63,9 +47,6 @@ func HTTPPost(uri string, data string) ([]byte, error) {
|
|||||||
|
|
||||||
// HTTPPostContext post 请求
|
// HTTPPostContext post 请求
|
||||||
func HTTPPostContext(ctx context.Context, uri string, data []byte, header map[string]string) ([]byte, error) {
|
func HTTPPostContext(ctx context.Context, uri string, data []byte, header map[string]string) ([]byte, error) {
|
||||||
if uriModifier != nil {
|
|
||||||
uri = uriModifier(uri)
|
|
||||||
}
|
|
||||||
body := bytes.NewBuffer(data)
|
body := bytes.NewBuffer(data)
|
||||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, uri, body)
|
request, err := http.NewRequestWithContext(ctx, http.MethodPost, uri, body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -76,7 +57,7 @@ func HTTPPostContext(ctx context.Context, uri string, data []byte, header map[st
|
|||||||
request.Header.Set(key, value)
|
request.Header.Set(key, value)
|
||||||
}
|
}
|
||||||
|
|
||||||
response, err := DefaultHTTPClient.Do(request)
|
response, err := http.DefaultClient.Do(request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -90,9 +71,6 @@ func HTTPPostContext(ctx context.Context, uri string, data []byte, header map[st
|
|||||||
|
|
||||||
// PostJSONContext post json 数据请求
|
// PostJSONContext post json 数据请求
|
||||||
func PostJSONContext(ctx context.Context, uri string, obj interface{}) ([]byte, error) {
|
func PostJSONContext(ctx context.Context, uri string, obj interface{}) ([]byte, error) {
|
||||||
if uriModifier != nil {
|
|
||||||
uri = uriModifier(uri)
|
|
||||||
}
|
|
||||||
jsonBuf := new(bytes.Buffer)
|
jsonBuf := new(bytes.Buffer)
|
||||||
enc := json.NewEncoder(jsonBuf)
|
enc := json.NewEncoder(jsonBuf)
|
||||||
enc.SetEscapeHTML(false)
|
enc.SetEscapeHTML(false)
|
||||||
@@ -105,7 +83,7 @@ func PostJSONContext(ctx context.Context, uri string, obj interface{}) ([]byte,
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
req.Header.Set("Content-Type", "application/json;charset=utf-8")
|
req.Header.Set("Content-Type", "application/json;charset=utf-8")
|
||||||
response, err := DefaultHTTPClient.Do(req)
|
response, err := http.DefaultClient.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -132,7 +110,7 @@ func PostJSONWithRespContentType(uri string, obj interface{}) ([]byte, string, e
|
|||||||
return nil, "", err
|
return nil, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
response, err := DefaultHTTPClient.Post(uri, "application/json;charset=utf-8", jsonBuf)
|
response, err := http.Post(uri, "application/json;charset=utf-8", jsonBuf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", err
|
return nil, "", err
|
||||||
}
|
}
|
||||||
@@ -146,41 +124,13 @@ func PostJSONWithRespContentType(uri string, obj interface{}) ([]byte, string, e
|
|||||||
return responseData, contentType, err
|
return responseData, contentType, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// PostFileByStream 上传文件
|
|
||||||
func PostFileByStream(fieldName, fileName, uri string, byteData []byte) ([]byte, error) {
|
|
||||||
fields := []MultipartFormField{
|
|
||||||
{
|
|
||||||
IsFile: false,
|
|
||||||
Fieldname: fieldName,
|
|
||||||
Filename: fileName,
|
|
||||||
Value: byteData,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
return PostMultipartForm(fields, uri)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PostFile 上传文件
|
// PostFile 上传文件
|
||||||
func PostFile(fieldName, filePath, uri string) ([]byte, error) {
|
func PostFile(fieldName, filename, uri string) ([]byte, error) {
|
||||||
fields := []MultipartFormField{
|
fields := []MultipartFormField{
|
||||||
{
|
{
|
||||||
IsFile: true,
|
IsFile: true,
|
||||||
Fieldname: fieldName,
|
Fieldname: fieldName,
|
||||||
FilePath: filePath,
|
Filename: filename,
|
||||||
Filename: filePath,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
return PostMultipartForm(fields, uri)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PostFileFromReader 上传文件,从 io.Reader 中读取
|
|
||||||
func PostFileFromReader(filedName, filePath, fileName, uri string, reader io.Reader) ([]byte, error) {
|
|
||||||
fields := []MultipartFormField{
|
|
||||||
{
|
|
||||||
IsFile: true,
|
|
||||||
Fieldname: filedName,
|
|
||||||
FilePath: filePath,
|
|
||||||
Filename: fileName,
|
|
||||||
FileReader: reader,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
return PostMultipartForm(fields, uri)
|
return PostMultipartForm(fields, uri)
|
||||||
@@ -188,19 +138,14 @@ func PostFileFromReader(filedName, filePath, fileName, uri string, reader io.Rea
|
|||||||
|
|
||||||
// MultipartFormField 保存文件或其他字段信息
|
// MultipartFormField 保存文件或其他字段信息
|
||||||
type MultipartFormField struct {
|
type MultipartFormField struct {
|
||||||
IsFile bool
|
IsFile bool
|
||||||
Fieldname string
|
Fieldname string
|
||||||
Value []byte
|
Value []byte
|
||||||
FilePath string
|
Filename string
|
||||||
Filename string
|
|
||||||
FileReader io.Reader
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// PostMultipartForm 上传文件或其他多个字段
|
// PostMultipartForm 上传文件或其他多个字段
|
||||||
func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte, err error) {
|
func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte, err error) {
|
||||||
if uriModifier != nil {
|
|
||||||
uri = uriModifier(uri)
|
|
||||||
}
|
|
||||||
bodyBuf := &bytes.Buffer{}
|
bodyBuf := &bytes.Buffer{}
|
||||||
bodyWriter := multipart.NewWriter(bodyBuf)
|
bodyWriter := multipart.NewWriter(bodyBuf)
|
||||||
|
|
||||||
@@ -212,24 +157,18 @@ func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if field.FileReader == nil {
|
fh, e := os.Open(field.Filename)
|
||||||
fh, e := os.Open(field.FilePath)
|
if e != nil {
|
||||||
if e != nil {
|
err = fmt.Errorf("error opening file , err=%v", e)
|
||||||
err = fmt.Errorf("error opening file , err=%v", e)
|
return
|
||||||
return
|
}
|
||||||
}
|
defer fh.Close()
|
||||||
_, err = io.Copy(fileWriter, fh)
|
|
||||||
_ = fh.Close()
|
if _, err = io.Copy(fileWriter, fh); err != nil {
|
||||||
if err != nil {
|
return
|
||||||
return
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if _, err = io.Copy(fileWriter, field.FileReader); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
partWriter, e := bodyWriter.CreateFormFile(field.Fieldname, field.Filename)
|
partWriter, e := bodyWriter.CreateFormField(field.Fieldname)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
err = e
|
err = e
|
||||||
return
|
return
|
||||||
@@ -244,14 +183,14 @@ func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte
|
|||||||
contentType := bodyWriter.FormDataContentType()
|
contentType := bodyWriter.FormDataContentType()
|
||||||
bodyWriter.Close()
|
bodyWriter.Close()
|
||||||
|
|
||||||
resp, e := DefaultHTTPClient.Post(uri, contentType, bodyBuf)
|
resp, e := http.Post(uri, contentType, bodyBuf)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
err = e
|
err = e
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
return nil, fmt.Errorf("http code error : uri=%v , statusCode=%v", uri, resp.StatusCode)
|
return nil, err
|
||||||
}
|
}
|
||||||
respBody, err = io.ReadAll(resp.Body)
|
respBody, err = io.ReadAll(resp.Body)
|
||||||
return
|
return
|
||||||
@@ -259,16 +198,13 @@ func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte
|
|||||||
|
|
||||||
// PostXML perform a HTTP/POST request with XML body
|
// PostXML perform a HTTP/POST request with XML body
|
||||||
func PostXML(uri string, obj interface{}) ([]byte, error) {
|
func PostXML(uri string, obj interface{}) ([]byte, error) {
|
||||||
if uriModifier != nil {
|
|
||||||
uri = uriModifier(uri)
|
|
||||||
}
|
|
||||||
xmlData, err := xml.Marshal(obj)
|
xmlData, err := xml.Marshal(obj)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
body := bytes.NewBuffer(xmlData)
|
body := bytes.NewBuffer(xmlData)
|
||||||
response, err := DefaultHTTPClient.Post(uri, "application/xml;charset=utf-8", body)
|
response, err := http.Post(uri, "application/xml;charset=utf-8", body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -291,10 +227,11 @@ func httpWithTLS(rootCa, key string) (*http.Client, error) {
|
|||||||
config := &tls.Config{
|
config := &tls.Config{
|
||||||
Certificates: []tls.Certificate{cert},
|
Certificates: []tls.Certificate{cert},
|
||||||
}
|
}
|
||||||
trans := (DefaultHTTPClient.Transport.(*http.Transport)).Clone()
|
tr := &http.Transport{
|
||||||
trans.TLSClientConfig = config
|
TLSClientConfig: config,
|
||||||
trans.DisableCompression = true
|
DisableCompression: true,
|
||||||
client = &http.Client{Transport: trans}
|
}
|
||||||
|
client = &http.Client{Transport: tr}
|
||||||
return client, nil
|
return client, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -322,9 +259,6 @@ func pkcs12ToPem(p12 []byte, password string) tls.Certificate {
|
|||||||
|
|
||||||
// PostXMLWithTLS perform a HTTP/POST request with XML body and TLS
|
// PostXMLWithTLS perform a HTTP/POST request with XML body and TLS
|
||||||
func PostXMLWithTLS(uri string, obj interface{}, ca, key string) ([]byte, error) {
|
func PostXMLWithTLS(uri string, obj interface{}, ca, key string) ([]byte, error) {
|
||||||
if uriModifier != nil {
|
|
||||||
uri = uriModifier(uri)
|
|
||||||
}
|
|
||||||
xmlData, err := xml.Marshal(obj)
|
xmlData, err := xml.Marshal(obj)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package wechat
|
package wechat
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
@@ -15,7 +14,6 @@ import (
|
|||||||
openConfig "github.com/silenceper/wechat/v2/openplatform/config"
|
openConfig "github.com/silenceper/wechat/v2/openplatform/config"
|
||||||
"github.com/silenceper/wechat/v2/pay"
|
"github.com/silenceper/wechat/v2/pay"
|
||||||
payConfig "github.com/silenceper/wechat/v2/pay/config"
|
payConfig "github.com/silenceper/wechat/v2/pay/config"
|
||||||
"github.com/silenceper/wechat/v2/util"
|
|
||||||
"github.com/silenceper/wechat/v2/work"
|
"github.com/silenceper/wechat/v2/work"
|
||||||
workConfig "github.com/silenceper/wechat/v2/work/config"
|
workConfig "github.com/silenceper/wechat/v2/work/config"
|
||||||
)
|
)
|
||||||
@@ -83,8 +81,3 @@ func (wc *Wechat) GetWork(cfg *workConfig.Config) *work.Work {
|
|||||||
}
|
}
|
||||||
return work.NewWork(cfg)
|
return work.NewWork(cfg)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetHTTPClient 设置HTTPClient
|
|
||||||
func (wc *Wechat) SetHTTPClient(client *http.Client) {
|
|
||||||
util.DefaultHTTPClient = client
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -9,16 +9,11 @@ import (
|
|||||||
const (
|
const (
|
||||||
// departmentCreateURL 创建部门
|
// departmentCreateURL 创建部门
|
||||||
departmentCreateURL = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=%s"
|
departmentCreateURL = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=%s"
|
||||||
// departmentUpdateURL 更新部门
|
|
||||||
departmentUpdateURL = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=%s"
|
|
||||||
// departmentDeleteURL 删除部门
|
|
||||||
departmentDeleteURL = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=%s&id=%d"
|
|
||||||
// departmentSimpleListURL 获取子部门ID列表
|
// departmentSimpleListURL 获取子部门ID列表
|
||||||
departmentSimpleListURL = "https://qyapi.weixin.qq.com/cgi-bin/department/simplelist?access_token=%s&id=%d"
|
departmentSimpleListURL = "https://qyapi.weixin.qq.com/cgi-bin/department/simplelist?access_token=%s&id=%d"
|
||||||
// departmentListURL 获取部门列表
|
// departmentListURL 获取部门列表
|
||||||
departmentListURL = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=%s"
|
departmentListURL = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=%s"
|
||||||
departmentListByIDURL = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=%s&id=%d"
|
// departmentGetURL 获取单个部门详情 https://qyapi.weixin.qq.com/cgi-bin/department/get?access_token=ACCESS_TOKEN&id=ID
|
||||||
// departmentGetURL 获取单个部门详情
|
|
||||||
departmentGetURL = "https://qyapi.weixin.qq.com/cgi-bin/department/get?access_token=%s&id=%d"
|
departmentGetURL = "https://qyapi.weixin.qq.com/cgi-bin/department/get?access_token=%s&id=%d"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -89,49 +84,6 @@ func (r *Client) DepartmentCreate(req *DepartmentCreateRequest) (*DepartmentCrea
|
|||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// DepartmentUpdateRequest 更新部门请求
|
|
||||||
type DepartmentUpdateRequest struct {
|
|
||||||
ID int `json:"id"`
|
|
||||||
Name string `json:"name,omitempty"`
|
|
||||||
NameEn string `json:"name_en,omitempty"`
|
|
||||||
ParentID int `json:"parentid,omitempty"`
|
|
||||||
Order int `json:"order,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// DepartmentUpdate 更新部门
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/90206
|
|
||||||
func (r *Client) DepartmentUpdate(req *DepartmentUpdateRequest) error {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(departmentUpdateURL, accessToken), req); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithCommonError(response, "DepartmentUpdate")
|
|
||||||
}
|
|
||||||
|
|
||||||
// DepartmentDelete 删除部门
|
|
||||||
// @see https://developer.work.weixin.qq.com/document/path/90207
|
|
||||||
func (r *Client) DepartmentDelete(departmentID int) error {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.HTTPGet(fmt.Sprintf(departmentDeleteURL, accessToken, departmentID)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithCommonError(response, "DepartmentDelete")
|
|
||||||
}
|
|
||||||
|
|
||||||
// DepartmentSimpleList 获取子部门ID列表
|
// DepartmentSimpleList 获取子部门ID列表
|
||||||
// see https://developer.work.weixin.qq.com/document/path/95350
|
// see https://developer.work.weixin.qq.com/document/path/95350
|
||||||
func (r *Client) DepartmentSimpleList(departmentID int) ([]*DepartmentID, error) {
|
func (r *Client) DepartmentSimpleList(departmentID int) ([]*DepartmentID, error) {
|
||||||
@@ -154,31 +106,13 @@ func (r *Client) DepartmentSimpleList(departmentID int) ([]*DepartmentID, error)
|
|||||||
// DepartmentList 获取部门列表
|
// DepartmentList 获取部门列表
|
||||||
// @desc https://developer.work.weixin.qq.com/document/path/90208
|
// @desc https://developer.work.weixin.qq.com/document/path/90208
|
||||||
func (r *Client) DepartmentList() ([]*Department, error) {
|
func (r *Client) DepartmentList() ([]*Department, error) {
|
||||||
return r.DepartmentListByID(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DepartmentListByID 获取部门列表
|
|
||||||
//
|
|
||||||
// departmentID 部门id。获取指定部门及其下的子部门(以及子部门的子部门等等,递归)
|
|
||||||
//
|
|
||||||
// @desc https://developer.work.weixin.qq.com/document/path/90208
|
|
||||||
func (r *Client) DepartmentListByID(departmentID int) ([]*Department, error) {
|
|
||||||
var formatURL string
|
|
||||||
|
|
||||||
// 获取accessToken
|
// 获取accessToken
|
||||||
accessToken, err := r.GetAccessToken()
|
accessToken, err := r.GetAccessToken()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if departmentID > 0 {
|
|
||||||
formatURL = fmt.Sprintf(departmentListByIDURL, accessToken, departmentID)
|
|
||||||
} else {
|
|
||||||
formatURL = fmt.Sprintf(departmentListURL, accessToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 发起http请求
|
// 发起http请求
|
||||||
response, err := util.HTTPGet(formatURL)
|
response, err := util.HTTPGet(fmt.Sprintf(departmentListURL, accessToken))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,8 +12,6 @@ const (
|
|||||||
userSimpleListURL = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist"
|
userSimpleListURL = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist"
|
||||||
// userCreateURL 创建成员
|
// userCreateURL 创建成员
|
||||||
userCreateURL = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=%s"
|
userCreateURL = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=%s"
|
||||||
// userUpdateURL 更新成员
|
|
||||||
userUpdateURL = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=%s"
|
|
||||||
// userGetURL 读取成员
|
// userGetURL 读取成员
|
||||||
userGetURL = "https://qyapi.weixin.qq.com/cgi-bin/user/get"
|
userGetURL = "https://qyapi.weixin.qq.com/cgi-bin/user/get"
|
||||||
// userDeleteURL 删除成员
|
// userDeleteURL 删除成员
|
||||||
@@ -156,52 +154,6 @@ func (r *Client) UserCreate(req *UserCreateRequest) (*UserCreateResponse, error)
|
|||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserUpdateRequest 更新成员请求
|
|
||||||
type UserUpdateRequest struct {
|
|
||||||
UserID string `json:"userid"`
|
|
||||||
NewUserID string `json:"new_userid"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Alias string `json:"alias"`
|
|
||||||
Mobile string `json:"mobile"`
|
|
||||||
Department []int `json:"department"`
|
|
||||||
Order []int `json:"order"`
|
|
||||||
Position string `json:"position"`
|
|
||||||
Gender int `json:"gender"`
|
|
||||||
Email string `json:"email"`
|
|
||||||
BizMail string `json:"biz_mail"`
|
|
||||||
BizMailAlias string `json:"biz_mail_alias"`
|
|
||||||
IsLeaderInDept []int `json:"is_leader_in_dept"`
|
|
||||||
DirectLeader []string `json:"direct_leader"`
|
|
||||||
Enable int `json:"enable"`
|
|
||||||
AvatarMediaid string `json:"avatar_mediaid"`
|
|
||||||
Telephone string `json:"telephone"`
|
|
||||||
Address string `json:"address"`
|
|
||||||
MainDepartment int `json:"main_department"`
|
|
||||||
Extattr struct {
|
|
||||||
Attrs []ExtraAttr `json:"attrs"`
|
|
||||||
} `json:"extattr"`
|
|
||||||
ToInvite bool `json:"to_invite"`
|
|
||||||
ExternalPosition string `json:"external_position"`
|
|
||||||
ExternalProfile ExternalProfile `json:"external_profile"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// UserUpdate 更新成员
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/90197
|
|
||||||
func (r *Client) UserUpdate(req *UserUpdateRequest) error {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(userUpdateURL, accessToken), req); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithCommonError(response, "UserUpdate")
|
|
||||||
}
|
|
||||||
|
|
||||||
// UserGetResponse 获取部门成员响应
|
// UserGetResponse 获取部门成员响应
|
||||||
type UserGetResponse struct {
|
type UserGetResponse struct {
|
||||||
util.CommonError
|
util.CommonError
|
||||||
|
|||||||
@@ -1,428 +0,0 @@
|
|||||||
package checkin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// setScheduleListURL 为打卡人员排班
|
|
||||||
setScheduleListURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/setcheckinschedulist?access_token=%s"
|
|
||||||
// punchCorrectionURL 为打卡人员补卡
|
|
||||||
punchCorrectionURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/punch_correction?access_token=%s"
|
|
||||||
// addUserFaceURL 录入打卡人员人脸信息
|
|
||||||
addUserFaceURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/addcheckinuserface?access_token=%s"
|
|
||||||
// addOptionURL 创建打卡规则
|
|
||||||
addOptionURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/add_checkin_option?access_token=%s"
|
|
||||||
// updateOptionURL 修改打卡规则
|
|
||||||
updateOptionURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/update_checkin_option?access_token=%s"
|
|
||||||
// clearOptionURL 清空打卡规则数组元素
|
|
||||||
clearOptionURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/clear_checkin_option_array_field?access_token=%s"
|
|
||||||
// delOptionURL 删除打卡规则
|
|
||||||
delOptionURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/del_checkin_option?access_token=%s"
|
|
||||||
// addRecordURL 添加打卡记录
|
|
||||||
addRecordURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/add_checkin_record?access_token=%s"
|
|
||||||
)
|
|
||||||
|
|
||||||
// SetScheduleListRequest 为打卡人员排班请求
|
|
||||||
type SetScheduleListRequest struct {
|
|
||||||
GroupID int64 `json:"groupid"`
|
|
||||||
Items []SetScheduleListItem `json:"items"`
|
|
||||||
YearMonth int64 `json:"yearmonth"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetScheduleListItem 排班表信息
|
|
||||||
type SetScheduleListItem struct {
|
|
||||||
UserID string `json:"userid"`
|
|
||||||
Day int64 `json:"day"`
|
|
||||||
ScheduleID int64 `json:"schedule_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetScheduleList 为打卡人员排班
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/93385
|
|
||||||
func (r *Client) SetScheduleList(req *SetScheduleListRequest) error {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(setScheduleListURL, accessToken), req); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithCommonError(response, "SetScheduleList")
|
|
||||||
}
|
|
||||||
|
|
||||||
// PunchCorrectionRequest 为打卡人员补卡请求
|
|
||||||
type PunchCorrectionRequest struct {
|
|
||||||
UserID string `json:"userid"`
|
|
||||||
ScheduleDateTime int64 `json:"schedule_date_time"`
|
|
||||||
ScheduleCheckinTime int64 `json:"schedule_checkin_time"`
|
|
||||||
CheckinTime int64 `json:"checkin_time"`
|
|
||||||
Remark string `json:"remark"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// PunchCorrection 为打卡人员补卡
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/95803
|
|
||||||
func (r *Client) PunchCorrection(req *PunchCorrectionRequest) error {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(punchCorrectionURL, accessToken), req); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithCommonError(response, "PunchCorrection")
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddUserFaceRequest 录入打卡人员人脸信息请求
|
|
||||||
type AddUserFaceRequest struct {
|
|
||||||
UserID string `json:"userid"`
|
|
||||||
UserFace string `json:"userface"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddUserFace 录入打卡人员人脸信息
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/93378
|
|
||||||
func (r *Client) AddUserFace(req *AddUserFaceRequest) error {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(addUserFaceURL, accessToken), req); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithCommonError(response, "AddUserFace")
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddOptionRequest 创建打卡规则请求
|
|
||||||
type AddOptionRequest struct {
|
|
||||||
EffectiveNow bool `json:"effective_now,omitempty"`
|
|
||||||
Group OptionGroupRule `json:"group,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupRule 打卡规则字段
|
|
||||||
type OptionGroupRule struct {
|
|
||||||
GroupID int64 `json:"groupid,omitempty"`
|
|
||||||
GroupType int64 `json:"grouptype"`
|
|
||||||
GroupName string `json:"groupname"`
|
|
||||||
CheckinDate []OptionGroupRuleCheckinDate `json:"checkindate,omitempty"`
|
|
||||||
SpeWorkdays []OptionGroupSpeWorkdays `json:"spe_workdays,omitempty"`
|
|
||||||
SpeOffDays []OptionGroupSpeOffDays `json:"spe_offdays,omitempty"`
|
|
||||||
SyncHolidays bool `json:"sync_holidays,omitempty"`
|
|
||||||
NeedPhoto bool `json:"need_photo,omitempty"`
|
|
||||||
NoteCanUseLocalPic bool `json:"note_can_use_local_pic,omitempty"`
|
|
||||||
WifiMacInfos []OptionGroupWifiMacInfos `json:"wifimac_infos,omitempty"`
|
|
||||||
LocInfos []OptionGroupLocInfos `json:"loc_infos,omitempty"`
|
|
||||||
AllowCheckinOffWorkday bool `json:"allow_checkin_offworkday,omitempty"`
|
|
||||||
AllowApplyOffWorkday bool `json:"allow_apply_offworkday,omitempty"`
|
|
||||||
Range []OptionGroupRange `json:"range"`
|
|
||||||
WhiteUsers []string `json:"white_users,omitempty"`
|
|
||||||
Type int64 `json:"type,omitempty"`
|
|
||||||
ReporterInfo OptionGroupReporterInfo `json:"reporterinfo,omitempty"`
|
|
||||||
AllowApplyBkCnt int64 `json:"allow_apply_bk_cnt,omitempty"`
|
|
||||||
AllowApplyBkDayLimit int64 `json:"allow_apply_bk_day_limit,omitempty"`
|
|
||||||
BukaLimitNextMonth int64 `json:"buka_limit_next_month,omitempty"`
|
|
||||||
OptionOutRange int64 `json:"option_out_range,omitempty"`
|
|
||||||
ScheduleList []OptionGroupScheduleList `json:"schedulelist,omitempty"`
|
|
||||||
OffWorkIntervalTime int64 `json:"offwork_interval_time,omitempty"`
|
|
||||||
UseFaceDetect bool `json:"use_face_detect,omitempty"`
|
|
||||||
OpenFaceLiveDetect bool `json:"open_face_live_detect,omitempty"`
|
|
||||||
OtInfoV2 OptionGroupOtInfoV2 `json:"ot_info_v2,omitempty"`
|
|
||||||
SyncOutCheckin bool `json:"sync_out_checkin,omitempty"`
|
|
||||||
BukaRemind OptionGroupBukaRemind `json:"buka_remind,omitempty"`
|
|
||||||
BukaRestriction int64 `json:"buka_restriction,omitempty"`
|
|
||||||
CheckinMethodType int64 `json:"checkin_method_type,omitempty"`
|
|
||||||
SpanDayTime int64 `json:"span_day_time,omitempty"`
|
|
||||||
StandardWorkDuration int64 `json:"standard_work_duration,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupRuleCheckinDate 固定时间上下班打卡时间
|
|
||||||
type OptionGroupRuleCheckinDate struct {
|
|
||||||
Workdays []int64 `json:"workdays"`
|
|
||||||
CheckinTime []OptionGroupRuleCheckinTime `json:"checkintime"`
|
|
||||||
FlexTime int64 `json:"flex_time"`
|
|
||||||
AllowFlex bool `json:"allow_flex"`
|
|
||||||
FlexOnDutyTime int64 `json:"flex_on_duty_time"`
|
|
||||||
FlexOffDutyTime int64 `json:"flex_off_duty_time"`
|
|
||||||
MaxAllowArriveEarly int64 `json:"max_allow_arrive_early"`
|
|
||||||
MaxAllowArriveLate int64 `json:"max_allow_arrive_late"`
|
|
||||||
LateRule OptionGroupLateRule `json:"late_rule"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupRuleCheckinTime 工作日上下班打卡时间信息
|
|
||||||
type OptionGroupRuleCheckinTime struct {
|
|
||||||
TimeID int64 `json:"time_id"`
|
|
||||||
WorkSec int64 `json:"work_sec"`
|
|
||||||
OffWorkSec int64 `json:"off_work_sec"`
|
|
||||||
RemindWorkSec int64 `json:"remind_work_sec"`
|
|
||||||
RemindOffWorkSec int64 `json:"remind_off_work_sec"`
|
|
||||||
AllowRest bool `json:"allow_rest"`
|
|
||||||
RestBeginTime int64 `json:"rest_begin_time"`
|
|
||||||
RestEndTime int64 `json:"rest_end_time"`
|
|
||||||
EarliestWorkSec int64 `json:"earliest_work_sec"`
|
|
||||||
LatestWorkSec int64 `json:"latest_work_sec"`
|
|
||||||
EarliestOffWorkSec int64 `json:"earliest_off_work_sec"`
|
|
||||||
LatestOffWorkSec int64 `json:"latest_off_work_sec"`
|
|
||||||
NoNeedCheckOn bool `json:"no_need_checkon"`
|
|
||||||
NoNeedCheckOff bool `json:"no_need_checkoff"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupLateRule 晚走晚到时间规则信息
|
|
||||||
type OptionGroupLateRule struct {
|
|
||||||
OffWorkAfterTime int64 `json:"offwork_after_time"`
|
|
||||||
OnWorkFlexTime int64 `json:"onwork_flex_time"`
|
|
||||||
AllowOffWorkAfterTime int64 `json:"allow_offwork_after_time"`
|
|
||||||
TimeRules []OptionGroupTimeRule `json:"timerules"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupTimeRule 晚走晚到时间规则
|
|
||||||
type OptionGroupTimeRule struct {
|
|
||||||
OffWorkAfterTime int64 `json:"offwork_after_time"`
|
|
||||||
OnWorkFlexTime int64 `json:"onwork_flex_time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupSpeWorkdays 特殊工作日
|
|
||||||
type OptionGroupSpeWorkdays struct {
|
|
||||||
Timestamp int64 `json:"timestamp"`
|
|
||||||
Notes string `json:"notes"`
|
|
||||||
CheckinTime []OptionGroupCheckinTime `json:"checkintime"`
|
|
||||||
Type int64 `json:"type"`
|
|
||||||
BegTime int64 `json:"begtime"`
|
|
||||||
EndTime int64 `json:"endtime"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupCheckinTime 特殊工作日的上下班打卡时间配置
|
|
||||||
type OptionGroupCheckinTime struct {
|
|
||||||
TimeID int64 `json:"time_id"`
|
|
||||||
WorkSec int64 `json:"work_sec"`
|
|
||||||
OffWorkSec int64 `json:"off_work_sec"`
|
|
||||||
RemindWorkSec int64 `json:"remind_work_sec"`
|
|
||||||
RemindOffWorkSec int64 `json:"remind_off_work_sec"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupSpeOffDays 特殊非工作日
|
|
||||||
type OptionGroupSpeOffDays struct {
|
|
||||||
Timestamp int64 `json:"timestamp"`
|
|
||||||
Notes string `json:"notes"`
|
|
||||||
Type int64 `json:"type"`
|
|
||||||
BegTime int64 `json:"begtime"`
|
|
||||||
EndTime int64 `json:"endtime"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupWifiMacInfos WIFI信息
|
|
||||||
type OptionGroupWifiMacInfos struct {
|
|
||||||
WifiName string `json:"wifiname"`
|
|
||||||
WifiMac string `json:"wifimac"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupLocInfos 地点信息
|
|
||||||
type OptionGroupLocInfos struct {
|
|
||||||
Lat int64 `json:"lat"`
|
|
||||||
Lng int64 `json:"lng"`
|
|
||||||
LocTitle string `json:"loc_title"`
|
|
||||||
LocDetail string `json:"loc_detail"`
|
|
||||||
Distance int64 `json:"distance"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupRange 人员信息
|
|
||||||
type OptionGroupRange struct {
|
|
||||||
PartyID []string `json:"party_id"`
|
|
||||||
UserID []string `json:"userid"`
|
|
||||||
TagID []int64 `json:"tagid"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupReporterInfo 汇报人
|
|
||||||
type OptionGroupReporterInfo struct {
|
|
||||||
Reporters []OptionGroupReporters `json:"reporters"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupReporters 汇报对象
|
|
||||||
type OptionGroupReporters struct {
|
|
||||||
UserID string `json:"userid"`
|
|
||||||
TagID int64 `json:"tagid"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupScheduleList 自定义排班规则所有排班
|
|
||||||
type OptionGroupScheduleList struct {
|
|
||||||
ScheduleID int64 `json:"schedule_id"`
|
|
||||||
ScheduleName string `json:"schedule_name"`
|
|
||||||
TimeSection []OptionGroupTimeSection `json:"time_section"`
|
|
||||||
AllowFlex bool `json:"allow_flex"`
|
|
||||||
FlexOnDutyTime int64 `json:"flex_on_duty_time"`
|
|
||||||
FlexOffDutyTime int64 `json:"flex_off_duty_time"`
|
|
||||||
LateRule OptionGroupLateRule `json:"late_rule"`
|
|
||||||
MaxAllowArriveEarly int64 `json:"max_allow_arrive_early"`
|
|
||||||
MaxAllowArriveLate int64 `json:"max_allow_arrive_late"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupTimeSection 班次上下班时段信息
|
|
||||||
type OptionGroupTimeSection struct {
|
|
||||||
TimeID int64 `json:"time_id"`
|
|
||||||
WorkSec int64 `json:"work_sec"`
|
|
||||||
OffWorkSec int64 `json:"off_work_sec"`
|
|
||||||
RemindWorkSec int64 `json:"remind_work_sec"`
|
|
||||||
RemindOffWorkSec int64 `json:"remind_off_work_sec"`
|
|
||||||
RestBeginTime int64 `json:"rest_begin_time"`
|
|
||||||
RestEndTime int64 `json:"rest_end_time"`
|
|
||||||
AllowRest bool `json:"allow_rest"`
|
|
||||||
EarliestWorkSec int64 `json:"earliest_work_sec"`
|
|
||||||
LatestWorkSec int64 `json:"latest_work_sec"`
|
|
||||||
EarliestOffWorkSec int64 `json:"earliest_off_work_sec"`
|
|
||||||
LatestOffWorkSec int64 `json:"latest_off_work_sec"`
|
|
||||||
NoNeedCheckOn bool `json:"no_need_checkon"`
|
|
||||||
NoNeedCheckOff bool `json:"no_need_checkoff"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupOtInfoV2 加班配置
|
|
||||||
type OptionGroupOtInfoV2 struct {
|
|
||||||
WorkdayConf OptionGroupWorkdayConf `json:"workdayconf"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupWorkdayConf 工作日加班配置
|
|
||||||
type OptionGroupWorkdayConf struct {
|
|
||||||
AllowOt bool `json:"allow_ot"`
|
|
||||||
Type int64 `json:"type"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroupBukaRemind 补卡提醒
|
|
||||||
type OptionGroupBukaRemind struct {
|
|
||||||
OpenRemind bool `json:"open_remind"`
|
|
||||||
BukaRemindDay int64 `json:"buka_remind_day"`
|
|
||||||
BukaRemindMonth int64 `json:"buka_remind_month"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddOption 创建打卡规则
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/98041#%E5%88%9B%E5%BB%BA%E6%89%93%E5%8D%A1%E8%A7%84%E5%88%99
|
|
||||||
func (r *Client) AddOption(req *AddOptionRequest) error {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(addOptionURL, accessToken), req); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithCommonError(response, "AddOption")
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateOptionRequest 修改打卡规则请求
|
|
||||||
type UpdateOptionRequest struct {
|
|
||||||
EffectiveNow bool `json:"effective_now,omitempty"`
|
|
||||||
Group OptionGroupRule `json:"group,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateOption 修改打卡规则
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/98041#%E4%BF%AE%E6%94%B9%E6%89%93%E5%8D%A1%E8%A7%84%E5%88%99
|
|
||||||
func (r *Client) UpdateOption(req *UpdateOptionRequest) error {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(updateOptionURL, accessToken), req); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithCommonError(response, "UpdateOption")
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClearOptionRequest 清空打卡规则数组元素请求
|
|
||||||
type ClearOptionRequest struct {
|
|
||||||
GroupID int64 `json:"groupid"`
|
|
||||||
ClearField []int64 `json:"clear_field"`
|
|
||||||
EffectiveNow bool `json:"effective_now"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClearOption 清空打卡规则数组元素
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/98041#%E6%B8%85%E7%A9%BA%E6%89%93%E5%8D%A1%E8%A7%84%E5%88%99%E6%95%B0%E7%BB%84%E5%85%83%E7%B4%A0
|
|
||||||
func (r *Client) ClearOption(req *ClearOptionRequest) error {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(clearOptionURL, accessToken), req); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithCommonError(response, "ClearOption")
|
|
||||||
}
|
|
||||||
|
|
||||||
// DelOptionRequest 删除打卡规则请求
|
|
||||||
type DelOptionRequest struct {
|
|
||||||
GroupID int64 `json:"groupid"`
|
|
||||||
EffectiveNow bool `json:"effective_now"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// DelOption 删除打卡规则
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/98041#%E5%88%A0%E9%99%A4%E6%89%93%E5%8D%A1%E8%A7%84%E5%88%99
|
|
||||||
func (r *Client) DelOption(req *DelOptionRequest) error {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(delOptionURL, accessToken), req); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithCommonError(response, "DelOption")
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddRecordRequest 添加打卡记录请求
|
|
||||||
type AddRecordRequest struct {
|
|
||||||
Records []Record `json:"records"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Record 打卡记录
|
|
||||||
type Record struct {
|
|
||||||
UserID string `json:"userid"`
|
|
||||||
CheckinTime int64 `json:"checkin_time"`
|
|
||||||
LocationTitle string `json:"location_title"`
|
|
||||||
LocationDetail string `json:"location_detail"`
|
|
||||||
MediaIDS []string `json:"mediaids"`
|
|
||||||
Notes string `json:"notes"`
|
|
||||||
DeviceType int `json:"device_type"`
|
|
||||||
Lat int64 `json:"lat"`
|
|
||||||
Lng int64 `json:"lng"`
|
|
||||||
DeviceDetail string `json:"device_detail"`
|
|
||||||
WifiName string `json:"wifiname"`
|
|
||||||
WifiMac string `json:"wifimac"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddRecord 添加打卡记录
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/99647
|
|
||||||
func (r *Client) AddRecord(req *AddRecordRequest) error {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(addRecordURL, accessToken), req); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return util.DecodeWithCommonError(response, "AddRecord")
|
|
||||||
}
|
|
||||||
@@ -13,14 +13,6 @@ const (
|
|||||||
getDayDataURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckin_daydata?access_token=%s"
|
getDayDataURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckin_daydata?access_token=%s"
|
||||||
// getMonthDataURL 获取打卡月报数据
|
// getMonthDataURL 获取打卡月报数据
|
||||||
getMonthDataURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckin_monthdata?access_token=%s"
|
getMonthDataURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckin_monthdata?access_token=%s"
|
||||||
// getCorpOptionURL 获取企业所有打卡规则
|
|
||||||
getCorpOptionURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcorpcheckinoption?access_token=%s"
|
|
||||||
// getOptionURL 获取员工打卡规则
|
|
||||||
getOptionURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckinoption?access_token=%s"
|
|
||||||
// getScheduleListURL 获取打卡人员排班信息
|
|
||||||
getScheduleListURL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckinschedulist?access_token=%s"
|
|
||||||
// getHardwareDataURL获取设备打卡数据
|
|
||||||
getHardwareDataURL = "https://qyapi.weixin.qq.com/cgi-bin/hardware/get_hardware_checkin_data?access_token=%s"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type (
|
type (
|
||||||
@@ -173,15 +165,9 @@ type (
|
|||||||
|
|
||||||
// OtInfo 加班信息
|
// OtInfo 加班信息
|
||||||
OtInfo struct {
|
OtInfo struct {
|
||||||
OtStatus int64 `json:"ot_status"`
|
OtStatus int64 `json:"ot_status"`
|
||||||
OtDuration int64 `json:"ot_duration"`
|
OtDuration int64 `json:"ot_duration"`
|
||||||
ExceptionDuration []uint64 `json:"exception_duration"`
|
ExceptionDuration []uint64 `json:"exception_duration"`
|
||||||
WorkdayOverAsVacation int64 `json:"workday_over_as_vacation"`
|
|
||||||
WorkdayOverAsMoney int64 `json:"workday_over_as_money"`
|
|
||||||
RestdayOverAsVacation int64 `json:"restday_over_as_vacation"`
|
|
||||||
RestdayOverAsMoney int64 `json:"restday_over_as_money"`
|
|
||||||
HolidayOverAsVacation int64 `json:"holiday_over_as_vacation"`
|
|
||||||
HolidayOverAsMoney int64 `json:"holiday_over_as_money"`
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -243,20 +229,13 @@ type (
|
|||||||
RegularDays int64 `json:"regular_days"`
|
RegularDays int64 `json:"regular_days"`
|
||||||
RegularWorkSec int64 `json:"regular_work_sec"`
|
RegularWorkSec int64 `json:"regular_work_sec"`
|
||||||
StandardWorkSec int64 `json:"standard_work_sec"`
|
StandardWorkSec int64 `json:"standard_work_sec"`
|
||||||
RestDays int64 `json:"rest_days"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// OverWorkInfo 加班情况
|
// OverWorkInfo 加班情况
|
||||||
OverWorkInfo struct {
|
OverWorkInfo struct {
|
||||||
WorkdayOverSec int64 `json:"workday_over_sec"`
|
WorkdayOverSec int64 `json:"workday_over_sec"`
|
||||||
HolidayOverSec int64 `json:"holidays_over_sec"`
|
HolidayOverSec int64 `json:"holidays_over_sec"`
|
||||||
RestDayOverSec int64 `json:"restdays_over_sec"`
|
RestDayOverSec int64 `json:"restdays_over_sec"`
|
||||||
WorkdaysOverAsVacation int64 `json:"workdays_over_as_vacation"`
|
|
||||||
WorkdaysOverAsMoney int64 `json:"workdays_over_as_money"`
|
|
||||||
RestdaysOverAsVacation int64 `json:"restdays_over_as_vacation"`
|
|
||||||
RestdaysOverAsMoney int64 `json:"restdays_over_as_money"`
|
|
||||||
HolidaysOverAsVacation int64 `json:"holidays_over_as_vacation"`
|
|
||||||
HolidaysOverAsMoney int64 `json:"holidays_over_as_money"`
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -278,405 +257,3 @@ func (r *Client) GetMonthData(req *GetCheckinDataRequest) (result *GetMonthDataR
|
|||||||
err = util.DecodeWithError(response, result, "GetMonthData")
|
err = util.DecodeWithError(response, result, "GetMonthData")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetCorpOptionResponse 获取企业所有打卡规则响应
|
|
||||||
type GetCorpOptionResponse struct {
|
|
||||||
util.CommonError
|
|
||||||
Group []CorpOptionGroup `json:"group"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// CorpOptionGroup 企业规则信息列表
|
|
||||||
type CorpOptionGroup struct {
|
|
||||||
GroupType int64 `json:"grouptype"`
|
|
||||||
GroupID int64 `json:"groupid"`
|
|
||||||
GroupName string `json:"groupname"`
|
|
||||||
CheckinDate []GroupCheckinDate `json:"checkindate"`
|
|
||||||
SpeWorkdays []SpeWorkdays `json:"spe_workdays"`
|
|
||||||
SpeOffDays []SpeOffDays `json:"spe_offdays"`
|
|
||||||
SyncHolidays bool `json:"sync_holidays"`
|
|
||||||
NeedPhoto bool `json:"need_photo"`
|
|
||||||
NoteCanUseLocalPic bool `json:"note_can_use_local_pic"`
|
|
||||||
AllowCheckinOffWorkday bool `json:"allow_checkin_offworkday"`
|
|
||||||
AllowApplyOffWorkday bool `json:"allow_apply_offworkday"`
|
|
||||||
WifiMacInfos []WifiMacInfos `json:"wifimac_infos"`
|
|
||||||
LocInfos []LocInfos `json:"loc_infos"`
|
|
||||||
Range []Range `json:"range"`
|
|
||||||
CreateTime int64 `json:"create_time"`
|
|
||||||
WhiteUsers []string `json:"white_users"`
|
|
||||||
Type int64 `json:"type"`
|
|
||||||
ReporterInfo ReporterInfo `json:"reporterinfo"`
|
|
||||||
OtInfo GroupOtInfo `json:"ot_info"`
|
|
||||||
OtApplyInfo OtApplyInfo `json:"otapplyinfo"`
|
|
||||||
Uptime int64 `json:"uptime"`
|
|
||||||
AllowApplyBkCnt int64 `json:"allow_apply_bk_cnt"`
|
|
||||||
OptionOutRange int64 `json:"option_out_range"`
|
|
||||||
CreateUserID string `json:"create_userid"`
|
|
||||||
UseFaceDetect bool `json:"use_face_detect"`
|
|
||||||
AllowApplyBkDayLimit int64 `json:"allow_apply_bk_day_limit"`
|
|
||||||
UpdateUserID string `json:"update_userid"`
|
|
||||||
BukaRestriction int64 `json:"buka_restriction"`
|
|
||||||
ScheduleList []ScheduleList `json:"schedulelist"`
|
|
||||||
OffWorkIntervalTime int64 `json:"offwork_interval_time"`
|
|
||||||
SpanDayTime int64 `json:"span_day_time"`
|
|
||||||
StandardWorkDuration int64 `json:"standard_work_duration"`
|
|
||||||
OpenSpCheckin bool `json:"open_sp_checkin"`
|
|
||||||
CheckinMethodType int64 `json:"checkin_method_type"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GroupCheckinDate 打卡时间,当规则类型为排班时没有意义
|
|
||||||
type GroupCheckinDate struct {
|
|
||||||
Workdays []int64 `json:"workdays"`
|
|
||||||
CheckinTime []GroupCheckinTime `json:"checkintime"`
|
|
||||||
NoNeedOffWork bool `json:"noneed_offwork"`
|
|
||||||
LimitAheadTime int64 `json:"limit_aheadtime"`
|
|
||||||
FlexOnDutyTime int64 `json:"flex_on_duty_time"`
|
|
||||||
FlexOffDutyTime int64 `json:"flex_off_duty_time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GroupCheckinTime 工作日上下班打卡时间信息
|
|
||||||
type GroupCheckinTime struct {
|
|
||||||
WorkSec int64 `json:"work_sec"`
|
|
||||||
OffWorkSec int64 `json:"off_work_sec"`
|
|
||||||
RemindWorkSec int64 `json:"remind_work_sec"`
|
|
||||||
RemindOffWorkSec int64 `json:"remind_off_work_sec"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SpeWorkdays 特殊日期-必须打卡日期信息
|
|
||||||
type SpeWorkdays struct {
|
|
||||||
Timestamp int64 `json:"timestamp"`
|
|
||||||
Notes string `json:"notes"`
|
|
||||||
CheckinTime []GroupCheckinTime `json:"checkintime"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SpeOffDays 特殊日期-不用打卡日期信息
|
|
||||||
type SpeOffDays struct {
|
|
||||||
Timestamp int64 `json:"timestamp"`
|
|
||||||
Notes string `json:"notes"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// WifiMacInfos 打卡地点-WiFi打卡信息
|
|
||||||
type WifiMacInfos struct {
|
|
||||||
WifiName string `json:"wifiname"`
|
|
||||||
WifiMac string `json:"wifimac"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// LocInfos 打卡地点-位置打卡信息
|
|
||||||
type LocInfos struct {
|
|
||||||
Lat int64 `json:"lat"`
|
|
||||||
Lng int64 `json:"lng"`
|
|
||||||
LocTitle string `json:"loc_title"`
|
|
||||||
LocDetail string `json:"loc_detail"`
|
|
||||||
Distance int64 `json:"distance"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Range 打卡人员信息
|
|
||||||
type Range struct {
|
|
||||||
PartyID []string `json:"partyid"`
|
|
||||||
UserID []string `json:"userid"`
|
|
||||||
TagID []int64 `json:"tagid"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ReporterInfo 汇报对象信息
|
|
||||||
type ReporterInfo struct {
|
|
||||||
Reporters []Reporters `json:"reporters"`
|
|
||||||
UpdateTime int64 `json:"updatetime"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reporters 汇报对象,每个汇报人用userid表示
|
|
||||||
type Reporters struct {
|
|
||||||
UserID string `json:"userid"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GroupOtInfo 加班信息
|
|
||||||
type GroupOtInfo struct {
|
|
||||||
Type int64 `json:"type"`
|
|
||||||
AllowOtWorkingDay bool `json:"allow_ot_workingday"`
|
|
||||||
AllowOtNonWorkingDay bool `json:"allow_ot_nonworkingday"`
|
|
||||||
OtCheckInfo OtCheckInfo `json:"otcheckinfo"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OtCheckInfo 以打卡时间为准-加班时长计算规则信息
|
|
||||||
type OtCheckInfo struct {
|
|
||||||
OtWorkingDayTimeStart int64 `json:"ot_workingday_time_start"`
|
|
||||||
OtWorkingDayTimeMin int64 `json:"ot_workingday_time_min"`
|
|
||||||
OtWorkingDayTimeMax int64 `json:"ot_workingday_time_max"`
|
|
||||||
OtNonworkingDayTimeMin int64 `json:"ot_nonworkingday_time_min"`
|
|
||||||
OtNonworkingDayTimeMax int64 `json:"ot_nonworkingday_time_max"`
|
|
||||||
OtNonworkingDaySpanDayTime int64 `json:"ot_nonworkingday_spanday_time"`
|
|
||||||
OtWorkingDayRestInfo OtRestInfo `json:"ot_workingday_restinfo"`
|
|
||||||
OtNonWorkingDayRestInfo OtRestInfo `json:"ot_nonworkingday_restinfo"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OtRestInfo 加班-休息扣除配置信息
|
|
||||||
type OtRestInfo struct {
|
|
||||||
Type int64 `json:"type"`
|
|
||||||
FixTimeRule FixTimeRule `json:"fix_time_rule"`
|
|
||||||
CalOtTimeRule CalOtTimeRule `json:"cal_ottime_rule"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// FixTimeRule 工作日加班-指定休息时间配置信息
|
|
||||||
type FixTimeRule struct {
|
|
||||||
FixTimeBeginSec int64 `json:"fix_time_begin_sec"`
|
|
||||||
FixTimeEndSec int64 `json:"fix_time_end_sec"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// CalOtTimeRule 工作日加班-按加班时长扣除配置信息
|
|
||||||
type CalOtTimeRule struct {
|
|
||||||
Items []CalOtTimeRuleItem `json:"items"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// CalOtTimeRuleItem 工作日加班-按加班时长扣除条件信息
|
|
||||||
type CalOtTimeRuleItem struct {
|
|
||||||
OtTime int64 `json:"ot_time"`
|
|
||||||
RestTime int64 `json:"rest_time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OtApplyInfo 以加班申请核算打卡记录相关信息
|
|
||||||
type OtApplyInfo struct {
|
|
||||||
AllowOtWorkingDay bool `json:"allow_ot_workingday"`
|
|
||||||
AllowOtNonWorkingDay bool `json:"allow_ot_nonworkingday"`
|
|
||||||
Uiptime int64 `json:"uptime"`
|
|
||||||
OtNonworkingDaySpanDayTime int64 `json:"ot_nonworkingday_spanday_time"`
|
|
||||||
OtWorkingDayRestInfo OtRestInfo `json:"ot_workingday_restinfo"`
|
|
||||||
OtNonWorkingDayRestInfo OtRestInfo `json:"ot_nonworkingday_restinfo"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ScheduleList 排班信息列表
|
|
||||||
type ScheduleList struct {
|
|
||||||
ScheduleID int64 `json:"schedule_id"`
|
|
||||||
ScheduleName string `json:"schedule_name"`
|
|
||||||
TimeSection []TimeSection `json:"time_section"`
|
|
||||||
LimitAheadTime int64 `json:"limit_aheadtime"`
|
|
||||||
NoNeedOffWork bool `json:"noneed_offwork"`
|
|
||||||
LimitOffTime int64 `json:"limit_offtime"`
|
|
||||||
FlexOnDutyTime int64 `json:"flex_on_duty_time"`
|
|
||||||
FlexOffDutyTime int64 `json:"flex_off_duty_time"`
|
|
||||||
AllowFlex bool `json:"allow_flex"`
|
|
||||||
LateRule LateRule `json:"late_rule"`
|
|
||||||
MaxAllowArriveEarly int64 `json:"max_allow_arrive_early"`
|
|
||||||
MaxAllowArriveLate int64 `json:"max_allow_arrive_late"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// TimeSection 班次上下班时段信息
|
|
||||||
type TimeSection struct {
|
|
||||||
TimeID int64 `json:"time_id"`
|
|
||||||
WorkSec int64 `json:"work_sec"`
|
|
||||||
OffWorkSec int64 `json:"off_work_sec"`
|
|
||||||
RemindWorkSec int64 `json:"remind_work_sec"`
|
|
||||||
RemindOffWorkSec int64 `json:"remind_off_work_sec"`
|
|
||||||
RestBeginTime int64 `json:"rest_begin_time"`
|
|
||||||
RestEndTime int64 `json:"rest_end_time"`
|
|
||||||
AllowRest bool `json:"allow_rest"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// LateRule 晚走晚到时间规则信息
|
|
||||||
type LateRule struct {
|
|
||||||
AllowOffWorkAfterTime bool `json:"allow_offwork_after_time"`
|
|
||||||
TimeRules []TimeRule `json:"timerules"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// TimeRule 迟到规则时间
|
|
||||||
type TimeRule struct {
|
|
||||||
OffWorkAfterTime int64 `json:"offwork_after_time"`
|
|
||||||
OnWorkFlexTime int64 `json:"onwork_flex_time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetCorpOption 获取企业所有打卡规则
|
|
||||||
// @see https://developer.work.weixin.qq.com/document/path/93384
|
|
||||||
func (r *Client) GetCorpOption() (*GetCorpOptionResponse, error) {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.HTTPPost(fmt.Sprintf(getCorpOptionURL, accessToken), ""); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result := &GetCorpOptionResponse{}
|
|
||||||
err = util.DecodeWithError(response, result, "GetCorpOption")
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetOptionRequest 获取员工打卡规则请求
|
|
||||||
type GetOptionRequest struct {
|
|
||||||
Datetime int64 `json:"datetime"`
|
|
||||||
UserIDList []string `json:"useridlist"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetOptionResponse 获取员工打卡规则响应
|
|
||||||
type GetOptionResponse struct {
|
|
||||||
util.CommonError
|
|
||||||
Info []OptionInfo `json:"info"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionInfo 打卡规则列表
|
|
||||||
type OptionInfo struct {
|
|
||||||
UserID string `json:"userid"`
|
|
||||||
Group OptionGroup `json:"group"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionGroup 打卡规则相关信息
|
|
||||||
type OptionGroup struct {
|
|
||||||
GroupType int64 `json:"grouptype"`
|
|
||||||
GroupID int64 `json:"groupid"`
|
|
||||||
OpenSpCheckin bool `json:"open_sp_checkin"`
|
|
||||||
GroupName string `json:"groupname"`
|
|
||||||
CheckinDate []OptionCheckinDate `json:"checkindate"`
|
|
||||||
SpeWorkdays []SpeWorkdays `json:"spe_workdays"`
|
|
||||||
SpeOffDays []SpeOffDays `json:"spe_offdays"`
|
|
||||||
SyncHolidays bool `json:"sync_holidays"`
|
|
||||||
NeedPhoto bool `json:"need_photo"`
|
|
||||||
WifiMacInfos []WifiMacInfos `json:"wifimac_infos"`
|
|
||||||
NoteCanUseLocalPic bool `json:"note_can_use_local_pic"`
|
|
||||||
AllowCheckinOffWorkday bool `json:"allow_checkin_offworkday"`
|
|
||||||
AllowApplyOffWorkday bool `json:"allow_apply_offworkday"`
|
|
||||||
LocInfos []LocInfos `json:"loc_infos"`
|
|
||||||
ScheduleList []ScheduleList `json:"schedulelist"`
|
|
||||||
BukaRestriction int64 `json:"buka_restriction"`
|
|
||||||
SpanDayTime int64 `json:"span_day_time"`
|
|
||||||
StandardWorkDuration int64 `json:"standard_work_duration"`
|
|
||||||
OffWorkIntervalTime int64 `json:"offwork_interval_time"`
|
|
||||||
CheckinMethodType int64 `json:"checkin_method_type"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// OptionCheckinDate 打卡时间配置
|
|
||||||
type OptionCheckinDate struct {
|
|
||||||
Workdays []int64 `json:"workdays"`
|
|
||||||
CheckinTime []GroupCheckinTime `json:"checkintime"`
|
|
||||||
FlexTime int64 `json:"flex_time"`
|
|
||||||
NoNeedOffWork bool `json:"noneed_offwork"`
|
|
||||||
LimitAheadTime int64 `json:"limit_aheadtime"`
|
|
||||||
FlexOnDutyTime int64 `json:"flex_on_duty_time"`
|
|
||||||
FlexOffDutyTime int64 `json:"flex_off_duty_time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetOption 获取员工打卡规则
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/90263
|
|
||||||
func (r *Client) GetOption(req *GetOptionRequest) (*GetOptionResponse, error) {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(getOptionURL, accessToken), req); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result := &GetOptionResponse{}
|
|
||||||
err = util.DecodeWithError(response, result, "GetOption")
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetScheduleListRequest 获取打卡人员排班信息请求
|
|
||||||
type GetScheduleListRequest struct {
|
|
||||||
StartTime int64 `json:"starttime"`
|
|
||||||
EndTime int64 `json:"endtime"`
|
|
||||||
UserIDList []string `json:"useridlist"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetScheduleListResponse 获取打卡人员排班信息响应
|
|
||||||
type GetScheduleListResponse struct {
|
|
||||||
util.CommonError
|
|
||||||
ScheduleList []ScheduleItem `json:"schedule_list"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ScheduleItem 排班表信息
|
|
||||||
type ScheduleItem struct {
|
|
||||||
UserID string `json:"userid"`
|
|
||||||
YearMonth int64 `json:"yearmonth"`
|
|
||||||
GroupID int64 `json:"groupid"`
|
|
||||||
GroupName string `json:"groupname"`
|
|
||||||
Schedule Schedule `json:"schedule"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Schedule 个人排班信息
|
|
||||||
type Schedule struct {
|
|
||||||
ScheduleList []ScheduleListItem `json:"scheduleList"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ScheduleListItem 个人排班表信息
|
|
||||||
type ScheduleListItem struct {
|
|
||||||
Day int64 `json:"day"`
|
|
||||||
ScheduleInfo ScheduleInfo `json:"schedule_info"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ScheduleInfo 个人当日排班信息
|
|
||||||
type ScheduleInfo struct {
|
|
||||||
ScheduleID int64 `json:"schedule_id"`
|
|
||||||
ScheduleName string `json:"schedule_name"`
|
|
||||||
TimeSection []ScheduleTimeSection `json:"time_section"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ScheduleTimeSection 班次上下班时段信息
|
|
||||||
type ScheduleTimeSection struct {
|
|
||||||
ID int64 `json:"id"`
|
|
||||||
WorkSec int64 `json:"work_sec"`
|
|
||||||
OffWorkSec int64 `json:"off_work_sec"`
|
|
||||||
RemindWorkSec int64 `json:"remind_work_sec"`
|
|
||||||
RemindOffWorkSec int64 `json:"remind_off_work_sec"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetScheduleList 获取打卡人员排班信息
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/93380
|
|
||||||
func (r *Client) GetScheduleList(req *GetScheduleListRequest) (*GetScheduleListResponse, error) {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(getScheduleListURL, accessToken), req); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result := &GetScheduleListResponse{}
|
|
||||||
err = util.DecodeWithError(response, result, "GetScheduleList")
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetHardwareDataRequest 获取设备打卡数据请求
|
|
||||||
type GetHardwareDataRequest struct {
|
|
||||||
FilterType int64 `json:"filter_type"`
|
|
||||||
StartTime int64 `json:"starttime"`
|
|
||||||
EndTime int64 `json:"endtime"`
|
|
||||||
UserIDList []string `json:"useridlist"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetHardwareDataResponse 获取设备打卡数据响应
|
|
||||||
type GetHardwareDataResponse struct {
|
|
||||||
util.CommonError
|
|
||||||
CheckinData []HardwareCheckinData `json:"checkindata"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// HardwareCheckinData 设备打卡数据
|
|
||||||
type HardwareCheckinData struct {
|
|
||||||
UserID string `json:"userid"`
|
|
||||||
CheckinTime int64 `json:"checkin_time"`
|
|
||||||
DeviceSn string `json:"device_sn"`
|
|
||||||
DeviceName string `json:"device_name"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetHardwareData 获取设备打卡数据
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/94126
|
|
||||||
func (r *Client) GetHardwareData(req *GetHardwareDataRequest) (*GetHardwareDataResponse, error) {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(getHardwareDataURL, accessToken), req); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result := &GetHardwareDataResponse{}
|
|
||||||
err = util.DecodeWithError(response, result, "GetHardwareData")
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -7,11 +7,12 @@ import (
|
|||||||
|
|
||||||
// Config for 企业微信
|
// Config for 企业微信
|
||||||
type Config struct {
|
type Config struct {
|
||||||
CorpID string `json:"corp_id"` // corp_id
|
CorpID string `json:"corp_id"` // corp_id
|
||||||
CorpSecret string `json:"corp_secret"` // corp_secret,如果需要获取会话存档实例,当前参数请填写聊天内容存档的Secret,可以在企业微信管理端--管理工具--聊天内容存档查看
|
CorpSecret string `json:"corp_secret"` // corp_secret,如果需要获取会话存档实例,当前参数请填写聊天内容存档的Secret,可以在企业微信管理端--管理工具--聊天内容存档查看
|
||||||
AgentID string `json:"agent_id"` // agent_id
|
AgentID string `json:"agent_id"` // agent_id
|
||||||
Cache cache.Cache
|
Cache cache.Cache
|
||||||
RasPrivateKey string // 消息加密私钥,可以在企业微信管理端--管理工具--消息加密公钥查看对用公钥,私钥一般由自己保存
|
RasPrivateKey string // 消息加密私钥,可以在企业微信管理端--管理工具--消息加密公钥查看对用公钥,私钥一般由自己保存
|
||||||
|
|
||||||
Token string `json:"token"` // 微信客服回调配置,用于生成签名校验回调请求的合法性
|
Token string `json:"token"` // 微信客服回调配置,用于生成签名校验回调请求的合法性
|
||||||
EncodingAESKey string `json:"encoding_aes_key"` // 微信客服回调p配置,用于解密回调消息内容对应的密文
|
EncodingAESKey string `json:"encoding_aes_key"` // 微信客服回调p配置,用于解密回调消息内容对应的密文
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,8 +23,6 @@ const (
|
|||||||
customerAcquisitionQuotaURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_acquisition_quota?access_token=%s"
|
customerAcquisitionQuotaURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_acquisition_quota?access_token=%s"
|
||||||
// customerAcquisitionStatistic 查询链接使用详情
|
// customerAcquisitionStatistic 查询链接使用详情
|
||||||
customerAcquisitionStatisticURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_acquisition/statistic?access_token=%s"
|
customerAcquisitionStatisticURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_acquisition/statistic?access_token=%s"
|
||||||
// customerAcquisitionGetChatInfo 获取成员多次收消息详情
|
|
||||||
customerAcquisitionGetChatInfoURL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/customer_acquisition/get_chat_info?access_token=%s"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type (
|
type (
|
||||||
@@ -310,42 +308,3 @@ func (r *Client) CustomerAcquisitionStatistic(req *CustomerAcquisitionStatisticR
|
|||||||
err = util.DecodeWithError(response, result, "CustomerAcquisitionStatistic")
|
err = util.DecodeWithError(response, result, "CustomerAcquisitionStatistic")
|
||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
|
|
||||||
type (
|
|
||||||
// GetChatInfoRequest 获取成员多次收消息详情请求
|
|
||||||
GetChatInfoRequest struct {
|
|
||||||
ChatKey string `json:"chat_key"`
|
|
||||||
}
|
|
||||||
// GetChatInfoResponse 获取成员多次收消息详情响应
|
|
||||||
GetChatInfoResponse struct {
|
|
||||||
util.CommonError
|
|
||||||
UserID string `json:"userid"`
|
|
||||||
ExternalUserID string `json:"external_userid"`
|
|
||||||
ChatInfo ChatInfo `json:"chat_info"`
|
|
||||||
}
|
|
||||||
// ChatInfo 聊天信息
|
|
||||||
ChatInfo struct {
|
|
||||||
RecvMsgCnt int64 `json:"recv_msg_cnt"` // 成员收到的此客户的消息次数
|
|
||||||
LinkID string `json:"link_id"` // 成员添加客户的获客链接id
|
|
||||||
State string `json:"state"` // 成员添加客户的state
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// GetChatInfo 获取成员多次收消息详情
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/100130
|
|
||||||
func (r *Client) GetChatInfo(req *GetChatInfoRequest) (*GetChatInfoResponse, error) {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(customerAcquisitionGetChatInfoURL, accessToken), req); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result := &GetChatInfoResponse{}
|
|
||||||
err = util.DecodeWithError(response, result, "GetChatInfo")
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -63,16 +63,16 @@ type ExternalUserDetailResponse struct {
|
|||||||
|
|
||||||
// ExternalUser 外部联系人
|
// ExternalUser 外部联系人
|
||||||
type ExternalUser struct {
|
type ExternalUser struct {
|
||||||
ExternalUserID string `json:"external_userid"`
|
ExternalUserID string `json:"external_userid"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Avatar string `json:"avatar"`
|
Avatar string `json:"avatar"`
|
||||||
Type int64 `json:"type"`
|
Type int64 `json:"type"`
|
||||||
Gender int64 `json:"gender"`
|
Gender int64 `json:"gender"`
|
||||||
UnionID string `json:"unionid"`
|
UnionID string `json:"unionid"`
|
||||||
Position string `json:"position"`
|
Position string `json:"position"`
|
||||||
CorpName string `json:"corp_name"`
|
CorpName string `json:"corp_name"`
|
||||||
CorpFullName string `json:"corp_full_name"`
|
CorpFullName string `json:"corp_full_name"`
|
||||||
ExternalProfile *ExternalProfile `json:"external_profile,omitempty"`
|
ExternalProfile string `json:"external_profile"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// FollowUser 跟进用户(指企业内部用户)
|
// FollowUser 跟进用户(指企业内部用户)
|
||||||
@@ -104,46 +104,6 @@ type WechatChannel struct {
|
|||||||
Source int `json:"source"`
|
Source int `json:"source"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExternalProfile 外部联系人的自定义展示信息,可以有多个字段和多种类型,包括文本,网页和小程序
|
|
||||||
type ExternalProfile struct {
|
|
||||||
ExternalCorpName string `json:"external_corp_name"`
|
|
||||||
WechatChannels WechatChannels `json:"wechat_channels"`
|
|
||||||
ExternalAttr []ExternalAttr `json:"external_attr"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// WechatChannels 视频号属性。须从企业绑定到企业微信的视频号中选择,可在“我的企业”页中查看绑定的视频号
|
|
||||||
type WechatChannels struct {
|
|
||||||
Nickname string `json:"nickname"`
|
|
||||||
Status int `json:"status"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExternalAttr 属性列表,目前支持文本、网页、小程序三种类型
|
|
||||||
type ExternalAttr struct {
|
|
||||||
Type int `json:"type"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Text *Text `json:"text,omitempty"`
|
|
||||||
Web *Web `json:"web,omitempty"`
|
|
||||||
MiniProgram *MiniProgram `json:"miniprogram,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Text 文本
|
|
||||||
type Text struct {
|
|
||||||
Value string `json:"value"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Web 网页
|
|
||||||
type Web struct {
|
|
||||||
URL string `json:"url"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// MiniProgram 小程序
|
|
||||||
type MiniProgram struct {
|
|
||||||
AppID string `json:"appid"`
|
|
||||||
Pagepath string `json:"pagepath"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetExternalUserDetail 获取外部联系人详情
|
// GetExternalUserDetail 获取外部联系人详情
|
||||||
// @see https://developer.work.weixin.qq.com/document/path/92114
|
// @see https://developer.work.weixin.qq.com/document/path/92114
|
||||||
func (r *Client) GetExternalUserDetail(externalUserID string, nextCursor ...string) (*ExternalUserDetailResponse, error) {
|
func (r *Client) GetExternalUserDetail(externalUserID string, nextCursor ...string) (*ExternalUserDetailResponse, error) {
|
||||||
|
|||||||
@@ -76,14 +76,13 @@ type (
|
|||||||
}
|
}
|
||||||
//GroupChat 客户群详情
|
//GroupChat 客户群详情
|
||||||
GroupChat struct {
|
GroupChat struct {
|
||||||
ChatID string `json:"chat_id"` //客户群ID
|
ChatID string `json:"chat_id"` //客户群ID
|
||||||
Name string `json:"name"` //群名
|
Name string `json:"name"` //群名
|
||||||
Owner string `json:"owner"` //群主ID
|
Owner string `json:"owner"` //群主ID
|
||||||
CreateTime int64 `json:"create_time"` //群的创建时间
|
CreateTime int64 `json:"create_time"` //群的创建时间
|
||||||
Notice string `json:"notice"` //群公告
|
Notice string `json:"notice"` //群公告
|
||||||
MemberList []GroupChatMember `json:"member_list"` //群成员列表
|
MemberList []GroupChatMember `json:"member_list"` //群成员列表
|
||||||
AdminList []GroupChatAdmin `json:"admin_list"` //群管理员列表
|
AdminList []GroupChatAdmin `json:"admin_list"` //群管理员列表
|
||||||
MemberVersion string `json:"member_version"` //当前群成员版本号。可以配合客户群变更事件减少主动调用本接口的次数
|
|
||||||
}
|
}
|
||||||
//GroupChatDetailResponse 客户群详情 返回值
|
//GroupChatDetailResponse 客户群详情 返回值
|
||||||
GroupChatDetailResponse struct {
|
GroupChatDetailResponse struct {
|
||||||
|
|||||||
@@ -287,14 +287,14 @@ func (r *Client) SendWelcomeMsg(req *SendWelcomeMsgRequest) error {
|
|||||||
|
|
||||||
// AddGroupWelcomeTemplateRequest 添加入群欢迎语素材请求
|
// AddGroupWelcomeTemplateRequest 添加入群欢迎语素材请求
|
||||||
type AddGroupWelcomeTemplateRequest struct {
|
type AddGroupWelcomeTemplateRequest struct {
|
||||||
Text MsgText `json:"text"`
|
Text MsgText `json:"text"`
|
||||||
Image *AttachmentImg `json:"image,omitempty"`
|
Image AttachmentImg `json:"image"`
|
||||||
Link *AttachmentLink `json:"link,omitempty"`
|
Link AttachmentLink `json:"link"`
|
||||||
MiniProgram *AttachmentMiniProgram `json:"miniprogram,omitempty"`
|
MiniProgram AttachmentMiniProgram `json:"miniprogram"`
|
||||||
File *AttachmentFile `json:"file,omitempty"`
|
File AttachmentFile `json:"file"`
|
||||||
Video *AttachmentVideo `json:"video,omitempty"`
|
Video AttachmentVideo `json:"video"`
|
||||||
AgentID int `json:"agentid,omitempty"`
|
AgentID int `json:"agentid"`
|
||||||
Notify int `json:"notify,omitempty"`
|
Notify int `json:"notify"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddGroupWelcomeTemplateResponse 添加入群欢迎语素材响应
|
// AddGroupWelcomeTemplateResponse 添加入群欢迎语素材响应
|
||||||
@@ -324,14 +324,14 @@ func (r *Client) AddGroupWelcomeTemplate(req *AddGroupWelcomeTemplateRequest) (*
|
|||||||
|
|
||||||
// EditGroupWelcomeTemplateRequest 编辑入群欢迎语素材请求
|
// EditGroupWelcomeTemplateRequest 编辑入群欢迎语素材请求
|
||||||
type EditGroupWelcomeTemplateRequest struct {
|
type EditGroupWelcomeTemplateRequest struct {
|
||||||
TemplateID string `json:"template_id"`
|
TemplateID string `json:"template_id"`
|
||||||
Text MsgText `json:"text"`
|
Text MsgText `json:"text"`
|
||||||
Image *AttachmentImg `json:"image"`
|
Image AttachmentImg `json:"image"`
|
||||||
Link *AttachmentLink `json:"link"`
|
Link AttachmentLink `json:"link"`
|
||||||
MiniProgram *AttachmentMiniProgram `json:"miniprogram"`
|
MiniProgram AttachmentMiniProgram `json:"miniprogram"`
|
||||||
File *AttachmentFile `json:"file"`
|
File AttachmentFile `json:"file"`
|
||||||
Video *AttachmentVideo `json:"video"`
|
Video AttachmentVideo `json:"video"`
|
||||||
AgentID int `json:"agentid"`
|
AgentID int `json:"agentid"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// EditGroupWelcomeTemplateResponse 编辑入群欢迎语素材响应
|
// EditGroupWelcomeTemplateResponse 编辑入群欢迎语素材响应
|
||||||
@@ -366,11 +366,11 @@ type GetGroupWelcomeTemplateRequest struct {
|
|||||||
type GetGroupWelcomeTemplateResponse struct {
|
type GetGroupWelcomeTemplateResponse struct {
|
||||||
util.CommonError
|
util.CommonError
|
||||||
Text MsgText `json:"text"`
|
Text MsgText `json:"text"`
|
||||||
Image AttachmentImg `json:"image,omitempty"`
|
Image AttachmentImg `json:"image"`
|
||||||
Link AttachmentLink `json:"link,omitempty"`
|
Link AttachmentLink `json:"link"`
|
||||||
MiniProgram AttachmentMiniProgram `json:"miniprogram,omitempty"`
|
MiniProgram AttachmentMiniProgram `json:"miniprogram"`
|
||||||
File AttachmentFile `json:"file,omitempty"`
|
File AttachmentFile `json:"file"`
|
||||||
Video AttachmentVideo `json:"video,omitempty"`
|
Video AttachmentVideo `json:"video"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetGroupWelcomeTemplate 获取入群欢迎语素材
|
// GetGroupWelcomeTemplate 获取入群欢迎语素材
|
||||||
|
|||||||
@@ -1,75 +0,0 @@
|
|||||||
package jsapi
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/credential"
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
|
||||||
"github.com/silenceper/wechat/v2/work/context"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Js struct
|
|
||||||
type Js struct {
|
|
||||||
*context.Context
|
|
||||||
jsTicket *credential.WorkJsTicket
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewJs init
|
|
||||||
func NewJs(context *context.Context) *Js {
|
|
||||||
js := new(Js)
|
|
||||||
js.Context = context
|
|
||||||
js.jsTicket = credential.NewWorkJsTicket(
|
|
||||||
context.Config.CorpID,
|
|
||||||
context.Config.AgentID,
|
|
||||||
credential.CacheKeyWorkPrefix,
|
|
||||||
context.Cache,
|
|
||||||
)
|
|
||||||
return js
|
|
||||||
}
|
|
||||||
|
|
||||||
// Config 返回给用户使用的配置
|
|
||||||
type Config struct {
|
|
||||||
Timestamp int64 `json:"timestamp"`
|
|
||||||
NonceStr string `json:"nonce_str"`
|
|
||||||
Signature string `json:"signature"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetConfig 获取企业微信JS配置 https://developer.work.weixin.qq.com/document/path/90514
|
|
||||||
func (js *Js) GetConfig(uri string) (config *Config, err error) {
|
|
||||||
config = new(Config)
|
|
||||||
var accessToken string
|
|
||||||
accessToken, err = js.GetAccessToken()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var ticketStr string
|
|
||||||
ticketStr, err = js.jsTicket.GetTicket(accessToken, credential.TicketTypeCorpJs)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
config.NonceStr = util.RandomStr(16)
|
|
||||||
config.Timestamp = util.GetCurrTS()
|
|
||||||
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s", ticketStr, config.NonceStr, config.Timestamp, uri)
|
|
||||||
config.Signature = util.Signature(str)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetAgentConfig 获取企业微信应用JS配置 https://developer.work.weixin.qq.com/document/path/94313
|
|
||||||
func (js *Js) GetAgentConfig(uri string) (config *Config, err error) {
|
|
||||||
config = new(Config)
|
|
||||||
var accessToken string
|
|
||||||
accessToken, err = js.GetAccessToken()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var ticketStr string
|
|
||||||
ticketStr, err = js.jsTicket.GetTicket(accessToken, credential.TicketTypeAgentJs)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
config.NonceStr = util.RandomStr(16)
|
|
||||||
config.Timestamp = util.GetCurrTS()
|
|
||||||
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s", ticketStr, config.NonceStr, config.Timestamp, uri)
|
|
||||||
config.Signature = util.Signature(str)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
@@ -33,7 +33,6 @@ type AccountAddSchema struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// AccountAdd 添加客服账号
|
// AccountAdd 添加客服账号
|
||||||
// see https://developer.work.weixin.qq.com/document/path/94662
|
|
||||||
func (r *Client) AccountAdd(options AccountAddOptions) (info AccountAddSchema, err error) {
|
func (r *Client) AccountAdd(options AccountAddOptions) (info AccountAddSchema, err error) {
|
||||||
var (
|
var (
|
||||||
accessToken string
|
accessToken string
|
||||||
@@ -60,7 +59,6 @@ type AccountDelOptions struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// AccountDel 删除客服账号
|
// AccountDel 删除客服账号
|
||||||
// see https://developer.work.weixin.qq.com/document/path/94663
|
|
||||||
func (r *Client) AccountDel(options AccountDelOptions) (info util.CommonError, err error) {
|
func (r *Client) AccountDel(options AccountDelOptions) (info util.CommonError, err error) {
|
||||||
var (
|
var (
|
||||||
accessToken string
|
accessToken string
|
||||||
@@ -88,8 +86,7 @@ type AccountUpdateOptions struct {
|
|||||||
MediaID string `json:"media_id"` // 客服头像临时素材。可以调用上传临时素材接口获取, 不多于128个字节
|
MediaID string `json:"media_id"` // 客服头像临时素材。可以调用上传临时素材接口获取, 不多于128个字节
|
||||||
}
|
}
|
||||||
|
|
||||||
// AccountUpdate 修改客服账号
|
// AccountUpdate 修复客服账号
|
||||||
// see https://developer.work.weixin.qq.com/document/path/94664
|
|
||||||
func (r *Client) AccountUpdate(options AccountUpdateOptions) (info util.CommonError, err error) {
|
func (r *Client) AccountUpdate(options AccountUpdateOptions) (info util.CommonError, err error) {
|
||||||
var (
|
var (
|
||||||
accessToken string
|
accessToken string
|
||||||
@@ -112,10 +109,9 @@ func (r *Client) AccountUpdate(options AccountUpdateOptions) (info util.CommonEr
|
|||||||
|
|
||||||
// AccountInfoSchema 客服详情
|
// AccountInfoSchema 客服详情
|
||||||
type AccountInfoSchema struct {
|
type AccountInfoSchema struct {
|
||||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||||
Name string `json:"name"` // 客服帐号名称
|
Name string `json:"name"` // 客服帐号名称
|
||||||
Avatar string `json:"avatar"` // 客服头像URL
|
Avatar string `json:"avatar"` // 客服头像URL
|
||||||
ManagePrivilege bool `json:"manage_privilege"` // 当前调用接口的应用身份,是否有该客服账号的管理权限(编辑客服账号信息、分配会话和收发消息)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// AccountListSchema 获取客服账号列表响应内容
|
// AccountListSchema 获取客服账号列表响应内容
|
||||||
@@ -145,31 +141,6 @@ func (r *Client) AccountList() (info AccountListSchema, err error) {
|
|||||||
return info, nil
|
return info, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// AccountPagingRequest 分页获取客服账号列表请求
|
|
||||||
type AccountPagingRequest struct {
|
|
||||||
Offset int `json:"offset"`
|
|
||||||
Limit int `json:"limit"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// AccountPaging 分页获取客服账号列表
|
|
||||||
// see https://developer.work.weixin.qq.com/document/path/94661
|
|
||||||
func (r *Client) AccountPaging(req *AccountPagingRequest) (*AccountListSchema, error) {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.ctx.GetAccessToken(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostJSON(fmt.Sprintf(accountListAddr, accessToken), req); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result := &AccountListSchema{}
|
|
||||||
err = util.DecodeWithError(response, result, "AccountPaging")
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddContactWayOptions 获取客服账号链接
|
// AddContactWayOptions 获取客服账号链接
|
||||||
// 1.若scene非空,返回的客服链接开发者可拼接scene_param=SCENE_PARAM参数使用,用户进入会话事件会将SCENE_PARAM原样返回。其中SCENE_PARAM需要urlencode,且长度不能超过128字节。
|
// 1.若scene非空,返回的客服链接开发者可拼接scene_param=SCENE_PARAM参数使用,用户进入会话事件会将SCENE_PARAM原样返回。其中SCENE_PARAM需要urlencode,且长度不能超过128字节。
|
||||||
// 如 https://work.weixin.qq.com/kf/kfcbf8f8d07ac7215f?enc_scene=ENCGFSDF567DF&scene_param=a%3D1%26b%3D2
|
// 如 https://work.weixin.qq.com/kf/kfcbf8f8d07ac7215f?enc_scene=ENCGFSDF567DF&scene_param=a%3D1%26b%3D2
|
||||||
@@ -187,7 +158,6 @@ type AddContactWaySchema struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// AddContactWay 获取客服账号链接
|
// AddContactWay 获取客服账号链接
|
||||||
// see https://developer.work.weixin.qq.com/document/path/94665
|
|
||||||
func (r *Client) AddContactWay(options AddContactWayOptions) (info AddContactWaySchema, err error) {
|
func (r *Client) AddContactWay(options AddContactWayOptions) (info AddContactWaySchema, err error) {
|
||||||
var (
|
var (
|
||||||
accessToken string
|
accessToken string
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ func NewClient(cfg *config.Config) (client *Client, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 初始化 AccessToken Handle
|
// 初始化 AccessToken Handle
|
||||||
defaultAkHandle := credential.NewWorkAccessToken(cfg.CorpID, cfg.CorpSecret, cfg.AgentID, credential.CacheKeyWorkPrefix, cfg.Cache)
|
defaultAkHandle := credential.NewWorkAccessToken(cfg.CorpID, cfg.CorpSecret, credential.CacheKeyWorkPrefix, cfg.Cache)
|
||||||
ctx := &context.Context{
|
ctx := &context.Context{
|
||||||
Config: cfg,
|
Config: cfg,
|
||||||
AccessTokenHandle: defaultAkHandle,
|
AccessTokenHandle: defaultAkHandle,
|
||||||
|
|||||||
@@ -18,23 +18,20 @@ const (
|
|||||||
|
|
||||||
// ReceptionistOptions 添加接待人员请求参数
|
// ReceptionistOptions 添加接待人员请求参数
|
||||||
type ReceptionistOptions struct {
|
type ReceptionistOptions struct {
|
||||||
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
OpenKFID string `json:"open_kfid"` // 客服帐号ID
|
||||||
UserIDList []string `json:"userid_list"` // 接待人员userid列表。第三方应用填密文userid,即open_userid 可填充个数:1 ~ 100。超过100个需分批调用。
|
UserIDList []string `json:"userid_list"` // 接待人员userid列表。第三方应用填密文userid,即open_userid 可填充个数:1 ~ 100。超过100个需分批调用。
|
||||||
DepartmentIDList []int `json:"department_id_list"` // 接待人员部门id列表 可填充个数:0 ~ 100。超过100个需分批调用。
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReceptionistSchema 添加接待人员响应内容
|
// ReceptionistSchema 添加接待人员响应内容
|
||||||
type ReceptionistSchema struct {
|
type ReceptionistSchema struct {
|
||||||
util.CommonError
|
util.CommonError
|
||||||
ResultList []struct {
|
ResultList []struct {
|
||||||
UserID string `json:"userid"`
|
UserID string `json:"userid"`
|
||||||
DepartmentID int `json:"department_id"`
|
|
||||||
util.CommonError
|
util.CommonError
|
||||||
} `json:"result_list"`
|
} `json:"result_list"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReceptionistAdd 添加接待人员
|
// ReceptionistAdd 添加接待人员
|
||||||
// @see https://developer.work.weixin.qq.com/document/path/94646
|
|
||||||
func (r *Client) ReceptionistAdd(options ReceptionistOptions) (info ReceptionistSchema, err error) {
|
func (r *Client) ReceptionistAdd(options ReceptionistOptions) (info ReceptionistSchema, err error) {
|
||||||
var (
|
var (
|
||||||
accessToken string
|
accessToken string
|
||||||
@@ -52,11 +49,10 @@ func (r *Client) ReceptionistAdd(options ReceptionistOptions) (info Receptionist
|
|||||||
if info.ErrCode != 0 {
|
if info.ErrCode != 0 {
|
||||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
}
|
}
|
||||||
return
|
return info, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReceptionistDel 删除接待人员
|
// ReceptionistDel 删除接待人员
|
||||||
// @see https://developer.work.weixin.qq.com/document/path/94647
|
|
||||||
func (r *Client) ReceptionistDel(options ReceptionistOptions) (info ReceptionistSchema, err error) {
|
func (r *Client) ReceptionistDel(options ReceptionistOptions) (info ReceptionistSchema, err error) {
|
||||||
var (
|
var (
|
||||||
accessToken string
|
accessToken string
|
||||||
@@ -76,22 +72,19 @@ func (r *Client) ReceptionistDel(options ReceptionistOptions) (info Receptionist
|
|||||||
if info.ErrCode != 0 {
|
if info.ErrCode != 0 {
|
||||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
}
|
}
|
||||||
return
|
return info, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReceptionistListSchema 获取接待人员列表响应内容
|
// ReceptionistListSchema 获取接待人员列表响应内容
|
||||||
type ReceptionistListSchema struct {
|
type ReceptionistListSchema struct {
|
||||||
util.CommonError
|
util.CommonError
|
||||||
ReceptionistList []struct {
|
ReceptionistList []struct {
|
||||||
UserID string `json:"userid"` // 接待人员的userid。第三方应用获取到的为密文userid,即open_userid
|
UserID string `json:"userid"` // 接待人员的userid。第三方应用获取到的为密文userid,即open_userid
|
||||||
Status int `json:"status"` // 接待人员的接待状态。0:接待中,1:停止接待。第三方应用需具有“管理帐号、分配会话和收发消息”权限才可获取
|
Status int `json:"status"` // 接待人员的接待状态。0:接待中,1:停止接待。第三方应用需具有“管理帐号、分配会话和收发消息”权限才可获取
|
||||||
DepartmentID int `json:"department_id"` // 接待人员部门的id
|
|
||||||
StopType int `json:"stop_type"` // 接待人员的接待状态为「停止接待」的子类型。0:停止接待,1:暂时挂起
|
|
||||||
} `json:"servicer_list"`
|
} `json:"servicer_list"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReceptionistList 获取接待人员列表
|
// ReceptionistList 获取接待人员列表
|
||||||
// @see https://developer.work.weixin.qq.com/document/path/94645
|
|
||||||
func (r *Client) ReceptionistList(kfID string) (info ReceptionistListSchema, err error) {
|
func (r *Client) ReceptionistList(kfID string) (info ReceptionistListSchema, err error) {
|
||||||
var (
|
var (
|
||||||
accessToken string
|
accessToken string
|
||||||
@@ -111,5 +104,5 @@ func (r *Client) ReceptionistList(kfID string) (info ReceptionistListSchema, err
|
|||||||
if info.ErrCode != 0 {
|
if info.ErrCode != 0 {
|
||||||
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
return info, NewSDKErr(info.ErrCode, info.ErrMsg)
|
||||||
}
|
}
|
||||||
return
|
return info, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package material
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
"github.com/silenceper/wechat/v2/util"
|
||||||
)
|
)
|
||||||
@@ -14,8 +13,6 @@ const (
|
|||||||
uploadTempFile = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s"
|
uploadTempFile = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s"
|
||||||
// uploadAttachment 上传附件资源
|
// uploadAttachment 上传附件资源
|
||||||
uploadAttachment = "https://qyapi.weixin.qq.com/cgi-bin/media/upload_attachment?access_token=%s&media_type=%s&attachment_type=%d"
|
uploadAttachment = "https://qyapi.weixin.qq.com/cgi-bin/media/upload_attachment?access_token=%s&media_type=%s&attachment_type=%d"
|
||||||
// getTempFile 获取临时素材
|
|
||||||
getTempFile = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// UploadImgResponse 上传图片响应
|
// UploadImgResponse 上传图片响应
|
||||||
@@ -59,30 +56,6 @@ func (r *Client) UploadImg(filename string) (*UploadImgResponse, error) {
|
|||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// UploadImgFromReader 从 io.Reader 上传图片
|
|
||||||
// @see https://developer.work.weixin.qq.com/document/path/90256
|
|
||||||
func (r *Client) UploadImgFromReader(filename string, reader io.Reader) (*UploadImgResponse, error) {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var byteData []byte
|
|
||||||
byteData, err = io.ReadAll(reader)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostFileByStream("media", filename, fmt.Sprintf(uploadImgURL, accessToken), byteData); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result := &UploadImgResponse{}
|
|
||||||
err = util.DecodeWithError(response, result, "UploadImg")
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// UploadTempFile 上传临时素材
|
// UploadTempFile 上传临时素材
|
||||||
// @see https://developer.work.weixin.qq.com/document/path/90253
|
// @see https://developer.work.weixin.qq.com/document/path/90253
|
||||||
// @mediaType 媒体文件类型,分别有图片(image)、语音(voice)、视频(video),普通文件(file)
|
// @mediaType 媒体文件类型,分别有图片(image)、语音(voice)、视频(video),普通文件(file)
|
||||||
@@ -123,80 +96,3 @@ func (r *Client) UploadAttachment(filename string, mediaType string, attachmentT
|
|||||||
err = util.DecodeWithError(response, result, "UploadAttachment")
|
err = util.DecodeWithError(response, result, "UploadAttachment")
|
||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// UploadTempFileFromReader 上传临时素材
|
|
||||||
// @see https://developer.work.weixin.qq.com/document/path/90253
|
|
||||||
// @mediaType 媒体文件类型,分别有图片(image)、语音(voice)、视频(video),普通文件(file)
|
|
||||||
func (r *Client) UploadTempFileFromReader(filename, mediaType string, reader io.Reader) (*UploadTempFileResponse, error) {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var byteData []byte
|
|
||||||
byteData, err = io.ReadAll(reader)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostFileByStream("media", filename, fmt.Sprintf(uploadTempFile, accessToken, mediaType), byteData); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result := &UploadTempFileResponse{}
|
|
||||||
err = util.DecodeWithError(response, result, "UploadTempFile")
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// UploadAttachmentFromReader 上传附件资源
|
|
||||||
// @see https://developer.work.weixin.qq.com/document/path/95098
|
|
||||||
// @mediaType 媒体文件类型,分别有图片(image)、视频(video)、普通文件(file)
|
|
||||||
// @attachment_type 附件类型,不同的附件类型用于不同的场景。1:朋友圈;2:商品图册
|
|
||||||
func (r *Client) UploadAttachmentFromReader(filename, mediaType string, reader io.Reader, attachmentType int) (*UploadAttachmentResponse, error) {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var byteData []byte
|
|
||||||
byteData, err = io.ReadAll(reader)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var response []byte
|
|
||||||
if response, err = util.PostFileByStream("media", filename, fmt.Sprintf(uploadAttachment, accessToken, mediaType, attachmentType), byteData); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result := &UploadAttachmentResponse{}
|
|
||||||
err = util.DecodeWithError(response, result, "UploadAttachment")
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetTempFile 获取临时素材
|
|
||||||
// @see https://developer.work.weixin.qq.com/document/path/90254
|
|
||||||
func (r *Client) GetTempFile(mediaID string) ([]byte, error) {
|
|
||||||
var (
|
|
||||||
accessToken string
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if accessToken, err = r.GetAccessToken(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
url := fmt.Sprintf(getTempFile, accessToken, mediaID)
|
|
||||||
response, err := util.HTTPGet(url)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查响应是否为错误信息
|
|
||||||
err = util.DecodeWithCommonError(response, "GetTempFile")
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果不是错误响应,则返回原始数据
|
|
||||||
return response, nil
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import (
|
|||||||
"github.com/silenceper/wechat/v2/work/context"
|
"github.com/silenceper/wechat/v2/work/context"
|
||||||
"github.com/silenceper/wechat/v2/work/externalcontact"
|
"github.com/silenceper/wechat/v2/work/externalcontact"
|
||||||
"github.com/silenceper/wechat/v2/work/invoice"
|
"github.com/silenceper/wechat/v2/work/invoice"
|
||||||
"github.com/silenceper/wechat/v2/work/jsapi"
|
|
||||||
"github.com/silenceper/wechat/v2/work/kf"
|
"github.com/silenceper/wechat/v2/work/kf"
|
||||||
"github.com/silenceper/wechat/v2/work/material"
|
"github.com/silenceper/wechat/v2/work/material"
|
||||||
"github.com/silenceper/wechat/v2/work/message"
|
"github.com/silenceper/wechat/v2/work/message"
|
||||||
@@ -25,7 +24,7 @@ type Work struct {
|
|||||||
|
|
||||||
// NewWork init work
|
// NewWork init work
|
||||||
func NewWork(cfg *config.Config) *Work {
|
func NewWork(cfg *config.Config) *Work {
|
||||||
defaultAkHandle := credential.NewWorkAccessToken(cfg.CorpID, cfg.CorpSecret, cfg.AgentID, credential.CacheKeyWorkPrefix, cfg.Cache)
|
defaultAkHandle := credential.NewWorkAccessToken(cfg.CorpID, cfg.CorpSecret, credential.CacheKeyWorkPrefix, cfg.Cache)
|
||||||
ctx := &context.Context{
|
ctx := &context.Context{
|
||||||
Config: cfg,
|
Config: cfg,
|
||||||
AccessTokenHandle: defaultAkHandle,
|
AccessTokenHandle: defaultAkHandle,
|
||||||
@@ -53,11 +52,6 @@ func (wk *Work) GetKF() (*kf.Client, error) {
|
|||||||
return kf.NewClient(wk.ctx.Config)
|
return kf.NewClient(wk.ctx.Config)
|
||||||
}
|
}
|
||||||
|
|
||||||
// JsSdk get JsSdk
|
|
||||||
func (wk *Work) JsSdk() *jsapi.Js {
|
|
||||||
return jsapi.NewJs(wk.ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetExternalContact get external_contact
|
// GetExternalContact get external_contact
|
||||||
func (wk *Work) GetExternalContact() *externalcontact.Client {
|
func (wk *Work) GetExternalContact() *externalcontact.Client {
|
||||||
return externalcontact.NewClient(wk.ctx)
|
return externalcontact.NewClient(wk.ctx)
|
||||||
|
|||||||
Reference in New Issue
Block a user