mirror of
https://github.com/silenceper/wechat.git
synced 2026-02-04 21:02:25 +08:00
Compare commits
49 Commits
feature/go
...
copilot/fi
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8157cad2cb | ||
|
|
be6e95e987 | ||
|
|
c806a0c172 | ||
|
|
c136b878ce | ||
|
|
d4a81916d5 | ||
|
|
ef1372b98a | ||
|
|
0d666b60ba | ||
|
|
e1122d42b0 | ||
|
|
be3f0d8bd5 | ||
|
|
66f9794d2f | ||
|
|
ee5f045b89 | ||
|
|
d35f0f0865 | ||
|
|
bbad169706 | ||
|
|
5927c26152 | ||
|
|
8ebff5c29c | ||
|
|
86ef690ecd | ||
|
|
ee85790123 | ||
|
|
8a810837a4 | ||
|
|
c51d41ee8a | ||
|
|
24f812d187 | ||
|
|
dd43b7baa3 | ||
|
|
2dfd2ff608 | ||
|
|
23bb10b0c9 | ||
|
|
b639d2235d | ||
|
|
26d2093bd7 | ||
|
|
cf42cd8d54 | ||
|
|
85ee45580b | ||
|
|
208d5c528a | ||
|
|
b5f9a8933e | ||
|
|
52fb5596d3 | ||
|
|
44150c557e | ||
|
|
635a0c640d | ||
|
|
010e49c35c | ||
|
|
9c87d1cb34 | ||
|
|
71c8ab58fb | ||
|
|
92bf6c7699 | ||
|
|
6b9d4f82da | ||
|
|
17521d047e | ||
|
|
d38e750876 | ||
|
|
3bd886d7f2 | ||
|
|
35af33f0bc | ||
|
|
4a8371e178 | ||
|
|
a571bf3546 | ||
|
|
3fbe8634d9 | ||
|
|
990ba6ede9 | ||
|
|
44b09c7c3b | ||
|
|
2e0708845b | ||
|
|
c1770130a0 | ||
|
|
c22a036b7f |
4
.github/FUNDING.yml
vendored
4
.github/FUNDING.yml
vendored
@@ -1,8 +1,8 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
github: # silenceper
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
open_collective: gowechat
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
|
||||
38
.github/workflows/ai-dev.yaml
vendored
Normal file
38
.github/workflows/ai-dev.yaml
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
name: Claude Code
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
jobs:
|
||||
claude:
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
- name: Run Claude Code
|
||||
id: claude
|
||||
uses: anthropics/claude-code-action@beta
|
||||
env:
|
||||
ANTHROPIC_BASE_URL: "${{ secrets.ANTHROPIC_BASE_URL }}"
|
||||
with:
|
||||
model: "${{ secrets.ANTHROPIC_MODEL }}"
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
8
.github/workflows/go.yml
vendored
8
.github/workflows/go.yml
vendored
@@ -10,7 +10,7 @@ jobs:
|
||||
golangci:
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [ '1.18','1.19','1.20','1.21.4','1.22' ]
|
||||
go-version: [ '1.16','1.17','1.18','1.19','1.20','1.21.4' ]
|
||||
name: golangci-lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -21,10 +21,10 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v6
|
||||
uses: golangci/golangci-lint-action@v4
|
||||
with:
|
||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||
version: v1.58.2
|
||||
version: v1.52.2
|
||||
build:
|
||||
name: Test
|
||||
runs-on: ubuntu-latest
|
||||
@@ -42,7 +42,7 @@ jobs:
|
||||
# strategy set
|
||||
strategy:
|
||||
matrix:
|
||||
go: [ '1.18','1.19','1.20','1.21','1.22' ]
|
||||
go: [ '1.16','1.17','1.18','1.19','1.20','1.21','1.22' ]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
@@ -4,32 +4,36 @@ linters:
|
||||
disable-all: true
|
||||
enable:
|
||||
- bodyclose
|
||||
- deadcode
|
||||
- depguard
|
||||
- dogsled
|
||||
- dupl
|
||||
- errcheck
|
||||
- exportloopref
|
||||
- funlen
|
||||
- goconst
|
||||
# - gocritic
|
||||
- gocyclo
|
||||
- gofmt
|
||||
- goimports
|
||||
- golint
|
||||
- goprintffuncname
|
||||
- gosimple
|
||||
- govet
|
||||
- ineffassign
|
||||
- interfacer
|
||||
- misspell
|
||||
- nolintlint
|
||||
- rowserrcheck
|
||||
- scopelint
|
||||
- staticcheck
|
||||
- structcheck
|
||||
- stylecheck
|
||||
# - typecheck
|
||||
- typecheck
|
||||
- unconvert
|
||||
- unparam
|
||||
- unused
|
||||
- varcheck
|
||||
- whitespace
|
||||
# - revive
|
||||
|
||||
issues:
|
||||
include:
|
||||
@@ -53,68 +57,10 @@ linters-settings:
|
||||
lines: 66
|
||||
statements: 50
|
||||
|
||||
errcheck:
|
||||
# Report about not checking of errors in type assertions: `a := b.(MyStruct)`.
|
||||
# Such cases aren't reported by default.
|
||||
# Default: false
|
||||
check-type-assertions: true
|
||||
# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`.
|
||||
# Such cases aren't reported by default.
|
||||
# Default: false
|
||||
check-blank: true
|
||||
# To disable the errcheck built-in exclude list.
|
||||
# See `-excludeonly` option in https://github.com/kisielk/errcheck#excluding-functions for details.
|
||||
# Default: false
|
||||
disable-default-exclusions: true
|
||||
# List of functions to exclude from checking, where each entry is a single function to exclude.
|
||||
# See https://github.com/kisielk/errcheck#excluding-functions for details.
|
||||
exclude-functions:
|
||||
- io/ioutil.ReadFile
|
||||
- io.Copy(*bytes.Buffer)
|
||||
- io.Copy(os.Stdout)
|
||||
- (*bytes.Buffer).WriteString
|
||||
- (*bytes.Buffer).Write
|
||||
- url.Parse
|
||||
- (*strings.Builder).WriteString
|
||||
- io.WriteString
|
||||
- (*bytes.Buffer).WriteByte
|
||||
- (*hmac.New).Write
|
||||
- (*int)
|
||||
- (*string)
|
||||
- (hash.Hash).Write
|
||||
|
||||
depguard:
|
||||
# Rules to apply.
|
||||
#
|
||||
# Variables:
|
||||
# - File Variables
|
||||
# you can still use and exclamation mark ! in front of a variable to say not to use it.
|
||||
# Example !$test will match any file that is not a go test file.
|
||||
#
|
||||
# `$all` - matches all go files
|
||||
# `$test` - matches all go test files
|
||||
#
|
||||
# - Package Variables
|
||||
#
|
||||
# `$gostd` - matches all of go's standard library (Pulled from `GOROOT`)
|
||||
#
|
||||
# Default: Only allow $gostd in all files.
|
||||
rules:
|
||||
# Name of a rule.
|
||||
main:
|
||||
# Used to determine the package matching priority.
|
||||
# There are three different modes: `original`, `strict`, and `lax`.
|
||||
# Default: "original"
|
||||
list-mode: lax
|
||||
# List of file globs that will match this list of settings to compare against.
|
||||
# Default: $all
|
||||
files:
|
||||
- "!**/*_a _file.go"
|
||||
# List of allowed packages.
|
||||
allow:
|
||||
- $gostd
|
||||
- github.com/OpenPeeDeeP
|
||||
# Packages that are not allowed where the value is a suggestion.
|
||||
deny:
|
||||
- pkg: "github.com/pkg/errors"
|
||||
desc: Should be replaced by standard lib errors package
|
||||
#issues:
|
||||
# include:
|
||||
# - EXC0002 # disable excluding of issues about comments from golint
|
||||
# exclude-rules:
|
||||
# - linters:
|
||||
# - stylecheck
|
||||
# text: "ST1000:"
|
||||
|
||||
43
README.md
43
README.md
@@ -1,16 +1,17 @@
|
||||
# WeChat SDK for Go
|
||||
|
||||

