mirror of
https://github.com/silenceper/wechat.git
synced 2026-02-04 12:52:27 +08:00
Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
010e49c35c | ||
|
|
9c87d1cb34 | ||
|
|
71c8ab58fb | ||
|
|
92bf6c7699 | ||
|
|
6b9d4f82da | ||
|
|
17521d047e | ||
|
|
d38e750876 | ||
|
|
3bd886d7f2 | ||
|
|
35af33f0bc | ||
|
|
4a8371e178 | ||
|
|
a571bf3546 | ||
|
|
3fbe8634d9 | ||
|
|
990ba6ede9 | ||
|
|
44b09c7c3b | ||
|
|
2e0708845b | ||
|
|
c1770130a0 | ||
|
|
c22a036b7f | ||
|
|
05ac7148d4 | ||
|
|
6b3532cc2d | ||
|
|
1138a7db0e | ||
|
|
1842f08f4c | ||
|
|
d28ca4f334 | ||
|
|
74795e86ee | ||
|
|
179704187b | ||
|
|
ceb006bf58 | ||
|
|
9f14122a87 | ||
|
|
7fcd7a34dd | ||
|
|
5b29289dbb | ||
|
|
74e3e9c04e | ||
|
|
97c9f7d908 | ||
|
|
97e1af5904 |
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/** ]
|
branches: [ master,release-*,v2,feature/**,fix/** ]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ master,release-*,v2,feature/** ]
|
branches: [ master,release-*,v2,feature/**,fix/** ]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
golangci:
|
golangci:
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
go-version: [ '1.16','1.17','1.18','1.19','1.20','1.21' ]
|
go-version: [ '1.16','1.17','1.18','1.19','1.20','1.21.4' ]
|
||||||
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@v4
|
uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ matrix.go-version }}
|
go-version: ${{ matrix.go-version }}
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
- name: golangci-lint
|
- name: golangci-lint
|
||||||
uses: golangci/golangci-lint-action@v3
|
uses: golangci/golangci-lint-action@v4
|
||||||
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' ]
|
go: [ '1.16','1.17','1.18','1.19','1.20','1.21','1.22' ]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
- name: Set up Go 1.x
|
- name: Set up Go 1.x
|
||||||
uses: actions/setup-go@v4
|
uses: actions/setup-go@v5
|
||||||
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,6 +16,7 @@ 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"`
|
||||||
@@ -28,6 +29,7 @@ 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,6 +7,16 @@ 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
|
||||||
|
|||||||
@@ -90,9 +90,9 @@ func (ak *DefaultAccessToken) GetAccessTokenContext(ctx context.Context) (access
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(resAccessToken.ExpiresIn-1500)*time.Second); err != nil {
|
expires := resAccessToken.ExpiresIn - 1500
|
||||||
return
|
err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
|
||||||
}
|
|
||||||
accessToken = resAccessToken.AccessToken
|
accessToken = resAccessToken.AccessToken
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -101,10 +101,11 @@ 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
|
||||||
@@ -113,10 +114,11 @@ 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),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,7 +132,20 @@ 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 {
|
||||||
return val.(string), nil
|
if accessToken = val.(string); accessToken != "" {
|
||||||
|
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失效,从微信服务器获取
|
||||||
@@ -141,7 +156,7 @@ func (ak *StableAccessToken) GetAccessTokenContext(ctx context.Context) (accessT
|
|||||||
}
|
}
|
||||||
|
|
||||||
expires := resAccessToken.ExpiresIn - 300
|
expires := resAccessToken.ExpiresIn - 300
|
||||||
_ = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
|
err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
|
||||||
|
|
||||||
accessToken = resAccessToken.AccessToken
|
accessToken = resAccessToken.AccessToken
|
||||||
return
|
return
|
||||||
@@ -174,19 +189,27 @@ 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, cacheKeyPrefix string, cache cache.Cache) AccessTokenContextHandle {
|
func NewWorkAccessToken(corpID, corpSecret, agentID, 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 the not exist")
|
panic("cache is needed")
|
||||||
}
|
}
|
||||||
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),
|
||||||
@@ -203,7 +226,18 @@ 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)
|
||||||
@@ -222,6 +256,7 @@ func (ak *WorkAccessToken) GetAccessTokenContext(ctx context.Context) (accessTok
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
accessToken = resAccessToken.AccessToken
|
accessToken = resAccessToken.AccessToken
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
118
credential/work_js_ticket.go
Normal file
118
credential/work_js_ticket.go
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -138,10 +138,8 @@ func (auth *Auth) GetPhoneNumberContext(ctx context2.Context, code string) (*Get
|
|||||||
}
|
}
|
||||||
|
|
||||||
var result GetPhoneNumberResponse
|
var result GetPhoneNumberResponse
|
||||||
if err = util.DecodeWithError(response, &result, "phonenumber.getPhoneNumber"); err != nil {
|
err = util.DecodeWithError(response, &result, "phonenumber.getPhoneNumber")
|
||||||
return nil, err
|
return &result, err
|
||||||
}
|
|
||||||
return &result, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetPhoneNumber 小程序通过code获取用户手机号
|
// GetPhoneNumber 小程序通过code获取用户手机号
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package business
|
package business
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
"github.com/silenceper/wechat/v2/util"
|
||||||
@@ -28,13 +29,18 @@ 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) {
|
||||||
accessToken, err := business.GetAccessToken()
|
return business.GetPhoneNumberWithContext(context.Background(), in)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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.PostJSON(uri, in)
|
response, err := util.PostJSONContext(ctx, uri, in)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -45,10 +51,5 @@ func (business *Business) GetPhoneNumber(in *GetPhoneNumberRequest) (info PhoneI
|
|||||||
PhoneInfo PhoneInfo `json:"phone_info"`
|
PhoneInfo PhoneInfo `json:"phone_info"`
|
||||||
}
|
}
|
||||||
err = util.DecodeWithError(response, &resp, "business.GetPhoneNumber")
|
err = util.DecodeWithError(response, &resp, "business.GetPhoneNumber")
|
||||||
if nil != err {
|
return resp.PhoneInfo, err
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
info = resp.PhoneInfo
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,4 +14,5 @@ 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.AccessTokenHandle
|
credential.AccessTokenContextHandle
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -398,7 +398,7 @@ type PushDataSecVodUpload struct {
|
|||||||
|
|
||||||
// SecVodUploadEvent 短剧媒资上传完成事件
|
// SecVodUploadEvent 短剧媒资上传完成事件
|
||||||
type SecVodUploadEvent struct {
|
type SecVodUploadEvent struct {
|
||||||
MediaID string `json:"media_id" xml:"media_id"` // 媒资 id
|
MediaID int64 `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 +412,7 @@ type PushDataSecVodAudit struct {
|
|||||||
|
|
||||||
// SecVodAuditEvent 短剧媒资审核状态事件
|
// SecVodAuditEvent 短剧媒资审核状态事件
|
||||||
type SecVodAuditEvent struct {
|
type SecVodAuditEvent struct {
|
||||||
DramaID string `json:"drama_id" xml:"drama_id"` // 剧目 id
|
DramaID int64 `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 查询剧集详情得到
|
||||||
}
|
}
|
||||||
|
|||||||
102
miniprogram/message/updatable_msg.go
Normal file
102
miniprogram/message/updatable_msg.go
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
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,6 +15,7 @@ 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"
|
||||||
@@ -33,17 +34,30 @@ type MiniProgram struct {
|
|||||||
|
|
||||||
// NewMiniProgram 实例化小程序 API
|
// NewMiniProgram 实例化小程序 API
|
||||||
func NewMiniProgram(cfg *config.Config) *MiniProgram {
|
func NewMiniProgram(cfg *config.Config) *MiniProgram {
|
||||||
defaultAkHandle := credential.NewDefaultAccessToken(cfg.AppID, cfg.AppSecret, credential.CacheKeyMiniProgramPrefix, cfg.Cache)
|
var defaultAkHandle credential.AccessTokenContextHandle
|
||||||
|
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,
|
||||||
AccessTokenHandle: defaultAkHandle,
|
AccessTokenContextHandle: 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.AccessTokenHandle = accessTokenHandle
|
miniProgram.ctx.AccessTokenContextHandle = credential.AccessTokenCompatibleHandle{
|
||||||
|
AccessTokenHandle: accessTokenHandle,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetAccessTokenContextHandle 自定义 access_token 获取方式
|
||||||
|
func (miniProgram *MiniProgram) SetAccessTokenContextHandle(accessTokenContextHandle credential.AccessTokenContextHandle) {
|
||||||
|
miniProgram.ctx.AccessTokenContextHandle = accessTokenContextHandle
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetContext get Context
|
// GetContext get Context
|
||||||
@@ -155,3 +169,13 @@ 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,11 +103,8 @@ func (s *Privacy) GetPrivacySetting(privacyVer int) (GetPrivacySettingResponse,
|
|||||||
}
|
}
|
||||||
// 返回错误信息
|
// 返回错误信息
|
||||||
var result GetPrivacySettingResponse
|
var result GetPrivacySettingResponse
|
||||||
if err = util.DecodeWithError(response, &result, "getprivacysetting"); err != nil {
|
err = util.DecodeWithError(response, &result, "getprivacysetting")
|
||||||
return GetPrivacySettingResponse{}, err
|
return result, err
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetPrivacySetting 更新小程序权限配置
|
// SetPrivacySetting 更新小程序权限配置
|
||||||
@@ -130,11 +127,7 @@ func (s *Privacy) SetPrivacySetting(privacyVer int, ownerSetting OwnerSetting, s
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 返回错误信息
|
// 返回错误信息
|
||||||
if err = util.DecodeWithCommonError(response, "setprivacysetting"); err != nil {
|
return util.DecodeWithCommonError(response, "setprivacysetting")
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// UploadPrivacyExtFileResponse 上传权限定义模板响应参数
|
// UploadPrivacyExtFileResponse 上传权限定义模板响应参数
|
||||||
@@ -159,9 +152,6 @@ func (s *Privacy) UploadPrivacyExtFile(fileData []byte) (UploadPrivacyExtFileRes
|
|||||||
|
|
||||||
// 返回错误信息
|
// 返回错误信息
|
||||||
var result UploadPrivacyExtFileResponse
|
var result UploadPrivacyExtFileResponse
|
||||||
if err = util.DecodeWithError(response, &result, "setprivacysetting"); err != nil {
|
err = util.DecodeWithError(response, &result, "setprivacysetting")
|
||||||
return UploadPrivacyExtFileResponse{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,6 +54,8 @@ 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 请求并返回二维码二进制数据
|
||||||
|
|||||||
59
miniprogram/redpacketcover/redpacketcover.go
Normal file
59
miniprogram/redpacketcover/redpacketcover.go
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
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,12 +51,7 @@ 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")
|
||||||
if err != nil {
|
return res.TraceID, err
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
traceID = res.TraceID
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MediaCheckAsyncRequest 图片/音频异步校验请求参数
|
// MediaCheckAsyncRequest 图片/音频异步校验请求参数
|
||||||
@@ -93,12 +88,7 @@ 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")
|
||||||
if err != nil {
|
return res.TraceID, err
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
traceID = res.TraceID
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ImageCheckV1 校验一张图片是否含有违法违规内容(同步)
|
// ImageCheckV1 校验一张图片是否含有违法违规内容(同步)
|
||||||
|
|||||||
@@ -60,11 +60,7 @@ 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")
|
||||||
if err != nil {
|
return res.Link, err
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return res.Link, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GenerateShortLinkPermanent 生成永久 shortLink
|
// GenerateShortLinkPermanent 生成永久 shortLink
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package subscribe
|
package subscribe
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/miniprogram/context"
|
"github.com/silenceper/wechat/v2/miniprogram/context"
|
||||||
@@ -70,6 +71,13 @@ 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
|
||||||
@@ -85,6 +93,33 @@ 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) {
|
||||||
@@ -168,11 +203,7 @@ 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")
|
||||||
if err != nil {
|
return result.TemplateID, err
|
||||||
return
|
|
||||||
}
|
|
||||||
templateID = result.TemplateID
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete 删除私有模板
|
// Delete 删除私有模板
|
||||||
|
|||||||
@@ -65,8 +65,5 @@ 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")
|
||||||
if err != nil {
|
return resp.URLLink, err
|
||||||
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,9 +62,5 @@ 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")
|
||||||
if err != nil {
|
return res.SchemeInfo, res.VisitOpenid, err
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
return res.SchemeInfo, res.VisitOpenid, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ 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 返回的结果
|
||||||
@@ -78,8 +79,5 @@ 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")
|
||||||
if err != nil {
|
return resp.OpenLink, err
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return resp.OpenLink, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,9 +44,6 @@ func (basic *Basic) Long2ShortURL(longURL string) (shortURL string, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err = util.DecodeWithError(responseBytes, resp, long2shortAction); err != nil {
|
err = util.DecodeWithError(responseBytes, resp, long2shortAction)
|
||||||
return
|
return resp.ShortURL, err
|
||||||
}
|
|
||||||
shortURL = resp.ShortURL
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,6 +79,10 @@ 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"`
|
||||||
// 发送卡券
|
// 发送卡券
|
||||||
@@ -183,7 +187,13 @@ func (broadcast *Broadcast) SendImage(user *User, images *Image) (*Result, error
|
|||||||
ToUser: nil,
|
ToUser: nil,
|
||||||
MsgType: MsgTypeImage,
|
MsgType: MsgTypeImage,
|
||||||
}
|
}
|
||||||
req.Images = images
|
if broadcast.preview {
|
||||||
|
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)
|
||||||
@@ -205,7 +215,7 @@ func (broadcast *Broadcast) SendVideo(user *User, mediaID string, title, descrip
|
|||||||
ToUser: nil,
|
ToUser: nil,
|
||||||
MsgType: MsgTypeVideo,
|
MsgType: MsgTypeVideo,
|
||||||
}
|
}
|
||||||
req.Voice = map[string]interface{}{
|
req.Mpvideo = map[string]interface{}{
|
||||||
"media_id": mediaID,
|
"media_id": mediaID,
|
||||||
"title": title,
|
"title": title,
|
||||||
"description": description,
|
"description": description,
|
||||||
|
|||||||
@@ -11,4 +11,5 @@ 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,11 +72,7 @@ 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")
|
||||||
if err != nil {
|
return res.KfList, err
|
||||||
return
|
|
||||||
}
|
|
||||||
customerServiceList = res.KfList
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// KeFuOnlineInfo 客服在线信息
|
// KeFuOnlineInfo 客服在线信息
|
||||||
@@ -107,11 +103,7 @@ 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")
|
||||||
if err != nil {
|
return res.KfOnlineList, err
|
||||||
return
|
|
||||||
}
|
|
||||||
customerServiceOnlineList = res.KfOnlineList
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add 添加客服账号
|
// Add 添加客服账号
|
||||||
|
|||||||
@@ -183,9 +183,6 @@ 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,11 +64,7 @@ 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")
|
||||||
if err != nil {
|
return res.MediaID, err
|
||||||
return
|
|
||||||
}
|
|
||||||
mediaID = res.MediaID
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDraft 获取草稿
|
// GetDraft 获取草稿
|
||||||
@@ -94,12 +90,7 @@ 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")
|
||||||
if err != nil {
|
return res.NewsItem, err
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
articles = res.NewsItem
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteDraft 删除草稿
|
// DeleteDraft 删除草稿
|
||||||
@@ -172,12 +163,7 @@ 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")
|
||||||
if nil != err {
|
return res.Total, err
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
total = res.Total
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ArticleList 草稿列表
|
// ArticleList 草稿列表
|
||||||
|
|||||||
@@ -73,12 +73,7 @@ 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")
|
||||||
if err != nil {
|
return res.PublishID, err
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
publishID = res.PublishID
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// PublishStatusList 发布任务状态列表
|
// PublishStatusList 发布任务状态列表
|
||||||
@@ -191,12 +186,7 @@ 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")
|
||||||
if err != nil {
|
return res.NewsItem, err
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
list = res.NewsItem
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ArticleList 发布列表
|
// ArticleList 发布列表
|
||||||
|
|||||||
@@ -39,7 +39,6 @@ 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) {
|
||||||
config = new(Config)
|
|
||||||
var accessToken string
|
var accessToken string
|
||||||
accessToken, err = js.GetAccessToken()
|
accessToken, err = js.GetAccessToken()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -50,12 +49,11 @@ func (js *Js) GetConfig(uri string) (config *Config, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
nonceStr := util.RandomStr(16)
|
nonceStr := util.RandomStr(16)
|
||||||
timestamp := util.GetCurrTS()
|
timestamp := util.GetCurrTS()
|
||||||
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
|
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
|
||||||
sigStr := util.Signature(str)
|
sigStr := util.Signature(str)
|
||||||
|
config = new(Config)
|
||||||
config.AppID = js.AppID
|
config.AppID = js.AppID
|
||||||
config.NonceStr = nonceStr
|
config.NonceStr = nonceStr
|
||||||
config.Timestamp = timestamp
|
config.Timestamp = timestamp
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ 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"
|
||||||
@@ -160,8 +163,8 @@ type resAddMaterial struct {
|
|||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddMaterial 上传永久性素材(处理视频需要单独上传)
|
// AddMaterialFromReader 上传永久性素材(处理视频需要单独上传),从 io.Reader 中读取
|
||||||
func (material *Material) AddMaterial(mediaType MediaType, filename string) (mediaID string, url string, err error) {
|
func (material *Material) AddMaterialFromReader(mediaType MediaType, filePath string, reader io.Reader) (mediaID string, url string, err error) {
|
||||||
if mediaType == MediaTypeVideo {
|
if mediaType == MediaTypeVideo {
|
||||||
err = errors.New("永久视频素材上传使用 AddVideo 方法")
|
err = errors.New("永久视频素材上传使用 AddVideo 方法")
|
||||||
return
|
return
|
||||||
@@ -173,8 +176,10 @@ func (material *Material) AddMaterial(mediaType MediaType, filename string) (med
|
|||||||
}
|
}
|
||||||
|
|
||||||
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.PostFile("media", filename, uri)
|
response, err = util.PostFileFromReader("media", filePath, filename, uri, reader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -192,13 +197,24 @@ func (material *Material) AddMaterial(mediaType MediaType, filename string) (med
|
|||||||
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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddVideo 永久视频素材文件上传
|
// AddVideoFromReader 永久视频素材文件上传,从 io.Reader 中读取
|
||||||
func (material *Material) AddVideo(filename, title, introduction string) (mediaID string, url string, err error) {
|
func (material *Material) AddVideoFromReader(filePath, title, introduction string, reader io.Reader) (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 {
|
||||||
@@ -216,16 +232,19 @@ func (material *Material) AddVideo(filename, title, introduction string) (mediaI
|
|||||||
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",
|
||||||
Filename: filename,
|
FilePath: filePath,
|
||||||
|
Filename: fileName,
|
||||||
|
FileReader: reader,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
IsFile: false,
|
IsFile: false,
|
||||||
Fieldname: "description",
|
Fieldname: "description",
|
||||||
|
Filename: fileName,
|
||||||
Value: fieldValue,
|
Value: fieldValue,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -250,6 +269,17 @@ func (material *Material) AddVideo(filename, title, introduction string) (mediaI
|
|||||||
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,6 +3,7 @@ package material
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
"github.com/silenceper/wechat/v2/util"
|
||||||
)
|
)
|
||||||
@@ -62,6 +63,38 @@ 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) {
|
||||||
|
|||||||
@@ -90,11 +90,7 @@ 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")
|
||||||
if err != nil {
|
return res.SubscriptionList, err
|
||||||
return
|
|
||||||
}
|
|
||||||
templateList = res.SubscriptionList
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type resSubscribeAdd struct {
|
type resSubscribeAdd struct {
|
||||||
@@ -123,11 +119,7 @@ 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")
|
||||||
if err != nil {
|
return result.TemplateID, err
|
||||||
return
|
|
||||||
}
|
|
||||||
templateID = result.TemplateID
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete 删除私有模板
|
// Delete 删除私有模板
|
||||||
@@ -175,11 +167,7 @@ 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")
|
||||||
if err != nil {
|
return result.CategoryList, err
|
||||||
return
|
|
||||||
}
|
|
||||||
categoryList = result.CategoryList
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// PublicTemplateKeyWords 模板中的关键词
|
// PublicTemplateKeyWords 模板中的关键词
|
||||||
@@ -210,11 +198,7 @@ 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")
|
||||||
if err != nil {
|
return result.KeyWordsList, err
|
||||||
return
|
|
||||||
}
|
|
||||||
keyWordsList = result.KeyWordsList
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// PublicTemplateTitle 类目下的公共模板
|
// PublicTemplateTitle 类目下的公共模板
|
||||||
@@ -246,10 +230,5 @@ 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")
|
||||||
if err != nil {
|
return result.Count, result.TemplateTitleList, err
|
||||||
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
|
||||||
}
|
}
|
||||||
uri := fmt.Sprintf("%s?access_token=%s", templateSendURL, accessToken)
|
var (
|
||||||
var response []byte
|
uri = fmt.Sprintf("%s?access_token=%s", templateSendURL, 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 resTemplateSend
|
var result resTemplateSend
|
||||||
err = json.Unmarshal(response, &result)
|
if err = json.Unmarshal(response, &result); err != nil {
|
||||||
if err != nil {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if result.ErrCode != 0 {
|
if result.ErrCode != 0 {
|
||||||
@@ -103,19 +103,16 @@ func (tpl *Template) List() (templateList []*TemplateItem, err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
uri := fmt.Sprintf("%s?access_token=%s", templateListURL, accessToken)
|
var (
|
||||||
var response []byte
|
uri = fmt.Sprintf("%s?access_token=%s", templateListURL, accessToken)
|
||||||
response, err = util.HTTPGet(uri)
|
response []byte
|
||||||
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")
|
||||||
if err != nil {
|
return res.TemplateList, err
|
||||||
return
|
|
||||||
}
|
|
||||||
templateList = res.TemplateList
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type resTemplateAdd struct {
|
type resTemplateAdd struct {
|
||||||
@@ -125,29 +122,26 @@ type resTemplateAdd struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add 添加模板.
|
// Add 添加模板.
|
||||||
func (tpl *Template) Add(shortID string) (templateID string, err error) {
|
func (tpl *Template) Add(shortID string, keyNameList []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 msg = struct {
|
var (
|
||||||
ShortID string `json:"template_id_short"`
|
msg = struct {
|
||||||
}{ShortID: shortID}
|
ShortID string `json:"template_id_short"`
|
||||||
uri := fmt.Sprintf("%s?access_token=%s", templateAddURL, accessToken)
|
KeyNameList []string `json:"keyword_name_list"`
|
||||||
var response []byte
|
}{ShortID: shortID, KeyNameList: keyNameList}
|
||||||
response, err = util.PostJSON(uri, msg)
|
uri = fmt.Sprintf("%s?access_token=%s", templateAddURL, accessToken)
|
||||||
if err != nil {
|
response []byte
|
||||||
|
)
|
||||||
|
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")
|
||||||
if err != nil {
|
return result.TemplateID, err
|
||||||
return
|
|
||||||
}
|
|
||||||
templateID = result.TemplateID
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete 删除私有模板.
|
// Delete 删除私有模板.
|
||||||
@@ -157,14 +151,14 @@ func (tpl *Template) Delete(templateID string) (err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var msg = struct {
|
var (
|
||||||
TemplateID string `json:"template_id"`
|
msg = struct {
|
||||||
}{TemplateID: templateID}
|
TemplateID string `json:"template_id"`
|
||||||
|
}{TemplateID: templateID}
|
||||||
uri := fmt.Sprintf("%s?access_token=%s", templateDelURL, accessToken)
|
uri = fmt.Sprintf("%s?access_token=%s", templateDelURL, 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
|
||||||
}
|
}
|
||||||
return util.DecodeWithCommonError(response, "DeleteTemplate")
|
return util.DecodeWithCommonError(response, "DeleteTemplate")
|
||||||
|
|||||||
@@ -49,7 +49,13 @@ type OfficialAccount struct {
|
|||||||
|
|
||||||
// NewOfficialAccount 实例化公众号API
|
// NewOfficialAccount 实例化公众号API
|
||||||
func NewOfficialAccount(cfg *config.Config) *OfficialAccount {
|
func NewOfficialAccount(cfg *config.Config) *OfficialAccount {
|
||||||
defaultAkHandle := credential.NewDefaultAccessToken(cfg.AppID, cfg.AppSecret, credential.CacheKeyOfficialAccountPrefix, cfg.Cache)
|
var defaultAkHandle credential.AccessTokenContextHandle
|
||||||
|
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,
|
||||||
|
|||||||
@@ -62,10 +62,6 @@ 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,10 +126,7 @@ 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)
|
||||||
if err != nil {
|
return result.Tags, err
|
||||||
return
|
|
||||||
}
|
|
||||||
return result.Tags, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// OpenIDListByTag 获取标签下粉丝列表
|
// OpenIDListByTag 获取标签下粉丝列表
|
||||||
@@ -154,9 +151,6 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -100,11 +100,8 @@ 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"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(body, &ret); err != nil {
|
err = json.Unmarshal(body, &ret)
|
||||||
return "", err
|
return ret.PreCode, err
|
||||||
}
|
|
||||||
|
|
||||||
return ret.PreCode, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetPreCode 获取预授权码
|
// GetPreCode 获取预授权码
|
||||||
|
|||||||
@@ -9,6 +9,12 @@ 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 基础信息设置
|
||||||
@@ -51,3 +57,181 @@ 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,6 +1,7 @@
|
|||||||
package miniprogram
|
package miniprogram
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
originalContext "context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/credential"
|
"github.com/silenceper/wechat/v2/credential"
|
||||||
@@ -37,6 +38,22 @@ 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
|
||||||
@@ -68,7 +85,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{
|
||||||
AccessTokenHandle: miniProgram,
|
AccessTokenContextHandle: miniProgram,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
93
util/http.go
93
util/http.go
@@ -22,6 +22,9 @@ type URIModifier func(uri string) string
|
|||||||
|
|
||||||
var uriModifier URIModifier
|
var uriModifier URIModifier
|
||||||
|
|
||||||
|
// DefaultHTTPClient 默认httpClient
|
||||||
|
var DefaultHTTPClient = http.DefaultClient
|
||||||
|
|
||||||
// SetURIModifier 设置URI修改器
|
// SetURIModifier 设置URI修改器
|
||||||
func SetURIModifier(fn URIModifier) {
|
func SetURIModifier(fn URIModifier) {
|
||||||
uriModifier = fn
|
uriModifier = fn
|
||||||
@@ -41,7 +44,7 @@ func HTTPGetContext(ctx context.Context, uri string) ([]byte, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
response, err := http.DefaultClient.Do(request)
|
response, err := DefaultHTTPClient.Do(request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -73,7 +76,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 := http.DefaultClient.Do(request)
|
response, err := DefaultHTTPClient.Do(request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -102,7 +105,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 := http.DefaultClient.Do(req)
|
response, err := DefaultHTTPClient.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -129,7 +132,7 @@ func PostJSONWithRespContentType(uri string, obj interface{}) ([]byte, string, e
|
|||||||
return nil, "", err
|
return nil, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
response, err := http.Post(uri, "application/json;charset=utf-8", jsonBuf)
|
response, err := DefaultHTTPClient.Post(uri, "application/json;charset=utf-8", jsonBuf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", err
|
return nil, "", err
|
||||||
}
|
}
|
||||||
@@ -143,13 +146,40 @@ 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, filename, uri string) ([]byte, error) {
|
func PostFile(fieldName, filePath, uri string) ([]byte, error) {
|
||||||
fields := []MultipartFormField{
|
fields := []MultipartFormField{
|
||||||
{
|
{
|
||||||
IsFile: true,
|
IsFile: true,
|
||||||
Fieldname: fieldName,
|
Fieldname: fieldName,
|
||||||
Filename: filename,
|
FilePath: 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)
|
||||||
@@ -157,10 +187,12 @@ func PostFile(fieldName, filename, uri string) ([]byte, error) {
|
|||||||
|
|
||||||
// MultipartFormField 保存文件或其他字段信息
|
// MultipartFormField 保存文件或其他字段信息
|
||||||
type MultipartFormField struct {
|
type MultipartFormField struct {
|
||||||
IsFile bool
|
IsFile bool
|
||||||
Fieldname string
|
Fieldname string
|
||||||
Value []byte
|
Value []byte
|
||||||
Filename string
|
FilePath string
|
||||||
|
Filename string
|
||||||
|
FileReader io.Reader
|
||||||
}
|
}
|
||||||
|
|
||||||
// PostMultipartForm 上传文件或其他多个字段
|
// PostMultipartForm 上传文件或其他多个字段
|
||||||
@@ -179,18 +211,24 @@ func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
fh, e := os.Open(field.Filename)
|
if field.FileReader == nil {
|
||||||
if e != nil {
|
fh, e := os.Open(field.FilePath)
|
||||||
err = fmt.Errorf("error opening file , err=%v", e)
|
if e != nil {
|
||||||
return
|
err = fmt.Errorf("error opening file , err=%v", e)
|
||||||
}
|
return
|
||||||
defer fh.Close()
|
}
|
||||||
|
_, err = io.Copy(fileWriter, fh)
|
||||||
if _, err = io.Copy(fileWriter, fh); err != nil {
|
_ = fh.Close()
|
||||||
return
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if _, err = io.Copy(fileWriter, field.FileReader); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
partWriter, e := bodyWriter.CreateFormField(field.Fieldname)
|
partWriter, e := bodyWriter.CreateFormFile(field.Fieldname, field.Filename)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
err = e
|
err = e
|
||||||
return
|
return
|
||||||
@@ -205,14 +243,14 @@ func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte
|
|||||||
contentType := bodyWriter.FormDataContentType()
|
contentType := bodyWriter.FormDataContentType()
|
||||||
bodyWriter.Close()
|
bodyWriter.Close()
|
||||||
|
|
||||||
resp, e := http.Post(uri, contentType, bodyBuf)
|
resp, e := DefaultHTTPClient.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, err
|
return nil, fmt.Errorf("http code error : uri=%v , statusCode=%v", uri, resp.StatusCode)
|
||||||
}
|
}
|
||||||
respBody, err = io.ReadAll(resp.Body)
|
respBody, err = io.ReadAll(resp.Body)
|
||||||
return
|
return
|
||||||
@@ -229,7 +267,7 @@ func PostXML(uri string, obj interface{}) ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
body := bytes.NewBuffer(xmlData)
|
body := bytes.NewBuffer(xmlData)
|
||||||
response, err := http.Post(uri, "application/xml;charset=utf-8", body)
|
response, err := DefaultHTTPClient.Post(uri, "application/xml;charset=utf-8", body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -252,11 +290,10 @@ func httpWithTLS(rootCa, key string) (*http.Client, error) {
|
|||||||
config := &tls.Config{
|
config := &tls.Config{
|
||||||
Certificates: []tls.Certificate{cert},
|
Certificates: []tls.Certificate{cert},
|
||||||
}
|
}
|
||||||
tr := &http.Transport{
|
trans := (DefaultHTTPClient.Transport.(*http.Transport)).Clone()
|
||||||
TLSClientConfig: config,
|
trans.TLSClientConfig = config
|
||||||
DisableCompression: true,
|
trans.DisableCompression = true
|
||||||
}
|
client = &http.Client{Transport: trans}
|
||||||
client = &http.Client{Transport: tr}
|
|
||||||
return client, nil
|
return client, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package wechat
|
package wechat
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
@@ -14,6 +15,7 @@ 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"
|
||||||
)
|
)
|
||||||
@@ -81,3 +83,8 @@ 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,12 +9,16 @@ 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"
|
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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -85,6 +89,49 @@ 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) {
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ 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 删除成员
|
||||||
@@ -154,6 +156,51 @@ 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"`
|
||||||
|
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
|
||||||
|
|||||||
387
work/checkin/checkin.go
Normal file
387
work/checkin/checkin.go
Normal file
@@ -0,0 +1,387 @@
|
|||||||
|
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"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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"`
|
||||||
|
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")
|
||||||
|
}
|
||||||
@@ -7,12 +7,11 @@ 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配置,用于解密回调消息内容对应的密文
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 string `json:"external_profile"`
|
ExternalProfile *ExternalProfile `json:"external_profile,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// FollowUser 跟进用户(指企业内部用户)
|
// FollowUser 跟进用户(指企业内部用户)
|
||||||
@@ -104,6 +104,46 @@ 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,13 +76,14 @@ 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 {
|
||||||
|
|||||||
75
work/jsapi/jsapi.go
Normal file
75
work/jsapi/jsapi.go
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
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,6 +33,7 @@ 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
|
||||||
@@ -59,6 +60,7 @@ 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
|
||||||
@@ -86,7 +88,8 @@ 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
|
||||||
@@ -109,9 +112,10 @@ 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 获取客服账号列表响应内容
|
||||||
@@ -141,6 +145,31 @@ 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
|
||||||
@@ -158,6 +187,7 @@ 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, credential.CacheKeyWorkPrefix, cfg.Cache)
|
defaultAkHandle := credential.NewWorkAccessToken(cfg.CorpID, cfg.CorpSecret, cfg.AgentID, credential.CacheKeyWorkPrefix, cfg.Cache)
|
||||||
ctx := &context.Context{
|
ctx := &context.Context{
|
||||||
Config: cfg,
|
Config: cfg,
|
||||||
AccessTokenHandle: defaultAkHandle,
|
AccessTokenHandle: defaultAkHandle,
|
||||||
|
|||||||
@@ -18,20 +18,23 @@ 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
|
||||||
@@ -49,10 +52,11 @@ 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 info, nil
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
@@ -72,19 +76,22 @@ 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 info, nil
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
@@ -104,5 +111,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 info, nil
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package material
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
"github.com/silenceper/wechat/v2/util"
|
"github.com/silenceper/wechat/v2/util"
|
||||||
)
|
)
|
||||||
@@ -13,6 +14,8 @@ 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 上传图片响应
|
||||||
@@ -56,6 +59,30 @@ 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)
|
||||||
@@ -96,3 +123,80 @@ 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,6 +9,7 @@ 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"
|
||||||
@@ -24,7 +25,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, credential.CacheKeyWorkPrefix, cfg.Cache)
|
defaultAkHandle := credential.NewWorkAccessToken(cfg.CorpID, cfg.CorpSecret, cfg.AgentID, credential.CacheKeyWorkPrefix, cfg.Cache)
|
||||||
ctx := &context.Context{
|
ctx := &context.Context{
|
||||||
Config: cfg,
|
Config: cfg,
|
||||||
AccessTokenHandle: defaultAkHandle,
|
AccessTokenHandle: defaultAkHandle,
|
||||||
@@ -52,6 +53,11 @@ 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