1
0
mirror of https://github.com/silenceper/wechat.git synced 2026-02-04 21:02:25 +08:00

Compare commits

..

4 Commits

Author SHA1 Message Date
houseme
d8e3208ef2 feat: upgrade go version 1.18 2024-07-19 12:09:54 +08:00
houseme
d8fde54f2d improve comment ,参考:https://github.com/huacnlee/autocorrect 2024-07-19 12:04:04 +08:00
houseme
ba0a1477eb improve comment 2024-07-19 11:26:06 +08:00
houseme
01eedc4274 chore: improve golangci 2024-07-19 11:14:38 +08:00
149 changed files with 1214 additions and 3572 deletions

4
.github/FUNDING.yml vendored
View File

@@ -1,8 +1,8 @@
# These are supported funding model platforms
github: # silenceper
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: gowechat
open_collective: # Replace with a single Open Collective username
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

View File

@@ -1,38 +0,0 @@
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 }}

View File

@@ -10,7 +10,7 @@ jobs:
golangci:
strategy:
matrix:
go-version: [ '1.16','1.17','1.18','1.19','1.20','1.21.4' ]
go-version: [ '1.18','1.19','1.20','1.21.4','1.22' ]
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@v4
uses: golangci/golangci-lint-action@v6
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.52.2
version: v1.58.2
build:
name: Test
runs-on: ubuntu-latest
@@ -42,7 +42,7 @@ jobs:
# strategy set
strategy:
matrix:
go: [ '1.16','1.17','1.18','1.19','1.20','1.21','1.22' ]
go: [ '1.18','1.19','1.20','1.21','1.22' ]
steps:
- uses: actions/checkout@v4

View File

@@ -4,36 +4,32 @@ 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:
@@ -57,10 +53,68 @@ linters-settings:
lines: 66
statements: 50
#issues:
# include:
# - EXC0002 # disable excluding of issues about comments from golint
# exclude-rules:
# - linters:
# - stylecheck
# text: "ST1000:"
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

View File