|
||||
[](https://goreportcard.com/report/github.com/silenceper/wechat)
|
||||

|
||||
[](https://goreportcard.com/report/github.com/silenceper/wechat/v2)
|
||||
[](https://pkg.go.dev/github.com/silenceper/wechat/v2?tab=doc)
|
||||

|
||||

|
||||

|
||||
|
||||
使用 Golang 开发的微信 SDK,简单、易用。
|
||||
> 注意:当前版本为 v2 版本,v1 版本已废弃
|
||||
|
||||
使用Golang开发的微信SDK,简单、易用。
|
||||
|
||||
## 文档 && 例子
|
||||
|
||||
[API 列表](https://github.com/silenceper/wechat/tree/v2/doc/api)
|
||||
[API列表](https://github.com/silenceper/wechat/tree/v2/doc/api)
|
||||
|
||||
[Wechat SDK 2.0 文档](https://silenceper.com/wechat)
|
||||
|
||||
@@ -25,7 +26,7 @@ import "github.com/silenceper/wechat/v2"
|
||||
以下是一个微信公众号处理消息接收以及回复的例子:
|
||||
|
||||
```go
|
||||
// 使用 memcache 保存 access_token,也可选择 redis 或自定义 cache
|
||||
// 使用memcache保存access_token,也可选择redis或自定义cache
|
||||
wc := wechat.NewWechat()
|
||||
memory := cache.NewMemory()
|
||||
cfg := &offConfig.Config{
|
||||
@@ -37,7 +38,7 @@ cfg := &offConfig.Config{
|
||||
}
|
||||
officialAccount := wc.GetOfficialAccount(cfg)
|
||||
|
||||
// 传入 request 和 responseWriter
|
||||
// 传入request和responseWriter
|
||||
server := officialAccount.GetServer(req, rw)
|
||||
// 设置接收消息的处理方法
|
||||
server.SetMessageHandler(func(msg *message.MixMessage) *message.Reply {
|
||||
@@ -60,22 +61,28 @@ server.Send()
|
||||
|
||||
## 目录说明
|
||||
|
||||
- officialaccount: 微信公众号 API
|
||||
- miniprogram: 小程序 API
|
||||
- minigame:小游戏 API
|
||||
- pay:微信支付 API
|
||||
- openplatform:开放平台 API
|
||||
- officialaccount: 微信公众号API
|
||||
- miniprogram: 小程序API
|
||||
- minigame:小游戏API
|
||||
- pay:微信支付API
|
||||
- openplatform:开放平台API
|
||||
- work:企业微信
|
||||
- aispeech:智能对话
|
||||
- doc: api 文档
|
||||
- doc: api文档
|
||||
|
||||
## 贡献
|
||||
|
||||
- 在[API 列表](https://github.com/silenceper/wechat/tree/v2/doc/api)中查看哪些 API 未实现
|
||||
- 提交 issue,描述需要贡献的内容
|
||||
- 完成更改后,提交 PR
|
||||
- 在[API列表](https://github.com/silenceper/wechat/tree/v2/doc/api)中查看哪些API未实现
|
||||
- 提交issue,描述需要贡献的内容
|
||||
- 完成更改后,提交PR
|
||||
|
||||
## 公众号
|
||||
|
||||
## 感谢以下贡献者
|
||||
|
||||
<a href="https://opencollective.com/gowechat"><img src="https://opencollective.com/gowechat/contributors.svg?width=890" /></a>
|
||||
|
||||
|
||||
## 作者公众号
|
||||
|
||||

|
||||
|
||||
|
||||
6
cache/memcache_test.go
vendored
6
cache/memcache_test.go
vendored
@@ -22,16 +22,12 @@ func TestMemcache(t *testing.T) {
|
||||
exists := mem.IsExist("unknown-key")
|
||||
assert.Equal(t, false, exists)
|
||||
|
||||
name, ok := mem.Get("username").(string)
|
||||
if !ok {
|
||||
t.Error("get Error")
|
||||
}
|
||||
name := mem.Get("username").(string)
|
||||
if name != "" {
|
||||
if name != "silenceper" {
|
||||
t.Error("get Error")
|
||||
}
|
||||
}
|
||||
|
||||
data := mem.Get("unknown-key")
|
||||
assert.Nil(t, data)
|
||||
|
||||
|
||||
47
cache/redis.go
vendored
47
cache/redis.go
vendored
@@ -2,6 +2,8 @@ package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
@@ -15,32 +17,47 @@ type Redis struct {
|
||||
|
||||
// RedisOpts redis 连接属性
|
||||
type RedisOpts struct {
|
||||
Host string `yml:"host" json:"host"`
|
||||
Password string `yml:"password" json:"password"`
|
||||
Database int `yml:"database" json:"database"`
|
||||
MaxIdle int `yml:"max_idle" json:"max_idle"`
|
||||
MaxActive int `yml:"max_active" json:"max_active"`
|
||||
IdleTimeout int `yml:"idle_timeout" json:"idle_timeout"` // second
|
||||
Host string `json:"host" yml:"host"`
|
||||
Username string `json:"username" yaml:"username"`
|
||||
Password string `json:"password" yml:"password"`
|
||||
Database int `json:"database" yml:"database"`
|
||||
MaxIdle int `json:"max_idle" yml:"max_idle"`
|
||||
MaxActive int `json:"max_active" yml:"max_active"`
|
||||
IdleTimeout int `json:"idle_timeout" yml:"idle_timeout"` // second
|
||||
UseTLS bool `json:"use_tls" yml:"use_tls"` // 是否使用TLS
|
||||
}
|
||||
|
||||
// NewRedis 实例化
|
||||
func NewRedis(ctx context.Context, opts *RedisOpts) *Redis {
|
||||
conn := redis.NewUniversalClient(&redis.UniversalOptions{
|
||||
uniOpt := &redis.UniversalOptions{
|
||||
Addrs: []string{opts.Host},
|
||||
DB: opts.Database,
|
||||
Username: opts.Username,
|
||||
Password: opts.Password,
|
||||
IdleTimeout: time.Second * time.Duration(opts.IdleTimeout),
|
||||
MinIdleConns: opts.MaxIdle,
|
||||
})
|
||||
}
|
||||
|
||||
if opts.UseTLS {
|
||||
h, _, err := net.SplitHostPort(opts.Host)
|
||||
if err != nil {
|
||||
h = opts.Host
|
||||
}
|
||||
uniOpt.TLSConfig = &tls.Config{
|
||||
ServerName: h,
|
||||
}
|
||||
}
|
||||
|
||||
conn := redis.NewUniversalClient(uniOpt)
|
||||
return &Redis{ctx: ctx, conn: conn}
|
||||
}
|
||||
|
||||
// SetConn 设置 conn
|
||||
// SetConn 设置conn
|
||||
func (r *Redis) SetConn(conn redis.UniversalClient) {
|
||||
r.conn = conn
|
||||
}
|
||||
|
||||
// SetRedisCtx 设置 redis ctx 参数
|
||||
// SetRedisCtx 设置redis ctx 参数
|
||||
func (r *Redis) SetRedisCtx(ctx context.Context) {
|
||||
r.ctx = ctx
|
||||
}
|
||||
@@ -69,17 +86,15 @@ func (r *Redis) SetContext(ctx context.Context, key string, val interface{}, tim
|
||||
return r.conn.SetEX(ctx, key, val, timeout).Err()
|
||||
}
|
||||
|
||||
// IsExist 判断 key 是否存在
|
||||
// IsExist 判断key是否存在
|
||||
func (r *Redis) IsExist(key string) bool {
|
||||
return r.IsExistContext(r.ctx, key)
|
||||
}
|
||||
|
||||
// IsExistContext 判断 key 是否存在
|
||||
// IsExistContext 判断key是否存在
|
||||
func (r *Redis) IsExistContext(ctx context.Context, key string) bool {
|
||||
result, err := r.conn.Exists(ctx, key).Result()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
result, _ := r.conn.Exists(ctx, key).Result()
|
||||
|
||||
return result > 0
|
||||
}
|
||||
|
||||
|
||||
5
cache/redis_test.go
vendored
5
cache/redis_test.go
vendored
@@ -35,10 +35,7 @@ func TestRedis(t *testing.T) {
|
||||
t.Error("IsExist Error")
|
||||
}
|
||||
|
||||
name, ok := redis.Get(key).(string)
|
||||
if !ok {
|
||||
t.Error("get Error")
|
||||
}
|
||||
name := redis.Get(key).(string)
|
||||
if name != val {
|
||||
t.Error("get Error")
|
||||
}
|
||||
|
||||
@@ -7,6 +7,16 @@ type AccessTokenHandle interface {
|
||||
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 接口
|
||||
type AccessTokenContextHandle interface {
|
||||
AccessTokenHandle
|
||||
|
||||
@@ -12,21 +12,21 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
// accessTokenURL 获取 access_token 的接口
|
||||
// accessTokenURL 获取access_token的接口
|
||||
accessTokenURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"
|
||||
// stableAccessTokenURL 获取稳定版 access_token 的接口
|
||||
// stableAccessTokenURL 获取稳定版access_token的接口
|
||||
stableAccessTokenURL = "https://api.weixin.qq.com/cgi-bin/stable_token"
|
||||
// workAccessTokenURL 企业微信获取 access_token 的接口
|
||||
// workAccessTokenURL 企业微信获取access_token的接口
|
||||
workAccessTokenURL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s"
|
||||
// CacheKeyOfficialAccountPrefix 微信公众号 cache key 前缀
|
||||
// CacheKeyOfficialAccountPrefix 微信公众号cache key前缀
|
||||
CacheKeyOfficialAccountPrefix = "gowechat_officialaccount_"
|
||||
// CacheKeyMiniProgramPrefix 小程序 cache key 前缀
|
||||
// CacheKeyMiniProgramPrefix 小程序cache key前缀
|
||||
CacheKeyMiniProgramPrefix = "gowechat_miniprogram_"
|
||||
// CacheKeyWorkPrefix 企业微信 cache key 前缀
|
||||
// CacheKeyWorkPrefix 企业微信cache key前缀
|
||||
CacheKeyWorkPrefix = "gowechat_work_"
|
||||
)
|
||||
|
||||
// DefaultAccessToken 默认 AccessToken 获取
|
||||
// DefaultAccessToken 默认AccessToken 获取
|
||||
type DefaultAccessToken struct {
|
||||
appID string
|
||||
appSecret string
|
||||
@@ -57,36 +57,34 @@ type ResAccessToken struct {
|
||||
ExpiresIn int64 `json:"expires_in"`
|
||||
}
|
||||
|
||||
// GetAccessToken 获取 access_token,先从 cache 中获取,没有则从服务端获取
|
||||
// GetAccessToken 获取access_token,先从cache中获取,没有则从服务端获取
|
||||
func (ak *DefaultAccessToken) GetAccessToken() (accessToken string, err error) {
|
||||
return ak.GetAccessTokenContext(context.Background())
|
||||
}
|
||||
|
||||
// GetAccessTokenContext 获取 access_token,先从 cache 中获取,没有则从服务端获取
|
||||
// GetAccessTokenContext 获取access_token,先从cache中获取,没有则从服务端获取
|
||||
func (ak *DefaultAccessToken) GetAccessTokenContext(ctx context.Context) (accessToken string, err error) {
|
||||
// 先从 cache 中取
|
||||
// 先从cache中取
|
||||
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.appID)
|
||||
|
||||
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
|
||||
var ok bool
|
||||
if accessToken, ok = val.(string); ok && accessToken != "" {
|
||||
if accessToken = val.(string); accessToken != "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 加上 lock,是为了防止在并发获取 token 时,cache 刚好失效,导致从微信服务器上获取到不同 token
|
||||
// 加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
|
||||
ak.accessTokenLock.Lock()
|
||||
defer ak.accessTokenLock.Unlock()
|
||||
|
||||
// 双检,防止重复从微信服务器获取
|
||||
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
|
||||
var ok bool
|
||||
if accessToken, ok = val.(string); ok && accessToken != "" {
|
||||
if accessToken = val.(string); accessToken != "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// cache 失效,从微信服务器获取
|
||||
// cache失效,从微信服务器获取
|
||||
var resAccessToken ResAccessToken
|
||||
if resAccessToken, err = GetTokenFromServerContext(ctx, fmt.Sprintf(accessTokenURL, ak.appID, ak.appSecret)); err != nil {
|
||||
return
|
||||
@@ -99,14 +97,15 @@ func (ak *DefaultAccessToken) GetAccessTokenContext(ctx context.Context) (access
|
||||
return
|
||||
}
|
||||
|
||||
// StableAccessToken 获取稳定版接口调用凭据 (与 getAccessToken 获取的调用凭证完全隔离,互不影响)
|
||||
// 不强制更新 access_token,可用于不同环境不同服务而不需要分布式锁以及公用缓存,避免 access_token 争抢
|
||||
// StableAccessToken 获取稳定版接口调用凭据(与getAccessToken获取的调用凭证完全隔离,互不影响)
|
||||
// 不强制更新access_token,可用于不同环境不同服务而不需要分布式锁以及公用缓存,避免access_token争抢
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html
|
||||
type StableAccessToken struct {
|
||||
appID string
|
||||
appSecret string
|
||||
cacheKeyPrefix string
|
||||
cache cache.Cache
|
||||
appID string
|
||||
appSecret string
|
||||
cacheKeyPrefix string
|
||||
cache cache.Cache
|
||||
accessTokenLock *sync.Mutex
|
||||
}
|
||||
|
||||
// NewStableAccessToken new StableAccessToken
|
||||
@@ -115,27 +114,41 @@ func NewStableAccessToken(appID, appSecret, cacheKeyPrefix string, cache cache.C
|
||||
panic("cache is need")
|
||||
}
|
||||
return &StableAccessToken{
|
||||
appID: appID,
|
||||
appSecret: appSecret,
|
||||
cache: cache,
|
||||
cacheKeyPrefix: cacheKeyPrefix,
|
||||
appID: appID,
|
||||
appSecret: appSecret,
|
||||
cache: cache,
|
||||
cacheKeyPrefix: cacheKeyPrefix,
|
||||
accessTokenLock: new(sync.Mutex),
|
||||
}
|
||||
}
|
||||
|
||||
// GetAccessToken 获取 access_token,先从 cache 中获取,没有则从服务端获取
|
||||
// GetAccessToken 获取access_token,先从cache中获取,没有则从服务端获取
|
||||
func (ak *StableAccessToken) GetAccessToken() (accessToken string, err error) {
|
||||
return ak.GetAccessTokenContext(context.Background())
|
||||
}
|
||||
|
||||
// GetAccessTokenContext 获取 access_token,先从 cache 中获取,没有则从服务端获取
|
||||
// GetAccessTokenContext 获取access_token,先从cache中获取,没有则从服务端获取
|
||||
func (ak *StableAccessToken) GetAccessTokenContext(ctx context.Context) (accessToken string, err error) {
|
||||
// 先从 cache 中取
|
||||
// 先从cache中取
|
||||
accessTokenCacheKey := fmt.Sprintf("%s_stable_access_token_%s", ak.cacheKeyPrefix, ak.appID)
|
||||
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
|
||||
return val.(string), nil
|
||||
if accessToken = val.(string); accessToken != "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// cache 失效,从微信服务器获取
|
||||
// 加上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失效,从微信服务器获取
|
||||
var resAccessToken ResAccessToken
|
||||
resAccessToken, err = ak.GetAccessTokenDirectly(ctx, false)
|
||||
if err != nil {
|
||||
@@ -149,7 +162,7 @@ func (ak *StableAccessToken) GetAccessTokenContext(ctx context.Context) (accessT
|
||||
return
|
||||
}
|
||||
|
||||
// GetAccessTokenDirectly 从微信获取 access_token
|
||||
// GetAccessTokenDirectly 从微信获取access_token
|
||||
func (ak *StableAccessToken) GetAccessTokenDirectly(ctx context.Context, forceRefresh bool) (resAccessToken ResAccessToken, err error) {
|
||||
b, err := util.PostJSONContext(ctx, stableAccessTokenURL, map[string]interface{}{
|
||||
"grant_type": "client_credential",
|
||||
@@ -172,50 +185,66 @@ func (ak *StableAccessToken) GetAccessTokenDirectly(ctx context.Context, forceRe
|
||||
return
|
||||
}
|
||||
|
||||
// WorkAccessToken 企业微信 AccessToken 获取
|
||||
// WorkAccessToken 企业微信AccessToken 获取
|
||||
type WorkAccessToken struct {
|
||||
CorpID string
|
||||
CorpSecret string
|
||||
AgentID string // 可选,用于区分不同应用
|
||||
cacheKeyPrefix string
|
||||
cache cache.Cache
|
||||
accessTokenLock *sync.Mutex
|
||||
}
|
||||
|
||||
// NewWorkAccessToken new WorkAccessToken
|
||||
func NewWorkAccessToken(corpID, corpSecret, cacheKeyPrefix string, cache cache.Cache) AccessTokenContextHandle {
|
||||
// NewWorkAccessToken new WorkAccessToken (保持向后兼容)
|
||||
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 {
|
||||
panic("cache the not exist")
|
||||
panic("cache is needed")
|
||||
}
|
||||
return &WorkAccessToken{
|
||||
CorpID: corpID,
|
||||
CorpSecret: corpSecret,
|
||||
AgentID: agentID,
|
||||
cache: cache,
|
||||
cacheKeyPrefix: cacheKeyPrefix,
|
||||
accessTokenLock: new(sync.Mutex),
|
||||
}
|
||||
}
|
||||
|
||||
// GetAccessToken 企业微信获取 access_token,先从 cache 中获取,没有则从服务端获取
|
||||
// GetAccessToken 企业微信获取access_token,先从cache中获取,没有则从服务端获取
|
||||
func (ak *WorkAccessToken) GetAccessToken() (accessToken string, err error) {
|
||||
return ak.GetAccessTokenContext(context.Background())
|
||||
}
|
||||
|
||||
// GetAccessTokenContext 企业微信获取 access_token,先从 cache 中获取,没有则从服务端获取
|
||||
// GetAccessTokenContext 企业微信获取access_token,先从cache中获取,没有则从服务端获取
|
||||
func (ak *WorkAccessToken) GetAccessTokenContext(ctx context.Context) (accessToken string, err error) {
|
||||
// 加上 lock,是为了防止在并发获取 token 时,cache 刚好失效,导致从微信服务器上获取到不同 token
|
||||
// 加上lock,是为了防止在并发获取token时,cache刚好失效,导致从微信服务器上获取到不同token
|
||||
ak.accessTokenLock.Lock()
|
||||
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)
|
||||
if val != nil {
|
||||
var ok bool
|
||||
if accessToken, ok = val.(string); !ok {
|
||||
accessToken = ""
|
||||
}
|
||||
accessToken = val.(string)
|
||||
return
|
||||
}
|
||||
|
||||
// cache 失效,从微信服务器获取
|
||||
// cache失效,从微信服务器获取
|
||||
var resAccessToken ResAccessToken
|
||||
resAccessToken, err = GetTokenFromServerContext(ctx, fmt.Sprintf(workAccessTokenURL, ak.CorpID, ak.CorpSecret))
|
||||
if err != nil {
|
||||
@@ -224,17 +253,20 @@ func (ak *WorkAccessToken) GetAccessTokenContext(ctx context.Context) (accessTok
|
||||
|
||||
expires := resAccessToken.ExpiresIn - 1500
|
||||
err = ak.cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
accessToken = resAccessToken.AccessToken
|
||||
return
|
||||
}
|
||||
|
||||
// GetTokenFromServer 强制从微信服务器获取 token
|
||||
// GetTokenFromServer 强制从微信服务器获取token
|
||||
func GetTokenFromServer(url string) (resAccessToken ResAccessToken, err error) {
|
||||
return GetTokenFromServerContext(context.Background(), url)
|
||||
}
|
||||
|
||||
// GetTokenFromServerContext 强制从微信服务器获取 token
|
||||
// GetTokenFromServerContext 强制从微信服务器获取token
|
||||
func GetTokenFromServerContext(ctx context.Context, url string) (resAccessToken ResAccessToken, err error) {
|
||||
var body []byte
|
||||
body, err = util.HTTPGetContext(ctx, url)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package credential
|
||||
|
||||
import (
|
||||
context2 "context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
@@ -10,15 +11,15 @@ import (
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
// getTicketURL 获取 ticket 的 url
|
||||
// getTicketURL 获取ticket的url
|
||||
const getTicketURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi"
|
||||
|
||||
// DefaultJsTicket 默认获取 js ticket 方法
|
||||
// DefaultJsTicket 默认获取js ticket方法
|
||||
type DefaultJsTicket struct {
|
||||
appID string
|
||||
cacheKeyPrefix string
|
||||
cache cache.Cache
|
||||
// jsAPITicket 读写锁 同一个 AppID 一个
|
||||
// jsAPITicket 读写锁 同一个AppID一个
|
||||
jsAPITicketLock *sync.Mutex
|
||||
}
|
||||
|
||||
@@ -32,7 +33,7 @@ func NewDefaultJsTicket(appID string, cacheKeyPrefix string, cache cache.Cache)
|
||||
}
|
||||
}
|
||||
|
||||
// ResTicket 请求 jsapi_tikcet 返回结果
|
||||
// ResTicket 请求jsapi_tikcet返回结果
|
||||
type ResTicket struct {
|
||||
util.CommonError
|
||||
|
||||
@@ -40,9 +41,19 @@ type ResTicket struct {
|
||||
ExpiresIn int64 `json:"expires_in"`
|
||||
}
|
||||
|
||||
// GetTicket 获取 jsapi_ticket
|
||||
// GetTicket 获取jsapi_ticket
|
||||
func (js *DefaultJsTicket) GetTicket(accessToken string) (ticketStr string, err error) {
|
||||
// 先从 cache 中取
|
||||
return js.GetTicketContext(context2.Background(), accessToken)
|
||||
}
|
||||
|
||||
// GetTicketFromServer 从服务器中获取ticket
|
||||
func GetTicketFromServer(accessToken string) (ticket ResTicket, err error) {
|
||||
return GetTicketFromServerContext(context2.Background(), accessToken)
|
||||
}
|
||||
|
||||
// GetTicketContext 获取jsapi_ticket
|
||||
func (js *DefaultJsTicket) GetTicketContext(ctx context2.Context, accessToken string) (ticketStr string, err error) {
|
||||
// 先从cache中取
|
||||
jsAPITicketCacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", js.cacheKeyPrefix, js.appID)
|
||||
if val := js.cache.Get(jsAPITicketCacheKey); val != nil {
|
||||
return val.(string), nil
|
||||
@@ -57,7 +68,7 @@ func (js *DefaultJsTicket) GetTicket(accessToken string) (ticketStr string, err
|
||||
}
|
||||
|
||||
var ticket ResTicket
|
||||
ticket, err = GetTicketFromServer(accessToken)
|
||||
ticket, err = GetTicketFromServerContext(ctx, accessToken)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -67,11 +78,11 @@ func (js *DefaultJsTicket) GetTicket(accessToken string) (ticketStr string, err
|
||||
return
|
||||
}
|
||||
|
||||
// GetTicketFromServer 从服务器中获取 ticket
|
||||
func GetTicketFromServer(accessToken string) (ticket ResTicket, err error) {
|
||||
// GetTicketFromServerContext 从服务器中获取ticket
|
||||
func GetTicketFromServerContext(ctx context2.Context, accessToken string) (ticket ResTicket, err error) {
|
||||
var response []byte
|
||||
url := fmt.Sprintf(getTicketURL, accessToken)
|
||||
response, err = util.HTTPGet(url)
|
||||
response, err = util.HTTPGetContext(ctx, url)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
22
credential/default_js_ticket_test.go
Normal file
22
credential/default_js_ticket_test.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package credential
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"gopkg.in/h2non/gock.v1"
|
||||
)
|
||||
|
||||
// TestGetTicketFromServerContext 测试 GetTicketFromServerContext 函数
|
||||
func TestGetTicketFromServerContext(t *testing.T) {
|
||||
defer gock.Off()
|
||||
gock.New(fmt.Sprintf(getTicketURL, "arg-ak")).Reply(200).JSON(&ResTicket{Ticket: "mock-ticket", ExpiresIn: 10})
|
||||
|
||||
ticket, err := GetTicketFromServerContext(context.Background(), "arg-ak")
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, int64(0), ticket.ErrCode)
|
||||
assert.Equal(t, "mock-ticket", ticket.Ticket, "they should be equal")
|
||||
assert.Equal(t, int64(10), ticket.ExpiresIn, "they should be equal")
|
||||
}
|
||||
@@ -1,7 +1,15 @@
|
||||
package credential
|
||||
|
||||
// JsTicketHandle js ticket 获取
|
||||
import context2 "context"
|
||||
|
||||
// JsTicketHandle js ticket获取
|
||||
type JsTicketHandle interface {
|
||||
// GetTicket 获取 ticket
|
||||
// GetTicket 获取ticket
|
||||
GetTicket(accessToken string) (ticket string, err error)
|
||||
}
|
||||
|
||||
// JsTicketContextHandle js ticket获取
|
||||
type JsTicketContextHandle interface {
|
||||
JsTicketHandle
|
||||
GetTicketContext(ctx context2.Context, accessToken string) (ticket string, err error)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
2
doc.go
2
doc.go
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Package wechat provide wechat sdk for go
|
||||
|
||||
使用 Golang 开发的微信 SDK,简单、易用。
|
||||
使用Golang开发的微信SDK,简单、易用。
|
||||
|
||||
|
||||
更多信息:https://github.com/silenceper/wechat
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# API 文档
|
||||
|
||||
已完成以及未完成 API 列表汇总
|
||||
已完成以及未完成API列表汇总
|
||||
|
||||
如果有兴趣参与贡献,可以在具体的 API 表格后面标识自己为贡献者以及完成时间,例如:
|
||||
如果有兴趣参与贡献,可以在具体的API表格后面标识自己为贡献者以及完成时间,例如:
|
||||
|
||||
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |贡献者 | 完成时间|
|
||||
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |贡献者|完成时间|
|
||||
| :---------------------: | -------- | :------------------------- | ---------- | -------- |-------- |-------- |
|
||||
| 获取公众号类目 | GET | /wxaapi/newtmpl/getcategory | NO | |silenceper| 2021-12-20|
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ TODO
|
||||
|
||||
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
|
||||
| :----------------: | -------- | :------------------------------- | ---------- | ----------------------------------- |
|
||||
| code 换取用户手机号 | POST | /wxa/business/getuserphonenumber | YES | (business *Business) GetPhoneNumber |
|
||||
| code换取用户手机号 | POST | /wxa/business/getuserphonenumber | YES | (business *Business) GetPhoneNumber |
|
||||
|
||||
|
||||
## 安全风控
|
||||
|
||||
@@ -155,7 +155,7 @@
|
||||
| 通过网页授权的 code 换取 access_token(区别于 context 中的 access_token) | GET | /sns/oauth2/access_token | YES | (oauth \*Oauth) GetUserAccessToken |
|
||||
| 刷新 access_token | GET | /sns/oauth2/refresh_token? | YES | (oauth \*Oauth) RefreshAccessToken |
|
||||
| 检验 access_token 是否有效 | GET | /sns/auth | YES | (oauth \*Oauth) CheckAccessToken( |
|
||||
| 拉取用户信息 (需 scope 为 snsapi_userinfo) | GET | /sns/userinfo | YES | (oauth \*Oauth) GetUserInfo |
|
||||
| 拉取用户信息(需 scope 为 snsapi_userinfo) | GET | /sns/userinfo | YES | (oauth \*Oauth) GetUserInfo |
|
||||
| 获取 jssdk 需要的配置参数 | GET | /cgi-bin/ticket/getticket | YES | (js \*Js) GetConfig |
|
||||
|
||||
## 素材管理
|
||||
|
||||
@@ -89,10 +89,10 @@ host: https://qyapi.weixin.qq.com/
|
||||
|
||||
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 | 贡献者 |
|
||||
|:---------:|------|:----------------------------------------| ---------- | ------------------------------- |----------|
|
||||
| 获取子部门 ID 列表 | GET | /cgi-bin/department/simplelist | YES | (r *Client) DepartmentSimpleList| MARKWANG |
|
||||
| 获取子部门ID列表 | GET | /cgi-bin/department/simplelist | YES | (r *Client) DepartmentSimpleList| MARKWANG |
|
||||
| 获取部门列表 | GET | /cgi-bin/department/list | YES | (r *Client) DepartmentList| just5325, ourines |
|
||||
| 获取部门成员 | GET | /cgi-bin/user/simplelist | YES | (r *Client) UserSimpleList | MARKWANG |
|
||||
| 获取成员 ID 列表 | Post | /cgi-bin/user/list_id | YES | (r *Client) UserListId | MARKWANG |
|
||||
| 获取成员ID列表 | Post | /cgi-bin/user/list_id | YES | (r *Client) UserListId | MARKWANG |
|
||||
|
||||
|
||||
|
||||
|
||||
30
go.mod
30
go.mod
@@ -1,30 +1,16 @@
|
||||
module github.com/silenceper/wechat/v2
|
||||
|
||||
go 1.18
|
||||
go 1.16
|
||||
|
||||
require (
|
||||
github.com/alicebob/miniredis/v2 v2.33.0
|
||||
github.com/bradfitz/gomemcache v0.0.0-20230905024940-24af94b03874
|
||||
github.com/alicebob/miniredis/v2 v2.30.0
|
||||
github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d
|
||||
github.com/fatih/structs v1.1.0
|
||||
github.com/go-redis/redis/v8 v8.11.5
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/spf13/cast v1.6.0
|
||||
github.com/stretchr/testify v1.9.0
|
||||
github.com/tidwall/gjson v1.17.1
|
||||
golang.org/x/crypto v0.25.0
|
||||
github.com/sirupsen/logrus v1.9.0
|
||||
github.com/spf13/cast v1.4.1
|
||||
github.com/stretchr/testify v1.7.1
|
||||
github.com/tidwall/gjson v1.14.1
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d
|
||||
gopkg.in/h2non/gock.v1 v1.1.2
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.0 // indirect
|
||||
github.com/yuin/gopher-lua v1.1.1 // indirect
|
||||
golang.org/x/sys v0.22.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
137
go.sum
137
go.sum
@@ -1,11 +1,14 @@
|
||||
github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a h1:HbKu58rmZpUGpz5+4FfNmIU+FmZg2P3Xaj2v2bfNWmk=
|
||||
github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
|
||||
github.com/alicebob/miniredis/v2 v2.33.0 h1:uvTF0EDeu9RLnUEG27Db5I68ESoIxTiXbNUiji6lZrA=
|
||||
github.com/alicebob/miniredis/v2 v2.33.0/go.mod h1:MhP4a3EU7aENRi9aO+tHfTBZicLqQevyi/DJpoj6mi0=
|
||||
github.com/bradfitz/gomemcache v0.0.0-20230905024940-24af94b03874 h1:N7oVaKyGp8bttX0bfZGmcGkjz7DLQXhAn3DNd3T0ous=
|
||||
github.com/bradfitz/gomemcache v0.0.0-20230905024940-24af94b03874/go.mod h1:r5xuitiExdLAJ09PR7vBVENGvp4ZuTBeWTGtxuX3K+c=
|
||||
github.com/alicebob/miniredis/v2 v2.30.0 h1:uA3uhDbCxfO9+DI/DuGeAMr9qI+noVWwGPNTFuKID5M=
|
||||
github.com/alicebob/miniredis/v2 v2.30.0/go.mod h1:84TWKZlxYkfgMucPBf5SOQBYJceZeQRFIaQgNMiCX6Q=
|
||||
github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d h1:pVrfxiGfwelyab6n21ZBkbkmbevaf+WvMIiR7sr97hw=
|
||||
github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
|
||||
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
|
||||
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
||||
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
@@ -13,52 +16,132 @@ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/r
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
|
||||
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
|
||||
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw=
|
||||
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4=
|
||||
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms=
|
||||
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
|
||||
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
|
||||
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
|
||||
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
|
||||
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
|
||||
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
|
||||
github.com/onsi/ginkgo/v2 v2.0.0/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c=
|
||||
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
|
||||
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
|
||||
github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
|
||||
github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
|
||||
github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
|
||||
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
|
||||
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/spf13/cast v1.4.1 h1:s0hze+J0196ZfEMTs80N7UlFt0BDuQ7Q+JDnHiMWKdA=
|
||||
github.com/spf13/cast v1.4.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/tidwall/gjson v1.17.1 h1:wlYEnwqAHgzmhNUFfw7Xalt2JzQvsMx2Se4PcoFCT/U=
|
||||
github.com/tidwall/gjson v1.17.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/tidwall/gjson v1.14.1 h1:iymTbGkQBhveq21bEvAQ81I0LEBork8BFe1CUZXdyuo=
|
||||
github.com/tidwall/gjson v1.14.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
|
||||
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
||||
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
|
||||
golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30=
|
||||
golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M=
|
||||
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/gopher-lua v0.0.0-20220504180219-658193537a64 h1:5mLPGnFdSsevFRFc9q3yYbBkB6tsm4aCwwQV/j1JQAQ=
|
||||
github.com/yuin/gopher-lua v0.0.0-20220504180219-658193537a64/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d h1:sK3txAijHtOK88l68nt020reeT1ZdKLIYetKl95FzVY=
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
|
||||
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/h2non/gock.v1 v1.1.2 h1:jBbHXgGBK/AoPVfJh5x4r/WxIrElvbLel8TCZkkZJoY=
|
||||
gopkg.in/h2non/gock.v1 v1.1.2/go.mod h1:n7UGz/ckNChHiK05rDoiC4MYSunEC/lyaUm2WWaDva0=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
@@ -11,13 +11,13 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
clearQuotaURL = "https://api.weixin.qq.com/cgi-bin/clear_quota" // 重置 API 调用次数
|
||||
getAPIQuotaURL = "https://api.weixin.qq.com/cgi-bin/openapi/quota/get" // 查询 API 调用额度
|
||||
getRidInfoURL = "https://api.weixin.qq.com/cgi-bin/openapi/rid/get" // 查询 rid 信息
|
||||
clearQuotaByAppSecretURL = "https://api.weixin.qq.com/cgi-bin/clear_quota/v2" // 使用 AppSecret 重置 API 调用次数
|
||||
clearQuotaURL = "https://api.weixin.qq.com/cgi-bin/clear_quota" // 重置API调用次数
|
||||
getAPIQuotaURL = "https://api.weixin.qq.com/cgi-bin/openapi/quota/get" // 查询API调用额度
|
||||
getRidInfoURL = "https://api.weixin.qq.com/cgi-bin/openapi/rid/get" // 查询rid信息
|
||||
clearQuotaByAppSecretURL = "https://api.weixin.qq.com/cgi-bin/clear_quota/v2" // 使用AppSecret重置 API 调用次数
|
||||
)
|
||||
|
||||
// OpenAPI openApi 管理
|
||||
// OpenAPI openApi管理
|
||||
type OpenAPI struct {
|
||||
ctx interface{}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ func NewOpenAPI(ctx interface{}) *OpenAPI {
|
||||
return &OpenAPI{ctx: ctx}
|
||||
}
|
||||
|
||||
// ClearQuota 重置 API 调用次数
|
||||
// ClearQuota 重置API调用次数
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/openApi-mgnt/clearQuota.html
|
||||
func (o *OpenAPI) ClearQuota() error {
|
||||
appID, _, err := o.getAppIDAndSecret()
|
||||
@@ -48,7 +48,7 @@ func (o *OpenAPI) ClearQuota() error {
|
||||
return util.DecodeWithCommonError(res, "ClearQuota")
|
||||
}
|
||||
|
||||
// GetAPIQuota 查询 API 调用额度
|
||||
// GetAPIQuota 查询API调用额度
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/openApi-mgnt/getApiQuota.html
|
||||
func (o *OpenAPI) GetAPIQuota(params openapi.GetAPIQuotaParams) (quota openapi.APIQuota, err error) {
|
||||
res, err := o.doPostRequest(getAPIQuotaURL, params)
|
||||
@@ -60,7 +60,7 @@ func (o *OpenAPI) GetAPIQuota(params openapi.GetAPIQuotaParams) (quota openapi.A
|
||||
return
|
||||
}
|
||||
|
||||
// GetRidInfo 查询 rid 信息
|
||||
// GetRidInfo 查询rid信息
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/openApi-mgnt/getRidInfo.html
|
||||
func (o *OpenAPI) GetRidInfo(params openapi.GetRidInfoParams) (r openapi.RidInfo, err error) {
|
||||
res, err := o.doPostRequest(getRidInfoURL, params)
|
||||
@@ -72,7 +72,7 @@ func (o *OpenAPI) GetRidInfo(params openapi.GetRidInfoParams) (r openapi.RidInfo
|
||||
return
|
||||
}
|
||||
|
||||
// ClearQuotaByAppSecret 使用 AppSecret 重置 API 调用次数
|
||||
// ClearQuotaByAppSecret 使用AppSecret重置 API 调用次数
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/openApi-mgnt/clearQuotaByAppSecret.html
|
||||
func (o *OpenAPI) ClearQuotaByAppSecret() error {
|
||||
id, secret, err := o.getAppIDAndSecret()
|
||||
@@ -93,16 +93,10 @@ func (o *OpenAPI) ClearQuotaByAppSecret() error {
|
||||
func (o *OpenAPI) getAppIDAndSecret() (string, string, error) {
|
||||
switch o.ctx.(type) {
|
||||
case *mpContext.Context:
|
||||
c, ok := o.ctx.(*mpContext.Context)
|
||||
if !ok {
|
||||
return "", "", errors.New("invalid context type")
|
||||
}
|
||||
c := o.ctx.(*mpContext.Context)
|
||||
return c.AppID, c.AppSecret, nil
|
||||
case *ocContext.Context:
|
||||
c, ok := o.ctx.(*ocContext.Context)
|
||||
if !ok {
|
||||
return "", "", errors.New("invalid context type")
|
||||
}
|
||||
c := o.ctx.(*ocContext.Context)
|
||||
return c.AppID, c.AppSecret, nil
|
||||
default:
|
||||
return "", "", errors.New("invalid context type")
|
||||
|
||||
@@ -30,6 +30,8 @@ const (
|
||||
getAnalysisVisitDistributionURL = "https://api.weixin.qq.com/datacube/getweanalysisappidvisitdistribution?access_token=%s"
|
||||
// 访问页面
|
||||
getAnalysisVisitPageURL = "https://api.weixin.qq.com/datacube/getweanalysisappidvisitpage?access_token=%s"
|
||||
// 获取小程序性能数据
|
||||
getPerformanceDataURL = "https://api.weixin.qq.com/wxa/business/performance/boot?access_token=%s"
|
||||
)
|
||||
|
||||
// Analysis analyis 数据分析
|
||||
@@ -56,8 +58,8 @@ func (analysis *Analysis) fetchData(urlStr string, body interface{}) (response [
|
||||
|
||||
// RetainItem 留存项结构
|
||||
type RetainItem struct {
|
||||
Key int `json:"key"` // 标识,0 开始表示当天,1 表示 1 甜后,以此类推
|
||||
Value int `json:"value"` // key 对应日期的新增用户数/活跃用户数(key=0 时)或留存用户数(k>0 时)
|
||||
Key int `json:"key"` // 标识,0开始表示当天,1表示1甜后,以此类推
|
||||
Value int `json:"value"` // key对应日期的新增用户数/活跃用户数(key=0时)或留存用户数(k>0时)
|
||||
}
|
||||
|
||||
// ResAnalysisRetain 小程序留存数据返回
|
||||
@@ -68,7 +70,7 @@ type ResAnalysisRetain struct {
|
||||
VisitUV []RetainItem `json:"visit_uv"` // 活跃用户留存
|
||||
}
|
||||
|
||||
// getAnalysisRetain 获取用户访问小程序留存数据 (日、月、周)
|
||||
// getAnalysisRetain 获取用户访问小程序留存数据(日、月、周)
|
||||
func (analysis *Analysis) getAnalysisRetain(urlStr string, beginDate, endDate string) (result ResAnalysisRetain, err error) {
|
||||
body := map[string]string{
|
||||
"begin_date": beginDate,
|
||||
@@ -137,7 +139,7 @@ func (analysis *Analysis) GetAnalysisDailySummary(beginDate, endDate string) (re
|
||||
return
|
||||
}
|
||||
|
||||
// ResAnalysisVisitTrend 小程序访问数据趋势 (日、月、周)
|
||||
// ResAnalysisVisitTrend 小程序访问数据趋势(日、月、周)
|
||||
type ResAnalysisVisitTrend struct {
|
||||
util.CommonError
|
||||
List []struct {
|
||||
@@ -152,7 +154,7 @@ type ResAnalysisVisitTrend struct {
|
||||
} `json:"list"`
|
||||
}
|
||||
|
||||
// getAnalysisRetain 获取小程序访问数据趋势 (日、月、周)
|
||||
// getAnalysisRetain 获取小程序访问数据趋势(日、月、周)
|
||||
func (analysis *Analysis) getAnalysisVisitTrend(urlStr string, beginDate, endDate string) (result ResAnalysisVisitTrend, err error) {
|
||||
body := map[string]string{
|
||||
"begin_date": beginDate,
|
||||
@@ -190,9 +192,9 @@ func (analysis *Analysis) GetAnalysisWeeklyVisitTrend(beginDate, endDate string)
|
||||
|
||||
// UserPortraitItem 用户画像项目
|
||||
type UserPortraitItem struct {
|
||||
ID int `json:"id"` // 属性值 id
|
||||
ID int `json:"id"` // 属性值id
|
||||
Name string `json:"name"` // 属性值名称
|
||||
Value int `json:"value"` // 该场景访问 uv
|
||||
Value int `json:"value"` // 该场景访问uv
|
||||
}
|
||||
|
||||
// UserPortrait 用户画像
|
||||
@@ -201,9 +203,9 @@ type UserPortrait struct {
|
||||
Province []UserPortraitItem `json:"province"` // 省份,如北京、广东等
|
||||
City []UserPortraitItem `json:"city"` // 城市,如北京、广州等
|
||||
Genders []UserPortraitItem `json:"genders"` // 性别,包括男、女、未知
|
||||
Platforms []UserPortraitItem `json:"platforms"` // 终端类型,包括 iPhone, android, 其他
|
||||
Devices []UserPortraitItem `json:"devices"` // 机型,如苹果 iPhone 6, OPPO R9 等
|
||||
Ages []UserPortraitItem `json:"ages"` // 年龄,包括 17 岁以下、18-24 对等区间
|
||||
Platforms []UserPortraitItem `json:"platforms"` // 终端类型,包括iPhone, android, 其他
|
||||
Devices []UserPortraitItem `json:"devices"` // 机型,如苹果iPhone 6, OPPO R9等
|
||||
Ages []UserPortraitItem `json:"ages"` // 年龄,包括17岁以下、18-24对等区间
|
||||
}
|
||||
|
||||
// ResAnalysisUserPortrait 小程序新增或活跃用户的画像分布数据返回
|
||||
@@ -237,9 +239,9 @@ func (analysis *Analysis) GetAnalysisUserPortrait(beginDate, endDate string) (re
|
||||
|
||||
// VisitDistributionIndexItem 访问分数数据结构
|
||||
type VisitDistributionIndexItem struct {
|
||||
Key int `json:"key"` // 场景 id
|
||||
Value int `json:"value"` // 该场景 id 访问 pv
|
||||
AccessSourceVisitUV int `json:"access_source_visit_uv"` // 该场景 id 访问 uv
|
||||
Key int `json:"key"` // 场景id
|
||||
Value int `json:"value"` // 该场景id访问pv
|
||||
AccessSourceVisitUV int `json:"access_source_visit_uv"` // 该场景id访问uv
|
||||
}
|
||||
|
||||
// VisitDistributionIndex 访问分布单分布类型数据
|
||||
@@ -315,3 +317,67 @@ func (analysis *Analysis) GetAnalysisVisitPage(beginDate, endDate string) (resul
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// GetPerformanceDataRequest 获取小程序性能数据请求
|
||||
type GetPerformanceDataRequest struct {
|
||||
Module string `json:"module"`
|
||||
Time PerformanceDataTime `json:"time"`
|
||||
Params []PerformanceDataParams `json:"params"`
|
||||
}
|
||||
|
||||
// PerformanceDataTime 获取小程序性能数据开始和结束日期
|
||||
type PerformanceDataTime struct {
|
||||
BeginTimestamp int64 `json:"begin_timestamp"`
|
||||
EndTimestamp int64 `json:"end_timestamp"`
|
||||
}
|
||||
|
||||
// PerformanceDataParams 获取小程序性能数据查询条件
|
||||
type PerformanceDataParams struct {
|
||||
Field string `json:"field"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// GetPerformanceDataResponse 获取小程序性能数据响应
|
||||
type GetPerformanceDataResponse struct {
|
||||
util.CommonError
|
||||
Body PerformanceDataBody `json:"body"`
|
||||
}
|
||||
|
||||
// PerformanceDataBody 性能数据
|
||||
type PerformanceDataBody struct {
|
||||
Tables []PerformanceDataTable `json:"tables"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
// PerformanceDataTable 数据数组
|
||||
type PerformanceDataTable struct {
|
||||
ID string `json:"id"`
|
||||
Lines []PerformanceDataTableLine `json:"lines"`
|
||||
Zh string `json:"zh"`
|
||||
}
|
||||
|
||||
// PerformanceDataTableLine 按时间排列的性能数据
|
||||
type PerformanceDataTableLine struct {
|
||||
Fields []PerformanceDataTableLineField `json:"fields"`
|
||||
}
|
||||
|
||||
// PerformanceDataTableLineField 单天的性能数据
|
||||
type PerformanceDataTableLineField struct {
|
||||
RefDate string `json:"refdate"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// GetPerformanceData 获取小程序性能数据
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/data-analysis/others/getPerformanceData.html
|
||||
func (analysis *Analysis) GetPerformanceData(req *GetPerformanceDataRequest) (res GetPerformanceDataResponse, err error) {
|
||||
var accessToken string
|
||||
if accessToken, err = analysis.GetAccessToken(); err != nil {
|
||||
return
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.PostJSON(fmt.Sprintf(getPerformanceDataURL, accessToken), req); err != nil {
|
||||
return
|
||||
}
|
||||
err = util.DecodeWithError(response, &res, "GetPerformanceData")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -10,11 +10,22 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
// code2SessionURL 小程序登录
|
||||
code2SessionURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
|
||||
|
||||
// checkEncryptedDataURL 检查加密信息
|
||||
checkEncryptedDataURL = "https://api.weixin.qq.com/wxa/business/checkencryptedmsg?access_token=%s"
|
||||
|
||||
// getPhoneNumber 获取手机号
|
||||
getPhoneNumber = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s"
|
||||
// checkSessionURL 检验登录态
|
||||
checkSessionURL = "https://api.weixin.qq.com/wxa/checksession?access_token=%s&signature=%s&openid=%s&sig_method=hmac_sha256"
|
||||
// resetUserSessionKeyURL 重置登录态
|
||||
resetUserSessionKeyURL = "https://api.weixin.qq.com/wxa/resetusersessionkey?access_token=%s&signature=%s&openid=%s&sig_method=hmac_sha256"
|
||||
// getPluginOpenPIDURL 获取插件用户openPID
|
||||
getPluginOpenPIDURL = "https://api.weixin.qq.com/wxa/getpluginopenpid?access_token=%s"
|
||||
// getPaidUnionIDURL 支付后获取 UnionID
|
||||
getPaidUnionIDURL = "https://api.weixin.qq.com/wxa/getpaidunionid"
|
||||
// getUserEncryptKeyURL 获取用户encryptKey
|
||||
getUserEncryptKeyURL = "https://api.weixin.qq.com/wxa/business/getuserencryptkey?access_token=%s&signature=%s&openid=%s&sig_method=hmac_sha256"
|
||||
)
|
||||
|
||||
// Auth 登录/用户信息
|
||||
@@ -33,7 +44,7 @@ type ResCode2Session struct {
|
||||
|
||||
OpenID string `json:"openid"` // 用户唯一标识
|
||||
SessionKey string `json:"session_key"` // 会话密钥
|
||||
UnionID string `json:"unionid"` // 用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回
|
||||
UnionID string `json:"unionid"` // 用户在开放平台的唯一标识符,在满足UnionID下发条件的情况下会返回
|
||||
}
|
||||
|
||||
// RspCheckEncryptedData .
|
||||
@@ -65,27 +76,63 @@ func (auth *Auth) Code2SessionContext(ctx context2.Context, jsCode string) (resu
|
||||
return
|
||||
}
|
||||
|
||||
type (
|
||||
// GetPaidUnionIDRequest 支付后获取UnionID请求
|
||||
GetPaidUnionIDRequest struct {
|
||||
OpenID string `json:"openid"`
|
||||
TransactionID string `json:"transaction_id,omitempty"`
|
||||
MchID string `json:"mch_id,omitempty"`
|
||||
OutTradeNo string `json:"out_trade_no,omitempty"`
|
||||
}
|
||||
|
||||
// GetPaidUnionIDResponse 支付后获取UnionID响应
|
||||
GetPaidUnionIDResponse struct {
|
||||
util.CommonError
|
||||
UnionID string `json:"unionid"`
|
||||
}
|
||||
)
|
||||
|
||||
// GetPaidUnionID 用户支付完成后,获取该用户的 UnionId,无需用户授权
|
||||
func (auth *Auth) GetPaidUnionID() {
|
||||
// TODO
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/basic-info/getPaidUnionid.html
|
||||
func (auth *Auth) GetPaidUnionID(req *GetPaidUnionIDRequest) (string, error) {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = auth.GetAccessToken(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
var url string
|
||||
if req.TransactionID != "" {
|
||||
url = fmt.Sprintf("%s?access_token=%s&openid=%s&transaction_id=%s", getPaidUnionIDURL, accessToken, req.OpenID, req.TransactionID)
|
||||
} else {
|
||||
url = fmt.Sprintf("%s?access_token=%s&openid=%s&mch_id=%s&out_trade_no=%s", getPaidUnionIDURL, accessToken, req.OpenID, req.MchID, req.OutTradeNo)
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.HTTPGet(url); err != nil {
|
||||
return "", err
|
||||
}
|
||||
result := &GetPaidUnionIDResponse{}
|
||||
err = util.DecodeWithError(response, result, "GetPaidUnionID")
|
||||
return result.UnionID, err
|
||||
}
|
||||
|
||||
// CheckEncryptedData .检查加密信息是否由微信生成(当前只支持手机号加密数据),只能检测最近 3 天生成的加密数据
|
||||
// CheckEncryptedData .检查加密信息是否由微信生成(当前只支持手机号加密数据),只能检测最近3天生成的加密数据
|
||||
func (auth *Auth) CheckEncryptedData(encryptedMsgHash string) (result RspCheckEncryptedData, err error) {
|
||||
return auth.CheckEncryptedDataContext(context2.Background(), encryptedMsgHash)
|
||||
}
|
||||
|
||||
// CheckEncryptedDataContext .检查加密信息是否由微信生成(当前只支持手机号加密数据),只能检测最近 3 天生成的加密数据
|
||||
// CheckEncryptedDataContext .检查加密信息是否由微信生成(当前只支持手机号加密数据),只能检测最近3天生成的加密数据
|
||||
func (auth *Auth) CheckEncryptedDataContext(ctx context2.Context, encryptedMsgHash string) (result RspCheckEncryptedData, err error) {
|
||||
var response []byte
|
||||
var (
|
||||
at string
|
||||
)
|
||||
if at, err = auth.GetAccessToken(); err != nil {
|
||||
if at, err = auth.GetAccessTokenContext(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 由于 GetPhoneNumberContext 需要传入 JSON,所以 HTTPPostContext 入参改为 []byte
|
||||
// 由于GetPhoneNumberContext需要传入JSON,所以HTTPPostContext入参改为[]byte
|
||||
if response, err = util.HTTPPostContext(ctx, fmt.Sprintf(checkEncryptedDataURL, at), []byte("encrypted_msg_hash="+encryptedMsgHash), nil); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -113,14 +160,14 @@ type PhoneInfo struct {
|
||||
} `json:"watermark"` // 数据水印
|
||||
}
|
||||
|
||||
// GetPhoneNumberContext 小程序通过 code 获取用户手机号
|
||||
// GetPhoneNumberContext 小程序通过code获取用户手机号
|
||||
func (auth *Auth) GetPhoneNumberContext(ctx context2.Context, code string) (*GetPhoneNumberResponse, error) {
|
||||
var response []byte
|
||||
var (
|
||||
at string
|
||||
err error
|
||||
)
|
||||
if at, err = auth.GetAccessToken(); err != nil {
|
||||
if at, err = auth.GetAccessTokenContext(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body := map[string]interface{}{
|
||||
@@ -142,7 +189,119 @@ func (auth *Auth) GetPhoneNumberContext(ctx context2.Context, code string) (*Get
|
||||
return &result, err
|
||||
}
|
||||
|
||||
// GetPhoneNumber 小程序通过 code 获取用户手机号
|
||||
// GetPhoneNumber 小程序通过code获取用户手机号
|
||||
func (auth *Auth) GetPhoneNumber(code string) (*GetPhoneNumberResponse, error) {
|
||||
return auth.GetPhoneNumberContext(context2.Background(), code)
|
||||
}
|
||||
|
||||
// CheckSession 检验登录态
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/checkSessionKey.html
|
||||
func (auth *Auth) CheckSession(signature, openID string) error {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = auth.GetAccessToken(); err != nil {
|
||||
return err
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.HTTPGet(fmt.Sprintf(checkSessionURL, accessToken, signature, openID)); err != nil {
|
||||
return err
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "CheckSession")
|
||||
}
|
||||
|
||||
// ResetUserSessionKeyResponse 重置登录态响应
|
||||
type ResetUserSessionKeyResponse struct {
|
||||
util.CommonError
|
||||
OpenID string `json:"openid"`
|
||||
SessionKey string `json:"session_key"`
|
||||
}
|
||||
|
||||
// ResetUserSessionKey 重置登录态
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/ResetUserSessionKey.html
|
||||
func (auth *Auth) ResetUserSessionKey(signature, openID string) (*ResetUserSessionKeyResponse, error) {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = auth.GetAccessToken(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.HTTPGet(fmt.Sprintf(resetUserSessionKeyURL, accessToken, signature, openID)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &ResetUserSessionKeyResponse{}
|
||||
err = util.DecodeWithError(response, result, "ResetUserSessionKey")
|
||||
return result, err
|
||||
}
|
||||
|
||||
type (
|
||||
// GetPluginOpenPIDRequest 获取插件用户openPID请求
|
||||
GetPluginOpenPIDRequest struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
// GetPluginOpenPIDResponse 获取插件用户openPID响应
|
||||
GetPluginOpenPIDResponse struct {
|
||||
util.CommonError
|
||||
OpenPID string `json:"openpid"`
|
||||
}
|
||||
)
|
||||
|
||||
// GetPluginOpenPID 获取插件用户openPID
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/basic-info/getPluginOpenPId.html
|
||||
func (auth *Auth) GetPluginOpenPID(code string) (string, error) {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = auth.GetAccessToken(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
req := &GetPluginOpenPIDRequest{
|
||||
Code: code,
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.PostJSON(fmt.Sprintf(getPluginOpenPIDURL, accessToken), req); err != nil {
|
||||
return "", err
|
||||
}
|
||||
result := &GetPluginOpenPIDResponse{}
|
||||
err = util.DecodeWithError(response, result, "GetPluginOpenPID")
|
||||
return result.OpenPID, err
|
||||
}
|
||||
|
||||
// GetUserEncryptKeyResponse 获取用户encryptKey响应
|
||||
type GetUserEncryptKeyResponse struct {
|
||||
util.CommonError
|
||||
KeyInfoList []KeyInfo `json:"key_info_list"`
|
||||
}
|
||||
|
||||
// KeyInfo 用户最近三次的加密key
|
||||
type KeyInfo struct {
|
||||
EncryptKey string `json:"encrypt_key"`
|
||||
Version int64 `json:"version"`
|
||||
ExpireIn int64 `json:"expire_in"`
|
||||
Iv string `json:"iv"`
|
||||
CreateTime int64 `json:"create_time"`
|
||||
}
|
||||
|
||||
// GetUserEncryptKey 获取用户encryptKey
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/internet/getUserEncryptKey.html
|
||||
func (auth *Auth) GetUserEncryptKey(signature, openID string) (*GetUserEncryptKeyResponse, error) {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = auth.GetAccessToken(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.HTTPGet(fmt.Sprintf(getUserEncryptKeyURL, accessToken, signature, openID)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &GetUserEncryptKeyResponse{}
|
||||
err = util.DecodeWithError(response, result, "GetUserEncryptKey")
|
||||
return result, err
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package business
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
@@ -21,20 +22,25 @@ type PhoneInfo struct {
|
||||
PurePhoneNumber string `json:"purePhoneNumber"` // 没有区号的手机号
|
||||
CountryCode string `json:"countryCode"` // 区号
|
||||
Watermark struct {
|
||||
AppID string `json:"appid"` // 小程序 appid
|
||||
AppID string `json:"appid"` // 小程序appid
|
||||
Timestamp int64 `json:"timestamp"` // 用户获取手机号操作的时间戳
|
||||
} `json:"watermark"`
|
||||
}
|
||||
|
||||
// GetPhoneNumber code 换取用户手机号。每个 code 只能使用一次,code 的有效期为 5min
|
||||
// GetPhoneNumber code换取用户手机号。 每个code只能使用一次,code的有效期为5min
|
||||
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 {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf(getPhoneNumberURL, accessToken)
|
||||
response, err := util.PostJSON(uri, in)
|
||||
response, err := util.PostJSONContext(ctx, uri, in)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -14,4 +14,5 @@ type Config struct {
|
||||
Token string `json:"token"` // token
|
||||
EncodingAESKey string `json:"encoding_aes_key"` // EncodingAESKey
|
||||
Cache cache.Cache
|
||||
UseStableAK bool // use the stable access_token
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ func (content *Content) CheckText(text string) error {
|
||||
}
|
||||
|
||||
// CheckImage 检测图片
|
||||
// 所传参数为要检测的图片文件的绝对路径,图片格式支持 PNG、JPEG、JPG、GIF, 像素不超过 750 x 1334,同时文件大小以不超过 300K 为宜,否则可能报错
|
||||
// 所传参数为要检测的图片文件的绝对路径,图片格式支持PNG、JPEG、JPG、GIF, 像素不超过 750 x 1334,同时文件大小以不超过 300K 为宜,否则可能报错
|
||||
// @media 图片文件的绝对路径
|
||||
// Deprecated
|
||||
// 采用 security.ImageCheckV1 替代,返回值更加丰富
|
||||
|
||||
@@ -8,5 +8,5 @@ import (
|
||||
// Context struct
|
||||
type Context struct {
|
||||
*config.Config
|
||||
credential.AccessTokenHandle
|
||||
credential.AccessTokenContextHandle
|
||||
}
|
||||
|
||||
@@ -24,13 +24,13 @@ func NewEncryptor(context *context.Context) *Encryptor {
|
||||
}
|
||||
|
||||
var (
|
||||
// ErrAppIDNotMatch appid 不匹配
|
||||
// ErrAppIDNotMatch appid不匹配
|
||||
ErrAppIDNotMatch = errors.New("app id not match")
|
||||
// ErrInvalidBlockSize block size 不合法
|
||||
// ErrInvalidBlockSize block size不合法
|
||||
ErrInvalidBlockSize = errors.New("invalid block size")
|
||||
// ErrInvalidPKCS7Data PKCS7 数据不合法
|
||||
// ErrInvalidPKCS7Data PKCS7数据不合法
|
||||
ErrInvalidPKCS7Data = errors.New("invalid PKCS7 data")
|
||||
// ErrInvalidPKCS7Padding 输入 padding 失败
|
||||
// ErrInvalidPKCS7Padding 输入padding失败
|
||||
ErrInvalidPKCS7Padding = errors.New("invalid padding on input")
|
||||
)
|
||||
|
||||
|
||||
295
miniprogram/express/delivery.go
Normal file
295
miniprogram/express/delivery.go
Normal file
@@ -0,0 +1,295 @@
|
||||
package express
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const (
|
||||
// 传运单接口,商户使用此接口向微信提供某交易单号对应的运单号。微信后台会跟踪运单的状态变化
|
||||
openMsgTraceWaybillURL = "https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/trace_waybill?access_token=%s"
|
||||
|
||||
// 查询运单接口,商户在调用完trace_waybill接口后,可以使用本接口查询到对应运单的详情信息
|
||||
openMsgQueryTraceURL = "https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/query_trace?access_token=%s"
|
||||
|
||||
// 更新物流信息,更新物品信息
|
||||
openMsgUpdateWaybillGoodsURL = "https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/update_waybill_goods?access_token=%s"
|
||||
|
||||
// 传运单接口,商户使用此接口向微信提供某交易单号对应的运单号。微信后台会跟踪运单的状态变化,在关键物流节点给下单用户推送消息通知
|
||||
openMsgFollowWaybillURL = "https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/follow_waybill?access_token=%s"
|
||||
|
||||
// 查运单接口,商户在调用完follow_waybill接口后,可以使用本接口查询到对应运单的详情信息
|
||||
openMsgQueryFollowTraceURL = "https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/query_follow_trace?access_token=%s"
|
||||
|
||||
// 更新物品信息接口
|
||||
openMsgUpdateFollowWaybillGoodsURL = "https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/update_follow_waybill_goods?access_token=%s"
|
||||
|
||||
// 获取运力id列表
|
||||
openMsgGetDeliveryListURL = "https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/get_delivery_list?access_token=%s"
|
||||
)
|
||||
|
||||
// TraceWaybill 传运单
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/industry/express/business/express_search.html#_2-%E6%8E%A5%E5%8F%A3%E5%88%97%E8%A1%A8
|
||||
func (express *Express) TraceWaybill(ctx context.Context, in *TraceWaybillRequest) (res TraceWaybillResponse, err error) {
|
||||
accessToken, err := express.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf(openMsgTraceWaybillURL, accessToken)
|
||||
response, err := util.PostJSONContext(ctx, uri, in)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用通用方法返回错误
|
||||
err = util.DecodeWithError(response, &res, "TraceWaybill")
|
||||
return
|
||||
}
|
||||
|
||||
// QueryTrace 查询运单详情信息
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/industry/express/business/express_search.html#_2-%E6%8E%A5%E5%8F%A3%E5%88%97%E8%A1%A8
|
||||
func (express *Express) QueryTrace(ctx context.Context, in *QueryTraceRequest) (res QueryTraceResponse, err error) {
|
||||
accessToken, err := express.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf(openMsgQueryTraceURL, accessToken)
|
||||
response, err := util.PostJSONContext(ctx, uri, in)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用通用方法返回错误
|
||||
err = util.DecodeWithError(response, &res, "QueryTrace")
|
||||
return
|
||||
}
|
||||
|
||||
// UpdateWaybillGoods 更新物品信息
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/industry/express/business/express_search.html#_2-%E6%8E%A5%E5%8F%A3%E5%88%97%E8%A1%A8
|
||||
func (express *Express) UpdateWaybillGoods(ctx context.Context, in *UpdateWaybillGoodsRequest) (err error) {
|
||||
accessToken, err := express.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf(openMsgUpdateWaybillGoodsURL, accessToken)
|
||||
response, err := util.PostJSONContext(ctx, uri, in)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用通用方法返回错误
|
||||
err = util.DecodeWithCommonError(response, "UpdateWaybillGoods")
|
||||
return
|
||||
}
|
||||
|
||||
// FollowWaybill 传运单
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/industry/express/business/express_open_msg.html#_4-1%E3%80%81%E4%BC%A0%E8%BF%90%E5%8D%95%E6%8E%A5%E5%8F%A3-follow-waybill
|
||||
func (express *Express) FollowWaybill(ctx context.Context, in *FollowWaybillRequest) (res FollowWaybillResponse, err error) {
|
||||
accessToken, err := express.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf(openMsgFollowWaybillURL, accessToken)
|
||||
response, err := util.PostJSONContext(ctx, uri, in)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用通用方法返回错误
|
||||
err = util.DecodeWithError(response, &res, "FollowWaybill")
|
||||
return
|
||||
}
|
||||
|
||||
// QueryFollowTrace 查询运单详情信息
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/industry/express/business/express_open_msg.html#_4-2%E3%80%81%E6%9F%A5%E8%BF%90%E5%8D%95%E6%8E%A5%E5%8F%A3-query-follow-trace
|
||||
func (express *Express) QueryFollowTrace(ctx context.Context, in *QueryFollowTraceRequest) (res QueryFollowTraceResponse, err error) {
|
||||
accessToken, err := express.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf(openMsgQueryFollowTraceURL, accessToken)
|
||||
response, err := util.PostJSONContext(ctx, uri, in)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用通用方法返回错误
|
||||
err = util.DecodeWithError(response, &res, "QueryFollowTrace")
|
||||
return
|
||||
}
|
||||
|
||||
// UpdateFollowWaybillGoods 更新物品信息
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/industry/express/business/express_open_msg.html#_4-3%E3%80%81%E6%9B%B4%E6%96%B0%E7%89%A9%E5%93%81%E4%BF%A1%E6%81%AF%E6%8E%A5%E5%8F%A3-update-follow-waybill-goods
|
||||
func (express *Express) UpdateFollowWaybillGoods(ctx context.Context, in *UpdateFollowWaybillGoodsRequest) (err error) {
|
||||
accessToken, err := express.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf(openMsgUpdateFollowWaybillGoodsURL, accessToken)
|
||||
response, err := util.PostJSONContext(ctx, uri, in)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用通用方法返回错误
|
||||
err = util.DecodeWithCommonError(response, "UpdateFollowWaybillGoods")
|
||||
return
|
||||
}
|
||||
|
||||
// GetDeliveryList 获取运力id列表
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/industry/express/business/express_open_msg.html#_4-4%E8%8E%B7%E5%8F%96%E8%BF%90%E5%8A%9Bid%E5%88%97%E8%A1%A8get-delivery-list
|
||||
func (express *Express) GetDeliveryList(ctx context.Context) (res GetDeliveryListResponse, err error) {
|
||||
accessToken, err := express.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf(openMsgGetDeliveryListURL, accessToken)
|
||||
response, err := util.PostJSONContext(ctx, uri, map[string]interface{}{})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用通用方法返回错误
|
||||
err = util.DecodeWithError(response, &res, "GetDeliveryList")
|
||||
return
|
||||
}
|
||||
|
||||
// TraceWaybillRequest 传运单接口请求参数
|
||||
type TraceWaybillRequest struct {
|
||||
GoodsInfo FollowWaybillGoodsInfo `json:"goods_info"` // 必选,商品信息
|
||||
Openid string `json:"openid"` // 必选,用户openid
|
||||
SenderPhone string `json:"sender_phone"` // 寄件人手机号
|
||||
ReceiverPhone string `json:"receiver_phone"` // 必选,收件人手机号,部分运力需要用户手机号作为查单依据
|
||||
DeliveryID string `json:"delivery_id"` // 运力id(运单号所属运力公司id)
|
||||
WaybillID string `json:"waybill_id"` // 必选,运单号
|
||||
TransID string `json:"trans_id"` // 必选,交易单号(微信支付生成的交易单号,一般以420开头)
|
||||
OrderDetailPath string `json:"order_detail_path"` // 订单详情页地址
|
||||
|
||||
}
|
||||
|
||||
// TraceWaybillResponse 传运单接口返回参数
|
||||
type TraceWaybillResponse struct {
|
||||
util.CommonError
|
||||
WaybillToken string `json:"waybill_token"` // 查询id
|
||||
}
|
||||
|
||||
// QueryTraceRequest 查询运单详情接口请求参数
|
||||
type QueryTraceRequest struct {
|
||||
WaybillToken string `json:"waybill_token"` // 必选,查询id
|
||||
}
|
||||
|
||||
// QueryTraceResponse 查询运单详情接口返回参数
|
||||
type QueryTraceResponse struct {
|
||||
util.CommonError
|
||||
WaybillInfo FlowWaybillInfo `json:"waybill_info"` // 运单信息
|
||||
ShopInfo FollowWaybillShopInfo `json:"shop_info"` // 商品信息
|
||||
DeliveryInfo FlowWaybillDeliveryInfo `json:"delivery_info"` // 运力信息
|
||||
}
|
||||
|
||||
// UpdateWaybillGoodsRequest 更新物品信息接口请求参数
|
||||
type UpdateWaybillGoodsRequest struct {
|
||||
WaybillToken string `json:"waybill_token"` // 必选,查询id
|
||||
GoodsInfo FollowWaybillGoodsInfo `json:"goods_info"` // 必选,商品信息
|
||||
}
|
||||
|
||||
// FollowWaybillRequest 传运单接口请求参数
|
||||
type FollowWaybillRequest struct {
|
||||
GoodsInfo FollowWaybillGoodsInfo `json:"goods_info"` // 必选,商品信息
|
||||
Openid string `json:"openid"` // 必选,用户openid
|
||||
SenderPhone string `json:"sender_phone"` // 寄件人手机号
|
||||
ReceiverPhone string `json:"receiver_phone"` // 必选,收件人手机号,部分运力需要用户手机号作为查单依据
|
||||
DeliveryID string `json:"delivery_id"` // 运力id(运单号所属运力公司id)
|
||||
WaybillID string `json:"waybill_id"` // 必选,运单号
|
||||
TransID string `json:"trans_id"` // 必选,交易单号(微信支付生成的交易单号,一般以420开头)
|
||||
OrderDetailPath string `json:"order_detail_path"` // 订单详情页地址
|
||||
}
|
||||
|
||||
// FollowWaybillGoodsInfo 商品信息
|
||||
type FollowWaybillGoodsInfo struct {
|
||||
DetailList []FollowWaybillGoodsInfoItem `json:"detail_list"`
|
||||
}
|
||||
|
||||
// FollowWaybillShopInfo 商品信息
|
||||
type FollowWaybillShopInfo struct {
|
||||
GoodsInfo FollowWaybillGoodsInfo `json:"goods_info"` // 商品信息
|
||||
}
|
||||
|
||||
// FollowWaybillGoodsInfoItem 商品信息详情
|
||||
type FollowWaybillGoodsInfoItem struct {
|
||||
GoodsName string `json:"goods_name"` // 必选,商品名称(最大长度为utf-8编码下的60个字符)
|
||||
GoodsImgURL string `json:"goods_img_url"` // 必选,商品图片url
|
||||
GoodsDesc string `json:"goods_desc,omitempty"` // 商品详情描述,不传默认取“商品名称”值,最多40汉字
|
||||
}
|
||||
|
||||
// FollowWaybillResponse 传运单接口返回参数
|
||||
type FollowWaybillResponse struct {
|
||||
util.CommonError
|
||||
WaybillToken string `json:"waybill_token"` // 查询id
|
||||
}
|
||||
|
||||
// QueryFollowTraceRequest 查询运单详情信息请求参数
|
||||
type QueryFollowTraceRequest struct {
|
||||
WaybillToken string `json:"waybill_token"` // 必选,查询id
|
||||
}
|
||||
|
||||
// QueryFollowTraceResponse 查询运单详情信息返回参数
|
||||
type QueryFollowTraceResponse struct {
|
||||
util.CommonError
|
||||
WaybillInfo FlowWaybillInfo `json:"waybill_info"` // 运单信息
|
||||
ShopInfo FollowWaybillShopInfo `json:"shop_info"` // 商品信息
|
||||
DeliveryInfo FlowWaybillDeliveryInfo `json:"delivery_info"` // 运力信息
|
||||
}
|
||||
|
||||
// FlowWaybillInfo 运单信息
|
||||
type FlowWaybillInfo struct {
|
||||
WaybillID string `json:"waybill_id"` // 运单号
|
||||
Status WaybillStatus `json:"status"` // 运单状态
|
||||
}
|
||||
|
||||
// UpdateFollowWaybillGoodsRequest 修改运单商品信息请求参数
|
||||
type UpdateFollowWaybillGoodsRequest struct {
|
||||
WaybillToken string `json:"waybill_token"` // 必选,查询id
|
||||
GoodsInfo FollowWaybillGoodsInfo `json:"goods_info"` // 必选,商品信息
|
||||
}
|
||||
|
||||
// GetDeliveryListResponse 获取运力id列表返回参数
|
||||
type GetDeliveryListResponse struct {
|
||||
util.CommonError
|
||||
DeliveryList []FlowWaybillDeliveryInfo `json:"delivery_list"` // 运力公司列表
|
||||
Count int `json:"count"` // 运力公司个数
|
||||
}
|
||||
|
||||
// FlowWaybillDeliveryInfo 运力公司信息
|
||||
type FlowWaybillDeliveryInfo struct {
|
||||
DeliveryID string `json:"delivery_id"` // 运力公司id
|
||||
DeliveryName string `json:"delivery_name"` // 运力公司名称
|
||||
}
|
||||
|
||||
// WaybillStatus 运单状态
|
||||
type WaybillStatus int
|
||||
|
||||
const (
|
||||
// WaybillStatusNotExist 运单不存在或者未揽收
|
||||
WaybillStatusNotExist WaybillStatus = iota
|
||||
// WaybillStatusPicked 已揽件
|
||||
WaybillStatusPicked
|
||||
// WaybillStatusTransporting 运输中
|
||||
WaybillStatusTransporting
|
||||
// WaybillStatusDispatching 派件中
|
||||
WaybillStatusDispatching
|
||||
// WaybillStatusSigned 已签收
|
||||
WaybillStatusSigned
|
||||
// WaybillStatusException 异常
|
||||
WaybillStatusException
|
||||
// WaybillStatusSignedByOthers 代签收
|
||||
WaybillStatusSignedByOthers
|
||||
)
|
||||
16
miniprogram/express/express.go
Normal file
16
miniprogram/express/express.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package express
|
||||
|
||||
import (
|
||||
"github.com/silenceper/wechat/v2/miniprogram/context"
|
||||
)
|
||||
|
||||
// Express 微信物流服务
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/industry/express/business/introduction.html
|
||||
type Express struct {
|
||||
*context.Context
|
||||
}
|
||||
|
||||
// NewExpress init
|
||||
func NewExpress(ctx *context.Context) *Express {
|
||||
return &Express{ctx}
|
||||
}
|
||||
@@ -556,7 +556,7 @@ type SubscribeMsgSentEvent struct {
|
||||
type SubscribeMsgSentList struct {
|
||||
TemplateID string `xml:"TemplateId" json:"TemplateId"`
|
||||
MsgID string `xml:"MsgID" json:"MsgID"`
|
||||
ErrorCode int `xml:"ErrorCode" json:"ErrorCode"`
|
||||
ErrorCode string `xml:"ErrorCode" json:"ErrorCode"`
|
||||
ErrorStatus string `xml:"ErrorStatus" json:"ErrorStatus"`
|
||||
}
|
||||
|
||||
|
||||
@@ -8,10 +8,12 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
// createActivityURL 创建 activity_id
|
||||
createActivityURL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/activityid/create?access_token=%s"
|
||||
// createActivityIDURL 创建activity_id
|
||||
createActivityIDURL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/activityid/create?access_token=%s&unionid=%s&openid=%s"
|
||||
// SendUpdatableMsgURL 修改动态消息
|
||||
setUpdatableMsgURL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/updatablemsg/send?access_token=%s"
|
||||
// setChatToolMsgURL 修改小程序聊天工具的动态卡片消息
|
||||
setChatToolMsgURL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/chattoolmsg/send?access_token=%s"
|
||||
)
|
||||
|
||||
// UpdatableTargetState 动态消息状态
|
||||
@@ -38,15 +40,26 @@ func NewUpdatableMessage(ctx *context.Context) *UpdatableMessage {
|
||||
}
|
||||
}
|
||||
|
||||
// CreateActivityID 创建 activity_id
|
||||
func (updatableMessage *UpdatableMessage) CreateActivityID() (res CreateActivityIDResponse, err error) {
|
||||
// CreateActivityIDRequest 创建activity_id请求
|
||||
type CreateActivityIDRequest struct {
|
||||
UnionID string
|
||||
OpenID string
|
||||
}
|
||||
|
||||
// CreateActivityID 创建activity_id
|
||||
func (updatableMessage *UpdatableMessage) CreateActivityID() (CreateActivityIDResponse, error) {
|
||||
return updatableMessage.CreateActivityIDWithReq(&CreateActivityIDRequest{})
|
||||
}
|
||||
|
||||
// CreateActivityIDWithReq 创建activity_id
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/updatable-message/createActivityId.html
|
||||
func (updatableMessage *UpdatableMessage) CreateActivityIDWithReq(req *CreateActivityIDRequest) (res CreateActivityIDResponse, err error) {
|
||||
accessToken, err := updatableMessage.GetAccessToken()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf(createActivityURL, accessToken)
|
||||
response, err := util.HTTPGet(uri)
|
||||
url := fmt.Sprintf(createActivityIDURL, accessToken, req.UnionID, req.OpenID)
|
||||
response, err := util.HTTPGet(url)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -75,7 +88,7 @@ func (updatableMessage *UpdatableMessage) SetUpdatableMsg(activityID string, tar
|
||||
return util.DecodeWithCommonError(response, "SendUpdatableMsg")
|
||||
}
|
||||
|
||||
// CreateActivityIDResponse 创建 activity_id 返回
|
||||
// CreateActivityIDResponse 创建activity_id 返回
|
||||
type CreateActivityIDResponse struct {
|
||||
util.CommonError
|
||||
|
||||
@@ -100,3 +113,35 @@ type SendUpdatableMsgReq struct {
|
||||
TemplateInfo UpdatableMsgTemplate `json:"template_info"`
|
||||
TargetState UpdatableTargetState `json:"target_state"`
|
||||
}
|
||||
|
||||
// SetChatToolMsgRequest 修改小程序聊天工具的动态卡片消息请求
|
||||
type SetChatToolMsgRequest struct {
|
||||
VersionType int64 `json:"version_type"`
|
||||
TargetState UpdatableTargetState `json:"target_state"`
|
||||
ActivityID string `json:"activity_id"`
|
||||
TemplateID string `json:"template_id"`
|
||||
ParticipatorInfoList []ParticipatorInfo `json:"participator_info_list,omitempty"`
|
||||
}
|
||||
|
||||
// ParticipatorInfo 更新后的聊天室成员状态
|
||||
type ParticipatorInfo struct {
|
||||
State int `json:"state"`
|
||||
GroupOpenID string `json:"group_openid"`
|
||||
}
|
||||
|
||||
// SetChatToolMsg 修改小程序聊天工具的动态卡片消息
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/updatable-message/setChatToolMsg.html
|
||||
func (updatableMessage *UpdatableMessage) SetChatToolMsg(req *SetChatToolMsgRequest) error {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = updatableMessage.GetAccessToken(); err != nil {
|
||||
return err
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.PostJSON(fmt.Sprintf(setChatToolMsgURL, accessToken), req); err != nil {
|
||||
return err
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "SetChatToolMsg")
|
||||
}
|
||||
|
||||
@@ -10,8 +10,10 @@ import (
|
||||
"github.com/silenceper/wechat/v2/miniprogram/content"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/context"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/encryptor"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/express"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/message"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/minidrama"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/operation"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/order"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/privacy"
|
||||
"github.com/silenceper/wechat/v2/miniprogram/qrcode"
|
||||
@@ -34,17 +36,30 @@ type MiniProgram struct {
|
||||
|
||||
// NewMiniProgram 实例化小程序 API
|
||||
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{
|
||||
Config: cfg,
|
||||
AccessTokenHandle: defaultAkHandle,
|
||||
Config: cfg,
|
||||
AccessTokenContextHandle: defaultAkHandle,
|
||||
}
|
||||
return &MiniProgram{ctx}
|
||||
}
|
||||
|
||||
// SetAccessTokenHandle 自定义 access_token 获取方式
|
||||
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
|
||||
@@ -166,3 +181,13 @@ func (miniProgram *MiniProgram) GetRedPacketCover() *redpacketcover.RedPacketCov
|
||||
func (miniProgram *MiniProgram) GetUpdatableMessage() *message.UpdatableMessage {
|
||||
return message.NewUpdatableMessage(miniProgram.ctx)
|
||||
}
|
||||
|
||||
// GetOperation 小程序运维中心
|
||||
func (miniProgram *MiniProgram) GetOperation() *operation.Operation {
|
||||
return operation.NewOperation(miniProgram.ctx)
|
||||
}
|
||||
|
||||
// GetExpress 微信物流服务
|
||||
func (miniProgram *MiniProgram) GetExpress() *express.Express {
|
||||
return express.NewExpress(miniProgram.ctx)
|
||||
}
|
||||
|
||||
456
miniprogram/operation/operation.go
Normal file
456
miniprogram/operation/operation.go
Normal file
@@ -0,0 +1,456 @@
|
||||
package operation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/miniprogram/context"
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const (
|
||||
// getDomainInfoURL 查询域名配置
|
||||
getDomainInfoURL = "https://api.weixin.qq.com/wxa/getwxadevinfo?access_token=%s"
|
||||
// getPerformanceURL 获取性能数据
|
||||
getPerformanceURL = "https://api.weixin.qq.com/wxaapi/log/get_performance?access_token=%s"
|
||||
// getSceneListURL 获取访问来源
|
||||
getSceneListURL = "https://api.weixin.qq.com/wxaapi/log/get_scene?access_token=%s"
|
||||
// getVersionListURL 获取客户端版本
|
||||
getVersionListURL = "https://api.weixin.qq.com/wxaapi/log/get_client_version?access_token=%s"
|
||||
// realTimeLogSearchURL 查询实时日志
|
||||
realTimeLogSearchURL = "https://api.weixin.qq.com/wxaapi/userlog/userlog_search?%s"
|
||||
// getFeedbackListURL 获取用户反馈列表
|
||||
getFeedbackListURL = "https://api.weixin.qq.com/wxaapi/feedback/list?%s"
|
||||
// getJsErrDetailURL 查询js错误详情
|
||||
getJsErrDetailURL = "https://api.weixin.qq.com/wxaapi/log/jserr_detail?access_token=%s"
|
||||
// getJsErrListURL 查询错误列表
|
||||
getJsErrListURL = "https://api.weixin.qq.com/wxaapi/log/jserr_list?access_token=%s"
|
||||
// getGrayReleasePlanURL 获取分阶段发布详情
|
||||
getGrayReleasePlanURL = "https://api.weixin.qq.com/wxa/getgrayreleaseplan?access_token=%s"
|
||||
)
|
||||
|
||||
// Operation 运维中心
|
||||
type Operation struct {
|
||||
*context.Context
|
||||
}
|
||||
|
||||
// NewOperation 实例化
|
||||
func NewOperation(ctx *context.Context) *Operation {
|
||||
return &Operation{ctx}
|
||||
}
|
||||
|
||||
// GetDomainInfoRequest 查询域名配置请求
|
||||
type GetDomainInfoRequest struct {
|
||||
Action string `json:"action"`
|
||||
}
|
||||
|
||||
// GetDomainInfoResponse 查询域名配置响应
|
||||
type GetDomainInfoResponse struct {
|
||||
util.CommonError
|
||||
RequestDomain []string `json:"requestdomain"`
|
||||
WsRequestDomain []string `json:"wsrequestdomain"`
|
||||
UploadDomain []string `json:"uploaddomain"`
|
||||
DownloadDomain []string `json:"downloaddomain"`
|
||||
UDPDomain []string `json:"udpdomain"`
|
||||
BizDomain []string `json:"bizdomain"`
|
||||
}
|
||||
|
||||
// GetDomainInfo 查询域名配置
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/operation/getDomainInfo.html
|
||||
func (o *Operation) GetDomainInfo(req *GetDomainInfoRequest) (res GetDomainInfoResponse, err error) {
|
||||
var accessToken string
|
||||
if accessToken, err = o.GetAccessToken(); err != nil {
|
||||
return
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.PostJSON(fmt.Sprintf(getDomainInfoURL, accessToken), req); err != nil {
|
||||
return
|
||||
}
|
||||
err = util.DecodeWithError(response, &res, "GetDomainInfo")
|
||||
return
|
||||
}
|
||||
|
||||
// GetPerformanceRequest 获取性能数据请求
|
||||
type GetPerformanceRequest struct {
|
||||
CostTimeType int64 `json:"cost_time_type"`
|
||||
DefaultStartTime int64 `json:"default_start_time"`
|
||||
DefaultEndTime int64 `json:"default_end_time"`
|
||||
Device string `json:"device"`
|
||||
IsDownloadCode string `json:"is_download_code"`
|
||||
Scene string `json:"scene"`
|
||||
NetworkType string `json:"networktype"`
|
||||
}
|
||||
|
||||
// GetPerformanceResponse 获取性能数据响应
|
||||
type GetPerformanceResponse struct {
|
||||
util.CommonError
|
||||
DefaultTimeData string `json:"default_time_data"`
|
||||
CompareTimeData string `json:"compare_time_data"`
|
||||
}
|
||||
|
||||
// PerformanceDefaultTimeData 查询数据
|
||||
type PerformanceDefaultTimeData struct {
|
||||
List []DefaultTimeDataItem `json:"list"`
|
||||
}
|
||||
|
||||
// DefaultTimeDataItem 查询数据
|
||||
type DefaultTimeDataItem struct {
|
||||
RefData string `json:"ref_data"`
|
||||
CostTimeType int64 `json:"cost_time_type"`
|
||||
CostTime int64 `json:"cost_time"`
|
||||
}
|
||||
|
||||
// GetPerformance 获取性能数据
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/operation/getPerformance.html
|
||||
func (o *Operation) GetPerformance(req *GetPerformanceRequest) (res GetPerformanceResponse, err error) {
|
||||
var accessToken string
|
||||
if accessToken, err = o.GetAccessToken(); err != nil {
|
||||
return
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.PostJSON(fmt.Sprintf(getPerformanceURL, accessToken), req); err != nil {
|
||||
return
|
||||
}
|
||||
err = util.DecodeWithError(response, &res, "GetPerformance")
|
||||
return
|
||||
}
|
||||
|
||||
// GetSceneListResponse 获取访问来源响应
|
||||
type GetSceneListResponse struct {
|
||||
util.CommonError
|
||||
Scene []Scene `json:"scene"`
|
||||
}
|
||||
|
||||
// Scene 访问来源
|
||||
type Scene struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// GetSceneList 获取访问来源
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/operation/getSceneList.html
|
||||
func (o *Operation) GetSceneList() (res GetSceneListResponse, err error) {
|
||||
var accessToken string
|
||||
if accessToken, err = o.GetAccessToken(); err != nil {
|
||||
return
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.HTTPGet(fmt.Sprintf(getSceneListURL, accessToken)); err != nil {
|
||||
return
|
||||
}
|
||||
err = util.DecodeWithError(response, &res, "GetSceneList")
|
||||
return
|
||||
}
|
||||
|
||||
// GetVersionListResponse 获取客户端版本响应
|
||||
type GetVersionListResponse struct {
|
||||
util.CommonError
|
||||
CvList []ClientVersion `json:"cvlist"`
|
||||
}
|
||||
|
||||
// ClientVersion 客户端版本
|
||||
type ClientVersion struct {
|
||||
Type int64 `json:"type"`
|
||||
ClientVersionList []string `json:"client_version_list"`
|
||||
}
|
||||
|
||||
// GetVersionList 获取客户端版本
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/operation/getVersionList.html
|
||||
func (o *Operation) GetVersionList() (res GetVersionListResponse, err error) {
|
||||
var accessToken string
|
||||
if accessToken, err = o.GetAccessToken(); err != nil {
|
||||
return
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.HTTPGet(fmt.Sprintf(getVersionListURL, accessToken)); err != nil {
|
||||
return
|
||||
}
|
||||
err = util.DecodeWithError(response, &res, "GetVersionList")
|
||||
return
|
||||
}
|
||||
|
||||
// RealTimeLogSearchRequest 查询实时日志请求
|
||||
type RealTimeLogSearchRequest struct {
|
||||
Date string
|
||||
BeginTime int64
|
||||
EndTime int64
|
||||
Start int64
|
||||
Limit int64
|
||||
Level int64
|
||||
TraceID string
|
||||
URL string
|
||||
ID string
|
||||
FilterMsg string
|
||||
}
|
||||
|
||||
// RealTimeLogSearchResponse 查询实时日志响应
|
||||
type RealTimeLogSearchResponse struct {
|
||||
util.CommonError
|
||||
Data RealTimeLogSearchData `json:"data"`
|
||||
}
|
||||
|
||||
// RealTimeLogSearchData 日志数据和日志条数总量
|
||||
type RealTimeLogSearchData struct {
|
||||
List []RealTimeLogSearchDataList `json:"list"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
// RealTimeLogSearchDataList 日志数据列表
|
||||
type RealTimeLogSearchDataList struct {
|
||||
Level int64 `json:"level"`
|
||||
LibraryVersion string `json:"libraryVersion"`
|
||||
ClientVersion string `json:"clientVersion"`
|
||||
ID string `json:"id"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
Platform int64 `json:"platform"`
|
||||
URL string `json:"url"`
|
||||
TraceID string `json:"traceid"`
|
||||
FilterMsg string `json:"filterMsg"`
|
||||
Msg []RealTimeLogSearchDataListMsg `json:"msg"`
|
||||
}
|
||||
|
||||
// RealTimeLogSearchDataListMsg 日志内容数组
|
||||
type RealTimeLogSearchDataListMsg struct {
|
||||
Time int64 `json:"time"`
|
||||
Level int64 `json:"level"`
|
||||
Msg []string `json:"msg"`
|
||||
}
|
||||
|
||||
// RealTimeLogSearch 查询实时日志
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/operation/realtimelogSearch.html
|
||||
func (o *Operation) RealTimeLogSearch(req *RealTimeLogSearchRequest) (res RealTimeLogSearchResponse, err error) {
|
||||
var accessToken string
|
||||
if accessToken, err = o.GetAccessToken(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
params := map[string]interface{}{
|
||||
"access_token": accessToken,
|
||||
"date": req.Date,
|
||||
"begintime": req.BeginTime,
|
||||
"endtime": req.EndTime,
|
||||
}
|
||||
if req.Start > 0 {
|
||||
params["start"] = req.Start
|
||||
}
|
||||
if req.Limit > 0 {
|
||||
params["limit"] = req.Limit
|
||||
}
|
||||
if req.TraceID != "" {
|
||||
params["traceId"] = req.TraceID
|
||||
}
|
||||
if req.URL != "" {
|
||||
params["url"] = req.URL
|
||||
}
|
||||
if req.ID != "" {
|
||||
params["id"] = req.ID
|
||||
}
|
||||
if req.FilterMsg != "" {
|
||||
params["filterMsg"] = req.FilterMsg
|
||||
}
|
||||
if req.Level > 0 {
|
||||
params["level"] = req.Level
|
||||
}
|
||||
query := util.Query(params)
|
||||
|
||||
var response []byte
|
||||
if response, err = util.HTTPGet(fmt.Sprintf(realTimeLogSearchURL, query)); err != nil {
|
||||
return
|
||||
}
|
||||
err = util.DecodeWithError(response, &res, "RealTimeLogSearch")
|
||||
return
|
||||
}
|
||||
|
||||
// GetFeedbackListRequest 获取用户反馈列表请求
|
||||
type GetFeedbackListRequest struct {
|
||||
Page int64
|
||||
Num int64
|
||||
Type int64
|
||||
}
|
||||
|
||||
// GetFeedbackListResponse 获取用户反馈列表响应
|
||||
type GetFeedbackListResponse struct {
|
||||
util.CommonError
|
||||
TotalNum int64 `json:"total_num"`
|
||||
List []Feedback `json:"list"`
|
||||
}
|
||||
|
||||
// Feedback 反馈列表
|
||||
type Feedback struct {
|
||||
RecordID int64 `json:"record_id"`
|
||||
CreateTime int64 `json:"create_time"`
|
||||
Content string `json:"content"`
|
||||
Phone string `json:"phone"`
|
||||
OpenID string `json:"openid"`
|
||||
Nickname string `json:"nickname"`
|
||||
HeadURL string `json:"head_url"`
|
||||
Type int64 `json:"type"`
|
||||
MediaIDS []string `json:"mediaIds"`
|
||||
SystemInfo string `json:"systemInfo"`
|
||||
}
|
||||
|
||||
// GetFeedbackList 获取用户反馈列表
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/operation/getFeedback.html
|
||||
func (o *Operation) GetFeedbackList(req *GetFeedbackListRequest) (res GetFeedbackListResponse, err error) {
|
||||
var accessToken string
|
||||
if accessToken, err = o.GetAccessToken(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
params := map[string]interface{}{
|
||||
"access_token": accessToken,
|
||||
"page": req.Page,
|
||||
"num": req.Num,
|
||||
}
|
||||
if req.Type > 0 {
|
||||
params["type"] = req.Type
|
||||
}
|
||||
query := util.Query(params)
|
||||
|
||||
var response []byte
|
||||
if response, err = util.HTTPGet(fmt.Sprintf(getFeedbackListURL, query)); err != nil {
|
||||
return
|
||||
}
|
||||
err = util.DecodeWithError(response, &res, "GetFeedbackList")
|
||||
return
|
||||
}
|
||||
|
||||
// GetJsErrDetailRequest 查询js错误详情请求
|
||||
type GetJsErrDetailRequest struct {
|
||||
StartTime string `json:"startTime"`
|
||||
EndTime string `json:"endTime"`
|
||||
ErrorMsgMd5 string `json:"errorMsgMd5"`
|
||||
ErrorStackMd5 string `json:"errorStackMd5"`
|
||||
AppVersion string `json:"appVersion"`
|
||||
SdkVersion string `json:"sdkVersion"`
|
||||
OsName string `json:"osName"`
|
||||
ClientVersion string `json:"clientVersion"`
|
||||
OpenID string `json:"openid"`
|
||||
Offset int64 `json:"offset"`
|
||||
Limit int64 `json:"limit"`
|
||||
Desc string `json:"desc"`
|
||||
}
|
||||
|
||||
// GetJsErrDetailResponse 查询js错误详情响应
|
||||
type GetJsErrDetailResponse struct {
|
||||
util.CommonError
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
OpenID string `json:"openid"`
|
||||
Data []JsErrDetailData `json:"data"`
|
||||
}
|
||||
|
||||
// JsErrDetailData 错误列表
|
||||
type JsErrDetailData struct {
|
||||
Count string `json:"Count"`
|
||||
SdkVersion string `json:"sdkVersion"`
|
||||
ClientVersion string `json:"ClientVersion"`
|
||||
ErrorStackMd5 string `json:"errorStackMd5"`
|
||||
TimeStamp string `json:"TimeStamp"`
|
||||
AppVersion string `json:"appVersion"`
|
||||
ErrorMsgMd5 string `json:"errorMsgMd5"`
|
||||
ErrorMsg string `json:"errorMsg"`
|
||||
ErrorStack string `json:"errorStack"`
|
||||
Ds string `json:"Ds"`
|
||||
OsName string `json:"OsName"`
|
||||
OpenID string `json:"openId"`
|
||||
PluginVersion string `json:"pluginversion"`
|
||||
AppID string `json:"appId"`
|
||||
DeviceModel string `json:"DeviceModel"`
|
||||
Source string `json:"source"`
|
||||
Route string `json:"route"`
|
||||
Uin string `json:"Uin"`
|
||||
Nickname string `json:"nickname"`
|
||||
}
|
||||
|
||||
// GetJsErrDetail 查询js错误详情
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/operation/getJsErrDetail.html
|
||||
func (o *Operation) GetJsErrDetail(req *GetJsErrDetailRequest) (res GetJsErrDetailResponse, err error) {
|
||||
var accessToken string
|
||||
if accessToken, err = o.GetAccessToken(); err != nil {
|
||||
return
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.PostJSON(fmt.Sprintf(getJsErrDetailURL, accessToken), req); err != nil {
|
||||
return
|
||||
}
|
||||
err = util.DecodeWithError(response, &res, "GetJsErrDetail")
|
||||
return
|
||||
}
|
||||
|
||||
// GetJsErrListRequest 查询错误列表请求
|
||||
type GetJsErrListRequest struct {
|
||||
AppVersion string `json:"appVersion"`
|
||||
ErrType string `json:"errType"`
|
||||
StartTime string `json:"startTime"`
|
||||
EndTime string `json:"endTime"`
|
||||
Keyword string `json:"keyword"`
|
||||
OpenID string `json:"openid"`
|
||||
OrderBy string `json:"orderby"`
|
||||
Desc string `json:"desc"`
|
||||
Offset int64 `json:"offset"`
|
||||
Limit int64 `json:"limit"`
|
||||
}
|
||||
|
||||
// GetJsErrListResponse 查询错误列表响应
|
||||
type GetJsErrListResponse struct {
|
||||
util.CommonError
|
||||
TotalCount int64 `json:"totalCount"`
|
||||
OpenID string `json:"openid"`
|
||||
Data []JsErrListData `json:"data"`
|
||||
}
|
||||
|
||||
// JsErrListData 错误列表
|
||||
type JsErrListData struct {
|
||||
ErrorMsgMd5 string `json:"errorMsgMd5"`
|
||||
ErrorMsg string `json:"errorMsg"`
|
||||
Uv int64 `json:"uv"`
|
||||
Pv int64 `json:"pv"`
|
||||
ErrorStackMd5 string `json:"errorStackMd5"`
|
||||
ErrorStack string `json:"errorStack"`
|
||||
PvPercent string `json:"pvPercent"`
|
||||
UvPercent string `json:"uvPercent"`
|
||||
}
|
||||
|
||||
// GetJsErrList 查询错误列表
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/operation/getJsErrList.html
|
||||
func (o *Operation) GetJsErrList(req *GetJsErrListRequest) (res GetJsErrListResponse, err error) {
|
||||
var accessToken string
|
||||
if accessToken, err = o.GetAccessToken(); err != nil {
|
||||
return
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.PostJSON(fmt.Sprintf(getJsErrListURL, accessToken), req); err != nil {
|
||||
return
|
||||
}
|
||||
err = util.DecodeWithError(response, &res, "GetJsErrList")
|
||||
return
|
||||
}
|
||||
|
||||
// GetGrayReleasePlanResponse 获取分阶段发布详情响应
|
||||
type GetGrayReleasePlanResponse struct {
|
||||
util.CommonError
|
||||
GrayReleasePlan GrayReleasePlanDetail `json:"gray_release_plan"`
|
||||
}
|
||||
|
||||
// GrayReleasePlanDetail 分阶段发布计划详情
|
||||
type GrayReleasePlanDetail struct {
|
||||
Status int64 `json:"status"`
|
||||
CreateTimestamp int64 `json:"create_timestamp"`
|
||||
GrayPercentage int64 `json:"gray_percentage"`
|
||||
SupportExperiencerFirst bool `json:"support_experiencer_first"`
|
||||
SupportDebugerFirst bool `json:"support_debuger_first"`
|
||||
}
|
||||
|
||||
// GetGrayReleasePlan 获取分阶段发布详情
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/operation/getGrayReleasePlan.html
|
||||
func (o *Operation) GetGrayReleasePlan() (res GetGrayReleasePlanResponse, err error) {
|
||||
var accessToken string
|
||||
if accessToken, err = o.GetAccessToken(); err != nil {
|
||||
return
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.HTTPGet(fmt.Sprintf(getGrayReleasePlanURL, accessToken)); err != nil {
|
||||
return
|
||||
}
|
||||
err = util.DecodeWithError(response, &res, "GetGrayReleasePlan")
|
||||
return
|
||||
}
|
||||
@@ -114,29 +114,29 @@ type UploadShippingInfoRequest struct {
|
||||
|
||||
// ShippingOrderKey 订单
|
||||
type ShippingOrderKey struct {
|
||||
OrderNumberType NumberType `json:"order_number_type"` // 订单单号类型,用于确认需要上传详情的订单。枚举值 1,使用下单商户号和商户侧单号;枚举值 2,使用微信支付单号。
|
||||
OrderNumberType NumberType `json:"order_number_type"` // 订单单号类型,用于确认需要上传详情的订单。枚举值1,使用下单商户号和商户侧单号;枚举值2,使用微信支付单号。
|
||||
TransactionID string `json:"transaction_id"` // 原支付交易对应的微信订单号
|
||||
Mchid string `json:"mchid"` // 支付下单商户的商户号,由微信支付生成并下发
|
||||
OutTradeNo string `json:"out_trade_no"` // 商户系统内部订单号,只能是数字、大小写字母 `_-*` 且在同一个商户号下唯一
|
||||
OutTradeNo string `json:"out_trade_no"` // 商户系统内部订单号,只能是数字、大小写字母`_-*`且在同一个商户号下唯一
|
||||
}
|
||||
|
||||
// ShippingPayer 支付者信息
|
||||
type ShippingPayer struct {
|
||||
Openid string `json:"openid"` // 用户标识,用户在小程序 appid 下的唯一标识
|
||||
Openid string `json:"openid"` // 用户标识,用户在小程序appid下的唯一标识
|
||||
}
|
||||
|
||||
// ShippingInfo 物流信息
|
||||
type ShippingInfo struct {
|
||||
TrackingNo string `json:"tracking_no"` // 物流单号,物流快递发货时必填
|
||||
ExpressCompany string `json:"express_company"` // 物流公司编码,快递公司 ID,物流快递发货时必填;参见「查询物流公司编码列表」
|
||||
ItemDesc string `json:"item_desc"` // 商品信息,例如:微信红包抱枕*1 个,限 120 个字以内
|
||||
ExpressCompany string `json:"express_company"` // 物流公司编码,快递公司ID,物流快递发货时必填;参见「查询物流公司编码列表」
|
||||
ItemDesc string `json:"item_desc"` // 商品信息,例如:微信红包抱枕*1个,限120个字以内
|
||||
Contact ShippingContact `json:"contact"` // 联系方式,当发货的物流公司为顺丰时,联系方式为必填,收件人或寄件人联系方式二选一
|
||||
}
|
||||
|
||||
// ShippingContact 联系方式
|
||||
type ShippingContact struct {
|
||||
ConsignorContact string `json:"consignor_contact"` // 寄件人联系方式,寄件人联系方式,采用掩码传输,最后 4 位数字不能打掩码
|
||||
ReceiverContact string `json:"receiver_contact"` // 收件人联系方式,收件人联系方式,采用掩码传输,最后 4 位数字不能打掩码
|
||||
ConsignorContact string `json:"consignor_contact"` // 寄件人联系方式,寄件人联系方式,采用掩码传输,最后4位数字不能打掩码
|
||||
ReceiverContact string `json:"receiver_contact"` // 收件人联系方式,收件人联系方式,采用掩码传输,最后4位数字不能打掩码
|
||||
}
|
||||
|
||||
// DeliveryMode 发货模式
|
||||
@@ -178,13 +178,13 @@ type GetShippingOrderRequest struct {
|
||||
TransactionID string `json:"transaction_id"` // 原支付交易对应的微信订单号
|
||||
MerchantID string `json:"merchant_id"` // 支付下单商户的商户号,由微信支付生成并下发
|
||||
SubMerchantID string `json:"sub_merchant_id"` //二级商户号
|
||||
MerchantTradeNo string `json:"merchant_trade_no"` //商户系统内部订单号,只能是数字、大小写字母 `_-*` 且在同一个商户号下唯一。
|
||||
MerchantTradeNo string `json:"merchant_trade_no"` //商户系统内部订单号,只能是数字、大小写字母`_-*`且在同一个商户号下唯一。
|
||||
}
|
||||
|
||||
// ShippingItem 物流信息
|
||||
type ShippingItem struct {
|
||||
TrackingNo string `json:"tracking_no"` // 物流单号,示例值:"323244567777
|
||||
ExpressCompany string `json:"express_company"` // 物流公司编码,快递公司 ID,物流快递发货时必填;参见「查询物流公司编码列表」
|
||||
TrackingNo string `json:"tracking_no"` // 物流单号,示例值: "323244567777
|
||||
ExpressCompany string `json:"express_company"` // 物流公司编码,快递公司ID,物流快递发货时必填;参见「查询物流公司编码列表」
|
||||
UploadTime int64 `json:"upload_time"` // 上传物流信息时间,时间戳形式
|
||||
}
|
||||
|
||||
@@ -201,12 +201,12 @@ type ShippingDetail struct {
|
||||
// ShippingOrder 订单发货状态
|
||||
type ShippingOrder struct {
|
||||
TransactionID string `json:"transaction_id"` // 原支付交易对应的微信订单号
|
||||
MerchantTradeNo string `json:"merchant_trade_no"` // 商户系统内部订单号,只能是数字、大小写字母 `_-*` 且在同一个商户号下唯一
|
||||
MerchantTradeNo string `json:"merchant_trade_no"` // 商户系统内部订单号,只能是数字、大小写字母`_-*`且在同一个商户号下唯一
|
||||
MerchantID string `json:"merchant_id"` // 支付下单商户的商户号,由微信支付生成并下发
|
||||
SubMerchantID string `json:"sub_merchant_id"` // 二级商户号
|
||||
Description string `json:"description"` // 以分号连接的该支付单的所有商品描述,当超过 120 字时自动截断并以“...”结尾
|
||||
Description string `json:"description"` // 以分号连接的该支付单的所有商品描述,当超过120字时自动截断并以 “...” 结尾
|
||||
PaidAmount int64 `json:"paid_amount"` // 支付单实际支付金额,整型,单位:分钱
|
||||
Openid string `json:"openid"` // 支付者 openid
|
||||
Openid string `json:"openid"` // 支付者openid
|
||||
TradeCreateTime int64 `json:"trade_create_time"` // 交易创建时间,时间戳形式
|
||||
PayTime int64 `json:"pay_time"` // 支付时间,时间戳形式
|
||||
InComplaint bool `json:"in_complaint"` // 是否处在交易纠纷中
|
||||
@@ -240,9 +240,9 @@ const (
|
||||
type GetShippingOrderListRequest struct {
|
||||
PayTimeRange *TimeRange `json:"pay_time_range"` // 支付时间范围
|
||||
OrderState State `json:"order_state,omitempty"` // 订单状态
|
||||
Openid string `json:"openid,omitempty"` // 支付者 openid
|
||||
Openid string `json:"openid,omitempty"` // 支付者openid
|
||||
LastIndex string `json:"last_index,omitempty"` // 翻页时使用,获取第一页时不用传入,如果查询结果中 has_more 字段为 true,则传入该次查询结果中返回的 last_index 字段可获取下一页
|
||||
PageSize int64 `json:"page_size"` // 每页数量,最多 50 条
|
||||
PageSize int64 `json:"page_size"` // 每页数量,最多50条
|
||||
}
|
||||
|
||||
// TimeRange 时间范围
|
||||
@@ -264,6 +264,6 @@ type NotifyConfirmReceiveRequest struct {
|
||||
TransactionID string `json:"transaction_id"` // 原支付交易对应的微信订单号
|
||||
MerchantID string `json:"merchant_id"` // 支付下单商户的商户号,由微信支付生成并下发
|
||||
SubMerchantID string `json:"sub_merchant_id"` // 二级商户号
|
||||
MerchantTradeNo string `json:"merchant_trade_no"` // 商户系统内部订单号,只能是数字、大小写字母 `_-*` 且在同一个商户号下唯一
|
||||
MerchantTradeNo string `json:"merchant_trade_no"` // 商户系统内部订单号,只能是数字、大小写字母`_-*`且在同一个商户号下唯一
|
||||
ReceivedTime int64 `json:"received_time"` // 收货时间,时间戳形式
|
||||
}
|
||||
|
||||
@@ -53,9 +53,9 @@ const (
|
||||
getPrivacySettingURL = "https://api.weixin.qq.com/cgi-bin/component/getprivacysetting"
|
||||
uploadPrivacyExtFileURL = "https://api.weixin.qq.com/cgi-bin/component/uploadprivacyextfile"
|
||||
|
||||
// PrivacyV1 用户隐私保护指引的版本,1 表示现网版本。
|
||||
// PrivacyV1 用户隐私保护指引的版本,1表示现网版本。
|
||||
PrivacyV1 = 1
|
||||
// PrivacyV2 2 表示开发版。默认是 2 开发版。
|
||||
// PrivacyV2 2表示开发版。默认是2开发版。
|
||||
PrivacyV2 = 2
|
||||
)
|
||||
|
||||
@@ -77,12 +77,12 @@ type SettingResponseItem struct {
|
||||
PrivacyLabel string `json:"privacy_label"`
|
||||
}
|
||||
|
||||
// DescList 权限列表 (保持与官方一致)
|
||||
// DescList 权限列表(保持与官方一致)
|
||||
type DescList struct {
|
||||
PrivacyDescList []Desc `json:"privacy_desc_list"`
|
||||
}
|
||||
|
||||
// Desc 权限列表明细 (保持与官方一致)
|
||||
// Desc 权限列表明细(保持与官方一致)
|
||||
type Desc struct {
|
||||
PrivacyDesc string `json:"privacy_desc"`
|
||||
PrivacyKey string `json:"privacy_key"`
|
||||
@@ -110,7 +110,7 @@ func (s *Privacy) GetPrivacySetting(privacyVer int) (GetPrivacySettingResponse,
|
||||
// SetPrivacySetting 更新小程序权限配置
|
||||
func (s *Privacy) SetPrivacySetting(privacyVer int, ownerSetting OwnerSetting, settingList []SettingItem) error {
|
||||
if privacyVer == PrivacyV1 && len(settingList) > 0 {
|
||||
return errors.New("当 privacy_ver 传 2 或者不传时,setting_list 是必填;当 privacy_ver 传 1 时,该参数不可传")
|
||||
return errors.New("当privacy_ver传2或者不传时,setting_list是必填;当privacy_ver传1时,该参数不可传")
|
||||
}
|
||||
accessToken, err := s.GetAccessToken()
|
||||
if err != nil {
|
||||
|
||||
@@ -36,24 +36,26 @@ type Color struct {
|
||||
|
||||
// QRCoder 小程序码参数
|
||||
type QRCoder struct {
|
||||
// page 必须是已经发布的小程序存在的页面,根路径前不要填加 /,不能携带参数(参数请放在 scene 字段里),如果不填写这个字段,默认跳主页面
|
||||
// page 必须是已经发布的小程序存在的页面,根路径前不要填加 /,不能携带参数(参数请放在scene字段里),如果不填写这个字段,默认跳主页面
|
||||
Page string `json:"page,omitempty"`
|
||||
// path 扫码进入的小程序页面路径
|
||||
Path string `json:"path,omitempty"`
|
||||
// checkPath 检查 page 是否存在,为 true 时 page 必须是已经发布的小程序存在的页面(否则报错);为 false 时允许小程序未发布或者 page 不存在,但 page 有数量上限(60000 个)请勿滥用,默认 true
|
||||
// checkPath 检查page 是否存在,为 true 时 page 必须是已经发布的小程序存在的页面(否则报错);为 false 时允许小程序未发布或者 page 不存在, 但page 有数量上限(60000个)请勿滥用,默认true
|
||||
CheckPath *bool `json:"check_path,omitempty"`
|
||||
// width 图片宽度
|
||||
Width int `json:"width,omitempty"`
|
||||
// scene 最大 32 个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用 urlencode 处理,请使用其他编码方式)
|
||||
// scene 最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用 urlencode 处理,请使用其他编码方式)
|
||||
Scene string `json:"scene,omitempty"`
|
||||
// autoColor 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false
|
||||
// autoColor 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认false
|
||||
AutoColor bool `json:"auto_color,omitempty"`
|
||||
// lineColor AutoColor 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"},十进制表示
|
||||
LineColor *Color `json:"line_color,omitempty"`
|
||||
// isHyaline 是否需要透明底色,默认 false
|
||||
// isHyaline 是否需要透明底色,默认false
|
||||
IsHyaline bool `json:"is_hyaline,omitempty"`
|
||||
// envVersion 要打开的小程序版本。正式版为 "release",体验版为 "trial",开发版为 "develop"
|
||||
EnvVersion string `json:"env_version,omitempty"`
|
||||
// ShowSplashAd 控制通过该小程序码进入小程序是否展示封面广告1、默认为true,展示封面广告2、传入为false时,不展示封面广告
|
||||
ShowSplashAd bool `json:"show_splash_ad,omitempty"`
|
||||
}
|
||||
|
||||
// fetchCode 请求并返回二维码二进制数据
|
||||
@@ -88,19 +90,19 @@ func (qrCode *QRCode) fetchCode(urlStr string, body interface{}) (response []byt
|
||||
}
|
||||
|
||||
// CreateWXAQRCode 获取小程序二维码,适用于需要的码数量较少的业务场景
|
||||
// 文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/createWXAQRCode.html
|
||||
// 文档地址: https://developers.weixin.qq.com/miniprogram/dev/api/createWXAQRCode.html
|
||||
func (qrCode *QRCode) CreateWXAQRCode(coderParams QRCoder) (response []byte, err error) {
|
||||
return qrCode.fetchCode(createWXAQRCodeURL, coderParams)
|
||||
}
|
||||
|
||||
// GetWXACode 获取小程序码,适用于需要的码数量较少的业务场景
|
||||
// 文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/getWXACode.html
|
||||
// 文档地址: https://developers.weixin.qq.com/miniprogram/dev/api/getWXACode.html
|
||||
func (qrCode *QRCode) GetWXACode(coderParams QRCoder) (response []byte, err error) {
|
||||
return qrCode.fetchCode(getWXACodeURL, coderParams)
|
||||
}
|
||||
|
||||
// GetWXACodeUnlimit 获取小程序码,适用于需要的码数量极多的业务场景
|
||||
// 文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/getWXACodeUnlimit.html
|
||||
// 文档地址: https://developers.weixin.qq.com/miniprogram/dev/api/getWXACodeUnlimit.html
|
||||
func (qrCode *QRCode) GetWXACodeUnlimit(coderParams QRCoder) (response []byte, err error) {
|
||||
return qrCode.fetchCode(getWXACodeUnlimitURL, coderParams)
|
||||
}
|
||||
|
||||
@@ -25,9 +25,9 @@ func NewRedPacketCover(context *context.Context) *RedPacketCover {
|
||||
|
||||
// GetRedPacketCoverRequest 获取微信红包封面参数
|
||||
type GetRedPacketCoverRequest struct {
|
||||
// openid 可领取用户的 openid
|
||||
// openid 可领取用户的openid
|
||||
OpenID string `json:"openid"`
|
||||
// ctoken 在红包封面平台获取发放 ctoken(需要指定可以发放的 appid)
|
||||
// ctoken 在红包封面平台获取发放ctoken(需要指定可以发放的appid)
|
||||
CToken string `json:"ctoken"`
|
||||
}
|
||||
|
||||
@@ -39,8 +39,8 @@ type GetRedPacketCoverResp struct {
|
||||
} `json:"data"` // 唯一请求标识
|
||||
}
|
||||
|
||||
// GetRedPacketCoverURL 获得指定用户可以领取的红包封面链接。获取参数 ctoken 参考微信红包封面开放平台
|
||||
// 文档地址:https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/red-packet-cover/getRedPacketCoverUrl.html
|
||||
// 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 {
|
||||
|
||||
@@ -26,7 +26,7 @@ type UserRiskRankRequest struct {
|
||||
AppID string `json:"appid"` // 小程序 app id
|
||||
OpenID string `json:"openid"` // 用户的 openid
|
||||
Scene uint8 `json:"scene"` // 场景值,0:注册,1:营销作弊
|
||||
ClientIP string `json:"client_ip"` // 用户访问源 ip
|
||||
ClientIP string `json:"client_ip"` // 用户访问源ip
|
||||
|
||||
Mobile string `json:"mobile_no"` // 用户手机号
|
||||
Email string `json:"email_address"` // 用户邮箱地址
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
context2 "context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
@@ -26,13 +27,13 @@ func NewSecurity(ctx *context.Context) *Security {
|
||||
|
||||
// MediaCheckAsyncV1Request 图片/音频异步校验请求参数
|
||||
type MediaCheckAsyncV1Request struct {
|
||||
MediaURL string `json:"media_url"` // 要检测的图片或音频的 url,支持图片格式包括 jpg, jepg, png, bmp, gif(取首帧),支持的音频格式包括 mp3, aac, ac3, wma, flac, vorbis, opus, wav
|
||||
MediaURL string `json:"media_url"` // 要检测的图片或音频的url,支持图片格式包括jpg, jepg, png, bmp, gif(取首帧),支持的音频格式包括mp3, aac, ac3, wma, flac, vorbis, opus, wav
|
||||
MediaType uint8 `json:"media_type"` // 1:音频;2:图片
|
||||
}
|
||||
|
||||
// MediaCheckAsyncV1 异步校验图片/音频是否含有违法违规内容
|
||||
// Deprecated
|
||||
// 在 2021 年 9 月 1 日停止更新,请尽快更新至 2.0 接口。建议使用 MediaCheckAsync
|
||||
// 在2021年9月1日停止更新,请尽快更新至 2.0 接口。建议使用 MediaCheckAsync
|
||||
func (security *Security) MediaCheckAsyncV1(in *MediaCheckAsyncV1Request) (traceID string, err error) {
|
||||
accessToken, err := security.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -56,28 +57,33 @@ func (security *Security) MediaCheckAsyncV1(in *MediaCheckAsyncV1Request) (trace
|
||||
|
||||
// MediaCheckAsyncRequest 图片/音频异步校验请求参数
|
||||
type MediaCheckAsyncRequest struct {
|
||||
MediaURL string `json:"media_url"` // 要检测的图片或音频的 url,支持图片格式包括 jpg, jepg, png, bmp, gif(取首帧),支持的音频格式包括 mp3, aac, ac3, wma, flac, vorbis, opus, wav
|
||||
MediaURL string `json:"media_url"` // 要检测的图片或音频的url,支持图片格式包括jpg, jepg, png, bmp, gif(取首帧),支持的音频格式包括mp3, aac, ac3, wma, flac, vorbis, opus, wav
|
||||
MediaType uint8 `json:"media_type"` // 1:音频;2:图片
|
||||
OpenID string `json:"openid"` // 用户的 openid(用户需在近两小时访问过小程序)
|
||||
OpenID string `json:"openid"` // 用户的openid(用户需在近两小时访问过小程序)
|
||||
Scene uint8 `json:"scene"` // 场景枚举值(1 资料;2 评论;3 论坛;4 社交日志)
|
||||
}
|
||||
|
||||
// MediaCheckAsync 异步校验图片/音频是否含有违法违规内容
|
||||
func (security *Security) MediaCheckAsync(in *MediaCheckAsyncRequest) (traceID string, err error) {
|
||||
accessToken, err := security.GetAccessToken()
|
||||
return security.MediaCheckAsyncContext(context2.Background(), in)
|
||||
}
|
||||
|
||||
// MediaCheckAsyncContext 异步校验图片/音频是否含有违法违规内容
|
||||
func (security *Security) MediaCheckAsyncContext(ctx context2.Context, in *MediaCheckAsyncRequest) (traceID string, err error) {
|
||||
accessToken, err := security.GetAccessTokenContext(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
MediaCheckAsyncRequest
|
||||
Version uint `json:"version"` // 接口版本号,2.0 版本为固定值 2
|
||||
Version uint `json:"version"` // 接口版本号,2.0版本为固定值2
|
||||
}
|
||||
req.MediaCheckAsyncRequest = *in
|
||||
req.Version = 2
|
||||
|
||||
uri := fmt.Sprintf(mediaCheckAsyncURL, accessToken)
|
||||
response, err := util.PostJSON(uri, req)
|
||||
response, err := util.PostJSONContext(ctx, uri, req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -94,7 +100,7 @@ func (security *Security) MediaCheckAsync(in *MediaCheckAsyncRequest) (traceID s
|
||||
// ImageCheckV1 校验一张图片是否含有违法违规内容(同步)
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/framework/security.imgSecCheck.html
|
||||
// Deprecated
|
||||
// 在 2021 年 9 月 1 日停止更新。建议使用 MediaCheckAsync
|
||||
// 在2021年9月1日停止更新。建议使用 MediaCheckAsync
|
||||
func (security *Security) ImageCheckV1(filename string) (err error) {
|
||||
accessToken, err := security.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -169,12 +175,12 @@ func (cl CheckLabel) String() string {
|
||||
|
||||
// MsgCheckRequest 文本检查请求
|
||||
type MsgCheckRequest struct {
|
||||
OpenID string `json:"openid"` // 用户的 openid(用户需在近两小时访问过小程序)
|
||||
OpenID string `json:"openid"` // 用户的openid(用户需在近两小时访问过小程序)
|
||||
Scene MsgScene `json:"scene"` // 场景枚举值(1 资料;2 评论;3 论坛;4 社交日志)
|
||||
Content string `json:"content"` // 需检测的文本内容,文本字数的上限为 2500 字,需使用 UTF-8 编码
|
||||
Nickname string `json:"nickname"` // (非必填)用户昵称,需使用 UTF-8 编码
|
||||
Title string `json:"title"` // (非必填)文本标题,需使用 UTF-8 编码
|
||||
Signature string `json:"signature"` // (非必填)个性签名,该参数仅在资料类场景有效 (scene=1),需使用 UTF-8 编码
|
||||
Nickname string `json:"nickname"` // (非必填)用户昵称,需使用UTF-8编码
|
||||
Title string `json:"title"` // (非必填)文本标题,需使用UTF-8编码
|
||||
Signature string `json:"signature"` // (非必填)个性签名,该参数仅在资料类场景有效(scene=1),需使用UTF-8编码
|
||||
}
|
||||
|
||||
// MsgCheckResponse 文本检查响应
|
||||
@@ -186,7 +192,7 @@ type MsgCheckResponse struct {
|
||||
Label CheckLabel `json:"label"` // 命中标签
|
||||
} `json:"result"` // 综合结果
|
||||
Detail []struct {
|
||||
ErrCode int64 `json:"errcode"` // 错误码,仅当该值为 0 时,该项结果有效
|
||||
ErrCode int64 `json:"errcode"` // 错误码,仅当该值为0时,该项结果有效
|
||||
Strategy string `json:"strategy"` // 策略类型
|
||||
Suggest string `json:"suggest"` // 建议
|
||||
Label CheckLabel `json:"label"` // 命中标签
|
||||
@@ -197,7 +203,7 @@ type MsgCheckResponse struct {
|
||||
|
||||
// MsgCheckV1 检查一段文本是否含有违法违规内容
|
||||
// Deprecated
|
||||
// 在 2021 年 9 月 1 日停止更新,请尽快更新至 2.0 接口。建议使用 MsgCheck
|
||||
// 在2021年9月1日停止更新,请尽快更新至 2.0 接口。建议使用 MsgCheck
|
||||
func (security *Security) MsgCheckV1(content string) (res MsgCheckResponse, err error) {
|
||||
accessToken, err := security.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -222,7 +228,12 @@ func (security *Security) MsgCheckV1(content string) (res MsgCheckResponse, err
|
||||
|
||||
// MsgCheck 检查一段文本是否含有违法违规内容
|
||||
func (security *Security) MsgCheck(in *MsgCheckRequest) (res MsgCheckResponse, err error) {
|
||||
accessToken, err := security.GetAccessToken()
|
||||
return security.MsgCheckContext(context2.Background(), in)
|
||||
}
|
||||
|
||||
// MsgCheckContext 检查一段文本是否含有违法违规内容
|
||||
func (security *Security) MsgCheckContext(ctx context2.Context, in *MsgCheckRequest) (res MsgCheckResponse, err error) {
|
||||
accessToken, err := security.GetAccessTokenContext(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -235,7 +246,7 @@ func (security *Security) MsgCheck(in *MsgCheckRequest) (res MsgCheckResponse, e
|
||||
req.Version = 2
|
||||
|
||||
uri := fmt.Sprintf(msgCheckURL, accessToken)
|
||||
response, err := util.PostJSON(uri, req)
|
||||
response, err := util.PostJSONContext(ctx, uri, req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package subscribe
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/miniprogram/context"
|
||||
@@ -11,22 +12,30 @@ const (
|
||||
// 发送订阅消息
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html
|
||||
subscribeSendURL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send"
|
||||
|
||||
// 获取当前帐号下的个人模板列表
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.getTemplateList.html
|
||||
getTemplateURL = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate"
|
||||
|
||||
// 添加订阅模板
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.addTemplate.html
|
||||
addTemplateURL = "https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate"
|
||||
|
||||
// 删除私有模板
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.deleteTemplate.html
|
||||
delTemplateURL = "https://api.weixin.qq.com/wxaapi/newtmpl/deltemplate"
|
||||
|
||||
// 统一服务消息
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/uniform-message/uniformMessage.send.html
|
||||
uniformMessageSend = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send"
|
||||
// getCategoryURL 获取类目
|
||||
getCategoryURL = "https://api.weixin.qq.com/wxaapi/newtmpl/getcategory?access_token=%s"
|
||||
// getPubTemplateKeyWordsByIDURL 获取关键词列表
|
||||
getPubTemplateKeyWordsByIDURL = "https://api.weixin.qq.com/wxaapi/newtmpl/getpubtemplatekeywords?access_token=%s&tid=%s"
|
||||
// getPubTemplateTitleListURL 获取所属类目下的公共模板
|
||||
getPubTemplateTitleListURL = "https://api.weixin.qq.com/wxaapi/newtmpl/getpubtemplatetitles?access_token=%s&ids=%s&start=%d&limit=%d"
|
||||
// setUserNotifyURL 激活与更新服务卡片
|
||||
setUserNotifyURL = "https://api.weixin.qq.com/wxa/set_user_notify?access_token=%s"
|
||||
// setUserNotifyExtURL 更新服务卡片扩展信息
|
||||
setUserNotifyExtURL = "https://api.weixin.qq.com/wxa/set_user_notifyext?access_token=%s"
|
||||
// getUserNotifyURL 查询服务卡片状态
|
||||
getUserNotifyURL = "https://api.weixin.qq.com/wxa/get_user_notify?access_token=%s"
|
||||
)
|
||||
|
||||
// Subscribe 订阅消息
|
||||
@@ -42,11 +51,11 @@ func NewSubscribe(ctx *context.Context) *Subscribe {
|
||||
// Message 订阅消息请求参数
|
||||
type Message struct {
|
||||
ToUser string `json:"touser"` // 必选,接收者(用户)的 openid
|
||||
TemplateID string `json:"template_id"` // 必选,所需下发的订阅模板 id
|
||||
Page string `json:"page"` // 可选,点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例 index?foo=bar)。该字段不填则模板无跳转。
|
||||
Data map[string]*DataItem `json:"data"` // 必选,模板内容
|
||||
MiniprogramState string `json:"miniprogram_state"` // 可选,跳转小程序类型:developer 为开发版;trial 为体验版;formal 为正式版;默认为正式版
|
||||
Lang string `json:"lang"` // 入小程序查看”的语言类型,支持 zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为 zh_CN
|
||||
TemplateID string `json:"template_id"` // 必选,所需下发的订阅模板id
|
||||
Page string `json:"page"` // 可选,点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
|
||||
Data map[string]*DataItem `json:"data"` // 必选, 模板内容
|
||||
MiniprogramState string `json:"miniprogram_state"` // 可选,跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版
|
||||
Lang string `json:"lang"` // 入小程序查看”的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN
|
||||
}
|
||||
|
||||
// DataItem 模版内某个 .DATA 的值
|
||||
@@ -57,11 +66,18 @@ type DataItem struct {
|
||||
|
||||
// TemplateItem template item
|
||||
type TemplateItem struct {
|
||||
PriTmplID string `json:"priTmplId"`
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
Example string `json:"example"`
|
||||
Type int64 `json:"type"`
|
||||
PriTmplID string `json:"priTmplId"`
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
Example string `json:"example"`
|
||||
Type int64 `json:"type"`
|
||||
KeywordEnumValueList []KeywordEnumValue `json:"keywordEnumValueList"`
|
||||
}
|
||||
|
||||
// KeywordEnumValue 枚举参数值范围
|
||||
type KeywordEnumValue struct {
|
||||
EnumValueList []string `json:"enumValueList"`
|
||||
KeywordCode string `json:"keywordCode"`
|
||||
}
|
||||
|
||||
// TemplateList template list
|
||||
@@ -70,6 +86,13 @@ type TemplateList struct {
|
||||
Data []TemplateItem `json:"data"`
|
||||
}
|
||||
|
||||
// resTemplateSend 发送获取 msg id
|
||||
type resTemplateSend struct {
|
||||
util.CommonError
|
||||
|
||||
MsgID int64 `json:"msgid"`
|
||||
}
|
||||
|
||||
// Send 发送订阅消息
|
||||
func (s *Subscribe) Send(msg *Message) (err error) {
|
||||
var accessToken string
|
||||
@@ -85,6 +108,33 @@ func (s *Subscribe) Send(msg *Message) (err error) {
|
||||
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 获取当前帐号下的个人模板列表
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.getTemplateList.html
|
||||
func (s *Subscribe) ListTemplates() (*TemplateList, error) {
|
||||
@@ -189,3 +239,200 @@ func (s *Subscribe) Delete(templateID string) (err error) {
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "DeleteSubscribe")
|
||||
}
|
||||
|
||||
// GetCategoryResponse 获取类目响应
|
||||
type GetCategoryResponse struct {
|
||||
util.CommonError
|
||||
Data []Category `json:"data"`
|
||||
}
|
||||
|
||||
// Category 类目
|
||||
type Category struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// GetCategory 获取类目
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/subscribe-message/getCategory.html
|
||||
func (s *Subscribe) GetCategory() ([]Category, error) {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = s.GetAccessToken(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.HTTPGet(fmt.Sprintf(getCategoryURL, accessToken)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &GetCategoryResponse{}
|
||||
err = util.DecodeWithError(response, result, "GetCategory")
|
||||
return result.Data, err
|
||||
}
|
||||
|
||||
// GetPubTemplateKeywordsByIDResponse 获取关键词列表响应
|
||||
type GetPubTemplateKeywordsByIDResponse struct {
|
||||
util.CommonError
|
||||
Count int64 `json:"count"`
|
||||
Data []PubTemplateKeywords `json:"data"`
|
||||
}
|
||||
|
||||
// PubTemplateKeywords 关键词
|
||||
type PubTemplateKeywords struct {
|
||||
KID int64 `json:"kid"`
|
||||
Name string `json:"name"`
|
||||
Example string `json:"example"`
|
||||
Rule string `json:"rule"`
|
||||
}
|
||||
|
||||
// GetPubTemplateKeywordsByID 获取关键词列表
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/subscribe-message/getPubTemplateKeyWordsById.html
|
||||
func (s *Subscribe) GetPubTemplateKeywordsByID(tid string) (*GetPubTemplateKeywordsByIDResponse, error) {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = s.GetAccessToken(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.HTTPGet(fmt.Sprintf(getPubTemplateKeyWordsByIDURL, accessToken, tid)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &GetPubTemplateKeywordsByIDResponse{}
|
||||
err = util.DecodeWithError(response, result, "GetPubTemplateKeywordsByID")
|
||||
return result, err
|
||||
}
|
||||
|
||||
// GetPubTemplateTitleListRequest 获取所属类目下的公共模板请求
|
||||
type GetPubTemplateTitleListRequest struct {
|
||||
Start int64
|
||||
Limit int64
|
||||
IDs string
|
||||
}
|
||||
|
||||
// GetPubTemplateTitleListResponse 获取所属类目下的公共模板响应
|
||||
type GetPubTemplateTitleListResponse struct {
|
||||
util.CommonError
|
||||
Count int64 `json:"count"`
|
||||
Data []PubTemplateTitle `json:"data"`
|
||||
}
|
||||
|
||||
// PubTemplateTitle 模板标题
|
||||
type PubTemplateTitle struct {
|
||||
Type int64 `json:"type"`
|
||||
TID string `json:"tid"`
|
||||
Title string `json:"title"`
|
||||
CategoryID string `json:"categoryId"`
|
||||
}
|
||||
|
||||
// GetPubTemplateTitleList 获取所属类目下的公共模板
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/subscribe-message/getPubTemplateTitleList.html
|
||||
func (s *Subscribe) GetPubTemplateTitleList(req *GetPubTemplateTitleListRequest) (*GetPubTemplateTitleListResponse, error) {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = s.GetAccessToken(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.HTTPGet(fmt.Sprintf(getPubTemplateTitleListURL, accessToken, req.IDs, req.Start, req.Limit)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &GetPubTemplateTitleListResponse{}
|
||||
err = util.DecodeWithError(response, result, "GetPubTemplateTitleList")
|
||||
return result, err
|
||||
}
|
||||
|
||||
// SetUserNotifyRequest 激活与更新服务卡片请求
|
||||
type SetUserNotifyRequest struct {
|
||||
OpenID string `json:"openid"`
|
||||
NotifyType int64 `json:"notify_type"`
|
||||
NotifyCode string `json:"notify_code"`
|
||||
ContentJSON string `json:"content_json"`
|
||||
CheckJSON string `json:"check_json,omitempty"`
|
||||
}
|
||||
|
||||
// SetUserNotify 激活与更新服务卡片
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/subscribe-message/setUserNotify.html
|
||||
func (s *Subscribe) SetUserNotify(req *SetUserNotifyRequest) error {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = s.GetAccessToken(); err != nil {
|
||||
return err
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.PostJSON(fmt.Sprintf(setUserNotifyURL, accessToken), req); err != nil {
|
||||
return err
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "SetUserNotify")
|
||||
}
|
||||
|
||||
// SetUserNotifyExtRequest 更新服务卡片扩展信息请求
|
||||
type SetUserNotifyExtRequest struct {
|
||||
OpenID string `json:"openid"`
|
||||
NotifyType int64 `json:"notify_type"`
|
||||
NotifyCode string `json:"notify_code"`
|
||||
ExtJSON string `json:"ext_json"`
|
||||
}
|
||||
|
||||
// SetUserNotifyExt 更新服务卡片扩展信息
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/subscribe-message/setUserNotifyExt.html
|
||||
func (s *Subscribe) SetUserNotifyExt(req *SetUserNotifyExtRequest) error {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = s.GetAccessToken(); err != nil {
|
||||
return err
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.PostJSON(fmt.Sprintf(setUserNotifyExtURL, accessToken), req); err != nil {
|
||||
return err
|
||||
}
|
||||
return util.DecodeWithCommonError(response, "SetUserNotifyExt")
|
||||
}
|
||||
|
||||
// GetUserNotifyRequest 查询服务卡片状态请求
|
||||
type GetUserNotifyRequest struct {
|
||||
OpenID string `json:"openid"`
|
||||
NotifyType int64 `json:"notify_type"`
|
||||
NotifyCode string `json:"notify_code"`
|
||||
}
|
||||
|
||||
// GetUserNotifyResponse 查询服务卡片状态响应
|
||||
type GetUserNotifyResponse struct {
|
||||
util.CommonError
|
||||
NotifyInfo NotifyInfo `json:"notify_info"`
|
||||
}
|
||||
|
||||
// NotifyInfo 卡片状态
|
||||
type NotifyInfo struct {
|
||||
NotifyType int64 `json:"notify_type"`
|
||||
ContentJSON string `json:"content_json"`
|
||||
CodeState int64 `json:"code_state"`
|
||||
CodeExpireTime int64 `json:"code_expire_time"`
|
||||
}
|
||||
|
||||
// GetUserNotify 查询服务卡片状态
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/subscribe-message/getUserNotify.html
|
||||
func (s *Subscribe) GetUserNotify(req *GetUserNotifyRequest) (*GetUserNotifyResponse, error) {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = s.GetAccessToken(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.PostJSON(fmt.Sprintf(getUserNotifyURL, accessToken), req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &GetUserNotifyResponse{}
|
||||
err = util.DecodeWithError(response, result, "GetUserNotify")
|
||||
return result, err
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# 小程序 - 云开发 SDK
|
||||
# 小程序-云开发 SDK
|
||||
|
||||
Tencent Cloud Base [文档](https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/)
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ const (
|
||||
// InvokeCloudFunctionRes 云函数调用返回结果
|
||||
type InvokeCloudFunctionRes struct {
|
||||
util.CommonError
|
||||
RespData string `json:"resp_data"` // 云函数返回的 buffer
|
||||
RespData string `json:"resp_data"` // 云函数返回的buffer
|
||||
}
|
||||
|
||||
// InvokeCloudFunction 云函数调用
|
||||
|
||||
@@ -49,13 +49,13 @@ type ConflictMode int
|
||||
// FileType 文件上传和导出的允许文件类型
|
||||
type FileType int
|
||||
|
||||
// ValidDirections 合法的 direction 值
|
||||
// ValidDirections 合法的direction值
|
||||
var ValidDirections = []string{"1", "-1", "2dsphere"}
|
||||
|
||||
// DatabaseMigrateExportReq 数据库出 请求参数
|
||||
type DatabaseMigrateExportReq struct {
|
||||
Env string `json:"env,omitempty"` // 云环境 ID
|
||||
FilePath string `json:"file_path,omitempty"` // 导出文件路径 (导入文件需先上传到同环境的存储中,可使用开发者工具或 HTTP API 的上传文件 API 上传)
|
||||
Env string `json:"env,omitempty"` // 云环境ID
|
||||
FilePath string `json:"file_path,omitempty"` // 导出文件路径(导入文件需先上传到同环境的存储中,可使用开发者工具或 HTTP API的上传文件 API上传)
|
||||
FileType FileType `json:"file_type,omitempty"` // 导出文件类型,文件格式参考数据库导入指引中的文件格式部分 1:json 2:csv
|
||||
Query string `json:"query,omitempty"` // 导出条件
|
||||
}
|
||||
@@ -63,12 +63,12 @@ type DatabaseMigrateExportReq struct {
|
||||
// DatabaseMigrateExportRes 数据库导出 返回结果
|
||||
type DatabaseMigrateExportRes struct {
|
||||
util.CommonError
|
||||
JobID int64 `json:"job_id"` // 导出任务 ID,可使用数据库迁移进度查询 API 查询导入进度及结果
|
||||
JobID int64 `json:"job_id"` // 导出任务ID,可使用数据库迁移进度查询 API 查询导入进度及结果
|
||||
}
|
||||
|
||||
// DatabaseMigrateImportReq 数据库导入 请求参数
|
||||
type DatabaseMigrateImportReq struct {
|
||||
Env string `json:"env,omitempty"` // 云环境 ID
|
||||
Env string `json:"env,omitempty"` // 云环境ID
|
||||
CollectionName string `json:"collection_name,omitempty"` // 集合名称
|
||||
FilePath string `json:"file_path,omitempty"` // 导出文件路径(文件会导出到同环境的云存储中,可使用获取下载链接 API 获取下载链接)
|
||||
FileType FileType `json:"file_type,omitempty"` // 导入文件类型,文件格式参考数据库导入指引中的文件格式部分 1:json 2:csv
|
||||
@@ -79,7 +79,7 @@ type DatabaseMigrateImportReq struct {
|
||||
// DatabaseMigrateImportRes 数据库导入 返回结果
|
||||
type DatabaseMigrateImportRes struct {
|
||||
util.CommonError
|
||||
JobID int64 `json:"job_id"` // 导入任务 ID,可使用数据库迁移进度查询 API 查询导入进度及结果
|
||||
JobID int64 `json:"job_id"` // 导入任务ID,可使用数据库迁移进度查询 API 查询导入进度及结果
|
||||
}
|
||||
|
||||
// DatabaseMigrateQueryInfoRes 数据库迁移状态查询
|
||||
@@ -94,7 +94,7 @@ type DatabaseMigrateQueryInfoRes struct {
|
||||
|
||||
// UpdateIndexReq 变更数据库索引 请求参数
|
||||
type UpdateIndexReq struct {
|
||||
Env string `json:"env,omitempty"` // 云环境 ID
|
||||
Env string `json:"env,omitempty"` // 云环境ID
|
||||
CollectionName string `json:"collection_name,omitempty"` // 集合名称
|
||||
CreateIndexes []CreateIndex `json:"create_indexes,omitempty"` // 新增索引
|
||||
DropIndexes []DropIndex `json:"drop_indexes,omitempty"` // 删除索引
|
||||
@@ -120,13 +120,13 @@ type DropIndex struct {
|
||||
|
||||
// DatabaseCollectionReq 新增/删除集合请求参数
|
||||
type DatabaseCollectionReq struct {
|
||||
Env string `json:"env,omitempty"` // 云环境 ID
|
||||
Env string `json:"env,omitempty"` // 云环境ID
|
||||
CollectionName string `json:"collection_name,omitempty"` // 集合名称
|
||||
}
|
||||
|
||||
// DatabaseCollectionGetReq 获取特定云环境下集合信息请求
|
||||
type DatabaseCollectionGetReq struct {
|
||||
Env string `json:"env,omitempty"` // 云环境 ID
|
||||
Env string `json:"env,omitempty"` // 云环境ID
|
||||
Limit int64 `json:"limit,omitempty"` // 获取数量限制
|
||||
Offset int64 `json:"offset,omitempty"` // 偏移量
|
||||
}
|
||||
@@ -150,7 +150,7 @@ type DatabaseCollectionGetRes struct {
|
||||
|
||||
// DatabaseReq 数据库插入/删除/更新/查询/统计记录请求参数
|
||||
type DatabaseReq struct {
|
||||
Env string `json:"env,omitempty"` // 云环境 ID
|
||||
Env string `json:"env,omitempty"` // 云环境ID
|
||||
Query string `json:"query,omitempty"` // 数据库操作语句
|
||||
}
|
||||
|
||||
@@ -170,7 +170,7 @@ type DatabaseDeleteRes struct {
|
||||
type DatabaseUpdateRes struct {
|
||||
util.CommonError
|
||||
Matched int64 `json:"matched"` // 更新条件匹配到的结果数
|
||||
Modified int64 `json:"modified"` // 修改的记录数,注意:使用 set 操作新插入的数据不计入修改数目
|
||||
Modified int64 `json:"modified"` // 修改的记录数,注意:使用set操作新插入的数据不计入修改数目
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
|
||||
@@ -24,11 +24,11 @@ type UploadFileReq struct {
|
||||
// UploadFileRes 上传文件返回结果
|
||||
type UploadFileRes struct {
|
||||
util.CommonError
|
||||
URL string `json:"url"` // 上传 url
|
||||
URL string `json:"url"` // 上传url
|
||||
Token string `json:"token"` // token
|
||||
Authorization string `json:"authorization"` // authorization
|
||||
FileID string `json:"file_id"` // 文件 ID
|
||||
CosFileID string `json:"cos_file_id"` // cos 文件 ID
|
||||
FileID string `json:"file_id"` // 文件ID
|
||||
CosFileID string `json:"cos_file_id"` // cos文件ID
|
||||
}
|
||||
|
||||
// BatchDownloadFileReq 上传文件请求值
|
||||
@@ -39,7 +39,7 @@ type BatchDownloadFileReq struct {
|
||||
|
||||
// DownloadFile 文件信息
|
||||
type DownloadFile struct {
|
||||
FileID string `json:"fileid"` // 文件 ID
|
||||
FileID string `json:"fileid"` // 文件ID
|
||||
MaxAge int64 `json:"max_age"` // 下载链接有效期
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ type DownloadFile struct {
|
||||
type BatchDownloadFileRes struct {
|
||||
util.CommonError
|
||||
FileList []struct {
|
||||
FileID string `json:"file_id"` // 文件 ID
|
||||
FileID string `json:"file_id"` // 文件ID
|
||||
DownloadURL string `json:"download_url"` // 下载链接
|
||||
Status int64 `json:"status"` // 状态码
|
||||
ErrMsg string `json:"errmsg"` // 该文件错误信息
|
||||
|
||||
@@ -6,7 +6,13 @@ import (
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
const queryURL = "https://api.weixin.qq.com/wxa/query_urllink"
|
||||
const queryURL = "https://api.weixin.qq.com/wxa/query_urllink?access_token=%s"
|
||||
|
||||
// ULQueryRequest 查询加密URLLink请求
|
||||
type ULQueryRequest struct {
|
||||
URLLink string `json:"url_link"`
|
||||
QueryType int `json:"query_type"`
|
||||
}
|
||||
|
||||
// ULQueryResult 返回的结果
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-link/urllink.query.html 返回值
|
||||
@@ -28,25 +34,35 @@ type ULQueryResult struct {
|
||||
ResourceAppid string `json:"resource_appid"`
|
||||
} `json:"cloud_base"`
|
||||
} `json:"url_link_info"`
|
||||
VisitOpenid string `json:"visit_openid"`
|
||||
VisitOpenid string `json:"visit_openid"`
|
||||
QuotaInfo QuotaInfo `json:"quota_info"`
|
||||
}
|
||||
|
||||
// QuotaInfo quota 配置
|
||||
type QuotaInfo struct {
|
||||
RemainVisitQuota int64 `json:"remain_visit_quota"`
|
||||
}
|
||||
|
||||
// Query 查询小程序 url_link 配置。
|
||||
func (u *URLLink) Query(urlLink string) (*ULQueryResult, error) {
|
||||
accessToken, err := u.GetAccessToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("%s?access_token=%s", queryURL, accessToken)
|
||||
response, err := util.PostJSON(uri, map[string]string{"url_link": urlLink})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var resp ULQueryResult
|
||||
err = util.DecodeWithError(response, &resp, "URLLink.Query")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp, nil
|
||||
return u.QueryWithType(&ULQueryRequest{URLLink: urlLink})
|
||||
}
|
||||
|
||||
// QueryWithType 查询加密URLLink
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/url-link/queryUrlLink.html
|
||||
func (u *URLLink) QueryWithType(req *ULQueryRequest) (*ULQueryResult, error) {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = u.GetAccessToken(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.PostJSON(fmt.Sprintf(queryURL, accessToken), req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &ULQueryResult{}
|
||||
err = util.DecodeWithError(response, result, "URLLink.Query")
|
||||
return result, err
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ type ULResult struct {
|
||||
URLLink string `json:"url_link"`
|
||||
}
|
||||
|
||||
// Generate 生成 url link
|
||||
// Generate 生成url link
|
||||
func (u *URLLink) Generate(params *ULParams) (string, error) {
|
||||
accessToken, err := u.GetAccessToken()
|
||||
if err != nil {
|
||||
|
||||
@@ -10,11 +10,12 @@ const (
|
||||
querySchemeURL = "https://api.weixin.qq.com/wxa/queryscheme?access_token=%s"
|
||||
)
|
||||
|
||||
// QueryScheme 获取小程序访问 scheme
|
||||
// QueryScheme 获取小程序访问scheme
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-scheme/urlscheme.query.html#参数
|
||||
type QueryScheme struct {
|
||||
// 小程序 scheme 码
|
||||
Scheme string `json:"scheme"`
|
||||
Scheme string `json:"scheme"`
|
||||
QueryType int `json:"query_type"`
|
||||
}
|
||||
|
||||
// SchemeInfo scheme 配置
|
||||
@@ -23,7 +24,7 @@ type SchemeInfo struct {
|
||||
AppID string `json:"appid"`
|
||||
// 小程序页面路径。
|
||||
Path string `json:"path"`
|
||||
// 小程序页面 query。
|
||||
// 小程序页面query。
|
||||
Query string `json:"query"`
|
||||
// 创建时间,为 Unix 时间戳。
|
||||
CreateTime int64 `json:"create_time"`
|
||||
@@ -33,34 +34,47 @@ type SchemeInfo struct {
|
||||
EnvVersion EnvVersion `json:"env_version"`
|
||||
}
|
||||
|
||||
// resQueryScheme 返回结构体
|
||||
// QuotaInfo quota 配置
|
||||
type QuotaInfo struct {
|
||||
RemainVisitQuota int64 `json:"remain_visit_quota"`
|
||||
}
|
||||
|
||||
// ResQueryScheme 返回结构体
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-scheme/urlscheme.query.html#参数
|
||||
type resQueryScheme struct {
|
||||
type ResQueryScheme struct {
|
||||
// 通用错误
|
||||
util.CommonError
|
||||
// scheme 配置
|
||||
SchemeInfo SchemeInfo `json:"scheme_info"`
|
||||
// 访问该链接的 openid,没有用户访问过则为空字符串
|
||||
VisitOpenid string `json:"visit_openid"`
|
||||
// 访问该链接的openid,没有用户访问过则为空字符串
|
||||
VisitOpenid string `json:"visit_openid"`
|
||||
QuotaInfo QuotaInfo `json:"quota_info"`
|
||||
}
|
||||
|
||||
// QueryScheme 查询小程序 scheme 码
|
||||
func (u *URLScheme) QueryScheme(querySchemeParams QueryScheme) (schemeInfo SchemeInfo, visitOpenid string, err error) {
|
||||
var accessToken string
|
||||
accessToken, err = u.GetAccessToken()
|
||||
res, err := u.QuerySchemeWithRes(querySchemeParams)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
urlStr := fmt.Sprintf(querySchemeURL, accessToken)
|
||||
var response []byte
|
||||
response, err = util.PostJSON(urlStr, querySchemeParams)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用通用方法返回错误
|
||||
var res resQueryScheme
|
||||
err = util.DecodeWithError(response, &res, "QueryScheme")
|
||||
return res.SchemeInfo, res.VisitOpenid, err
|
||||
}
|
||||
|
||||
// QuerySchemeWithRes 查询scheme码
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/url-scheme/queryScheme.html
|
||||
func (u *URLScheme) QuerySchemeWithRes(req QueryScheme) (*ResQueryScheme, error) {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = u.GetAccessToken(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.PostJSON(fmt.Sprintf(querySchemeURL, accessToken), req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &ResQueryScheme{}
|
||||
err = util.DecodeWithError(response, result, "QueryScheme")
|
||||
return result, err
|
||||
}
|
||||
|
||||
@@ -17,7 +17,12 @@ func NewURLScheme(ctx *context.Context) *URLScheme {
|
||||
return &URLScheme{Context: ctx}
|
||||
}
|
||||
|
||||
const generateURL = "https://api.weixin.qq.com/wxa/generatescheme"
|
||||
const (
|
||||
// generateURL 获取加密scheme码
|
||||
generateURL = "https://api.weixin.qq.com/wxa/generatescheme"
|
||||
// generateNFCURL 获取 NFC 的小程序 scheme
|
||||
generateNFCURL = "https://api.weixin.qq.com/wxa/generatenfcscheme?access_token=%s"
|
||||
)
|
||||
|
||||
// TExpireType 失效类型 (指定时间戳/指定间隔)
|
||||
type TExpireType int
|
||||
@@ -50,10 +55,13 @@ type JumpWxa struct {
|
||||
// USParams 请求参数
|
||||
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-scheme/urlscheme.generate.html#请求参数
|
||||
type USParams struct {
|
||||
JumpWxa *JumpWxa `json:"jump_wxa"`
|
||||
ExpireType TExpireType `json:"expire_type"`
|
||||
ExpireTime int64 `json:"expire_time"`
|
||||
ExpireInterval int `json:"expire_interval"`
|
||||
JumpWxa *JumpWxa `json:"jump_wxa,omitempty"`
|
||||
ExpireType TExpireType `json:"expire_type,omitempty"`
|
||||
ExpireTime int64 `json:"expire_time,omitempty"`
|
||||
ExpireInterval int `json:"expire_interval,omitempty"`
|
||||
IsExpire bool `json:"is_expire,omitempty"`
|
||||
ModelID string `json:"model_id,omitempty"`
|
||||
Sn string `json:"sn,omitempty"`
|
||||
}
|
||||
|
||||
// USResult 返回的结果
|
||||
@@ -64,7 +72,7 @@ type USResult struct {
|
||||
OpenLink string `json:"openlink"`
|
||||
}
|
||||
|
||||
// Generate 生成 url link
|
||||
// Generate 生成url link
|
||||
func (u *URLScheme) Generate(params *USParams) (string, error) {
|
||||
accessToken, err := u.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -80,3 +88,22 @@ func (u *URLScheme) Generate(params *USParams) (string, error) {
|
||||
err = util.DecodeWithError(response, &resp, "URLScheme.Generate")
|
||||
return resp.OpenLink, err
|
||||
}
|
||||
|
||||
// GenerateNFC 获取 NFC 的小程序 scheme
|
||||
// see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/url-scheme/generateNFCScheme.html
|
||||
func (u *URLScheme) GenerateNFC(params *USParams) (string, error) {
|
||||
var (
|
||||
accessToken string
|
||||
err error
|
||||
)
|
||||
if accessToken, err = u.GetAccessToken(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
var response []byte
|
||||
if response, err = util.PostJSON(fmt.Sprintf(generateNFCURL, accessToken), params); err != nil {
|
||||
return "", err
|
||||
}
|
||||
result := &USResult{}
|
||||
err = util.DecodeWithError(response, result, "URLScheme.GenerateNFC")
|
||||
return result.OpenLink, err
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ type OrderItem struct {
|
||||
PaidFee int `json:"paid_fee"` // 用户支付金额,单位:分
|
||||
OrderType int `json:"order_type"` // 订单类型 0-支付单 1-退款单
|
||||
RefundFee int `json:"refund_fee"` // 当类型为退款单时表示退款金额,单位分
|
||||
PaidTime int64 `json:"paid_time"` // 支付/退款时间,unix 秒级时间戳
|
||||
PaidTime int64 `json:"paid_time"` // 支付/退款时间,unix秒级时间戳
|
||||
ProvideTime int64 `json:"provide_time"` // 发货时间,unix 秒级时间戳
|
||||
BizMeta string `json:"biz_meta"` // 业务自定义数据 订单创建时传的信息
|
||||
EnvType int `json:"env_type"` // 环境类型 1-现网 2-沙箱
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
// 获取微信服务器 IP 地址
|
||||
// 获取微信服务器IP地址
|
||||
// 文档:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_the_WeChat_server_IP_address.html
|
||||
getCallbackIPURL = "https://api.weixin.qq.com/cgi-bin/getcallbackip"
|
||||
getAPIDomainIPURL = "https://api.weixin.qq.com/cgi-bin/get_api_domain_ip"
|
||||
@@ -29,13 +29,13 @@ func NewBasic(context *context.Context) *Basic {
|
||||
return basic
|
||||
}
|
||||
|
||||
// IPListRes 获取微信服务器 IP 地址 返回结果
|
||||
// IPListRes 获取微信服务器IP地址 返回结果
|
||||
type IPListRes struct {
|
||||
util.CommonError
|
||||
IPList []string `json:"ip_list"`
|
||||
}
|
||||
|
||||
// GetCallbackIP 获取微信 callback IP 地址
|
||||
// GetCallbackIP 获取微信callback IP地址
|
||||
func (basic *Basic) GetCallbackIP() ([]string, error) {
|
||||
ak, err := basic.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -51,7 +51,7 @@ func (basic *Basic) GetCallbackIP() ([]string, error) {
|
||||
return ipListRes.IPList, err
|
||||
}
|
||||
|
||||
// GetAPIDomainIP 获取微信 API 接口 IP 地址
|
||||
// GetAPIDomainIP 获取微信API接口 IP地址
|
||||
func (basic *Basic) GetAPIDomainIP() ([]string, error) {
|
||||
ak, err := basic.GetAccessToken()
|
||||
if err != nil {
|
||||
|
||||
@@ -34,7 +34,7 @@ type Request struct {
|
||||
} `json:"action_info"`
|
||||
}
|
||||
|
||||
// Ticket 二维码 ticket
|
||||
// Ticket 二维码ticket
|
||||
type Ticket struct {
|
||||
util.CommonError `json:",inline"`
|
||||
Ticket string `json:"ticket"`
|
||||
@@ -70,34 +70,26 @@ func (basic *Basic) GetQRTicket(tq *Request) (t *Ticket, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// ShowQRCode 通过 ticket 换取二维码
|
||||
// ShowQRCode 通过ticket换取二维码
|
||||
func ShowQRCode(tk *Ticket) string {
|
||||
return fmt.Sprintf(getQRImgURL, tk.Ticket)
|
||||
}
|
||||
|
||||
// NewTmpQrRequest 新建临时二维码请求实例
|
||||
func NewTmpQrRequest(exp time.Duration, scene interface{}) *Request {
|
||||
var (
|
||||
tq = &Request{
|
||||
ExpireSeconds: int64(exp.Seconds()),
|
||||
}
|
||||
ok bool
|
||||
)
|
||||
tq := &Request{
|
||||
ExpireSeconds: int64(exp.Seconds()),
|
||||
}
|
||||
switch reflect.ValueOf(scene).Kind() {
|
||||
case reflect.String:
|
||||
tq.ActionName = actionStr
|
||||
if tq.ActionInfo.Scene.SceneStr, ok = scene.(string); !ok {
|
||||
panic("scene must be string")
|
||||
}
|
||||
tq.ActionInfo.Scene.SceneStr = scene.(string)
|
||||
case reflect.Int, reflect.Int8, reflect.Int16,
|
||||
reflect.Int32, reflect.Int64,
|
||||
reflect.Uint, reflect.Uint8, reflect.Uint16,
|
||||
reflect.Uint32, reflect.Uint64:
|
||||
tq.ActionName = actionID
|
||||
if tq.ActionInfo.Scene.SceneID, ok = scene.(int); !ok {
|
||||
panic("scene must be int")
|
||||
}
|
||||
default:
|
||||
tq.ActionInfo.Scene.SceneID = scene.(int)
|
||||
}
|
||||
|
||||
return tq
|
||||
@@ -105,25 +97,17 @@ func NewTmpQrRequest(exp time.Duration, scene interface{}) *Request {
|
||||
|
||||
// NewLimitQrRequest 新建永久二维码请求实例
|
||||
func NewLimitQrRequest(scene interface{}) *Request {
|
||||
var (
|
||||
tq = &Request{}
|
||||
ok bool
|
||||
)
|
||||
tq := &Request{}
|
||||
switch reflect.ValueOf(scene).Kind() {
|
||||
case reflect.String:
|
||||
tq.ActionName = actionLimitStr
|
||||
if tq.ActionInfo.Scene.SceneStr, ok = scene.(string); !ok {
|
||||
panic("scene must be string")
|
||||
}
|
||||
tq.ActionInfo.Scene.SceneStr = scene.(string)
|
||||
case reflect.Int, reflect.Int8, reflect.Int16,
|
||||
reflect.Int32, reflect.Int64,
|
||||
reflect.Uint, reflect.Uint8, reflect.Uint16,
|
||||
reflect.Uint32, reflect.Uint64:
|
||||
tq.ActionName = actionLimitID
|
||||
if tq.ActionInfo.Scene.SceneID, ok = scene.(int); !ok {
|
||||
panic("scene must be int")
|
||||
}
|
||||
default:
|
||||
tq.ActionInfo.Scene.SceneID = scene.(int)
|
||||
}
|
||||
|
||||
return tq
|
||||
|
||||
@@ -69,9 +69,9 @@ type SpeedResult struct {
|
||||
|
||||
// sendRequest 发送请求的数据
|
||||
type sendRequest struct {
|
||||
// 根据 tag 获全部发送
|
||||
// 根据tag获全部发送
|
||||
Filter map[string]interface{} `json:"filter,omitempty"`
|
||||
// 根据 OpenID 发送
|
||||
// 根据OpenID发送
|
||||
ToUser interface{} `json:"touser,omitempty"`
|
||||
// 发送文本
|
||||
Text map[string]interface{} `json:"text,omitempty"`
|
||||
@@ -81,7 +81,7 @@ type sendRequest struct {
|
||||
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"`
|
||||
@@ -100,9 +100,9 @@ type Image struct {
|
||||
}
|
||||
|
||||
// SendText 群发文本
|
||||
// user 为 nil,表示全员发送
|
||||
// &User{TagID:2} 根据 tag 发送
|
||||
// &User{OpenID:[]string("xxx","xxx")} 根据 openid 发送
|
||||
// user 为nil,表示全员发送
|
||||
// &User{TagID:2} 根据tag发送
|
||||
// &User{OpenID:[]string("xxx","xxx")} 根据openid发送
|
||||
func (broadcast *Broadcast) SendText(user *User, content string) (*Result, error) {
|
||||
ak, err := broadcast.GetAccessToken()
|
||||
if err != nil {
|
||||
|
||||
@@ -11,4 +11,5 @@ type Config struct {
|
||||
Token string `json:"token"` // token
|
||||
EncodingAESKey string `json:"encoding_aes_key"` // EncodingAESKey
|
||||
Cache cache.Cache
|
||||
UseStableAK bool // use the stable access_token
|
||||
}
|
||||
|
||||
@@ -46,10 +46,10 @@ type KeFuInfo struct {
|
||||
KfNick string `json:"kf_nick"` // 客服昵称
|
||||
KfID int `json:"kf_id"` // 客服编号
|
||||
KfHeadImgURL string `json:"kf_headimgurl"` // 客服头像
|
||||
KfWX string `json:"kf_wx"` // 如果客服帐号已绑定了客服人员微信号,则此处显示微信号
|
||||
InviteWX string `json:"invite_wx"` // 如果客服帐号尚未绑定微信号,但是已经发起了一个绑定邀请,则此处显示绑定邀请的微信号
|
||||
InviteExpTime int `json:"invite_expire_time"` // 如果客服帐号尚未绑定微信号,但是已经发起过一个绑定邀请,邀请的过期时间,为 unix 时间戳
|
||||
InviteStatus string `json:"invite_status"` // 邀请的状态,有等待确认“waiting”,被拒绝“rejected”,过期“expired”
|
||||
KfWX string `json:"kf_wx"` // 如果客服帐号已绑定了客服人员微信号, 则此处显示微信号
|
||||
InviteWX string `json:"invite_wx"` // 如果客服帐号尚未绑定微信号,但是已经发起了一个绑定邀请, 则此处显示绑定邀请的微信号
|
||||
InviteExpTime int `json:"invite_expire_time"` // 如果客服帐号尚未绑定微信号,但是已经发起过一个绑定邀请, 邀请的过期时间,为unix 时间戳
|
||||
InviteStatus string `json:"invite_status"` // 邀请的状态,有等待确认“waiting”,被拒绝“rejected”, 过期“expired”
|
||||
}
|
||||
|
||||
type resKeFuList struct {
|
||||
@@ -108,8 +108,8 @@ func (csm *Manager) OnlineList() (customerServiceOnlineList []*KeFuOnlineInfo, e
|
||||
|
||||
// Add 添加客服账号
|
||||
func (csm *Manager) Add(kfAccount, nickName string) (err error) {
|
||||
// kfAccount:完整客服帐号,格式为:帐号前缀@公众号微信号,帐号前缀最多 10 个字符,必须是英文、数字字符或者下划线,后缀为公众号微信号,长度不超过 30 个字符
|
||||
// nickName:客服昵称,最长 16 个字
|
||||
// kfAccount:完整客服帐号,格式为:帐号前缀@公众号微信号,帐号前缀最多10个字符,必须是英文、数字字符或者下划线,后缀为公众号微信号,长度不超过30个字符
|
||||
// nickName:客服昵称,最长16个字
|
||||
// 参数此处均不做校验
|
||||
var accessToken string
|
||||
accessToken, err = csm.GetAccessToken()
|
||||
|
||||
@@ -22,7 +22,7 @@ const (
|
||||
SlotIDBizSponsor AdSlot = "SLOT_ID_BIZ_SPONSOR"
|
||||
// SlotIDBizCps 公众号返佣商品
|
||||
SlotIDBizCps AdSlot = "SLOT_ID_BIZ_CPS"
|
||||
// SlotIDWeappBanner 小程序 banner
|
||||
// SlotIDWeappBanner 小程序banner
|
||||
SlotIDWeappBanner AdSlot = "SLOT_ID_WEAPP_BANNER"
|
||||
// SlotIDWeappRewardVideo 小程序激励视频
|
||||
SlotIDWeappRewardVideo AdSlot = "SLOT_ID_WEAPP_REWARD_VIDEO"
|
||||
|
||||
@@ -16,11 +16,11 @@ const (
|
||||
)
|
||||
|
||||
type reqDeviceAuthorize struct {
|
||||
// 设备 id 的个数
|
||||
// 设备id的个数
|
||||
DeviceNum string `json:"device_num"`
|
||||
// 设备 id 的列表,json 的 array 格式,其 size 必须等于 device_num
|
||||
// 设备id的列表,json的array格式,其size必须等于device_num
|
||||
DeviceList []ReqDevice `json:"device_list"`
|
||||
// 请求操作的类型,限定取值为:0:设备授权(缺省值为 0)1:设备更新(更新已授权设备的各属性值)
|
||||
// 请求操作的类型,限定取值为:0:设备授权(缺省值为0) 1:设备更新(更新已授权设备的各属性值)
|
||||
OpType string `json:"op_type,omitempty"`
|
||||
// 设备的产品编号(由微信硬件平台分配)。可在公众号设备功能管理页面查询。
|
||||
// 当 op_type 为‘0’,product_id 为‘1’时,不要填写 product_id 字段(会引起不必要错误);
|
||||
@@ -33,39 +33,39 @@ type reqDeviceAuthorize struct {
|
||||
type ReqDevice struct {
|
||||
// 设备的 device id
|
||||
ID string `json:"id"`
|
||||
// 设备的 mac 地址 格式采用 16 进制串的方式(长度为 12 字节),
|
||||
// 不需要 0X 前缀,如:1234567890AB
|
||||
// 设备的mac地址 格式采用16进制串的方式(长度为12字节),
|
||||
// 不需要0X前缀,如: 1234567890AB
|
||||
Mac string `json:"mac"`
|
||||
// 支持以下四种连接协议:
|
||||
// android classic bluetooth – 1
|
||||
// ios classic bluetooth – 2
|
||||
// ble – 3
|
||||
// wifi -- 4
|
||||
// 一个设备可以支持多种连接类型,用符号"|"做分割,客户端优先选择靠前的连接方式(优先级按 | 关系的排序依次降低),举例:
|
||||
// 1:表示设备仅支持 andiod classic bluetooth 1|2:表示设备支持 android 和 ios 两种 classic bluetooth,但是客户端优先选择 android classic bluetooth 协议,如果 android classic bluetooth 协议连接失败,再选择 ios classic bluetooth 协议进行连接
|
||||
// (注:安卓平台不同时支持 BLE 和 classic 类型)
|
||||
// 一个设备可以支持多种连接类型,用符号"|"做分割,客户端优先选择靠前的连接方式(优先级按|关系的排序依次降低),举例:
|
||||
// 1:表示设备仅支持andiod classic bluetooth 1|2:表示设备支持android 和ios 两种classic bluetooth,但是客户端优先选择android classic bluetooth 协议,如果android classic bluetooth协议连接失败,再选择ios classic bluetooth协议进行连接
|
||||
// (注:安卓平台不同时支持BLE和classic类型)
|
||||
ConnectProtocol string `json:"connect_protocol"`
|
||||
// auth 及通信的加密 key,第三方需要将 key 烧制在设备上(128bit),格式采用 16 进制串的方式(长度为 32 字节),不需要 0X 前缀,如:1234567890ABCDEF1234567890ABCDEF
|
||||
// auth及通信的加密key,第三方需要将key烧制在设备上(128bit),格式采用16进制串的方式(长度为32字节),不需要0X前缀,如: 1234567890ABCDEF1234567890ABCDEF
|
||||
AuthKey string `json:"auth_key"`
|
||||
// 断开策略,目前支持:1:退出公众号页面时即断开连接 2:退出公众号之后保持连接不断开
|
||||
// 断开策略,目前支持: 1:退出公众号页面时即断开连接 2:退出公众号之后保持连接不断开
|
||||
CloseStrategy string `json:"close_strategy"`
|
||||
// 连接策略,32 位整型,按 bit 位置位,目前仅第 1bit 和第 3bit 位有效(bit 置 0 为无效,1 为有效;第 2bit 已被废弃),且 bit 位可以按或置位(如 1|4=5),各 bit 置位含义说明如下:
|
||||
// 1:(第 1bit 置位)在公众号对话页面,不停的尝试连接设备
|
||||
// 4:(第 3bit 置位)处于非公众号页面(如主界面等),微信自动连接。当用户切换微信到前台时,可能尝试去连接设备,连上后一定时间会断开
|
||||
// 连接策略,32位整型,按bit位置位,目前仅第1bit和第3bit位有效(bit置0为无效,1为有效;第2bit已被废弃),且bit位可以按或置位(如1|4=5),各bit置位含义说明如下:
|
||||
// 1:(第1bit置位)在公众号对话页面,不停的尝试连接设备
|
||||
// 4:(第3bit置位)处于非公众号页面(如主界面等),微信自动连接。当用户切换微信到前台时,可能尝试去连接设备,连上后一定时间会断开
|
||||
ConnStrategy string `json:"conn_strategy"`
|
||||
// auth version,设备和微信进行 auth 时,会根据该版本号来确认 auth buf 和 auth key 的格式(各 version 对应的 auth buf 及 key 的具体格式可以参看“客户端蓝牙外设协议”),该字段目前支持取值:
|
||||
// 0:不加密的 version
|
||||
// auth version,设备和微信进行auth时,会根据该版本号来确认auth buf和auth key的格式(各version对应的auth buf及key的具体格式可以参看“客户端蓝牙外设协议”),该字段目前支持取值:
|
||||
// 0:不加密的version
|
||||
// 1:version 1
|
||||
AuthVer string `json:"auth_ver"`
|
||||
// 表示 mac 地址在厂商广播 manufacture data 里含有 mac 地址的偏移,取值如下:
|
||||
// 表示mac地址在厂商广播manufacture data里含有mac地址的偏移,取值如下:
|
||||
// -1:在尾部、
|
||||
// -2:表示不包含 mac 地址 其他:非法偏移
|
||||
// -2:表示不包含mac地址 其他:非法偏移
|
||||
ManuMacPos string `json:"manu_mac_pos"`
|
||||
// 表示 mac 地址在厂商 serial number 里含有 mac 地址的偏移,取值如下:
|
||||
// 表示mac地址在厂商serial number里含有mac地址的偏移,取值如下:
|
||||
// -1:表示在尾部
|
||||
// -2:表示不包含 mac 地址 其他:非法偏移
|
||||
// -2:表示不包含mac地址 其他:非法偏移
|
||||
SerMacPost string `json:"ser_mac_post"`
|
||||
// 精简协议类型,取值如下:计步设备精简协议:1(若该字段填 1,connect_protocol 必须包括 3。非精简协议设备切勿填写该字段)
|
||||
// 精简协议类型,取值如下:计步设备精简协议:1 (若该字段填1,connect_protocol 必须包括3。非精简协议设备切勿填写该字段)
|
||||
BleSimpleProtocol string `json:"ble_simple_protocol,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -33,12 +33,12 @@ type Article struct {
|
||||
Title string `json:"title"` // 标题
|
||||
Author string `json:"author"` // 作者
|
||||
Digest string `json:"digest"` // 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空。
|
||||
Content string `json:"content"` // 图文消息的具体内容,支持 HTML 标签,必须少于 2 万字符,小于 1M,且去除 JS
|
||||
ContentSourceURL string `json:"content_source_url"` // 图文消息的原文地址,即点击“阅读原文”后的 URL
|
||||
ThumbMediaID string `json:"thumb_media_id"` // 图文消息的封面图片素材 id(必须是永久 MediaID)
|
||||
ShowCoverPic uint `json:"show_cover_pic"` // 是否显示封面,0 为 false,即不显示,1 为 true,即显示 (默认)
|
||||
NeedOpenComment uint `json:"need_open_comment"` // 是否打开评论,0 不打开 (默认),1 打开
|
||||
OnlyFansCanComment uint `json:"only_fans_can_comment"` // 是否粉丝才可评论,0 所有人可评论 (默认),1 粉丝才可评论
|
||||
Content string `json:"content"` // 图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且去除JS
|
||||
ContentSourceURL string `json:"content_source_url"` // 图文消息的原文地址,即点击“阅读原文”后的URL
|
||||
ThumbMediaID string `json:"thumb_media_id"` // 图文消息的封面图片素材id(必须是永久MediaID)
|
||||
ShowCoverPic uint `json:"show_cover_pic"` // 是否显示封面,0为false,即不显示,1为true,即显示(默认)
|
||||
NeedOpenComment uint `json:"need_open_comment"` // 是否打开评论,0不打开(默认),1打开
|
||||
OnlyFansCanComment uint `json:"only_fans_can_comment"` // 是否粉丝才可评论,0所有人可评论(默认),1粉丝才可评论
|
||||
}
|
||||
|
||||
// AddDraft 新建草稿
|
||||
@@ -117,7 +117,7 @@ func (draft *Draft) DeleteDraft(mediaID string) (err error) {
|
||||
}
|
||||
|
||||
// UpdateDraft 修改草稿
|
||||
// index 要更新的文章在图文消息中的位置(多图文消息时,此字段才有意义),第一篇为 0
|
||||
// index 要更新的文章在图文消息中的位置(多图文消息时,此字段才有意义),第一篇为0
|
||||
func (draft *Draft) UpdateDraft(article *Article, mediaID string, index uint) (err error) {
|
||||
accessToken, err := draft.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -176,7 +176,7 @@ type ArticleList struct {
|
||||
|
||||
// ArticleListItem 用于 ArticleList 的 item 节点
|
||||
type ArticleListItem struct {
|
||||
MediaID string `json:"media_id"` // 图文消息的 id
|
||||
MediaID string `json:"media_id"` // 图文消息的id
|
||||
Content ArticleListContent `json:"content"` // 内容
|
||||
UpdateTime int64 `json:"update_time"` // 这篇图文消息素材的最后更新时间
|
||||
}
|
||||
|
||||
@@ -79,23 +79,23 @@ func (freePublish *FreePublish) Publish(mediaID string) (publishID int64, err er
|
||||
// PublishStatusList 发布任务状态列表
|
||||
type PublishStatusList struct {
|
||||
util.CommonError
|
||||
PublishID int64 `json:"publish_id"` // 发布任务 id
|
||||
PublishID int64 `json:"publish_id"` // 发布任务id
|
||||
PublishStatus PublishStatus `json:"publish_status"` // 发布状态
|
||||
ArticleID string `json:"article_id"` // 当发布状态为 0 时(即成功)时,返回图文的 article_id,可用于“客服消息”场景
|
||||
ArticleID string `json:"article_id"` // 当发布状态为0时(即成功)时,返回图文的 article_id,可用于“客服消息”场景
|
||||
ArticleDetail PublishArticleDetail `json:"article_detail"` // 发布任务文章成功状态详情
|
||||
FailIndex []uint `json:"fail_idx"` // 当发布状态为 2 或 4 时,返回不通过的文章编号,第一篇为 1;其他发布状态则为空
|
||||
FailIndex []uint `json:"fail_idx"` // 当发布状态为2或4时,返回不通过的文章编号,第一篇为 1;其他发布状态则为空
|
||||
}
|
||||
|
||||
// PublishArticleDetail 发布任务成功详情
|
||||
type PublishArticleDetail struct {
|
||||
Count uint `json:"count"` // 当发布状态为 0 时(即成功)时,返回文章数量
|
||||
Count uint `json:"count"` // 当发布状态为0时(即成功)时,返回文章数量
|
||||
Items []PublishArticleItem `json:"item"`
|
||||
}
|
||||
|
||||
// PublishArticleItem 发布任务成功的文章内容
|
||||
type PublishArticleItem struct {
|
||||
Index uint `json:"idx"` // 当发布状态为 0 时(即成功)时,返回文章对应的编号
|
||||
ArticleURL string `json:"article_url"` // 当发布状态为 0 时(即成功)时,返回图文的永久链接
|
||||
Index uint `json:"idx"` // 当发布状态为0时(即成功)时,返回文章对应的编号
|
||||
ArticleURL string `json:"article_url"` // 当发布状态为0时(即成功)时,返回图文的永久链接
|
||||
}
|
||||
|
||||
// SelectStatus 发布状态轮询接口
|
||||
@@ -122,8 +122,8 @@ func (freePublish *FreePublish) SelectStatus(publishID int64) (list PublishStatu
|
||||
}
|
||||
|
||||
// Delete 删除发布。
|
||||
// index 要删除的文章在图文消息中的位置,第一篇编号为 1,该字段不填或填 0 会删除全部文章
|
||||
// !!! 此操作不可逆,请谨慎操作!!! 删除后微信公众号后台仍然会有记录!!!
|
||||
// index 要删除的文章在图文消息中的位置,第一篇编号为1,该字段不填或填0会删除全部文章
|
||||
// !!!此操作不可逆,请谨慎操作!!!删除后微信公众号后台仍然会有记录!!!
|
||||
func (freePublish *FreePublish) Delete(articleID string, index uint) (err error) {
|
||||
accessToken, err := freePublish.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -152,13 +152,13 @@ type Article struct {
|
||||
Title string `json:"title"` // 标题
|
||||
Author string `json:"author"` // 作者
|
||||
Digest string `json:"digest"` // 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
|
||||
Content string `json:"content"` // 图文消息的具体内容,支持 HTML 标签,必须少于 2 万字符,小于 1M,且此处会去除 JS
|
||||
ContentSourceURL string `json:"content_source_url"` // 图文消息的原文地址,即点击“阅读原文”后的 URL
|
||||
ThumbMediaID string `json:"thumb_media_id"` // 图文消息的封面图片素材 id(一定是永久 MediaID)
|
||||
ShowCoverPic uint `json:"show_cover_pic"` // 是否显示封面,0 为 false,即不显示,1 为 true,即显示 (默认)
|
||||
NeedOpenComment uint `json:"need_open_comment"` // 是否打开评论,0 不打开 (默认),1 打开
|
||||
OnlyFansCanComment uint `json:"only_fans_can_comment"` // 是否粉丝才可评论,0 所有人可评论 (默认),1 粉丝才可评论
|
||||
URL string `json:"url"` // 图文消息的 URL
|
||||
Content string `json:"content"` // 图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且此处会去除JS
|
||||
ContentSourceURL string `json:"content_source_url"` // 图文消息的原文地址,即点击“阅读原文”后的URL
|
||||
ThumbMediaID string `json:"thumb_media_id"` // 图文消息的封面图片素材id(一定是永久MediaID)
|
||||
ShowCoverPic uint `json:"show_cover_pic"` // 是否显示封面,0为false,即不显示,1为true,即显示(默认)
|
||||
NeedOpenComment uint `json:"need_open_comment"` // 是否打开评论,0不打开(默认),1打开
|
||||
OnlyFansCanComment uint `json:"only_fans_can_comment"` // 是否粉丝才可评论,0所有人可评论(默认),1粉丝才可评论
|
||||
URL string `json:"url"` // 图文消息的URL
|
||||
IsDeleted bool `json:"is_deleted"` // 该图文是否被删除
|
||||
}
|
||||
|
||||
@@ -199,7 +199,7 @@ type ArticleList struct {
|
||||
|
||||
// ArticleListItem 用于 ArticleList 的 item 节点
|
||||
type ArticleListItem struct {
|
||||
ArticleID string `json:"article_id"` // 成功发布的图文消息 id
|
||||
ArticleID string `json:"article_id"` // 成功发布的图文消息id
|
||||
Content ArticleListContent `json:"content"` // 内容
|
||||
UpdateTime int64 `json:"update_time"` // 这篇图文消息素材的最后更新时间
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package js
|
||||
|
||||
import (
|
||||
context2 "context"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/credential"
|
||||
@@ -14,7 +15,7 @@ type Js struct {
|
||||
credential.JsTicketHandle
|
||||
}
|
||||
|
||||
// Config 返回给用户 jssdk 配置信息
|
||||
// Config 返回给用户jssdk配置信息
|
||||
type Config struct {
|
||||
AppID string `json:"app_id"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
@@ -31,22 +32,39 @@ func NewJs(context *context.Context) *Js {
|
||||
return js
|
||||
}
|
||||
|
||||
// SetJsTicketHandle 自定义 js ticket 取值方式
|
||||
// SetJsTicketHandle 自定义js ticket取值方式
|
||||
func (js *Js) SetJsTicketHandle(ticketHandle credential.JsTicketHandle) {
|
||||
js.JsTicketHandle = ticketHandle
|
||||
}
|
||||
|
||||
// GetConfig 获取 jssdk 需要的配置参数
|
||||
// GetConfig 获取jssdk需要的配置参数
|
||||
// uri 为当前网页地址
|
||||
func (js *Js) GetConfig(uri string) (config *Config, err error) {
|
||||
config = new(Config)
|
||||
return js.GetConfigContext(context2.Background(), uri)
|
||||
}
|
||||
|
||||
// GetConfigContext 新方法,允许传入上下文,避免协程泄漏
|
||||
func (js *Js) GetConfigContext(ctx context2.Context, uri string) (config *Config, err error) {
|
||||
var accessToken string
|
||||
accessToken, err = js.GetAccessToken()
|
||||
// 类型断言,如果断言成功,调用安全的 GetAccessTokenContext 方法
|
||||
if ctxHandle, ok := js.Context.AccessTokenHandle.(credential.AccessTokenContextHandle); ok {
|
||||
accessToken, err = ctxHandle.GetAccessTokenContext(ctx)
|
||||
} else {
|
||||
// 如果没有实现 AccessTokenContextHandle 接口,调用旧的 GetAccessToken 方法
|
||||
accessToken, err = js.Context.GetAccessToken()
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var ticketStr string
|
||||
ticketStr, err = js.GetTicket(accessToken)
|
||||
// 类型断言 jsTicket
|
||||
if ticketCtxHandle, ok := js.JsTicketHandle.(credential.JsTicketContextHandle); ok {
|
||||
ticketStr, err = ticketCtxHandle.GetTicketContext(ctx, accessToken)
|
||||
} else {
|
||||
// 如果没有实现 JsTicketContextHandle 接口,调用旧的 GetTicket 方法
|
||||
ticketStr, err = js.GetTicket(accessToken)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -56,6 +74,7 @@ func (js *Js) GetConfig(uri string) (config *Config, err error) {
|
||||
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
|
||||
sigStr := util.Signature(str)
|
||||
|
||||
config = new(Config)
|
||||
config.AppID = js.AppID
|
||||
config.NonceStr = nonceStr
|
||||
config.Timestamp = timestamp
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"github.com/silenceper/wechat/v2/officialaccount/context"
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
@@ -163,7 +164,7 @@ type resAddMaterial struct {
|
||||
}
|
||||
|
||||
// AddMaterialFromReader 上传永久性素材(处理视频需要单独上传),从 io.Reader 中读取
|
||||
func (material *Material) AddMaterialFromReader(mediaType MediaType, filename string, reader io.Reader) (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 {
|
||||
err = errors.New("永久视频素材上传使用 AddVideo 方法")
|
||||
return
|
||||
@@ -175,8 +176,10 @@ func (material *Material) AddMaterialFromReader(mediaType MediaType, filename st
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("%s?access_token=%s&type=%s", addMaterialURL, accessToken, mediaType)
|
||||
// 获取文件名
|
||||
filename := path.Base(filePath)
|
||||
var response []byte
|
||||
response, err = util.PostFileFromReader("media", filename, uri, reader)
|
||||
response, err = util.PostFileFromReader("media", filePath, filename, uri, reader)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -211,7 +214,7 @@ type reqVideo struct {
|
||||
}
|
||||
|
||||
// AddVideoFromReader 永久视频素材文件上传,从 io.Reader 中读取
|
||||
func (material *Material) AddVideoFromReader(filename, title, introduction string, reader io.Reader) (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
|
||||
accessToken, err = material.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -229,17 +232,19 @@ func (material *Material) AddVideoFromReader(filename, title, introduction strin
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
fileName := path.Base(filePath)
|
||||
fields := []util.MultipartFormField{
|
||||
{
|
||||
IsFile: true,
|
||||
Fieldname: "media",
|
||||
Filename: filename,
|
||||
FilePath: filePath,
|
||||
Filename: fileName,
|
||||
FileReader: reader,
|
||||
},
|
||||
{
|
||||
IsFile: false,
|
||||
Fieldname: "description",
|
||||
Filename: fileName,
|
||||
Value: fieldValue,
|
||||
},
|
||||
}
|
||||
@@ -265,14 +270,14 @@ func (material *Material) AddVideoFromReader(filename, title, introduction strin
|
||||
}
|
||||
|
||||
// AddVideo 永久视频素材文件上传
|
||||
func (material *Material) AddVideo(filename, title, introduction string) (mediaID string, url string, err error) {
|
||||
f, err := os.Open(filename)
|
||||
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(filename, title, introduction, f)
|
||||
return material.AddVideoFromReader(directory, title, introduction, f)
|
||||
}
|
||||
|
||||
type reqDeleteMaterial struct {
|
||||
|
||||
@@ -3,6 +3,7 @@ package material
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
@@ -11,13 +12,13 @@ import (
|
||||
type MediaType string
|
||||
|
||||
const (
|
||||
// MediaTypeImage 媒体文件:图片
|
||||
// MediaTypeImage 媒体文件:图片
|
||||
MediaTypeImage MediaType = "image"
|
||||
// MediaTypeVoice 媒体文件:声音
|
||||
// MediaTypeVoice 媒体文件:声音
|
||||
MediaTypeVoice MediaType = "voice"
|
||||
// MediaTypeVideo 媒体文件:视频
|
||||
// MediaTypeVideo 媒体文件:视频
|
||||
MediaTypeVideo MediaType = "video"
|
||||
// MediaTypeThumb 媒体文件:缩略图
|
||||
// MediaTypeThumb 媒体文件:缩略图
|
||||
MediaTypeThumb MediaType = "thumb"
|
||||
)
|
||||
|
||||
@@ -62,8 +63,40 @@ func (material *Material) MediaUpload(mediaType MediaType, filename string) (med
|
||||
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 返回临时素材的下载地址供用户自己处理
|
||||
// NOTICE: URL 不可公开,因为含 access_token 需要立即另存文件
|
||||
// NOTICE: URL 不可公开,因为含access_token 需要立即另存文件
|
||||
func (material *Material) GetMediaURL(mediaID string) (mediaURL string, err error) {
|
||||
var accessToken string
|
||||
accessToken, err = material.GetAccessToken()
|
||||
|
||||
@@ -23,7 +23,7 @@ func (btn *Button) SetSubButton(name string, subButtons []*Button) *Button {
|
||||
return btn
|
||||
}
|
||||
|
||||
// SetClickButton btn 为 click 类型
|
||||
// SetClickButton btn 为click类型
|
||||
func (btn *Button) SetClickButton(name, key string) *Button {
|
||||
btn.Type = "click"
|
||||
btn.Name = name
|
||||
@@ -34,7 +34,7 @@ func (btn *Button) SetClickButton(name, key string) *Button {
|
||||
return btn
|
||||
}
|
||||
|
||||
// SetViewButton view 类型
|
||||
// SetViewButton view类型
|
||||
func (btn *Button) SetViewButton(name, url string) *Button {
|
||||
btn.Type = "view"
|
||||
btn.Name = name
|
||||
@@ -116,7 +116,7 @@ func (btn *Button) SetLocationSelectButton(name, key string) *Button {
|
||||
return btn
|
||||
}
|
||||
|
||||
// SetMediaIDButton 设置 下发消息 (除文本消息) 类型按钮
|
||||
// SetMediaIDButton 设置 下发消息(除文本消息) 类型按钮
|
||||
func (btn *Button) SetMediaIDButton(name, mediaID string) *Button {
|
||||
btn.Type = "media_id"
|
||||
btn.Name = name
|
||||
@@ -128,7 +128,7 @@ func (btn *Button) SetMediaIDButton(name, mediaID string) *Button {
|
||||
return btn
|
||||
}
|
||||
|
||||
// SetViewLimitedButton 设置 跳转图文消息 URL 类型按钮
|
||||
// SetViewLimitedButton 设置 跳转图文消息URL 类型按钮
|
||||
func (btn *Button) SetViewLimitedButton(name, mediaID string) *Button {
|
||||
btn.Type = "view_limited"
|
||||
btn.Name = name
|
||||
@@ -159,12 +159,12 @@ func NewSubButton(name string, subButtons []*Button) *Button {
|
||||
return (&Button{}).SetSubButton(name, subButtons)
|
||||
}
|
||||
|
||||
// NewClickButton btn 为 click 类型
|
||||
// NewClickButton btn 为click类型
|
||||
func NewClickButton(name, key string) *Button {
|
||||
return (&Button{}).SetClickButton(name, key)
|
||||
}
|
||||
|
||||
// NewViewButton view 类型
|
||||
// NewViewButton view类型
|
||||
func NewViewButton(name, url string) *Button {
|
||||
return (&Button{}).SetViewButton(name, url)
|
||||
}
|
||||
@@ -199,12 +199,12 @@ func NewLocationSelectButton(name, key string) *Button {
|
||||
return (&Button{}).SetLocationSelectButton(name, key)
|
||||
}
|
||||
|
||||
// NewMediaIDButton 下发消息 (除文本消息) 类型按钮
|
||||
// NewMediaIDButton 下发消息(除文本消息) 类型按钮
|
||||
func NewMediaIDButton(name, mediaID string) *Button {
|
||||
return (&Button{}).SetMediaIDButton(name, mediaID)
|
||||
}
|
||||
|
||||
// NewViewLimitedButton 跳转图文消息 URL 类型按钮
|
||||
// NewViewLimitedButton 跳转图文消息URL 类型按钮
|
||||
func NewViewLimitedButton(name, mediaID string) *Button {
|
||||
return (&Button{}).SetViewLimitedButton(name, mediaID)
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ func NewMessageManager(context *context.Context) *Manager {
|
||||
|
||||
// CustomerMessage 客服消息
|
||||
type CustomerMessage struct {
|
||||
ToUser string `json:"touser"` // 接受者 OpenID
|
||||
ToUser string `json:"touser"` // 接受者OpenID
|
||||
Msgtype MsgType `json:"msgtype"` // 客服消息类型
|
||||
Text *MediaText `json:"text,omitempty"` // 可选
|
||||
Image *MediaResource `json:"image,omitempty"` // 可选
|
||||
@@ -93,12 +93,12 @@ type MediaText struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// MediaResource 消息使用的永久素材 id
|
||||
// MediaResource 消息使用的永久素材id
|
||||
type MediaResource struct {
|
||||
MediaID string `json:"media_id"`
|
||||
}
|
||||
|
||||
// MediaArticle 消息使用的已发布文章 id
|
||||
// MediaArticle 消息使用的已发布文章id
|
||||
type MediaArticle struct {
|
||||
ArticleID string `json:"article_id"`
|
||||
}
|
||||
@@ -146,7 +146,7 @@ type MsgmenuItem struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// MediaWxcard 卡券的 id
|
||||
// MediaWxcard 卡券的id
|
||||
type MediaWxcard struct {
|
||||
CardID string `json:"card_id"`
|
||||
}
|
||||
|
||||
@@ -31,14 +31,14 @@ func NewSubscribe(context *context.Context) *Subscribe {
|
||||
|
||||
// SubscribeMessage 发送的订阅消息内容
|
||||
type SubscribeMessage struct {
|
||||
ToUser string `json:"touser"` // 必须,接受者 OpenID
|
||||
TemplateID string `json:"template_id"` // 必须,模版 ID
|
||||
Page string `json:"page,omitempty"` // 可选,跳转网页时填写
|
||||
Data map[string]*SubscribeDataItem `json:"data"` // 必须,模板数据
|
||||
ToUser string `json:"touser"` // 必须, 接受者OpenID
|
||||
TemplateID string `json:"template_id"` // 必须, 模版ID
|
||||
Page string `json:"page,omitempty"` // 可选, 跳转网页时填写
|
||||
Data map[string]*SubscribeDataItem `json:"data"` // 必须, 模板数据
|
||||
MiniProgram struct {
|
||||
AppID string `json:"appid"` // 所需跳转到的小程序 appid(该小程序 appid 必须与发模板消息的公众号是绑定关联关系)
|
||||
PagePath string `json:"pagepath"` // 所需跳转到小程序的具体页面路径,支持带参数,(示例 index?foo=bar)
|
||||
} `json:"miniprogram"` // 可选,跳转至小程序地址
|
||||
AppID string `json:"appid"` // 所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)
|
||||
PagePath string `json:"pagepath"` // 所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar)
|
||||
} `json:"miniprogram"` // 可选,跳转至小程序地址
|
||||
}
|
||||
|
||||
// SubscribeDataItem 模版内某个 .DATA 的值
|
||||
@@ -143,7 +143,7 @@ func (tpl *Subscribe) Delete(templateID string) (err error) {
|
||||
|
||||
// PublicTemplateCategory 公众号类目
|
||||
type PublicTemplateCategory struct {
|
||||
ID int `json:"id"` // 类目 ID
|
||||
ID int `json:"id"` // 类目ID
|
||||
Name string `json:"name"` // 类目的中文名
|
||||
}
|
||||
|
||||
|
||||
@@ -29,17 +29,17 @@ func NewTemplate(context *context.Context) *Template {
|
||||
|
||||
// TemplateMessage 发送的模板消息内容
|
||||
type TemplateMessage struct {
|
||||
ToUser string `json:"touser"` // 必须,接受者 OpenID
|
||||
TemplateID string `json:"template_id"` // 必须,模版 ID
|
||||
URL string `json:"url,omitempty"` // 可选,用户点击后跳转的 URL, 该 URL 必须处于开发者在公众平台网站中设置的域中
|
||||
Color string `json:"color,omitempty"` // 可选,整个消息的颜色,可以不设置
|
||||
Data map[string]*TemplateDataItem `json:"data"` // 必须,模板数据
|
||||
ClientMsgID string `json:"client_msg_id,omitempty"` // 可选,防重入 ID
|
||||
ToUser string `json:"touser"` // 必须, 接受者OpenID
|
||||
TemplateID string `json:"template_id"` // 必须, 模版ID
|
||||
URL string `json:"url,omitempty"` // 可选, 用户点击后跳转的URL, 该URL必须处于开发者在公众平台网站中设置的域中
|
||||
Color string `json:"color,omitempty"` // 可选, 整个消息的颜色, 可以不设置
|
||||
Data map[string]*TemplateDataItem `json:"data"` // 必须, 模板数据
|
||||
ClientMsgID string `json:"client_msg_id,omitempty"` // 可选, 防重入ID
|
||||
|
||||
MiniProgram struct {
|
||||
AppID string `json:"appid"` // 所需跳转到的小程序 appid(该小程序 appid 必须与发模板消息的公众号是绑定关联关系)
|
||||
PagePath string `json:"pagepath"` // 所需跳转到小程序的具体页面路径,支持带参数,(示例 index?foo=bar)
|
||||
} `json:"miniprogram"` // 可选,跳转至小程序地址
|
||||
AppID string `json:"appid"` // 所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)
|
||||
PagePath string `json:"pagepath"` // 所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar)
|
||||
} `json:"miniprogram"` // 可选,跳转至小程序地址
|
||||
}
|
||||
|
||||
// TemplateDataItem 模版内某个 .DATA 的值
|
||||
@@ -80,7 +80,7 @@ func (tpl *Template) Send(msg *TemplateMessage) (msgID int64, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// TemplateItem 模板消息。
|
||||
// TemplateItem 模板消息.
|
||||
type TemplateItem struct {
|
||||
TemplateID string `json:"template_id"`
|
||||
Title string `json:"title"`
|
||||
@@ -121,7 +121,7 @@ type resTemplateAdd struct {
|
||||
TemplateID string `json:"template_id"`
|
||||
}
|
||||
|
||||
// Add 添加模板。
|
||||
// Add 添加模板.
|
||||
func (tpl *Template) Add(shortID string, keyNameList []string) (templateID string, err error) {
|
||||
var accessToken string
|
||||
accessToken, err = tpl.GetAccessToken()
|
||||
@@ -144,7 +144,7 @@ func (tpl *Template) Add(shortID string, keyNameList []string) (templateID strin
|
||||
return result.TemplateID, err
|
||||
}
|
||||
|
||||
// Delete 删除私有模板。
|
||||
// Delete 删除私有模板.
|
||||
func (tpl *Template) Delete(templateID string) (err error) {
|
||||
var accessToken string
|
||||
accessToken, err = tpl.GetAccessToken()
|
||||
|
||||
@@ -32,14 +32,14 @@ func NewOauth(context *context.Context) *Oauth {
|
||||
return auth
|
||||
}
|
||||
|
||||
// GetRedirectURL 获取跳转的 url 地址
|
||||
// GetRedirectURL 获取跳转的url地址
|
||||
func (oauth *Oauth) GetRedirectURL(redirectURI, scope, state string) (string, error) {
|
||||
// url encode
|
||||
urlStr := url.QueryEscape(redirectURI)
|
||||
return fmt.Sprintf(redirectOauthURL, oauth.AppID, urlStr, scope, state), nil
|
||||
}
|
||||
|
||||
// GetWebAppRedirectURL 获取网页应用跳转的 url 地址
|
||||
// GetWebAppRedirectURL 获取网页应用跳转的url地址
|
||||
func (oauth *Oauth) GetWebAppRedirectURL(redirectURI, scope, state string) (string, error) {
|
||||
urlStr := url.QueryEscape(redirectURI)
|
||||
return fmt.Sprintf(webAppRedirectOauthURL, oauth.AppID, urlStr, scope, state), nil
|
||||
@@ -55,7 +55,7 @@ func (oauth *Oauth) Redirect(writer http.ResponseWriter, req *http.Request, redi
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResAccessToken 获取用户授权 access_token 的返回结果
|
||||
// ResAccessToken 获取用户授权access_token的返回结果
|
||||
type ResAccessToken struct {
|
||||
util.CommonError
|
||||
|
||||
@@ -65,7 +65,7 @@ type ResAccessToken struct {
|
||||
OpenID string `json:"openid"`
|
||||
Scope string `json:"scope"`
|
||||
|
||||
// IsSnapShotUser 是否为快照页模式虚拟账号,只有当用户是快照页模式虚拟账号时返回,值为 1
|
||||
// IsSnapShotUser 是否为快照页模式虚拟账号,只有当用户是快照页模式虚拟账号时返回,值为1
|
||||
// 公众号文档 https://developers.weixin.qq.com/community/minihome/doc/000c2c34068880629ced91a2f56001
|
||||
IsSnapShotUser int `json:"is_snapshotuser"`
|
||||
|
||||
@@ -74,7 +74,7 @@ type ResAccessToken struct {
|
||||
UnionID string `json:"unionid"`
|
||||
}
|
||||
|
||||
// GetUserInfoByCodeContext 通过网页授权的 code 换取用户的信息
|
||||
// GetUserInfoByCodeContext 通过网页授权的code 换取用户的信息
|
||||
func (oauth *Oauth) GetUserInfoByCodeContext(ctx ctx2.Context, code string) (result UserInfo, err error) {
|
||||
var (
|
||||
token ResAccessToken
|
||||
@@ -86,12 +86,12 @@ func (oauth *Oauth) GetUserInfoByCodeContext(ctx ctx2.Context, code string) (res
|
||||
return oauth.GetUserInfoContext(ctx, token.AccessToken, token.OpenID, "")
|
||||
}
|
||||
|
||||
// GetUserAccessToken 通过网页授权的 code 换取 access_token(区别于 context 中的 access_token)
|
||||
// GetUserAccessToken 通过网页授权的code 换取access_token(区别于context中的access_token)
|
||||
func (oauth *Oauth) GetUserAccessToken(code string) (result ResAccessToken, err error) {
|
||||
return oauth.GetUserAccessTokenContext(ctx2.Background(), code)
|
||||
}
|
||||
|
||||
// GetUserAccessTokenContext 通过网页授权的 code 换取 access_token(区别于 context 中的 access_token) with context
|
||||
// GetUserAccessTokenContext 通过网页授权的code 换取access_token(区别于context中的access_token) with context
|
||||
func (oauth *Oauth) GetUserAccessTokenContext(ctx ctx2.Context, code string) (result ResAccessToken, err error) {
|
||||
urlStr := fmt.Sprintf(accessTokenURL, oauth.AppID, oauth.AppSecret, code)
|
||||
var response []byte
|
||||
@@ -110,12 +110,12 @@ func (oauth *Oauth) GetUserAccessTokenContext(ctx ctx2.Context, code string) (re
|
||||
return
|
||||
}
|
||||
|
||||
// RefreshAccessToken 刷新 access_token
|
||||
// RefreshAccessToken 刷新access_token
|
||||
func (oauth *Oauth) RefreshAccessToken(refreshToken string) (result ResAccessToken, err error) {
|
||||
return oauth.RefreshAccessTokenContext(ctx2.Background(), refreshToken)
|
||||
}
|
||||
|
||||
// RefreshAccessTokenContext 刷新 access_token with context
|
||||
// RefreshAccessTokenContext 刷新access_token with context
|
||||
func (oauth *Oauth) RefreshAccessTokenContext(ctx ctx2.Context, refreshToken string) (result ResAccessToken, err error) {
|
||||
urlStr := fmt.Sprintf(refreshAccessTokenURL, oauth.AppID, refreshToken)
|
||||
var response []byte
|
||||
@@ -134,12 +134,12 @@ func (oauth *Oauth) RefreshAccessTokenContext(ctx ctx2.Context, refreshToken str
|
||||
return
|
||||
}
|
||||
|
||||
// CheckAccessToken 检验 access_token 是否有效
|
||||
// CheckAccessToken 检验access_token是否有效
|
||||
func (oauth *Oauth) CheckAccessToken(accessToken, openID string) (b bool, err error) {
|
||||
return oauth.CheckAccessTokenContext(ctx2.Background(), accessToken, openID)
|
||||
}
|
||||
|
||||
// CheckAccessTokenContext 检验 access_token 是否有效 with context
|
||||
// CheckAccessTokenContext 检验access_token是否有效 with context
|
||||
func (oauth *Oauth) CheckAccessTokenContext(ctx ctx2.Context, accessToken, openID string) (b bool, err error) {
|
||||
urlStr := fmt.Sprintf(checkAccessTokenURL, accessToken, openID)
|
||||
var response []byte
|
||||
@@ -175,12 +175,12 @@ type UserInfo struct {
|
||||
Unionid string `json:"unionid"`
|
||||
}
|
||||
|
||||
// GetUserInfo 如果 scope 为 snsapi_userinfo 则可以通过此方法获取到用户基本信息
|
||||
// GetUserInfo 如果scope为 snsapi_userinfo 则可以通过此方法获取到用户基本信息
|
||||
func (oauth *Oauth) GetUserInfo(accessToken, openID, lang string) (result UserInfo, err error) {
|
||||
return oauth.GetUserInfoContext(ctx2.Background(), accessToken, openID, lang)
|
||||
}
|
||||
|
||||
// GetUserInfoContext 如果 scope 为 snsapi_userinfo 则可以通过此方法获取到用户基本信息 with context
|
||||
// GetUserInfoContext 如果scope为 snsapi_userinfo 则可以通过此方法获取到用户基本信息 with context
|
||||
func (oauth *Oauth) GetUserInfoContext(ctx ctx2.Context, accessToken, openID, lang string) (result UserInfo, err error) {
|
||||
if lang == "" {
|
||||
lang = "zh_CN"
|
||||
|
||||
@@ -153,7 +153,7 @@ func NewOCR(c *context.Context) *OCR {
|
||||
return ocr
|
||||
}
|
||||
|
||||
// IDCard 身份证 OCR 识别接口
|
||||
// IDCard 身份证OCR识别接口
|
||||
func (ocr *OCR) IDCard(path string) (resIDCard ResIDCard, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -170,7 +170,7 @@ func (ocr *OCR) IDCard(path string) (resIDCard ResIDCard, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// BankCard 银行卡 OCR 识别接口
|
||||
// BankCard 银行卡OCR识别接口
|
||||
func (ocr *OCR) BankCard(path string) (resBankCard ResBankCard, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -187,7 +187,7 @@ func (ocr *OCR) BankCard(path string) (resBankCard ResBankCard, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// Driving 行驶证 OCR 识别接口
|
||||
// Driving 行驶证OCR识别接口
|
||||
func (ocr *OCR) Driving(path string) (resDriving ResDriving, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -204,7 +204,7 @@ func (ocr *OCR) Driving(path string) (resDriving ResDriving, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// DrivingLicense 驾驶证 OCR 识别接口
|
||||
// DrivingLicense 驾驶证OCR识别接口
|
||||
func (ocr *OCR) DrivingLicense(path string) (resDrivingLicense ResDrivingLicense, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -221,7 +221,7 @@ func (ocr *OCR) DrivingLicense(path string) (resDrivingLicense ResDrivingLicense
|
||||
return
|
||||
}
|
||||
|
||||
// BizLicense 营业执照 OCR 识别接口
|
||||
// BizLicense 营业执照OCR识别接口
|
||||
func (ocr *OCR) BizLicense(path string) (resBizLicense ResBizLicense, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -238,7 +238,7 @@ func (ocr *OCR) BizLicense(path string) (resBizLicense ResBizLicense, err error)
|
||||
return
|
||||
}
|
||||
|
||||
// Common 通用印刷体 OCR 识别接口
|
||||
// Common 通用印刷体OCR识别接口
|
||||
func (ocr *OCR) Common(path string) (resCommon ResCommon, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
@@ -255,7 +255,7 @@ func (ocr *OCR) Common(path string) (resCommon ResCommon, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// PlateNumber 车牌 OCR 识别接口
|
||||
// PlateNumber 车牌OCR识别接口
|
||||
func (ocr *OCR) PlateNumber(path string) (resPlateNumber ResPlateNumber, err error) {
|
||||
accessToken, err := ocr.GetAccessToken()
|
||||
if err != nil {
|
||||
|
||||
@@ -4,28 +4,30 @@ import (
|
||||
stdcontext "context"
|
||||
"net/http"
|
||||
|
||||
"github.com/silenceper/wechat/v2/credential"
|
||||
"github.com/silenceper/wechat/v2/internal/openapi"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/draft"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/freepublish"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/ocr"
|
||||
|
||||
"github.com/silenceper/wechat/v2/officialaccount/datacube"
|
||||
|
||||
"github.com/silenceper/wechat/v2/credential"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/basic"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/broadcast"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/config"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/context"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/customerservice"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/datacube"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/device"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/draft"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/freepublish"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/js"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/material"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/menu"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/message"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/oauth"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/ocr"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/server"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/user"
|
||||
)
|
||||
|
||||
// OfficialAccount 微信公众号相关 API
|
||||
// OfficialAccount 微信公众号相关API
|
||||
type OfficialAccount struct {
|
||||
ctx *context.Context
|
||||
basic *basic.Basic
|
||||
@@ -45,9 +47,15 @@ type OfficialAccount struct {
|
||||
subscribeMsg *message.Subscribe
|
||||
}
|
||||
|
||||
// NewOfficialAccount 实例化公众号 API
|
||||
// NewOfficialAccount 实例化公众号API
|
||||
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{
|
||||
Config: cfg,
|
||||
AccessTokenHandle: defaultAkHandle,
|
||||
@@ -55,7 +63,7 @@ func NewOfficialAccount(cfg *config.Config) *OfficialAccount {
|
||||
return &OfficialAccount{ctx: ctx}
|
||||
}
|
||||
|
||||
// SetAccessTokenHandle 自定义 access_token 获取方式
|
||||
// SetAccessTokenHandle 自定义access_token获取方式
|
||||
func (officialAccount *OfficialAccount) SetAccessTokenHandle(accessTokenHandle credential.AccessTokenHandle) {
|
||||
officialAccount.ctx.AccessTokenHandle = accessTokenHandle
|
||||
}
|
||||
@@ -89,12 +97,12 @@ func (officialAccount *OfficialAccount) GetServer(req *http.Request, writer http
|
||||
return srv
|
||||
}
|
||||
|
||||
// GetAccessToken 获取 access_token
|
||||
// GetAccessToken 获取access_token
|
||||
func (officialAccount *OfficialAccount) GetAccessToken() (string, error) {
|
||||
return officialAccount.ctx.GetAccessToken()
|
||||
}
|
||||
|
||||
// GetAccessTokenContext 获取 access_token
|
||||
// GetAccessTokenContext 获取access_token
|
||||
func (officialAccount *OfficialAccount) GetAccessTokenContext(ctx stdcontext.Context) (string, error) {
|
||||
if c, ok := officialAccount.ctx.AccessTokenHandle.(credential.AccessTokenContextHandle); ok {
|
||||
return c.GetAccessTokenContext(ctx)
|
||||
@@ -102,7 +110,7 @@ func (officialAccount *OfficialAccount) GetAccessTokenContext(ctx stdcontext.Con
|
||||
return officialAccount.ctx.GetAccessToken()
|
||||
}
|
||||
|
||||
// GetOauth oauth2 网页授权
|
||||
// GetOauth oauth2网页授权
|
||||
func (officialAccount *OfficialAccount) GetOauth() *oauth.Oauth {
|
||||
if officialAccount.oauth == nil {
|
||||
officialAccount.oauth = oauth.NewOauth(officialAccount.ctx)
|
||||
@@ -134,7 +142,7 @@ func (officialAccount *OfficialAccount) GetFreePublish() *freepublish.FreePublis
|
||||
return officialAccount.freepublish
|
||||
}
|
||||
|
||||
// GetJs js-sdk 配置
|
||||
// GetJs js-sdk配置
|
||||
func (officialAccount *OfficialAccount) GetJs() *js.Js {
|
||||
if officialAccount.js == nil {
|
||||
officialAccount.js = js.NewJs(officialAccount.ctx)
|
||||
@@ -191,7 +199,7 @@ func (officialAccount *OfficialAccount) GetDataCube() *datacube.DataCube {
|
||||
return officialAccount.datacube
|
||||
}
|
||||
|
||||
// GetOCR OCR 接口
|
||||
// GetOCR OCR接口
|
||||
func (officialAccount *OfficialAccount) GetOCR() *ocr.OCR {
|
||||
if officialAccount.ocr == nil {
|
||||
officialAccount.ocr = ocr.NewOCR(officialAccount.ctx)
|
||||
@@ -212,7 +220,7 @@ func (officialAccount *OfficialAccount) GetCustomerServiceManager() *customerser
|
||||
return customerservice.NewCustomerServiceManager(officialAccount.ctx)
|
||||
}
|
||||
|
||||
// GetOpenAPI openApi 管理接口
|
||||
// GetOpenAPI openApi管理接口
|
||||
func (officialAccount *OfficialAccount) GetOpenAPI() *openapi.OpenAPI {
|
||||
return openapi.NewOpenAPI(officialAccount.ctx)
|
||||
}
|
||||
|
||||
@@ -19,11 +19,11 @@ const (
|
||||
)
|
||||
|
||||
// GetBlackList 获取公众号的黑名单列表
|
||||
// 该接口每次调用最多可拉取 1000 个 OpenID,当列表数较多时,可以通过多次拉取的方式来满足需求。
|
||||
// 该接口每次调用最多可拉取 1000 个OpenID,当列表数较多时,可以通过多次拉取的方式来满足需求。
|
||||
// 参数 beginOpenid:当 begin_openid 为空时,默认从开头拉取。
|
||||
func (user *User) GetBlackList(beginOpenid ...string) (userlist *OpenidList, err error) {
|
||||
if len(beginOpenid) > 1 {
|
||||
return nil, errors.New("参数 beginOpenid 错误:请传递 1 个 openID,若需要从头开始拉取列表请留空。")
|
||||
return nil, errors.New("参数 beginOpenid 错误:请传递 1 个openID,若需要从头开始拉取列表请留空。")
|
||||
}
|
||||
// 获取 AccessToken
|
||||
var accessToken string
|
||||
@@ -62,13 +62,13 @@ func (user *User) GetAllBlackList() (openIDList []string, err error) {
|
||||
)
|
||||
|
||||
for {
|
||||
// 获取列表(每次 1k 条)
|
||||
// 获取列表(每次1k条)
|
||||
if userlist, err = user.GetBlackList(beginOpenid); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
openIDList = append(openIDList, userlist.Data.OpenIDs...) // 存储本次获得的 OpenIDs
|
||||
openIDList = append(openIDList, userlist.Data.OpenIDs...) // 存储本次获得的OpenIDs
|
||||
count += userlist.Count // 记录获得的总数量
|
||||
beginOpenid = userlist.NextOpenID // 记录下次循环的起始 openID
|
||||
beginOpenid = userlist.NextOpenID // 记录下次循环的起始openID
|
||||
if count >= userlist.Total {
|
||||
break // 获得的数量=total,结束循环
|
||||
}
|
||||
@@ -78,13 +78,13 @@ func (user *User) GetAllBlackList() (openIDList []string, err error) {
|
||||
}
|
||||
|
||||
// BatchBlackList 拉黑用户
|
||||
// 参数 openidList:需要拉入黑名单的用户的 openid,每次拉黑最多允许 20 个
|
||||
// 参数 openidList:需要拉入黑名单的用户的openid,每次拉黑最多允许20个
|
||||
func (user *User) BatchBlackList(openidList ...string) (err error) {
|
||||
return user.batch(batchblacklistURL, "BatchBlackList", openidList...)
|
||||
}
|
||||
|
||||
// BatchUnBlackList 取消拉黑用户
|
||||
// 参数 openidList:需要取消拉入黑名单的用户的 openid,每次拉黑最多允许 20 个
|
||||
// 参数 openidList:需要取消拉入黑名单的用户的openid,每次拉黑最多允许20个
|
||||
func (user *User) BatchUnBlackList(openidList ...string) (err error) {
|
||||
return user.batch(batchunblacklistURL, "BatchUnBlackList", openidList...)
|
||||
}
|
||||
@@ -93,7 +93,7 @@ func (user *User) BatchUnBlackList(openidList ...string) (err error) {
|
||||
func (user *User) batch(url, apiName string, openidList ...string) (err error) {
|
||||
// 检查参数
|
||||
if len(openidList) == 0 || len(openidList) > 20 {
|
||||
return errors.New("参数 openidList 错误:每次操作黑名单用户数量为 1-20 个。")
|
||||
return errors.New("参数 openidList 错误:每次操作黑名单用户数量为1-20个。")
|
||||
}
|
||||
|
||||
// 获取 AccessToken
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Package user migrate 用于微信公众号账号迁移,获取 openID 变化
|
||||
// Package user migrate 用于微信公众号账号迁移,获取openID变化
|
||||
// 参考文档:https://kf.qq.com/faq/1901177NrqMr190117nqYJze.html
|
||||
package user
|
||||
|
||||
@@ -13,23 +13,23 @@ const (
|
||||
changeOpenIDURL = "https://api.weixin.qq.com/cgi-bin/changeopenid"
|
||||
)
|
||||
|
||||
// ChangeOpenIDResult OpenID 迁移变化
|
||||
// ChangeOpenIDResult OpenID迁移变化
|
||||
type ChangeOpenIDResult struct {
|
||||
OriOpenID string `json:"ori_openid"`
|
||||
NewOpenID string `json:"new_openid"`
|
||||
ErrMsg string `json:"err_msg,omitempty"`
|
||||
}
|
||||
|
||||
// ChangeOpenIDResultList OpenID 迁移变化列表
|
||||
// ChangeOpenIDResultList OpenID迁移变化列表
|
||||
type ChangeOpenIDResultList struct {
|
||||
util.CommonError
|
||||
List []ChangeOpenIDResult `json:"result_list"`
|
||||
}
|
||||
|
||||
// ListChangeOpenIDs 返回指定 OpenID 变化列表
|
||||
// fromAppID 为老账号 AppID
|
||||
// openIDs 为老账号的 openID,openIDs 限 100 个以内
|
||||
// AccessToken 为新账号的 AccessToken
|
||||
// ListChangeOpenIDs 返回指定OpenID变化列表
|
||||
// fromAppID 为老账号AppID
|
||||
// openIDs 为老账号的openID,openIDs限100个以内
|
||||
// AccessToken 为新账号的AccessToken
|
||||
func (user *User) ListChangeOpenIDs(fromAppID string, openIDs ...string) (list *ChangeOpenIDResultList, err error) {
|
||||
list = &ChangeOpenIDResultList{}
|
||||
// list.List = make([]ChangeOpenIDResult, 0)
|
||||
@@ -65,10 +65,10 @@ func (user *User) ListChangeOpenIDs(fromAppID string, openIDs ...string) (list *
|
||||
return
|
||||
}
|
||||
|
||||
// ListAllChangeOpenIDs 返回所有用户 OpenID 列表
|
||||
// fromAppID 为老账号 AppID
|
||||
// openIDs 为老账号的 openID
|
||||
// AccessToken 为新账号的 AccessToken
|
||||
// ListAllChangeOpenIDs 返回所有用户OpenID列表
|
||||
// fromAppID 为老账号AppID
|
||||
// openIDs 为老账号的openID
|
||||
// AccessToken 为新账号的AccessToken
|
||||
func (user *User) ListAllChangeOpenIDs(fromAppID string, openIDs ...string) (list []ChangeOpenIDResult, err error) {
|
||||
list = make([]ChangeOpenIDResult, 0)
|
||||
chunks := util.SliceChunk(openIDs, 100)
|
||||
|
||||
@@ -102,7 +102,7 @@ type BatchGetUserInfoParams struct {
|
||||
// BatchGetUserListItem 需要获取基本信息的用户
|
||||
type BatchGetUserListItem struct {
|
||||
OpenID string `json:"openid"` // 用户的标识,对当前公众号唯一
|
||||
Lang string `json:"lang"` // 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语,默认为 zh-CN
|
||||
Lang string `json:"lang"` // 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语,默认为zh-CN
|
||||
}
|
||||
|
||||
// InfoList 用户基本信息列表
|
||||
@@ -161,10 +161,7 @@ func (user *User) ListUserOpenIDs(nextOpenid ...string) (*OpenidList, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
uri, err := url.Parse(userListURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
uri, _ := url.Parse(userListURL)
|
||||
q := uri.Query()
|
||||
q.Set("access_token", accessToken)
|
||||
if len(nextOpenid) > 0 && nextOpenid[0] != "" {
|
||||
@@ -187,7 +184,7 @@ func (user *User) ListUserOpenIDs(nextOpenid ...string) (*OpenidList, error) {
|
||||
return &userlist, nil
|
||||
}
|
||||
|
||||
// ListAllUserOpenIDs 返回所有用户 OpenID 列表
|
||||
// ListAllUserOpenIDs 返回所有用户OpenID列表
|
||||
func (user *User) ListAllUserOpenIDs() ([]string, error) {
|
||||
nextOpenid := ""
|
||||
openids := make([]string, 0)
|
||||
|
||||
@@ -19,7 +19,7 @@ cfg := &openplatform.Config{
|
||||
|
||||
|
||||
openPlatform := wc.GetOpenPlatform(cfg)
|
||||
// 传入 request 和 responseWriter
|
||||
// 传入request和responseWriter
|
||||
server := openPlatform.GetServer(req, rw)
|
||||
//设置接收消息的处理方法
|
||||
server.SetMessageHandler(func(msg *message.MixMessage) *message.Reply {
|
||||
@@ -57,7 +57,7 @@ server.Send()
|
||||
|
||||
```go
|
||||
|
||||
//授权的第三方公众号的 appID
|
||||
//授权的第三方公众号的appID
|
||||
appID := "xxx"
|
||||
openPlatform := wc.GetOpenPlatform(cfg)
|
||||
openPlatform.GetOfficialAccount(appID)
|
||||
|
||||
@@ -2,7 +2,7 @@ package account
|
||||
|
||||
import "github.com/silenceper/wechat/v2/openplatform/context"
|
||||
|
||||
// Account 开放平台张哈管理
|
||||
// Account 开放平台帐号管理
|
||||
// TODO 实现方法
|
||||
type Account struct {
|
||||
*context.Context
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Package context 开放平台相关 context
|
||||
// Package context 开放平台相关context
|
||||
package context
|
||||
|
||||
import (
|
||||
@@ -20,6 +20,7 @@ const (
|
||||
getComponentInfoURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=%s"
|
||||
componentLoginURL = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=%s&pre_auth_code=%s&redirect_uri=%s&auth_type=%d&biz_appid=%s"
|
||||
bindComponentURL = "https://mp.weixin.qq.com/safe/bindcomponent?action=bindcomponent&auth_type=%d&no_scan=1&component_appid=%s&pre_auth_code=%s&redirect_uri=%s&biz_appid=%s#wechat_redirect"
|
||||
bindComponentURLV2 = "https://open.weixin.qq.com/wxaopen/safe/bindcomponent?action=bindcomponent&auth_type=%d&no_scan=1&component_appid=%s&pre_auth_code=%s&redirect_uri=%s&biz_appid=%s#wechat_redirect"
|
||||
// TODO 获取授权方选项信息
|
||||
// getComponentConfigURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_option?component_access_token=%s"
|
||||
// TODO 获取已授权的账号信息
|
||||
@@ -48,7 +49,7 @@ func (ctx *Context) GetComponentAccessToken() (string, error) {
|
||||
return ctx.GetComponentAccessTokenContext(context.Background())
|
||||
}
|
||||
|
||||
// SetComponentAccessTokenContext 通过 component_verify_ticket 获取 ComponentAccessToken
|
||||
// SetComponentAccessTokenContext 通过component_verify_ticket 获取 ComponentAccessToken
|
||||
func (ctx *Context) SetComponentAccessTokenContext(stdCtx context.Context, verifyTicket string) (*ComponentAccessToken, error) {
|
||||
body := map[string]string{
|
||||
"component_appid": ctx.AppID,
|
||||
@@ -77,7 +78,7 @@ func (ctx *Context) SetComponentAccessTokenContext(stdCtx context.Context, verif
|
||||
return at, nil
|
||||
}
|
||||
|
||||
// SetComponentAccessToken 通过 component_verify_ticket 获取 ComponentAccessToken
|
||||
// SetComponentAccessToken 通过component_verify_ticket 获取 ComponentAccessToken
|
||||
func (ctx *Context) SetComponentAccessToken(stdCtx context.Context, verifyTicket string) (*ComponentAccessToken, error) {
|
||||
return ctx.SetComponentAccessTokenContext(stdCtx, verifyTicket)
|
||||
}
|
||||
@@ -109,7 +110,7 @@ func (ctx *Context) GetPreCode() (string, error) {
|
||||
return ctx.GetPreCodeContext(context.Background())
|
||||
}
|
||||
|
||||
// GetComponentLoginPageContext 获取第三方公众号授权链接 (扫码授权)
|
||||
// GetComponentLoginPageContext 获取第三方公众号授权链接(扫码授权)
|
||||
func (ctx *Context) GetComponentLoginPageContext(stdCtx context.Context, redirectURI string, authType int, bizAppID string) (string, error) {
|
||||
code, err := ctx.GetPreCodeContext(stdCtx)
|
||||
if err != nil {
|
||||
@@ -118,12 +119,12 @@ func (ctx *Context) GetComponentLoginPageContext(stdCtx context.Context, redirec
|
||||
return fmt.Sprintf(componentLoginURL, ctx.AppID, code, url.QueryEscape(redirectURI), authType, bizAppID), nil
|
||||
}
|
||||
|
||||
// GetComponentLoginPage 获取第三方公众号授权链接 (扫码授权)
|
||||
// GetComponentLoginPage 获取第三方公众号授权链接(扫码授权)
|
||||
func (ctx *Context) GetComponentLoginPage(redirectURI string, authType int, bizAppID string) (string, error) {
|
||||
return ctx.GetComponentLoginPageContext(context.Background(), redirectURI, authType, bizAppID)
|
||||
}
|
||||
|
||||
// GetBindComponentURLContext 获取第三方公众号授权链接 (链接跳转,适用移动端)
|
||||
// GetBindComponentURLContext 获取第三方公众号授权链接(链接跳转,适用移动端)
|
||||
func (ctx *Context) GetBindComponentURLContext(stdCtx context.Context, redirectURI string, authType int, bizAppID string) (string, error) {
|
||||
code, err := ctx.GetPreCodeContext(stdCtx)
|
||||
if err != nil {
|
||||
@@ -132,11 +133,25 @@ func (ctx *Context) GetBindComponentURLContext(stdCtx context.Context, redirectU
|
||||
return fmt.Sprintf(bindComponentURL, authType, ctx.AppID, code, url.QueryEscape(redirectURI), bizAppID), nil
|
||||
}
|
||||
|
||||
// GetBindComponentURL 获取第三方公众号授权链接 (链接跳转,适用移动端)
|
||||
// GetBindComponentURL 获取第三方公众号授权链接(链接跳转,适用移动端)
|
||||
func (ctx *Context) GetBindComponentURL(redirectURI string, authType int, bizAppID string) (string, error) {
|
||||
return ctx.GetBindComponentURLContext(context.Background(), redirectURI, authType, bizAppID)
|
||||
}
|
||||
|
||||
// GetBindComponentURLV2Context 获取新版本第三方公众号授权链接(链接跳转,适用移动端)
|
||||
func (ctx *Context) GetBindComponentURLV2Context(stdCtx context.Context, redirectURI string, authType int, bizAppID string) (string, error) {
|
||||
code, err := ctx.GetPreCodeContext(stdCtx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf(bindComponentURLV2, authType, ctx.AppID, code, url.QueryEscape(redirectURI), bizAppID), nil
|
||||
}
|
||||
|
||||
// GetBindComponentURLV2 获取新版本第三方公众号授权链接(链接跳转,适用移动端)
|
||||
func (ctx *Context) GetBindComponentURLV2(redirectURI string, authType int, bizAppID string) (string, error) {
|
||||
return ctx.GetBindComponentURLContext(context.Background(), redirectURI, authType, bizAppID)
|
||||
}
|
||||
|
||||
// ID 微信返回接口中各种类型字段
|
||||
type ID struct {
|
||||
ID int `json:"id"`
|
||||
@@ -153,7 +168,7 @@ type AuthFuncInfo struct {
|
||||
FuncscopeCategory ID `json:"funcscope_category"`
|
||||
}
|
||||
|
||||
// AuthrAccessToken 授权方 AccessToken
|
||||
// AuthrAccessToken 授权方AccessToken
|
||||
type AuthrAccessToken struct {
|
||||
Appid string `json:"authorizer_appid"`
|
||||
AccessToken string `json:"authorizer_access_token"`
|
||||
@@ -225,6 +240,10 @@ func (ctx *Context) RefreshAuthrTokenContext(stdCtx context.Context, appid, refr
|
||||
if err := cache.SetContext(stdCtx, ctx.Cache, authrTokenKey, ret.AccessToken, time.Second*time.Duration(ret.ExpiresIn-30)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
refreshTokenKey := "authorizer_refresh_token_" + appid
|
||||
if err := cache.SetContext(stdCtx, ctx.Cache, refreshTokenKey, ret.RefreshToken, 10*365*24*60*60*time.Second); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
@@ -233,17 +252,27 @@ func (ctx *Context) RefreshAuthrToken(appid, refreshToken string) (*AuthrAccessT
|
||||
return ctx.RefreshAuthrTokenContext(context.Background(), appid, refreshToken)
|
||||
}
|
||||
|
||||
// GetAuthrAccessTokenContext 获取授权方 AccessToken
|
||||
// GetAuthrAccessTokenContext 获取授权方AccessToken
|
||||
func (ctx *Context) GetAuthrAccessTokenContext(stdCtx context.Context, appid string) (string, error) {
|
||||
authrTokenKey := "authorizer_access_token_" + appid
|
||||
val := cache.GetContext(stdCtx, ctx.Cache, authrTokenKey)
|
||||
if val == nil {
|
||||
return "", fmt.Errorf("cannot get authorizer %s access token", appid)
|
||||
refreshTokenKey := "authorizer_refresh_token_" + appid
|
||||
val := cache.GetContext(stdCtx, ctx.Cache, refreshTokenKey)
|
||||
if val == nil {
|
||||
return "", fmt.Errorf("cannot get authorizer %s refresh token", appid)
|
||||
}
|
||||
token, err := ctx.RefreshAuthrTokenContext(stdCtx, appid, val.(string))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return token.AccessToken, nil
|
||||
}
|
||||
|
||||
return val.(string), nil
|
||||
}
|
||||
|
||||
// GetAuthrAccessToken 获取授权方 AccessToken
|
||||
// GetAuthrAccessToken 获取授权方AccessToken
|
||||
func (ctx *Context) GetAuthrAccessToken(appid string) (string, error) {
|
||||
return ctx.GetAuthrAccessTokenContext(context.Background(), appid)
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ func (basic *Basic) GetAccountBasicInfo() (*AccountBasicInfo, error) {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// modify_domain 设置服务器域名
|
||||
// modify_domain设置服务器域名
|
||||
// TODO
|
||||
// func (encryptor *Basic) modifyDomain() {
|
||||
// }
|
||||
@@ -87,7 +87,7 @@ func (basic *Basic) CheckNickName(nickname string) (*CheckNickNameResp, error) {
|
||||
// SetNickNameResp 设置小程序名称结果
|
||||
type SetNickNameResp struct {
|
||||
util.CommonError
|
||||
AuditID int64 `json:"audit_id"` // 审核单 Id,通过用于查询改名审核状态
|
||||
AuditID int64 `json:"audit_id"` // 审核单Id,通过用于查询改名审核状态
|
||||
Wording string `json:"wording"` // 材料说明
|
||||
}
|
||||
|
||||
@@ -221,7 +221,7 @@ func (basic *Basic) SetHeadImage(imgMediaID string) error {
|
||||
}
|
||||
|
||||
// SetHeadImageFull 修改小程序头像
|
||||
// 新增临时素材:https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/New_temporary_materials.html
|
||||
// 新增临时素材: 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)
|
||||
|
||||
@@ -25,7 +25,7 @@ func NewComponent(opContext *openContext.Context) *Component {
|
||||
type RegisterMiniProgramParam struct {
|
||||
Name string `json:"name"` // 企业名
|
||||
Code string `json:"code"` // 企业代码
|
||||
CodeType string `json:"code_type"` // 企业代码类型 1:统一社会信用代码(18 位)2:组织机构代码(9 位 xxxxxxxx-x)3:营业执照注册号 (15 位)
|
||||
CodeType string `json:"code_type"` // 企业代码类型 1:统一社会信用代码(18 位) 2:组织机构代码(9 位 xxxxxxxx-x) 3:营业执照注册号(15 位)
|
||||
LegalPersonaWechat string `json:"legal_persona_wechat"` // 法人微信号
|
||||
LegalPersonaName string `json:"legal_persona_name"` // 法人姓名(绑定银行卡)
|
||||
ComponentPhone string `json:"component_phone"` // 第三方联系电话(方便法人与第三方联系)
|
||||
@@ -54,7 +54,7 @@ type GetRegistrationStatusParam struct {
|
||||
|
||||
}
|
||||
|
||||
// GetRegistrationStatus 查询创建任务状态。
|
||||
// GetRegistrationStatus 查询创建任务状态.
|
||||
func (component *Component) GetRegistrationStatus(param *GetRegistrationStatusParam) error {
|
||||
componentAK, err := component.GetComponentAccessToken()
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package miniprogram
|
||||
|
||||
import (
|
||||
originalContext "context"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/credential"
|
||||
@@ -21,7 +22,7 @@ type MiniProgram struct {
|
||||
authorizerRefreshToken string
|
||||
}
|
||||
|
||||
// GetAccessToken 获取 ak
|
||||
// GetAccessToken 获取ak
|
||||
func (miniProgram *MiniProgram) GetAccessToken() (string, error) {
|
||||
ak, akErr := miniProgram.openContext.GetAuthrAccessToken(miniProgram.AppID)
|
||||
if akErr == nil {
|
||||
@@ -37,7 +38,23 @@ func (miniProgram *MiniProgram) GetAccessToken() (string, error) {
|
||||
return akRes.AccessToken, nil
|
||||
}
|
||||
|
||||
// SetAuthorizerRefreshToken 设置代执操作业务授权账号 authorizer_refresh_token
|
||||
// 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
|
||||
func (miniProgram *MiniProgram) SetAuthorizerRefreshToken(authorizerRefreshToken string) *MiniProgram {
|
||||
miniProgram.authorizerRefreshToken = authorizerRefreshToken
|
||||
return miniProgram
|
||||
@@ -49,7 +66,7 @@ func NewMiniProgram(opCtx *openContext.Context, appID string) *MiniProgram {
|
||||
AppID: opCtx.AppID,
|
||||
Cache: opCtx.Cache,
|
||||
})
|
||||
// 设置获取 access_token 的函数
|
||||
// 设置获取access_token的函数
|
||||
miniProgram.SetAccessTokenHandle(NewDefaultAuthrAccessToken(opCtx, appID))
|
||||
return &MiniProgram{AppID: appID, MiniProgram: miniProgram, openContext: opCtx}
|
||||
}
|
||||
@@ -65,20 +82,20 @@ func (miniProgram *MiniProgram) GetBasic() *basic.Basic {
|
||||
return basic.NewBasic(miniProgram.openContext, miniProgram.AppID)
|
||||
}
|
||||
|
||||
// GetURLLink 小程序 URL Link 接口 调用前需确认已调用 SetAuthorizerRefreshToken 避免由于缓存中 authorizer_access_token 过期执行中断
|
||||
// GetURLLink 小程序URL Link接口 调用前需确认已调用 SetAuthorizerRefreshToken 避免由于缓存中 authorizer_access_token 过期执行中断
|
||||
func (miniProgram *MiniProgram) GetURLLink() *urllink.URLLink {
|
||||
return urllink.NewURLLink(&miniContext.Context{
|
||||
AccessTokenHandle: miniProgram,
|
||||
AccessTokenContextHandle: miniProgram,
|
||||
})
|
||||
}
|
||||
|
||||
// DefaultAuthrAccessToken 默认获取授权 ak 的方法
|
||||
// DefaultAuthrAccessToken 默认获取授权ak的方法
|
||||
type DefaultAuthrAccessToken struct {
|
||||
opCtx *openContext.Context
|
||||
appID string
|
||||
}
|
||||
|
||||
// NewDefaultAuthrAccessToken 设置 access_token
|
||||
// NewDefaultAuthrAccessToken 设置access_token
|
||||
func NewDefaultAuthrAccessToken(opCtx *openContext.Context, appID string) credential.AccessTokenHandle {
|
||||
return &DefaultAuthrAccessToken{
|
||||
opCtx: opCtx,
|
||||
@@ -86,7 +103,7 @@ func NewDefaultAuthrAccessToken(opCtx *openContext.Context, appID string) creden
|
||||
}
|
||||
}
|
||||
|
||||
// GetAccessToken 获取 ak
|
||||
// GetAccessToken 获取ak
|
||||
func (ak *DefaultAuthrAccessToken) GetAccessToken() (string, error) {
|
||||
return ak.opCtx.GetAuthrAccessToken(ak.appID)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package js
|
||||
|
||||
import (
|
||||
context2 "context"
|
||||
"fmt"
|
||||
|
||||
"github.com/silenceper/wechat/v2/credential"
|
||||
@@ -24,22 +25,39 @@ func NewJs(context *context.Context, appID string) *Js {
|
||||
return js
|
||||
}
|
||||
|
||||
// SetJsTicketHandle 自定义 js ticket 取值方式
|
||||
// SetJsTicketHandle 自定义js ticket取值方式
|
||||
func (js *Js) SetJsTicketHandle(ticketHandle credential.JsTicketHandle) {
|
||||
js.JsTicketHandle = ticketHandle
|
||||
}
|
||||
|
||||
// GetConfig 第三方平台 - 获取 jssdk 需要的配置参数
|
||||
// GetConfig 第三方平台 - 获取jssdk需要的配置参数
|
||||
// uri 为当前网页地址
|
||||
func (js *Js) GetConfig(uri, appid string) (config *officialJs.Config, err error) {
|
||||
config = new(officialJs.Config)
|
||||
return js.GetConfigContext(context2.Background(), uri, appid)
|
||||
}
|
||||
|
||||
// GetConfigContext 新方法,允许传入上下文,避免协程泄漏
|
||||
func (js *Js) GetConfigContext(ctx context2.Context, uri, appid string) (config *officialJs.Config, err error) {
|
||||
var accessToken string
|
||||
accessToken, err = js.GetAccessToken()
|
||||
// 类型断言,如果断言成功,调用安全的 GetAccessTokenContext 方法
|
||||
if ctxHandle, ok := js.Context.AccessTokenHandle.(credential.AccessTokenContextHandle); ok {
|
||||
accessToken, err = ctxHandle.GetAccessTokenContext(ctx)
|
||||
} else {
|
||||
// 如果没有实现 AccessTokenContextHandle 接口,调用旧的 GetAccessToken 方法
|
||||
accessToken, err = js.Context.GetAccessToken()
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var ticketStr string
|
||||
ticketStr, err = js.GetTicket(accessToken)
|
||||
// 类型断言 jsTicket
|
||||
if ticketCtxHandle, ok := js.JsTicketHandle.(credential.JsTicketContextHandle); ok {
|
||||
ticketStr, err = ticketCtxHandle.GetTicketContext(ctx, accessToken)
|
||||
} else {
|
||||
// 如果没有实现 JsTicketContextHandle 接口,调用旧的 GetTicket 方法
|
||||
ticketStr, err = js.GetTicket(accessToken)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -49,6 +67,7 @@ func (js *Js) GetConfig(uri, appid string) (config *officialJs.Config, err error
|
||||
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
|
||||
sigStr := util.Signature(str)
|
||||
|
||||
config = new(officialJs.Config)
|
||||
config.AppID = appid
|
||||
config.NonceStr = nonceStr
|
||||
config.Timestamp = timestamp
|
||||
|
||||
147
openplatform/officialaccount/js/js_test.go
Normal file
147
openplatform/officialaccount/js/js_test.go
Normal file
@@ -0,0 +1,147 @@
|
||||
// 验证 js.GetConfigContext 是否能正确传递上下文到 HTTP 请求,确保上下文正确传播,防止在获取 JSSDK 配置时发生协程泄露。
|
||||
package js
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
context2 "context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/silenceper/wechat/v2/cache"
|
||||
"github.com/silenceper/wechat/v2/credential"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/config"
|
||||
"github.com/silenceper/wechat/v2/officialaccount/context"
|
||||
"github.com/silenceper/wechat/v2/util"
|
||||
)
|
||||
|
||||
// mockAccessTokenHandle 模拟 AccessTokenHandle
|
||||
type mockAccessTokenHandle struct{}
|
||||
|
||||
func (m *mockAccessTokenHandle) GetAccessToken() (string, error) {
|
||||
return "mock-access-token", nil
|
||||
}
|
||||
|
||||
func (m *mockAccessTokenHandle) GetAccessTokenContext(_ context2.Context) (string, error) {
|
||||
return "mock-access-token", nil
|
||||
}
|
||||
|
||||
// contextCheckingRoundTripper 自定义 RoundTripper 用于检查 context
|
||||
type contextCheckingRoundTripper struct {
|
||||
originalCtx context2.Context
|
||||
t *testing.T
|
||||
key interface{}
|
||||
expectedVal interface{}
|
||||
}
|
||||
|
||||
func (rt *contextCheckingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
// 获取请求中的 context
|
||||
reqCtx := req.Context()
|
||||
|
||||
// 打印 context 比较结果
|
||||
rt.t.Logf("比较上下文的内存地址:\n")
|
||||
if reqCtx == rt.originalCtx {
|
||||
rt.t.Logf("上下文具有相同的内存地址。原始上下文: %p, 请求上下文: %p\n", rt.originalCtx, reqCtx)
|
||||
} else {
|
||||
rt.t.Logf("上下文具有不同的内存地址。原始上下文: %p, 请求上下文: %p\n", rt.originalCtx, reqCtx)
|
||||
}
|
||||
|
||||
// 检查 context 中的键值对
|
||||
if rt.key != nil {
|
||||
value := reqCtx.Value(rt.key)
|
||||
rt.t.Logf("检查请求上下文中的键 %v:\n", rt.key)
|
||||
if value != rt.expectedVal {
|
||||
rt.t.Errorf("上下文键 %v 的值不匹配: 预期 %v, 实际 %v\n", rt.key, rt.expectedVal, value)
|
||||
} else {
|
||||
rt.t.Logf("上下文键 %v 的值匹配: 预期 %v, 实际 %v\n", rt.key, rt.expectedVal, value)
|
||||
}
|
||||
}
|
||||
|
||||
// 检查上下文是否已取消
|
||||
select {
|
||||
case <-reqCtx.Done():
|
||||
return nil, reqCtx.Err() // 返回上下文取消错误
|
||||
default:
|
||||
// 返回模拟的 HTTP 响应,包含有效的 JSON
|
||||
responseBody := `{"ticket":"mock-ticket","expires_in":7200}`
|
||||
response := &http.Response{
|
||||
Status: "200 OK",
|
||||
StatusCode: http.StatusOK,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Body: io.NopCloser(bytes.NewReader([]byte(responseBody))),
|
||||
ContentLength: int64(len(responseBody)),
|
||||
Header: make(http.Header),
|
||||
}
|
||||
response.Header.Set("Content-Type", "application/json")
|
||||
return response, nil
|
||||
}
|
||||
}
|
||||
|
||||
// contextKey 定义自定义上下文键类型,避免使用内置 string 类型
|
||||
type contextKey string
|
||||
|
||||
// setupJsInstance 初始化 Js 实例和 HTTP 客户端
|
||||
func setupJsInstance(t *testing.T, ctx context2.Context, key, val interface{}) (*Js, func()) {
|
||||
cfg := &config.Config{
|
||||
AppID: "test-app-id",
|
||||
AppSecret: "test-app-secret",
|
||||
Cache: cache.NewMemory(),
|
||||
}
|
||||
cacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", credential.CacheKeyOfficialAccountPrefix, cfg.AppID)
|
||||
if err := cfg.Cache.Delete(cacheKey); err != nil {
|
||||
t.Fatalf("清除缓存失败: %v", err)
|
||||
}
|
||||
t.Log("清除 jsapi_ticket 的缓存:", cacheKey)
|
||||
|
||||
ctxHandle := &context.Context{Config: cfg, AccessTokenHandle: &mockAccessTokenHandle{}}
|
||||
jsInstance := NewJs(ctxHandle, cfg.AppID)
|
||||
jsInstance.SetJsTicketHandle(credential.NewDefaultJsTicket(cfg.AppID, credential.CacheKeyOfficialAccountPrefix, cfg.Cache))
|
||||
|
||||
originalClient := util.DefaultHTTPClient
|
||||
util.DefaultHTTPClient = &http.Client{
|
||||
Transport: &contextCheckingRoundTripper{originalCtx: ctx, t: t, key: key, expectedVal: val},
|
||||
}
|
||||
return jsInstance, func() { util.DefaultHTTPClient = originalClient }
|
||||
}
|
||||
|
||||
// TestGetConfigContext 测试GetConfigContext的上下文传递和取消行为。
|
||||
func TestGetConfigContext(t *testing.T) {
|
||||
t.Run("ContextPassing", func(t *testing.T) {
|
||||
ctxKey := contextKey("testKey111") // 使用自定义类型 contextKey
|
||||
ctxValue := "testValue222"
|
||||
ctx := context2.WithValue(context2.Background(), ctxKey, ctxValue)
|
||||
t.Logf("创建的测试上下文: %p, 添加的键值对: %v=%v\n", ctx, ctxKey, ctxValue)
|
||||
|
||||
jsInstance, cleanup := setupJsInstance(t, ctx, ctxKey, ctxValue)
|
||||
defer cleanup()
|
||||
t.Log("调用 GetConfigContext")
|
||||
config2, err := jsInstance.GetConfigContext(ctx, "https://www.baidu.com", "test-app-id")
|
||||
if err != nil {
|
||||
t.Fatalf("GetConfigContext 失败: %v", err)
|
||||
}
|
||||
if config2.AppID != "test-app-id" {
|
||||
t.Errorf("预期 AppID 为 %s,实际为 %s", "test-app-id", config2.AppID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ContextCancellation", func(t *testing.T) {
|
||||
ctx, cancel := context2.WithCancel(context2.Background())
|
||||
defer cancel()
|
||||
|
||||
jsInstance, cleanup := setupJsInstance(t, ctx, nil, nil)
|
||||
defer cleanup()
|
||||
|
||||
cancel()
|
||||
t.Log("调用 GetConfigContext(已取消上下文)")
|
||||
_, err := jsInstance.GetConfigContext(ctx, "https://www.baidu.com", "test-app-id")
|
||||
if err == nil {
|
||||
t.Error("预期上下文取消错误,但 GetConfigContext 未返回错误")
|
||||
} else if !errors.Is(err, context2.Canceled) {
|
||||
t.Errorf("预期错误为 context.Canceled,实际为: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -16,19 +16,19 @@ const (
|
||||
platformAccessTokenURL = "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=%s&code=%s&grant_type=authorization_code&component_appid=%s&component_access_token=%s"
|
||||
)
|
||||
|
||||
// Oauth 平台代发起 oauth2 网页授权
|
||||
// Oauth 平台代发起oauth2网页授权
|
||||
type Oauth struct {
|
||||
*context.Context
|
||||
}
|
||||
|
||||
// NewOauth 实例化平台代发起 oauth2 网页授权
|
||||
// NewOauth 实例化平台代发起oauth2网页授权
|
||||
func NewOauth(context *context.Context) *Oauth {
|
||||
auth := new(Oauth)
|
||||
auth.Context = context
|
||||
return auth
|
||||
}
|
||||
|
||||
// GetRedirectURL 第三方平台 - 获取跳转的 url 地址
|
||||
// GetRedirectURL 第三方平台 - 获取跳转的url地址
|
||||
func (oauth *Oauth) GetRedirectURL(redirectURI, scope, state, appID string) (string, error) {
|
||||
// url encode
|
||||
urlStr := url.QueryEscape(redirectURI)
|
||||
@@ -45,7 +45,7 @@ func (oauth *Oauth) Redirect(writer http.ResponseWriter, req *http.Request, redi
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetUserAccessToken 第三方平台 - 通过网页授权的 code 换取 access_token(区别于 context 中的 access_token)
|
||||
// GetUserAccessToken 第三方平台 - 通过网页授权的code 换取access_token(区别于context中的access_token)
|
||||
func (oauth *Oauth) GetUserAccessToken(code, appID, componentAccessToken string) (result officialOauth.ResAccessToken, err error) {
|
||||
urlStr := fmt.Sprintf(platformAccessTokenURL, appID, code, oauth.AppID, componentAccessToken)
|
||||
var response []byte
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
// OfficialAccount 代公众号实现业务
|
||||
type OfficialAccount struct {
|
||||
// 授权的公众号的 appID
|
||||
// 授权的公众号的appID
|
||||
appID string
|
||||
*officialaccount.OfficialAccount
|
||||
}
|
||||
@@ -25,22 +25,22 @@ func NewOfficialAccount(opCtx *opContext.Context, appID string) *OfficialAccount
|
||||
Token: opCtx.Token,
|
||||
Cache: opCtx.Cache,
|
||||
})
|
||||
// 设置获取 access_token 的函数
|
||||
// 设置获取access_token的函数
|
||||
officialAccount.SetAccessTokenHandle(NewDefaultAuthrAccessToken(opCtx, appID))
|
||||
return &OfficialAccount{appID: appID, OfficialAccount: officialAccount}
|
||||
}
|
||||
|
||||
// PlatformOauth 平台代发起 oauth2 网页授权
|
||||
// PlatformOauth 平台代发起oauth2网页授权
|
||||
func (officialAccount *OfficialAccount) PlatformOauth() *oauth.Oauth {
|
||||
return oauth.NewOauth(officialAccount.GetContext())
|
||||
}
|
||||
|
||||
// PlatformJs 平台代获取 js-sdk 配置
|
||||
// PlatformJs 平台代获取js-sdk配置
|
||||
func (officialAccount *OfficialAccount) PlatformJs() *js.Js {
|
||||
return js.NewJs(officialAccount.GetContext(), officialAccount.appID)
|
||||
}
|
||||
|
||||
// DefaultAuthrAccessToken 默认获取授权 ak 的方法
|
||||
// DefaultAuthrAccessToken 默认获取授权ak的方法
|
||||
type DefaultAuthrAccessToken struct {
|
||||
opCtx *opContext.Context
|
||||
appID string
|
||||
@@ -54,7 +54,7 @@ func NewDefaultAuthrAccessToken(opCtx *opContext.Context, appID string) credenti
|
||||
}
|
||||
}
|
||||
|
||||
// GetAccessToken 获取 ak
|
||||
// GetAccessToken 获取ak
|
||||
func (ak *DefaultAuthrAccessToken) GetAccessToken() (string, error) {
|
||||
return ak.opCtx.GetAuthrAccessToken(ak.appID)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"github.com/silenceper/wechat/v2/openplatform/officialaccount"
|
||||
)
|
||||
|
||||
// OpenPlatform 微信开放平台相关 api
|
||||
// OpenPlatform 微信开放平台相关api
|
||||
type OpenPlatform struct {
|
||||
*context.Context
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ func (notify *Notify) PaidVerifySign(notifyRes PaidResult) bool {
|
||||
}
|
||||
sort.Strings(sortedKeys)
|
||||
|
||||
// STEP2, 对 key=value 的键值对用&连接起来,略过空值 & sign
|
||||
// STEP2, 对key=value的键值对用&连接起来,略过空值 & sign
|
||||
var signStrings string
|
||||
for _, k := range sortedKeys {
|
||||
value := fmt.Sprintf("%v", cast.ToString(resMap[k]))
|
||||
@@ -84,10 +84,10 @@ func (notify *Notify) PaidVerifySign(notifyRes PaidResult) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// STEP3, 在键值对的最后加上 key=API_KEY
|
||||
// STEP3, 在键值对的最后加上key=API_KEY
|
||||
signStrings = signStrings + "key=" + notify.Key
|
||||
|
||||
// STEP4, 根据 SignType 计算出签名
|
||||
// STEP4, 根据SignType计算出签名
|
||||
var signType string
|
||||
if notifyRes.SignType != nil {
|
||||
signType = *notifyRes.SignType
|
||||
|
||||
@@ -18,7 +18,7 @@ type CloseParams struct {
|
||||
|
||||
// closeRequest 接口请求参数
|
||||
type closeRequest struct {
|
||||
AppID string `xml:"appid"` // 公众账号 ID
|
||||
AppID string `xml:"appid"` // 公众账号ID
|
||||
MchID string `xml:"mch_id"` // 商户号
|
||||
NonceStr string `xml:"nonce_str"` // 随机字符串
|
||||
Sign string `xml:"sign"` // 签名
|
||||
|
||||
@@ -35,7 +35,7 @@ type Params struct {
|
||||
CreateIP string
|
||||
Body string
|
||||
OutTradeNo string
|
||||
TimeExpire string // 订单失效时间,格式为 yyyyMMddHHmmss,如 2009 年 12 月 27 日 9 点 10 分 10 秒表示为 20091227091010。
|
||||
TimeExpire string // 订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。
|
||||
OpenID string
|
||||
TradeType string
|
||||
SignType string
|
||||
@@ -85,7 +85,7 @@ type PreOrder struct {
|
||||
|
||||
// payRequest 接口请求参数
|
||||
type payRequest struct {
|
||||
AppID string `xml:"appid"` // 公众账号 ID
|
||||
AppID string `xml:"appid"` // 公众账号ID
|
||||
MchID string `xml:"mch_id"` // 商户号
|
||||
DeviceInfo string `xml:"device_info,omitempty"` // 设备号
|
||||
NonceStr string `xml:"nonce_str"` // 随机字符串
|
||||
@@ -97,13 +97,13 @@ type payRequest struct {
|
||||
OutTradeNo string `xml:"out_trade_no"` // 商户订单号
|
||||
FeeType string `xml:"fee_type,omitempty"` // 标价币种
|
||||
TotalFee string `xml:"total_fee"` // 标价金额
|
||||
SpbillCreateIP string `xml:"spbill_create_ip"` // 终端 IP
|
||||
SpbillCreateIP string `xml:"spbill_create_ip"` // 终端IP
|
||||
TimeStart string `xml:"time_start,omitempty"` // 交易起始时间
|
||||
TimeExpire string `xml:"time_expire,omitempty"` // 交易结束时间
|
||||
GoodsTag string `xml:"goods_tag,omitempty"` // 订单优惠标记
|
||||
NotifyURL string `xml:"notify_url"` // 通知地址
|
||||
TradeType string `xml:"trade_type"` // 交易类型
|
||||
ProductID string `xml:"product_id,omitempty"` // 商品 ID
|
||||
ProductID string `xml:"product_id,omitempty"` // 商品ID
|
||||
LimitPay string `xml:"limit_pay,omitempty"` // 指定支付方式
|
||||
OpenID string `xml:"openid,omitempty"` // 用户标识
|
||||
SceneInfo string `xml:"scene_info,omitempty"` // 场景信息
|
||||
@@ -213,7 +213,7 @@ func (o *Order) PrePayOrder(p *Params) (payOrder PreOrder, err error) {
|
||||
|
||||
// 通知地址
|
||||
if len(p.NotifyURL) == 0 {
|
||||
p.NotifyURL = o.NotifyURL // 默认使用 order.NotifyURL
|
||||
p.NotifyURL = o.NotifyURL // 默认使用order.NotifyURL
|
||||
}
|
||||
|
||||
// 签名类型
|
||||
|
||||
@@ -19,7 +19,7 @@ type QueryParams struct {
|
||||
|
||||
// queryRequest 接口请求参数
|
||||
type queryRequest struct {
|
||||
AppID string `xml:"appid"` // 公众账号 ID
|
||||
AppID string `xml:"appid"` // 公众账号ID
|
||||
MchID string `xml:"mch_id"` // 商户号
|
||||
NonceStr string `xml:"nonce_str"` // 随机字符串
|
||||
Sign string `xml:"sign"` // 签名
|
||||
|
||||
@@ -9,12 +9,12 @@ import (
|
||||
"github.com/silenceper/wechat/v2/pay/transfer"
|
||||
)
|
||||
|
||||
// Pay 微信支付相关 API
|
||||
// Pay 微信支付相关API
|
||||
type Pay struct {
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
// NewPay 实例化微信支付相关 API
|
||||
// NewPay 实例化微信支付相关API
|
||||
func NewPay(cfg *config.Config) *Pay {
|
||||
return &Pay{cfg}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ type Params struct {
|
||||
ActName string
|
||||
Remark string
|
||||
|
||||
RootCa string // ca 证书
|
||||
RootCa string // ca证书
|
||||
}
|
||||
|
||||
// request 接口请求参数
|
||||
|
||||
@@ -29,7 +29,7 @@ type Params struct {
|
||||
TotalFee string
|
||||
RefundFee string
|
||||
RefundDesc string
|
||||
RootCa string // ca 证书
|
||||
RootCa string // ca证书
|
||||
NotifyURL string
|
||||
SignType string
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ type Params struct {
|
||||
Amount int
|
||||
Desc string
|
||||
SpbillCreateIP string
|
||||
RootCa string // ca 证书
|
||||
RootCa string // ca证书
|
||||
}
|
||||
|
||||
// request 接口请求参数
|
||||
|
||||
@@ -44,7 +44,7 @@ func EncryptMsg(random, rawXMLMsg []byte, appID, aesKey string) (encrtptMsg []by
|
||||
func AESEncryptMsg(random, rawXMLMsg []byte, appID string, aesKey []byte) (ciphertext []byte) {
|
||||
const (
|
||||
BlockSize = 32 // PKCS#7
|
||||
BlockMask = BlockSize - 1 // BLOCK_SIZE 为 2^n 时,可以用 mask 获取针对 BLOCK_SIZE 的余数
|
||||
BlockMask = BlockSize - 1 // BLOCK_SIZE 为 2^n 时, 可以用 mask 获取针对 BLOCK_SIZE 的余数
|
||||
)
|
||||
|
||||
appIDOffset := 20 + len(rawXMLMsg)
|
||||
@@ -100,7 +100,7 @@ func DecryptMsg(appID, encryptedMsg, aesKey string) (random, rawMsgXMLBytes []by
|
||||
return
|
||||
}
|
||||
if appID != string(getAppIDBytes) {
|
||||
err = fmt.Errorf("消息解密校验 APPID 失败")
|
||||
err = fmt.Errorf("消息解密校验APPID失败")
|
||||
return
|
||||
}
|
||||
return
|
||||
@@ -127,7 +127,7 @@ func aesKeyDecode(encodedAESKey string) (key []byte, err error) {
|
||||
func AESDecryptMsg(ciphertext []byte, aesKey []byte) (random, rawXMLMsg, appID []byte, err error) {
|
||||
const (
|
||||
BlockSize = 32 // PKCS#7
|
||||
BlockMask = BlockSize - 1 // BLOCK_SIZE 为 2^n 时,可以用 mask 获取针对 BLOCK_SIZE 的余数
|
||||
BlockMask = BlockSize - 1 // BLOCK_SIZE 为 2^n 时, 可以用 mask 获取针对 BLOCK_SIZE 的余数
|
||||
)
|
||||
|
||||
if len(ciphertext) < BlockSize {
|
||||
|
||||
@@ -68,3 +68,18 @@ func DecodeWithError(response []byte, obj interface{}, apiName string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// HandleFileResponse 通用处理微信等接口返回:有时 JSON 错误,有时文件内容
|
||||
func HandleFileResponse(response []byte, apiName string) ([]byte, error) {
|
||||
var commErr CommonError
|
||||
if err := json.Unmarshal(response, &commErr); err == nil {
|
||||
// 能解析成 JSON,判断是否为错误
|
||||
if commErr.ErrCode != 0 {
|
||||
commErr.apiName = apiName
|
||||
return nil, &commErr
|
||||
}
|
||||
// 能解析成 JSON 且没错误码,极少情况(比如微信返回的业务数据是 JSON 但无 errcode 字段),可根据需要调整
|
||||
}
|
||||
// 不能解析成 JSON,或没错误码,直接返回原始内容
|
||||
return response, nil
|
||||
}
|
||||
|
||||
41
util/http.go
41
util/http.go
@@ -17,15 +17,15 @@ import (
|
||||
"golang.org/x/crypto/pkcs12"
|
||||
)
|
||||
|
||||
// URIModifier URI 修改器
|
||||
// URIModifier URI修改器
|
||||
type URIModifier func(uri string) string
|
||||
|
||||
var uriModifier URIModifier
|
||||
|
||||
// DefaultHTTPClient 默认 httpClient
|
||||
// DefaultHTTPClient 默认httpClient
|
||||
var DefaultHTTPClient = http.DefaultClient
|
||||
|
||||
// SetURIModifier 设置 URI 修改器
|
||||
// SetURIModifier 设置URI修改器
|
||||
func SetURIModifier(fn URIModifier) {
|
||||
uriModifier = fn
|
||||
}
|
||||
@@ -146,24 +146,39 @@ func PostJSONWithRespContentType(uri string, obj interface{}) ([]byte, string, e
|
||||
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 上传文件
|
||||
func PostFile(fieldName, filename, uri string) ([]byte, error) {
|
||||
func PostFile(fieldName, filePath, uri string) ([]byte, error) {
|
||||
fields := []MultipartFormField{
|
||||
{
|
||||
IsFile: true,
|
||||
Fieldname: fieldName,
|
||||
Filename: filename,
|
||||
FilePath: filePath,
|
||||
Filename: filePath,
|
||||
},
|
||||
}
|
||||
return PostMultipartForm(fields, uri)
|
||||
}
|
||||
|
||||
// PostFileFromReader 上传文件,从 io.Reader 中读取
|
||||
func PostFileFromReader(filedName, fileName, uri string, reader io.Reader) ([]byte, error) {
|
||||
func PostFileFromReader(filedName, filePath, fileName, uri string, reader io.Reader) ([]byte, error) {
|
||||
fields := []MultipartFormField{
|
||||
{
|
||||
IsFile: true,
|
||||
Fieldname: filedName,
|
||||
FilePath: filePath,
|
||||
Filename: fileName,
|
||||
FileReader: reader,
|
||||
},
|
||||
@@ -176,6 +191,7 @@ type MultipartFormField struct {
|
||||
IsFile bool
|
||||
Fieldname string
|
||||
Value []byte
|
||||
FilePath string
|
||||
Filename string
|
||||
FileReader io.Reader
|
||||
}
|
||||
@@ -197,7 +213,7 @@ func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte
|
||||
}
|
||||
|
||||
if field.FileReader == nil {
|
||||
fh, e := os.Open(field.Filename)
|
||||
fh, e := os.Open(field.FilePath)
|
||||
if e != nil {
|
||||
err = fmt.Errorf("error opening file , err=%v", e)
|
||||
return
|
||||
@@ -213,7 +229,7 @@ func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte
|
||||
}
|
||||
}
|
||||
} else {
|
||||
partWriter, e := bodyWriter.CreateFormField(field.Fieldname)
|
||||
partWriter, e := bodyWriter.CreateFormFile(field.Fieldname, field.Filename)
|
||||
if e != nil {
|
||||
err = e
|
||||
return
|
||||
@@ -275,7 +291,14 @@ func httpWithTLS(rootCa, key string) (*http.Client, error) {
|
||||
config := &tls.Config{
|
||||
Certificates: []tls.Certificate{cert},
|
||||
}
|
||||
trans := (DefaultHTTPClient.Transport.(*http.Transport)).Clone()
|
||||
|
||||
var baseTransport http.RoundTripper
|
||||
if DefaultHTTPClient.Transport != nil {
|
||||
baseTransport = DefaultHTTPClient.Transport
|
||||
} else {
|
||||
baseTransport = http.DefaultTransport
|
||||
}
|
||||
trans := baseTransport.(*http.Transport).Clone()
|
||||
trans.TLSClientConfig = config
|
||||
trans.DisableCompression = true
|
||||
client = &http.Client{Transport: trans}
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Query 将 Map 序列化为 Query 参数
|
||||
// Query 将Map序列化为Query参数
|
||||
func Query(params map[string]interface{}) string {
|
||||
finalString := make([]string, 0)
|
||||
for key, value := range params {
|
||||
|
||||
@@ -12,8 +12,8 @@ func TestQuery(t *testing.T) {
|
||||
"cat": "Peter",
|
||||
})
|
||||
if result == "" {
|
||||
// 由于 hash 是乱序 所以没法很好的预测输出的字符串
|
||||
// 将会输出符合 Query 规则的字符串 "age=12&name=Alan&cat=Peter"
|
||||
// 由于hash是乱序 所以没法很好的预测输出的字符串
|
||||
// 将会输出符合Query规则的字符串 "age=12&name=Alan&cat=Peter"
|
||||
t.Error("NOT PASS")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,10 +25,7 @@ func RSADecrypt(privateKey string, ciphertext []byte) ([]byte, error) {
|
||||
}
|
||||
switch t := key.(type) {
|
||||
case *rsa.PrivateKey:
|
||||
var ok bool
|
||||
if priv, ok = key.(*rsa.PrivateKey); !ok {
|
||||
return nil, fmt.Errorf(" ParsePKCS8PrivateKey error: Not supported privatekey format, should be *rsa.PrivateKey, got %T", t)
|
||||
}
|
||||
priv = key.(*rsa.PrivateKey)
|
||||
default:
|
||||
return nil, fmt.Errorf("ParsePKCS1PrivateKey error: %s, ParsePKCS8PrivateKey error: Not supported privatekey format, should be *rsa.PrivateKey, got %T", oldErr.Error(), t)
|
||||
}
|
||||
@@ -36,7 +33,7 @@ func RSADecrypt(privateKey string, ciphertext []byte) ([]byte, error) {
|
||||
return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
|
||||
}
|
||||
|
||||
// RSADecryptBase64 Base64 解码后再次进行 RSA 解密
|
||||
// RSADecryptBase64 Base64解码后再次进行RSA解密
|
||||
func RSADecryptBase64(privateKey string, cryptoText string) ([]byte, error) {
|
||||
encryptedData, err := base64.StdEncoding.DecodeString(cryptoText)
|
||||
if err != nil {
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Signature sha1 签名
|
||||
// Signature sha1签名
|
||||
func Signature(params ...string) string {
|
||||
sort.Strings(params)
|
||||
h := sha1.New()
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Template 对字符串中的和 map 的 key 相同的字符串进行模板替换 仅支持 形如:{name}
|
||||
// Template 对字符串中的和map的key相同的字符串进行模板替换 仅支持 形如: {name}
|
||||
func Template(source string, data map[string]interface{}) string {
|
||||
sourceCopy := &source
|
||||
for k, val := range data {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user