@@ -1,17 +1,16 @@
# WeChat SDK for Go
![Go](https://github.com/silenceper/wechat/actions/workflows/go.yml/badge.svg?branch=v2)
[![Go Report Card](https://goreportcard.com/badge/github.com/silenceper/wechat/v2)](https://goreportcard.com/report/github.com/silenceper/wechat/v2)
![Go](https://github.com/silenceper/wechat/workflows/Go/badge.svg?branch=release-2.0)
[![Go Report Card](https://goreportcard.com/badge/github.com/silenceper/wechat)](https://goreportcard.com/report/github.com/silenceper/wechat)
[![pkg](https://img.shields.io/badge/dev-reference-007d9c?logo=go&logoColor=white&style=flat)](https://pkg.go.dev/github.com/silenceper/wechat/v2?tab=doc)
![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/silenceper/wechat?sort=semver)
![star](https://gitcode.com/silenceper/wechat/star/badge.svg)
![version](https://img.shields.io/badge/version-v2-green)
使用Golang开发的微信SDK简单、易用。
使用 Golang 开发的微信 SDK简单、易用。
> 注意:当前版本为 v2 版本v1 版本已废弃
## 文档 && 例子
[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)
@@ -26,7 +25,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{
@@ -38,7 +37,7 @@ cfg := &offConfig.Config{
}
officialAccount := wc.GetOfficialAccount(cfg)
// 传入requestresponseWriter
// 传入 requestresponseWriter
server := officialAccount.GetServer(req, rw)
// 设置接收消息的处理方法
server.SetMessageHandler(func(msg *message.MixMessage) *message.Reply {
@@ -61,28 +60,22 @@ 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>
## 作者公众号
## 公众号
![img](https://silenceper.oss-cn-beijing.aliyuncs.com/qrcode/search_study_program.png)

View File

@@ -22,12 +22,16 @@ func TestMemcache(t *testing.T) {
exists := mem.IsExist("unknown-key")
assert.Equal(t, false, exists)
name := mem.Get("username").(string)
name, ok := mem.Get("username").(string)
if !ok {
t.Error("get Error")
}
if name != "" {
if name != "silenceper" {
t.Error("get Error")
}
}
data := mem.Get("unknown-key")
assert.Nil(t, data)

47
cache/redis.go vendored
View File

@@ -2,8 +2,6 @@ package cache
import (
"context"
"crypto/tls"
"net"
"time"
"github.com/go-redis/redis/v8"
@@ -17,47 +15,32 @@ type Redis struct {
// RedisOpts redis 连接属性
type RedisOpts struct {
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
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
}
// NewRedis 实例化
func NewRedis(ctx context.Context, opts *RedisOpts) *Redis {
uniOpt := &redis.UniversalOptions{
conn := redis.NewUniversalClient(&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
}
@@ -86,15 +69,17 @@ 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, _ := r.conn.Exists(ctx, key).Result()
result, err := r.conn.Exists(ctx, key).Result()
if err != nil {
return false
}
return result > 0
}

5
cache/redis_test.go vendored
View File

@@ -35,7 +35,10 @@ func TestRedis(t *testing.T) {
t.Error("IsExist Error")
}
name := redis.Get(key).(string)
name, ok := redis.Get(key).(string)
if !ok {
t.Error("get Error")
}
if name != val {
t.Error("get Error")
}

View File

@@ -7,16 +7,6 @@ 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

View File

@@ -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,34 +57,36 @@ 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 {
if accessToken = val.(string); accessToken != "" {
var ok bool
if accessToken, ok = val.(string); ok && 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 {
if accessToken = val.(string); accessToken != "" {
var ok bool
if accessToken, ok = val.(string); ok && accessToken != "" {
return
}
}
// cache失效从微信服务器获取
// cache 失效,从微信服务器获取
var resAccessToken ResAccessToken
if resAccessToken, err = GetTokenFromServerContext(ctx, fmt.Sprintf(accessTokenURL, ak.appID, ak.appSecret)); err != nil {
return
@@ -97,15 +99,14 @@ 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
accessTokenLock *sync.Mutex
appID string
appSecret string
cacheKeyPrefix string
cache cache.Cache
}
// NewStableAccessToken new StableAccessToken
@@ -114,41 +115,27 @@ func NewStableAccessToken(appID, appSecret, cacheKeyPrefix string, cache cache.C
panic("cache is need")
}
return &StableAccessToken{
appID: appID,
appSecret: appSecret,
cache: cache,
cacheKeyPrefix: cacheKeyPrefix,
accessTokenLock: new(sync.Mutex),
appID: appID,
appSecret: appSecret,
cache: cache,
cacheKeyPrefix: cacheKeyPrefix,
}
}
// 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 {
if accessToken = val.(string); accessToken != "" {
return
}
return val.(string), nil
}
// 加上lock是为了防止在并发获取token时cache刚好失效,导致从微信服务器获取到不同token
ak.accessTokenLock.Lock()
defer ak.accessTokenLock.Unlock()
// 双检,防止重复从微信服务器获取
if val := ak.cache.Get(accessTokenCacheKey); val != nil {
if accessToken = val.(string); accessToken != "" {
return
}
}
// cache失效从微信服务器获取
// cache 失效,从微信服务器获取
var resAccessToken ResAccessToken
resAccessToken, err = ak.GetAccessTokenDirectly(ctx, false)
if err != nil {
@@ -162,7 +149,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",
@@ -185,66 +172,50 @@ 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, 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 {
// NewWorkAccessToken new WorkAccessToken
func NewWorkAccessToken(corpID, corpSecret, cacheKeyPrefix string, cache cache.Cache) AccessTokenContextHandle {
if cache == nil {
panic("cache is needed")
panic("cache the not exist")
}
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()
// 构建缓存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)
}
accessTokenCacheKey := fmt.Sprintf("%s_access_token_%s", ak.cacheKeyPrefix, ak.CorpID)
val := ak.cache.Get(accessTokenCacheKey)
if val != nil {
accessToken = val.(string)
var ok bool
if accessToken, ok = val.(string); !ok {
accessToken = ""
}
return
}
// cache失效从微信服务器获取
// cache 失效,从微信服务器获取
var resAccessToken ResAccessToken
resAccessToken, err = GetTokenFromServerContext(ctx, fmt.Sprintf(workAccessTokenURL, ak.CorpID, ak.CorpSecret))
if err != nil {
@@ -253,20 +224,17 @@ 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)

View File

@@ -1,7 +1,6 @@
package credential
import (
context2 "context"
"encoding/json"
"fmt"
"sync"
@@ -11,15 +10,15 @@ import (
"github.com/silenceper/wechat/v2/util"
)
// getTicketURL 获取ticketurl
// getTicketURL 获取 ticketurl
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
}
@@ -33,7 +32,7 @@ func NewDefaultJsTicket(appID string, cacheKeyPrefix string, cache cache.Cache)
}
}
// ResTicket 请求jsapi_tikcet返回结果
// ResTicket 请求 jsapi_tikcet 返回结果
type ResTicket struct {
util.CommonError
@@ -41,19 +40,9 @@ type ResTicket struct {
ExpiresIn int64 `json:"expires_in"`
}
// GetTicket 获取jsapi_ticket
// GetTicket 获取 jsapi_ticket
func (js *DefaultJsTicket) GetTicket(accessToken string) (ticketStr string, err error) {
return js.GetTicketContext(context2.Background(), accessToken)
}
// GetTicketFromServer 从服务器中获取ticket
func GetTicketFromServer(accessToken string) (ticket ResTicket, err error) {
return GetTicketFromServerContext(context2.Background(), accessToken)
}
// GetTicketContext 获取jsapi_ticket
func (js *DefaultJsTicket) GetTicketContext(ctx context2.Context, accessToken string) (ticketStr string, err error) {
// 先从cache中取
// 先从 cache 中取
jsAPITicketCacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", js.cacheKeyPrefix, js.appID)
if val := js.cache.Get(jsAPITicketCacheKey); val != nil {
return val.(string), nil
@@ -68,7 +57,7 @@ func (js *DefaultJsTicket) GetTicketContext(ctx context2.Context, accessToken st
}
var ticket ResTicket
ticket, err = GetTicketFromServerContext(ctx, accessToken)
ticket, err = GetTicketFromServer(accessToken)
if err != nil {
return
}
@@ -78,11 +67,11 @@ func (js *DefaultJsTicket) GetTicketContext(ctx context2.Context, accessToken st
return
}
// GetTicketFromServerContext 从服务器中获取ticket
func GetTicketFromServerContext(ctx context2.Context, accessToken string) (ticket ResTicket, err error) {
// GetTicketFromServer 从服务器中获取 ticket
func GetTicketFromServer(accessToken string) (ticket ResTicket, err error) {
var response []byte
url := fmt.Sprintf(getTicketURL, accessToken)
response, err = util.HTTPGetContext(ctx, url)
response, err = util.HTTPGet(url)
if err != nil {
return
}

View File

@@ -1,22 +0,0 @@
package credential
import (
"context"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)
// TestGetTicketFromServerContext 测试 GetTicketFromServerContext 函数
func TestGetTicketFromServerContext(t *testing.T) {
defer gock.Off()
gock.New(fmt.Sprintf(getTicketURL, "arg-ak")).Reply(200).JSON(&ResTicket{Ticket: "mock-ticket", ExpiresIn: 10})
ticket, err := GetTicketFromServerContext(context.Background(), "arg-ak")
assert.Nil(t, err)
assert.Equal(t, int64(0), ticket.ErrCode)
assert.Equal(t, "mock-ticket", ticket.Ticket, "they should be equal")
assert.Equal(t, int64(10), ticket.ExpiresIn, "they should be equal")
}

View File

@@ -1,15 +1,7 @@
package credential
import context2 "context"
// JsTicketHandle js ticket获取
// 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)
}

View File

@@ -1,118 +0,0 @@
package credential
import (
"encoding/json"
"fmt"
"sync"
"time"
"github.com/silenceper/wechat/v2/cache"
"github.com/silenceper/wechat/v2/util"
)
// TicketType ticket类型
type TicketType int
const (
// TicketTypeCorpJs 企业jsapi ticket
TicketTypeCorpJs TicketType = iota
// TicketTypeAgentJs 应用jsapi ticket
TicketTypeAgentJs
)
// 企业微信相关的 ticket URL
const (
// 企业微信 jsapi ticket
getWorkJsTicketURL = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=%s"
// 企业微信应用 jsapi ticket
getWorkAgentJsTicketURL = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=%s&type=agent_config"
)
// WorkJsTicket 企业微信js ticket获取
type WorkJsTicket struct {
corpID string
agentID string
cacheKeyPrefix string
cache cache.Cache
jsAPITicketLock *sync.Mutex
}
// NewWorkJsTicket new WorkJsTicket
func NewWorkJsTicket(corpID, agentID, cacheKeyPrefix string, cache cache.Cache) *WorkJsTicket {
return &WorkJsTicket{
corpID: corpID,
agentID: agentID,
cache: cache,
cacheKeyPrefix: cacheKeyPrefix,
jsAPITicketLock: new(sync.Mutex),
}
}
// GetTicket 根据类型获取相应的jsapi_ticket
func (js *WorkJsTicket) GetTicket(accessToken string, ticketType TicketType) (ticketStr string, err error) {
var cacheKey string
switch ticketType {
case TicketTypeCorpJs:
cacheKey = fmt.Sprintf("%s_corp_jsapi_ticket_%s", js.cacheKeyPrefix, js.corpID)
case TicketTypeAgentJs:
if js.agentID == "" {
err = fmt.Errorf("agentID is empty")
return
}
cacheKey = fmt.Sprintf("%s_agent_jsapi_ticket_%s_%s", js.cacheKeyPrefix, js.corpID, js.agentID)
default:
err = fmt.Errorf("unsupported ticket type: %v", ticketType)
return
}
if val := js.cache.Get(cacheKey); val != nil {
return val.(string), nil
}
js.jsAPITicketLock.Lock()
defer js.jsAPITicketLock.Unlock()
// 双检,防止重复从微信服务器获取
if val := js.cache.Get(cacheKey); val != nil {
return val.(string), nil
}
var ticket ResTicket
ticket, err = js.getTicketFromServer(accessToken, ticketType)
if err != nil {
return
}
expires := ticket.ExpiresIn - 1500
err = js.cache.Set(cacheKey, ticket.Ticket, time.Duration(expires)*time.Second)
ticketStr = ticket.Ticket
return
}
// getTicketFromServer 从服务器中获取ticket
func (js *WorkJsTicket) getTicketFromServer(accessToken string, ticketType TicketType) (ticket ResTicket, err error) {
var url string
switch ticketType {
case TicketTypeCorpJs:
url = fmt.Sprintf(getWorkJsTicketURL, accessToken)
case TicketTypeAgentJs:
url = fmt.Sprintf(getWorkAgentJsTicketURL, accessToken)
default:
err = fmt.Errorf("unsupported ticket type: %v", ticketType)
return
}
var response []byte
response, err = util.HTTPGet(url)
if err != nil {
return
}
err = json.Unmarshal(response, &ticket)
if err != nil {
return
}
if ticket.ErrCode != 0 {
err = fmt.Errorf("getTicket Error : errcode=%d , errmsg=%s", ticket.ErrCode, ticket.ErrMsg)
return
}
return
}

2
doc.go
View File

@@ -1,7 +1,7 @@
/*
Package wechat provide wechat sdk for go
使用Golang开发的微信SDK简单、易用。
使用 Golang 开发的微信 SDK简单、易用。
更多信息https://github.com/silenceper/wechat

View File

@@ -1,10 +1,10 @@
# API 文档
已完成以及未完成API列表汇总
已完成以及未完成 API 列表汇总
如果有兴趣参与贡献可以在具体的API表格后面标识自己为贡献者以及完成时间例如
如果有兴趣参与贡献,可以在具体的 API 表格后面标识自己为贡献者以及完成时间,例如:
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |贡献者|完成时间|
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |贡献者 | 完成时间|
| :---------------------: | -------- | :------------------------- | ---------- | -------- |-------- |-------- |
| 获取公众号类目 | GET | /wxaapi/newtmpl/getcategory | NO | |silenceper| 2021-12-20|

View File

@@ -37,7 +37,7 @@ TODO
| 名称 | 请求方式 | URL | 是否已实现 | 使用方法 |
| :----------------: | -------- | :------------------------------- | ---------- | ----------------------------------- |
| code换取用户手机号 | POST | /wxa/business/getuserphonenumber | YES | (business *Business) GetPhoneNumber |
| code 换取用户手机号 | POST | /wxa/business/getuserphonenumber | YES | (business *Business) GetPhoneNumber |
## 安全风控

View File

@@ -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 |
## 素材管理

View File

@@ -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
View File

@@ -1,16 +1,30 @@
module github.com/silenceper/wechat/v2
go 1.16
go 1.18
require (
github.com/alicebob/miniredis/v2 v2.30.0
github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d
github.com/alicebob/miniredis/v2 v2.33.0
github.com/bradfitz/gomemcache v0.0.0-20230905024940-24af94b03874
github.com/fatih/structs v1.1.0
github.com/go-redis/redis/v8 v8.11.5
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
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
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
View File

@@ -1,14 +1,11 @@
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.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/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/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=
@@ -16,132 +13,52 @@ 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/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
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/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/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
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/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/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
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/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/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/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.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/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/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/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=
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=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
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=
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=
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=

View File

@@ -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,10 +93,16 @@ func (o *OpenAPI) ClearQuotaByAppSecret() error {
func (o *OpenAPI) getAppIDAndSecret() (string, string, error) {
switch o.ctx.(type) {
case *mpContext.Context:
c := o.ctx.(*mpContext.Context)
c, ok := o.ctx.(*mpContext.Context)
if !ok {
return "", "", errors.New("invalid context type")
}
return c.AppID, c.AppSecret, nil
case *ocContext.Context:
c := o.ctx.(*ocContext.Context)
c, ok := o.ctx.(*ocContext.Context)
if !ok {
return "", "", errors.New("invalid context type")
}
return c.AppID, c.AppSecret, nil
default:
return "", "", errors.New("invalid context type")

View File

@@ -30,8 +30,6 @@ 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 数据分析
@@ -58,8 +56,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 小程序留存数据返回
@@ -70,7 +68,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,
@@ -139,7 +137,7 @@ func (analysis *Analysis) GetAnalysisDailySummary(beginDate, endDate string) (re
return
}
// ResAnalysisVisitTrend 小程序访问数据趋势(日、月、周)
// ResAnalysisVisitTrend 小程序访问数据趋势 (日、月、周)
type ResAnalysisVisitTrend struct {
util.CommonError
List []struct {
@@ -154,7 +152,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,
@@ -192,9 +190,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 用户画像
@@ -203,9 +201,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 小程序新增或活跃用户的画像分布数据返回
@@ -239,9 +237,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 访问分布单分布类型数据
@@ -317,67 +315,3 @@ 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
}

View File

@@ -10,22 +10,11 @@ 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 登录/用户信息
@@ -44,7 +33,7 @@ type ResCode2Session struct {
OpenID string `json:"openid"` // 用户唯一标识
SessionKey string `json:"session_key"` // 会话密钥
UnionID string `json:"unionid"` // 用户在开放平台的唯一标识符在满足UnionID下发条件的情况下会返回
UnionID string `json:"unionid"` // 用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回
}
// RspCheckEncryptedData .
@@ -76,63 +65,27 @@ 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无需用户授权
// 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
func (auth *Auth) GetPaidUnionID() {
// TODO
}
// 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.GetAccessTokenContext(ctx); err != nil {
if at, err = auth.GetAccessToken(); 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
}
@@ -160,14 +113,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.GetAccessTokenContext(ctx); err != nil {
if at, err = auth.GetAccessToken(); err != nil {
return nil, err
}
body := map[string]interface{}{
@@ -189,119 +142,7 @@ 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
}

View File

@@ -1,7 +1,6 @@
package business
import (
"context"
"fmt"
"github.com/silenceper/wechat/v2/util"
@@ -22,25 +21,20 @@ 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) {
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)
accessToken, err := business.GetAccessToken()
if err != nil {
return
}
uri := fmt.Sprintf(getPhoneNumberURL, accessToken)
response, err := util.PostJSONContext(ctx, uri, in)
response, err := util.PostJSON(uri, in)
if err != nil {
return
}

View File

@@ -14,5 +14,4 @@ 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
}

View File

@@ -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 替代,返回值更加丰富

View File

@@ -8,5 +8,5 @@ import (
// Context struct
type Context struct {
*config.Config
credential.AccessTokenContextHandle
credential.AccessTokenHandle
}

View File

@@ -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")
)

View File

@@ -1,295 +0,0 @@
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
)

View File

@@ -1,16 +0,0 @@
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}
}

View File

@@ -556,7 +556,7 @@ type SubscribeMsgSentEvent struct {
type SubscribeMsgSentList struct {
TemplateID string `xml:"TemplateId" json:"TemplateId"`
MsgID string `xml:"MsgID" json:"MsgID"`
ErrorCode string `xml:"ErrorCode" json:"ErrorCode"`
ErrorCode int `xml:"ErrorCode" json:"ErrorCode"`
ErrorStatus string `xml:"ErrorStatus" json:"ErrorStatus"`
}

View File

@@ -8,12 +8,10 @@ import (
)
const (
// createActivityIDURL 创建activity_id
createActivityIDURL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/activityid/create?access_token=%s&unionid=%s&openid=%s"
// createActivityURL 创建 activity_id
createActivityURL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/activityid/create?access_token=%s"
// SendUpdatableMsgURL 修改动态消息
setUpdatableMsgURL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/updatablemsg/send?access_token=%s"
// setChatToolMsgURL 修改小程序聊天工具的动态卡片消息
setChatToolMsgURL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/chattoolmsg/send?access_token=%s"
)
// UpdatableTargetState 动态消息状态
@@ -40,26 +38,15 @@ func NewUpdatableMessage(ctx *context.Context) *UpdatableMessage {
}
}
// 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) {
// CreateActivityID 创建 activity_id
func (updatableMessage *UpdatableMessage) CreateActivityID() (res CreateActivityIDResponse, err error) {
accessToken, err := updatableMessage.GetAccessToken()
if err != nil {
return
}
url := fmt.Sprintf(createActivityIDURL, accessToken, req.UnionID, req.OpenID)
response, err := util.HTTPGet(url)
uri := fmt.Sprintf(createActivityURL, accessToken)
response, err := util.HTTPGet(uri)
if err != nil {
return
}
@@ -88,7 +75,7 @@ func (updatableMessage *UpdatableMessage) SetUpdatableMsg(activityID string, tar
return util.DecodeWithCommonError(response, "SendUpdatableMsg")
}
// CreateActivityIDResponse 创建activity_id 返回
// CreateActivityIDResponse 创建 activity_id 返回
type CreateActivityIDResponse struct {
util.CommonError
@@ -113,35 +100,3 @@ 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")
}

View File

@@ -10,10 +10,8 @@ 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"
@@ -36,30 +34,17 @@ type MiniProgram struct {
// NewMiniProgram 实例化小程序 API
func NewMiniProgram(cfg *config.Config) *MiniProgram {
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)
}
defaultAkHandle := credential.NewDefaultAccessToken(cfg.AppID, cfg.AppSecret, credential.CacheKeyMiniProgramPrefix, cfg.Cache)
ctx := &context.Context{
Config: cfg,
AccessTokenContextHandle: defaultAkHandle,
Config: cfg,
AccessTokenHandle: defaultAkHandle,
}
return &MiniProgram{ctx}
}
// SetAccessTokenHandle 自定义 access_token 获取方式
func (miniProgram *MiniProgram) SetAccessTokenHandle(accessTokenHandle credential.AccessTokenHandle) {
miniProgram.ctx.AccessTokenContextHandle = credential.AccessTokenCompatibleHandle{
AccessTokenHandle: accessTokenHandle,
}
}
// SetAccessTokenContextHandle 自定义 access_token 获取方式
func (miniProgram *MiniProgram) SetAccessTokenContextHandle(accessTokenContextHandle credential.AccessTokenContextHandle) {
miniProgram.ctx.AccessTokenContextHandle = accessTokenContextHandle
miniProgram.ctx.AccessTokenHandle = accessTokenHandle
}
// GetContext get Context
@@ -181,13 +166,3 @@ 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)
}

View File

@@ -1,456 +0,0 @@
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
}

View File

@@ -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"` // 收货时间,时间戳形式
}

View File

@@ -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 {

View File

@@ -36,26 +36,24 @@ 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 请求并返回二维码二进制数据
@@ -90,19 +88,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)
}

View File

@@ -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 {

View File

@@ -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"` // 用户邮箱地址

View File

@@ -1,7 +1,6 @@
package security
import (
context2 "context"
"fmt"
"strconv"
@@ -27,13 +26,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 {
@@ -57,33 +56,28 @@ 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) {
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)
accessToken, err := security.GetAccessToken()
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.PostJSONContext(ctx, uri, req)
response, err := util.PostJSON(uri, req)
if err != nil {
return
}
@@ -100,7 +94,7 @@ func (security *Security) MediaCheckAsyncContext(ctx context2.Context, in *Media
// 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 {
@@ -175,12 +169,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 文本检查响应
@@ -192,7 +186,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"` // 命中标签
@@ -203,7 +197,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 {
@@ -228,12 +222,7 @@ func (security *Security) MsgCheckV1(content string) (res MsgCheckResponse, err
// MsgCheck 检查一段文本是否含有违法违规内容
func (security *Security) MsgCheck(in *MsgCheckRequest) (res MsgCheckResponse, err error) {
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)
accessToken, err := security.GetAccessToken()
if err != nil {
return
}
@@ -246,7 +235,7 @@ func (security *Security) MsgCheckContext(ctx context2.Context, in *MsgCheckRequ
req.Version = 2
uri := fmt.Sprintf(msgCheckURL, accessToken)
response, err := util.PostJSONContext(ctx, uri, req)
response, err := util.PostJSON(uri, req)
if err != nil {
return
}

View File

@@ -1,7 +1,6 @@
package subscribe
import (
"encoding/json"
"fmt"
"github.com/silenceper/wechat/v2/miniprogram/context"
@@ -12,30 +11,22 @@ 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 订阅消息
@@ -51,11 +42,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 的值
@@ -66,18 +57,11 @@ 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"`
KeywordEnumValueList []KeywordEnumValue `json:"keywordEnumValueList"`
}
// KeywordEnumValue 枚举参数值范围
type KeywordEnumValue struct {
EnumValueList []string `json:"enumValueList"`
KeywordCode string `json:"keywordCode"`
PriTmplID string `json:"priTmplId"`
Title string `json:"title"`
Content string `json:"content"`
Example string `json:"example"`
Type int64 `json:"type"`
}
// TemplateList template list
@@ -86,13 +70,6 @@ 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
@@ -108,33 +85,6 @@ 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) {
@@ -239,200 +189,3 @@ 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
}

View File

@@ -1,4 +1,4 @@
# 小程序-云开发 SDK
# 小程序 - 云开发 SDK
Tencent Cloud Base [文档](https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/)

View File

@@ -14,7 +14,7 @@ const (
// InvokeCloudFunctionRes 云函数调用返回结果
type InvokeCloudFunctionRes struct {
util.CommonError
RespData string `json:"resp_data"` // 云函数返回的buffer
RespData string `json:"resp_data"` // 云函数返回的 buffer
}
// InvokeCloudFunction 云函数调用

View File

@@ -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"`
}

View File

@@ -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"` // 该文件错误信息

View File

@@ -6,13 +6,7 @@ import (
"github.com/silenceper/wechat/v2/util"
)
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"`
}
const queryURL = "https://api.weixin.qq.com/wxa/query_urllink"
// ULQueryResult 返回的结果
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-link/urllink.query.html 返回值
@@ -34,35 +28,25 @@ type ULQueryResult struct {
ResourceAppid string `json:"resource_appid"`
} `json:"cloud_base"`
} `json:"url_link_info"`
VisitOpenid string `json:"visit_openid"`
QuotaInfo QuotaInfo `json:"quota_info"`
}
// QuotaInfo quota 配置
type QuotaInfo struct {
RemainVisitQuota int64 `json:"remain_visit_quota"`
VisitOpenid string `json:"visit_openid"`
}
// Query 查询小程序 url_link 配置。
func (u *URLLink) Query(urlLink string) (*ULQueryResult, error) {
return u.QueryWithType(&ULQueryRequest{URLLink: urlLink})
}
accessToken, err := u.GetAccessToken()
if err != nil {
return nil, err
}
// 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 {
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 response []byte
if response, err = util.PostJSON(fmt.Sprintf(queryURL, accessToken), req); err != nil {
var resp ULQueryResult
err = util.DecodeWithError(response, &resp, "URLLink.Query")
if err != nil {
return nil, err
}
result := &ULQueryResult{}
err = util.DecodeWithError(response, result, "URLLink.Query")
return result, err
return &resp, nil
}

View File

@@ -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 {

View File

@@ -10,12 +10,11 @@ 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"`
QueryType int `json:"query_type"`
Scheme string `json:"scheme"`
}
// SchemeInfo scheme 配置
@@ -24,7 +23,7 @@ type SchemeInfo struct {
AppID string `json:"appid"`
// 小程序页面路径。
Path string `json:"path"`
// 小程序页面query。
// 小程序页面 query。
Query string `json:"query"`
// 创建时间,为 Unix 时间戳。
CreateTime int64 `json:"create_time"`
@@ -34,47 +33,34 @@ type SchemeInfo struct {
EnvVersion EnvVersion `json:"env_version"`
}
// QuotaInfo quota 配置
type QuotaInfo struct {
RemainVisitQuota int64 `json:"remain_visit_quota"`
}
// ResQueryScheme 返回结构体
// 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"`
QuotaInfo QuotaInfo `json:"quota_info"`
// 访问该链接的 openid没有用户访问过则为空字符串
VisitOpenid string `json:"visit_openid"`
}
// QueryScheme 查询小程序 scheme 码
func (u *URLScheme) QueryScheme(querySchemeParams QueryScheme) (schemeInfo SchemeInfo, visitOpenid string, err error) {
res, err := u.QuerySchemeWithRes(querySchemeParams)
var accessToken string
accessToken, err = u.GetAccessToken()
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
}

View File

@@ -17,12 +17,7 @@ func NewURLScheme(ctx *context.Context) *URLScheme {
return &URLScheme{Context: ctx}
}
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"
)
const generateURL = "https://api.weixin.qq.com/wxa/generatescheme"
// TExpireType 失效类型 (指定时间戳/指定间隔)
type TExpireType int
@@ -55,13 +50,10 @@ 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,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"`
JumpWxa *JumpWxa `json:"jump_wxa"`
ExpireType TExpireType `json:"expire_type"`
ExpireTime int64 `json:"expire_time"`
ExpireInterval int `json:"expire_interval"`
}
// USResult 返回的结果
@@ -72,7 +64,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 {
@@ -88,22 +80,3 @@ 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
}

View File

@@ -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-沙箱

View File

@@ -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 {

View File

@@ -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,26 +70,34 @@ 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 {
tq := &Request{
ExpireSeconds: int64(exp.Seconds()),
}
var (
tq = &Request{
ExpireSeconds: int64(exp.Seconds()),
}
ok bool
)
switch reflect.ValueOf(scene).Kind() {
case reflect.String:
tq.ActionName = actionStr
tq.ActionInfo.Scene.SceneStr = scene.(string)
if tq.ActionInfo.Scene.SceneStr, ok = scene.(string); !ok {
panic("scene must be 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
tq.ActionInfo.Scene.SceneID = scene.(int)
if tq.ActionInfo.Scene.SceneID, ok = scene.(int); !ok {
panic("scene must be int")
}
default:
}
return tq
@@ -97,17 +105,25 @@ func NewTmpQrRequest(exp time.Duration, scene interface{}) *Request {
// NewLimitQrRequest 新建永久二维码请求实例
func NewLimitQrRequest(scene interface{}) *Request {
tq := &Request{}
var (
tq = &Request{}
ok bool
)
switch reflect.ValueOf(scene).Kind() {
case reflect.String:
tq.ActionName = actionLimitStr
tq.ActionInfo.Scene.SceneStr = scene.(string)
if tq.ActionInfo.Scene.SceneStr, ok = scene.(string); !ok {
panic("scene must be 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
tq.ActionInfo.Scene.SceneID = scene.(int)
if tq.ActionInfo.Scene.SceneID, ok = scene.(int); !ok {
panic("scene must be int")
}
default:
}
return tq

View File

@@ -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 {

View File

@@ -11,5 +11,4 @@ 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
}

View File

@@ -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()

View File

@@ -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"

View File

@@ -16,11 +16,11 @@ const (
)
type reqDeviceAuthorize struct {
// 设备id的个数
// 设备 id 的个数
DeviceNum string `json:"device_num"`
// 设备id的列表jsonarray格式其size必须等于device_num
// 设备 id 的列表jsonarray 格式,其 size 必须等于 device_num
DeviceList []ReqDevice `json:"device_list"`
// 请求操作的类型限定取值为0设备授权缺省值为0 1设备更新更新已授权设备的各属性值
// 请求操作的类型限定取值为0设备授权缺省值为 01设备更新更新已授权设备的各属性值
OpType string `json:"op_type,omitempty"`
// 设备的产品编号(由微信硬件平台分配)。可在公众号设备功能管理页面查询。
// 当 op_type 为0product_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协议进行连接
// 安卓平台不同时支持BLEclassic类型
// 一个设备可以支持多种连接类型,用符号"|"做分割,客户端优先选择靠前的连接方式(优先级按 | 关系的排序依次降低),举例:
// 1表示设备仅支持 andiod classic bluetooth 1|2表示设备支持 android 和 ios 两种 classic bluetooth但是客户端优先选择 android classic bluetooth 协议,如果 android classic bluetooth 协议连接失败,再选择 ios classic bluetooth 协议进行连接
// (注:安卓平台不同时支持 BLEclassic 类型)
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 bufauth key的格式各version对应的auth bufkey的具体格式可以参看“客户端蓝牙外设协议”该字段目前支持取值
// 0不加密的version
// auth version设备和微信进行 auth 时,会根据该版本号来确认 auth bufauth key 的格式(各 version 对应的 auth bufkey 的具体格式可以参看“客户端蓝牙外设协议”),该字段目前支持取值:
// 0不加密的 version
// 1version 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 若该字段填1connect_protocol 必须包括3。非精简协议设备切勿填写该字段
// 精简协议类型取值如下计步设备精简协议1若该字段填 1connect_protocol 必须包括 3。非精简协议设备切勿填写该字段
BleSimpleProtocol string `json:"ble_simple_protocol,omitempty"`
}

View File

@@ -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"` // 是否显示封面0false即不显示1true即显示(默认)
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"` // 是否显示封面0false即不显示1true即显示 (默认)
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"` // 这篇图文消息素材的最后更新时间
}

View File

@@ -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"` // 是否显示封面0false即不显示1true即显示(默认)
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"` // 是否显示封面0false即不显示1true即显示 (默认)
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"` // 这篇图文消息素材的最后更新时间
}

View File

@@ -1,7 +1,6 @@
package js
import (
context2 "context"
"fmt"
"github.com/silenceper/wechat/v2/credential"
@@ -15,7 +14,7 @@ type Js struct {
credential.JsTicketHandle
}
// Config 返回给用户jssdk配置信息
// Config 返回给用户 jssdk 配置信息
type Config struct {
AppID string `json:"app_id"`
Timestamp int64 `json:"timestamp"`
@@ -32,39 +31,22 @@ 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) {
return js.GetConfigContext(context2.Background(), uri)
}
// GetConfigContext 新方法,允许传入上下文,避免协程泄漏
func (js *Js) GetConfigContext(ctx context2.Context, uri string) (config *Config, err error) {
config = new(Config)
var accessToken string
// 类型断言,如果断言成功,调用安全的 GetAccessTokenContext 方法
if ctxHandle, ok := js.Context.AccessTokenHandle.(credential.AccessTokenContextHandle); ok {
accessToken, err = ctxHandle.GetAccessTokenContext(ctx)
} else {
// 如果没有实现 AccessTokenContextHandle 接口,调用旧的 GetAccessToken 方法
accessToken, err = js.Context.GetAccessToken()
}
accessToken, err = js.GetAccessToken()
if err != nil {
return
}
var ticketStr string
// 类型断言 jsTicket
if ticketCtxHandle, ok := js.JsTicketHandle.(credential.JsTicketContextHandle); ok {
ticketStr, err = ticketCtxHandle.GetTicketContext(ctx, accessToken)
} else {
// 如果没有实现 JsTicketContextHandle 接口,调用旧的 GetTicket 方法
ticketStr, err = js.GetTicket(accessToken)
}
ticketStr, err = js.GetTicket(accessToken)
if err != nil {
return
}
@@ -74,7 +56,6 @@ func (js *Js) GetConfigContext(ctx context2.Context, uri string) (config *Config
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
sigStr := util.Signature(str)
config = new(Config)
config.AppID = js.AppID
config.NonceStr = nonceStr
config.Timestamp = timestamp

View File

@@ -6,7 +6,6 @@ import (
"fmt"
"io"
"os"
"path"
"github.com/silenceper/wechat/v2/officialaccount/context"
"github.com/silenceper/wechat/v2/util"
@@ -164,7 +163,7 @@ type resAddMaterial struct {
}
// AddMaterialFromReader 上传永久性素材(处理视频需要单独上传),从 io.Reader 中读取
func (material *Material) AddMaterialFromReader(mediaType MediaType, filePath string, reader io.Reader) (mediaID string, url string, err error) {
func (material *Material) AddMaterialFromReader(mediaType MediaType, filename string, reader io.Reader) (mediaID string, url string, err error) {
if mediaType == MediaTypeVideo {
err = errors.New("永久视频素材上传使用 AddVideo 方法")
return
@@ -176,10 +175,8 @@ func (material *Material) AddMaterialFromReader(mediaType MediaType, filePath 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", filePath, filename, uri, reader)
response, err = util.PostFileFromReader("media", filename, uri, reader)
if err != nil {
return
}
@@ -214,7 +211,7 @@ type reqVideo struct {
}
// AddVideoFromReader 永久视频素材文件上传,从 io.Reader 中读取
func (material *Material) AddVideoFromReader(filePath, title, introduction string, reader io.Reader) (mediaID string, url string, err error) {
func (material *Material) AddVideoFromReader(filename, title, introduction string, reader io.Reader) (mediaID string, url string, err error) {
var accessToken string
accessToken, err = material.GetAccessToken()
if err != nil {
@@ -232,19 +229,17 @@ func (material *Material) AddVideoFromReader(filePath, title, introduction strin
if err != nil {
return
}
fileName := path.Base(filePath)
fields := []util.MultipartFormField{
{
IsFile: true,
Fieldname: "media",
FilePath: filePath,
Filename: fileName,
Filename: filename,
FileReader: reader,
},
{
IsFile: false,
Fieldname: "description",
Filename: fileName,
Value: fieldValue,
},
}
@@ -270,14 +265,14 @@ func (material *Material) AddVideoFromReader(filePath, title, introduction strin
}
// AddVideo 永久视频素材文件上传
func (material *Material) AddVideo(directory, title, introduction string) (mediaID string, url string, err error) {
f, err := os.Open(directory)
func (material *Material) AddVideo(filename, title, introduction string) (mediaID string, url string, err error) {
f, err := os.Open(filename)
if err != nil {
return "", "", err
}
defer func() { _ = f.Close() }()
return material.AddVideoFromReader(directory, title, introduction, f)
return material.AddVideoFromReader(filename, title, introduction, f)
}
type reqDeleteMaterial struct {

View File

@@ -3,7 +3,6 @@ package material
import (
"encoding/json"
"fmt"
"io"
"github.com/silenceper/wechat/v2/util"
)
@@ -12,13 +11,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"
)
@@ -63,40 +62,8 @@ 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()

View File

@@ -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)
}

View File

@@ -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"`
}

View File

@@ -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"` // 类目的中文名
}

View File

@@ -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()

View File

@@ -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"

View File

@@ -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 {

View File

@@ -4,30 +4,28 @@ import (
stdcontext "context"
"net/http"
"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/internal/openapi"
"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
@@ -47,15 +45,9 @@ type OfficialAccount struct {
subscribeMsg *message.Subscribe
}
// NewOfficialAccount 实例化公众号API
// NewOfficialAccount 实例化公众号 API
func NewOfficialAccount(cfg *config.Config) *OfficialAccount {
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)
}
defaultAkHandle := credential.NewDefaultAccessToken(cfg.AppID, cfg.AppSecret, credential.CacheKeyOfficialAccountPrefix, cfg.Cache)
ctx := &context.Context{
Config: cfg,
AccessTokenHandle: defaultAkHandle,
@@ -63,7 +55,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
}
@@ -97,12 +89,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)
@@ -110,7 +102,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)
@@ -142,7 +134,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)
@@ -199,7 +191,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)
@@ -220,7 +212,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)
}

View File

@@ -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

View File

@@ -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 为老账号的openIDopenIDs100个以内
// AccessToken 为新账号的AccessToken
// ListChangeOpenIDs 返回指定 OpenID 变化列表
// fromAppID 为老账号 AppID
// openIDs 为老账号的 openIDopenIDs100 个以内
// 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)

View File

@@ -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,7 +161,10 @@ func (user *User) ListUserOpenIDs(nextOpenid ...string) (*OpenidList, error) {
return nil, err
}
uri, _ := url.Parse(userListURL)
uri, err := url.Parse(userListURL)
if err != nil {
return nil, err
}
q := uri.Query()
q.Set("access_token", accessToken)
if len(nextOpenid) > 0 && nextOpenid[0] != "" {
@@ -184,7 +187,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)

View File

@@ -19,7 +19,7 @@ cfg := &openplatform.Config{
openPlatform := wc.GetOpenPlatform(cfg)
// 传入requestresponseWriter
// 传入 requestresponseWriter
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)

View File

@@ -2,7 +2,7 @@ package account
import "github.com/silenceper/wechat/v2/openplatform/context"
// Account 开放平台帐号管理
// Account 开放平台张哈管理
// TODO 实现方法
type Account struct {
*context.Context

View File

@@ -1,4 +1,4 @@
// Package context 开放平台相关context
// Package context 开放平台相关 context
package context
import (
@@ -20,7 +20,6 @@ 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 获取已授权的账号信息
@@ -49,7 +48,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,
@@ -78,7 +77,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)
}
@@ -110,7 +109,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 {
@@ -119,12 +118,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 {
@@ -133,25 +132,11 @@ 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"`
@@ -168,7 +153,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"`
@@ -240,10 +225,6 @@ func (ctx *Context) RefreshAuthrTokenContext(stdCtx context.Context, appid, refr
if err := cache.SetContext(stdCtx, ctx.Cache, authrTokenKey, ret.AccessToken, time.Second*time.Duration(ret.ExpiresIn-30)); err != nil {
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
}
@@ -252,27 +233,17 @@ 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 {
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 "", fmt.Errorf("cannot get authorizer %s access token", appid)
}
return val.(string), nil
}
// GetAuthrAccessToken 获取授权方AccessToken
// GetAuthrAccessToken 获取授权方 AccessToken
func (ctx *Context) GetAuthrAccessToken(appid string) (string, error) {
return ctx.GetAuthrAccessTokenContext(context.Background(), appid)
}

View File

@@ -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)

View File

@@ -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-x3营业执照注册号 (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 {

View File

@@ -1,7 +1,6 @@
package miniprogram
import (
originalContext "context"
"fmt"
"github.com/silenceper/wechat/v2/credential"
@@ -22,7 +21,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 {
@@ -38,23 +37,7 @@ func (miniProgram *MiniProgram) GetAccessToken() (string, error) {
return akRes.AccessToken, nil
}
// GetAccessTokenContext 利用ctx获取ak
func (miniProgram *MiniProgram) GetAccessTokenContext(ctx originalContext.Context) (string, error) {
ak, akErr := miniProgram.openContext.GetAuthrAccessTokenContext(ctx, miniProgram.AppID)
if akErr == nil {
return ak, nil
}
if miniProgram.authorizerRefreshToken == "" {
return "", fmt.Errorf("please set the authorizer_refresh_token first")
}
akRes, akResErr := miniProgram.GetComponent().RefreshAuthrTokenContext(ctx, miniProgram.AppID, miniProgram.authorizerRefreshToken)
if akResErr != nil {
return "", akResErr
}
return akRes.AccessToken, nil
}
// SetAuthorizerRefreshToken 设置代执操作业务授权账号authorizer_refresh_token
// SetAuthorizerRefreshToken 设置代执操作业务授权账号 authorizer_refresh_token
func (miniProgram *MiniProgram) SetAuthorizerRefreshToken(authorizerRefreshToken string) *MiniProgram {
miniProgram.authorizerRefreshToken = authorizerRefreshToken
return miniProgram
@@ -66,7 +49,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}
}
@@ -82,20 +65,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{
AccessTokenContextHandle: miniProgram,
AccessTokenHandle: 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,
@@ -103,7 +86,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)
}

View File

@@ -1,7 +1,6 @@
package js
import (
context2 "context"
"fmt"
"github.com/silenceper/wechat/v2/credential"
@@ -25,39 +24,22 @@ 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) {
return js.GetConfigContext(context2.Background(), uri, appid)
}
// GetConfigContext 新方法,允许传入上下文,避免协程泄漏
func (js *Js) GetConfigContext(ctx context2.Context, uri, appid string) (config *officialJs.Config, err error) {
config = new(officialJs.Config)
var accessToken string
// 类型断言,如果断言成功,调用安全的 GetAccessTokenContext 方法
if ctxHandle, ok := js.Context.AccessTokenHandle.(credential.AccessTokenContextHandle); ok {
accessToken, err = ctxHandle.GetAccessTokenContext(ctx)
} else {
// 如果没有实现 AccessTokenContextHandle 接口,调用旧的 GetAccessToken 方法
accessToken, err = js.Context.GetAccessToken()
}
accessToken, err = js.GetAccessToken()
if err != nil {
return
}
var ticketStr string
// 类型断言 jsTicket
if ticketCtxHandle, ok := js.JsTicketHandle.(credential.JsTicketContextHandle); ok {
ticketStr, err = ticketCtxHandle.GetTicketContext(ctx, accessToken)
} else {
// 如果没有实现 JsTicketContextHandle 接口,调用旧的 GetTicket 方法
ticketStr, err = js.GetTicket(accessToken)
}
ticketStr, err = js.GetTicket(accessToken)
if err != nil {
return
}
@@ -67,7 +49,6 @@ func (js *Js) GetConfigContext(ctx context2.Context, uri, appid string) (config
str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s", ticketStr, nonceStr, timestamp, uri)
sigStr := util.Signature(str)
config = new(officialJs.Config)
config.AppID = appid
config.NonceStr = nonceStr
config.Timestamp = timestamp

View File

@@ -1,147 +0,0 @@
// 验证 js.GetConfigContext 是否能正确传递上下文到 HTTP 请求,确保上下文正确传播,防止在获取 JSSDK 配置时发生协程泄露。
package js
import (
"bytes"
context2 "context"
"errors"
"fmt"
"io"
"net/http"
"testing"
"github.com/silenceper/wechat/v2/cache"
"github.com/silenceper/wechat/v2/credential"
"github.com/silenceper/wechat/v2/officialaccount/config"
"github.com/silenceper/wechat/v2/officialaccount/context"
"github.com/silenceper/wechat/v2/util"
)
// mockAccessTokenHandle 模拟 AccessTokenHandle
type mockAccessTokenHandle struct{}
func (m *mockAccessTokenHandle) GetAccessToken() (string, error) {
return "mock-access-token", nil
}
func (m *mockAccessTokenHandle) GetAccessTokenContext(_ context2.Context) (string, error) {
return "mock-access-token", nil
}
// contextCheckingRoundTripper 自定义 RoundTripper 用于检查 context
type contextCheckingRoundTripper struct {
originalCtx context2.Context
t *testing.T
key interface{}
expectedVal interface{}
}
func (rt *contextCheckingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
// 获取请求中的 context
reqCtx := req.Context()
// 打印 context 比较结果
rt.t.Logf("比较上下文的内存地址:\n")
if reqCtx == rt.originalCtx {
rt.t.Logf("上下文具有相同的内存地址。原始上下文: %p, 请求上下文: %p\n", rt.originalCtx, reqCtx)
} else {
rt.t.Logf("上下文具有不同的内存地址。原始上下文: %p, 请求上下文: %p\n", rt.originalCtx, reqCtx)
}
// 检查 context 中的键值对
if rt.key != nil {
value := reqCtx.Value(rt.key)
rt.t.Logf("检查请求上下文中的键 %v:\n", rt.key)
if value != rt.expectedVal {
rt.t.Errorf("上下文键 %v 的值不匹配: 预期 %v, 实际 %v\n", rt.key, rt.expectedVal, value)
} else {
rt.t.Logf("上下文键 %v 的值匹配: 预期 %v, 实际 %v\n", rt.key, rt.expectedVal, value)
}
}
// 检查上下文是否已取消
select {
case <-reqCtx.Done():
return nil, reqCtx.Err() // 返回上下文取消错误
default:
// 返回模拟的 HTTP 响应,包含有效的 JSON
responseBody := `{"ticket":"mock-ticket","expires_in":7200}`
response := &http.Response{
Status: "200 OK",
StatusCode: http.StatusOK,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Body: io.NopCloser(bytes.NewReader([]byte(responseBody))),
ContentLength: int64(len(responseBody)),
Header: make(http.Header),
}
response.Header.Set("Content-Type", "application/json")
return response, nil
}
}
// contextKey 定义自定义上下文键类型,避免使用内置 string 类型
type contextKey string
// setupJsInstance 初始化 Js 实例和 HTTP 客户端
func setupJsInstance(t *testing.T, ctx context2.Context, key, val interface{}) (*Js, func()) {
cfg := &config.Config{
AppID: "test-app-id",
AppSecret: "test-app-secret",
Cache: cache.NewMemory(),
}
cacheKey := fmt.Sprintf("%s_jsapi_ticket_%s", credential.CacheKeyOfficialAccountPrefix, cfg.AppID)
if err := cfg.Cache.Delete(cacheKey); err != nil {
t.Fatalf("清除缓存失败: %v", err)
}
t.Log("清除 jsapi_ticket 的缓存:", cacheKey)
ctxHandle := &context.Context{Config: cfg, AccessTokenHandle: &mockAccessTokenHandle{}}
jsInstance := NewJs(ctxHandle, cfg.AppID)
jsInstance.SetJsTicketHandle(credential.NewDefaultJsTicket(cfg.AppID, credential.CacheKeyOfficialAccountPrefix, cfg.Cache))
originalClient := util.DefaultHTTPClient
util.DefaultHTTPClient = &http.Client{
Transport: &contextCheckingRoundTripper{originalCtx: ctx, t: t, key: key, expectedVal: val},
}
return jsInstance, func() { util.DefaultHTTPClient = originalClient }
}
// TestGetConfigContext 测试GetConfigContext的上下文传递和取消行为。
func TestGetConfigContext(t *testing.T) {
t.Run("ContextPassing", func(t *testing.T) {
ctxKey := contextKey("testKey111") // 使用自定义类型 contextKey
ctxValue := "testValue222"
ctx := context2.WithValue(context2.Background(), ctxKey, ctxValue)
t.Logf("创建的测试上下文: %p, 添加的键值对: %v=%v\n", ctx, ctxKey, ctxValue)
jsInstance, cleanup := setupJsInstance(t, ctx, ctxKey, ctxValue)
defer cleanup()
t.Log("调用 GetConfigContext")
config2, err := jsInstance.GetConfigContext(ctx, "https://www.baidu.com", "test-app-id")
if err != nil {
t.Fatalf("GetConfigContext 失败: %v", err)
}
if config2.AppID != "test-app-id" {
t.Errorf("预期 AppID 为 %s实际为 %s", "test-app-id", config2.AppID)
}
})
t.Run("ContextCancellation", func(t *testing.T) {
ctx, cancel := context2.WithCancel(context2.Background())
defer cancel()
jsInstance, cleanup := setupJsInstance(t, ctx, nil, nil)
defer cleanup()
cancel()
t.Log("调用 GetConfigContext已取消上下文")
_, err := jsInstance.GetConfigContext(ctx, "https://www.baidu.com", "test-app-id")
if err == nil {
t.Error("预期上下文取消错误,但 GetConfigContext 未返回错误")
} else if !errors.Is(err, context2.Canceled) {
t.Errorf("预期错误为 context.Canceled实际为: %v", err)
}
})
}

View File

@@ -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

View File

@@ -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)
}

View File

@@ -11,7 +11,7 @@ import (
"github.com/silenceper/wechat/v2/openplatform/officialaccount"
)
// OpenPlatform 微信开放平台相关api
// OpenPlatform 微信开放平台相关 api
type OpenPlatform struct {
*context.Context
}

View File

@@ -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

View File

@@ -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"` // 签名

View File

@@ -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
}
// 签名类型

View File

@@ -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"` // 签名

View File

@@ -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}
}

View File

@@ -35,7 +35,7 @@ type Params struct {
ActName string
Remark string
RootCa string // ca证书
RootCa string // ca 证书
}
// request 接口请求参数

View File

@@ -29,7 +29,7 @@ type Params struct {
TotalFee string
RefundFee string
RefundDesc string
RootCa string // ca证书
RootCa string // ca 证书
NotifyURL string
SignType string
}

View File

@@ -33,7 +33,7 @@ type Params struct {
Amount int
Desc string
SpbillCreateIP string
RootCa string // ca证书
RootCa string // ca 证书
}
// request 接口请求参数

View File

@@ -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 {

View File

@@ -68,18 +68,3 @@ 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
}

View File

@@ -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,39 +146,24 @@ 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, filePath, uri string) ([]byte, error) {
func PostFile(fieldName, filename, uri string) ([]byte, error) {
fields := []MultipartFormField{
{
IsFile: true,
Fieldname: fieldName,
FilePath: filePath,
Filename: filePath,
Filename: filename,
},
}
return PostMultipartForm(fields, uri)
}
// PostFileFromReader 上传文件,从 io.Reader 中读取
func PostFileFromReader(filedName, filePath, fileName, uri string, reader io.Reader) ([]byte, error) {
func PostFileFromReader(filedName, fileName, uri string, reader io.Reader) ([]byte, error) {
fields := []MultipartFormField{
{
IsFile: true,
Fieldname: filedName,
FilePath: filePath,
Filename: fileName,
FileReader: reader,
},
@@ -191,7 +176,6 @@ type MultipartFormField struct {
IsFile bool
Fieldname string
Value []byte
FilePath string
Filename string
FileReader io.Reader
}
@@ -213,7 +197,7 @@ func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte
}
if field.FileReader == nil {
fh, e := os.Open(field.FilePath)
fh, e := os.Open(field.Filename)
if e != nil {
err = fmt.Errorf("error opening file , err=%v", e)
return
@@ -229,7 +213,7 @@ func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte
}
}
} else {
partWriter, e := bodyWriter.CreateFormFile(field.Fieldname, field.Filename)
partWriter, e := bodyWriter.CreateFormField(field.Fieldname)
if e != nil {
err = e
return
@@ -291,14 +275,7 @@ func httpWithTLS(rootCa, key string) (*http.Client, error) {
config := &tls.Config{
Certificates: []tls.Certificate{cert},
}
var baseTransport http.RoundTripper
if DefaultHTTPClient.Transport != nil {
baseTransport = DefaultHTTPClient.Transport
} else {
baseTransport = http.DefaultTransport
}
trans := baseTransport.(*http.Transport).Clone()
trans := (DefaultHTTPClient.Transport.(*http.Transport)).Clone()
trans.TLSClientConfig = config
trans.DisableCompression = true
client = &http.Client{Transport: trans}

View File

@@ -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 {

View File

@@ -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")
}
}

View File

@@ -25,7 +25,10 @@ func RSADecrypt(privateKey string, ciphertext []byte) ([]byte, error) {
}
switch t := key.(type) {
case *rsa.PrivateKey:
priv = key.(*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)
}
default:
return nil, fmt.Errorf("ParsePKCS1PrivateKey error: %s, ParsePKCS8PrivateKey error: Not supported privatekey format, should be *rsa.PrivateKey, got %T", oldErr.Error(), t)
}
@@ -33,7 +36,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 {

View File

@@ -7,7 +7,7 @@ import (
"sort"
)
// Signature sha1签名
// Signature sha1 签名
func Signature(params ...string) string {
sort.Strings(params)
h := sha1.New()

View File

@@ -5,7 +5,7 @@ import (
"strings"
)
// Template 对字符串中的和mapkey相同的字符串进行模板替换 仅支持 形如: {name}
// Template 对字符串中的和 mapkey 相同的字符串进行模板替换 仅支持 形如{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