openplatform

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Overview

Package openplatform 微信开放平台API - 调用授权方接口

Index

Constants

View Source
const (
	// 组件OAuth
	URLComponentOAuth2AccessToken = core.BaseAPIURL + "/sns/oauth2/component/access_token"
	URLComponentOAuth2UserInfo    = core.BaseAPIURL + "/sns/userinfo"

	// 组件基础接口
	URLComponentToken      = core.BaseAPIURL + "/cgi-bin/component/api_component_token"
	URLPreAuthCode         = core.BaseAPIURL + "/cgi-bin/component/api_create_preauthcode"
	URLQueryAuth           = core.BaseAPIURL + "/cgi-bin/component/api_query_auth"
	URLAuthorizerToken     = core.BaseAPIURL + "/cgi-bin/component/api_authorizer_token"
	URLGetAuthorizerInfo   = core.BaseAPIURL + "/cgi-bin/component/api_get_authorizer_info"
	URLGetAuthorizerList   = core.BaseAPIURL + "/cgi-bin/component/api_get_authorizer_list"
	URLGetAuthorizerOption = core.BaseAPIURL + "/cgi-bin/component/api_get_authorizer_option"
	URLSetAuthorizerOption = core.BaseAPIURL + "/cgi-bin/component/api_set_authorizer_option"
	URLStartPushTicket     = core.BaseAPIURL + "/cgi-bin/component/api_start_push_ticket"
	URLClearComponentQuota = core.BaseAPIURL + "/cgi-bin/component/clear_quota"
	URLModifyServerDomain  = core.BaseAPIURL + "/cgi-bin/component/modify_wxa_server_domain"
	URLGetJumpDomainFile   = core.BaseAPIURL + "/cgi-bin/component/get_domain_confirmfile"
	URLModifyJumpDomain    = core.BaseAPIURL + "/cgi-bin/component/modify_wxa_jump_domain"

	// 通用接口
	URLClearQuota  = core.BaseAPIURL + "/cgi-bin/clear_quota"
	URLGetApiQuota = core.BaseAPIURL + "/cgi-bin/openapi/quota/get"
	URLGetRidInfo  = core.BaseAPIURL + "/cgi-bin/openapi/rid/get"

	// 小程序
	URLWxaGetTemplateDraftList = core.BaseAPIURL + "/wxa/gettemplatedraftlist"
	URLWxaAddToTemplate        = core.BaseAPIURL + "/wxa/addtotemplate"
	URLWxaGetTemplateList      = core.BaseAPIURL + "/wxa/gettemplatelist"
	URLWxaDeleteTemplate       = core.BaseAPIURL + "/wxa/deletetemplate"

	// 小程序码
	URLGetWxaCode = core.BaseAPIURL + "/wxa/getwxacode"

	// 用户信息
	URLGetUserInfo = core.BaseAPIURL + "/cgi-bin/user/info"

	// 刷新令牌
	URLRefreshComponentAccessToken = core.BaseAPIURL + "/cgi-bin/component/api_authorizer_token"
)

微信开放平台API地址常量

View Source
const (
	// AuthTypeOfficialAccount 公众号授权
	AuthTypeOfficialAccount = 1

	// AuthTypeMiniProgram 小程序授权
	AuthTypeMiniProgram = 2

	// AuthTypeBoth 公众号和小程序都展示
	AuthTypeBoth = 3

	// AuthTypeMiniProgramPromoter 小程序推客账号
	AuthTypeMiniProgramPromoter = 4

	// AuthTypeChannels 视频号账号
	AuthTypeChannels = 5

	// AuthTypeAll 全部
	AuthTypeAll = 6

	// AuthTypeLiveStreamingAssistant 带货助手账号
	AuthTypeLiveStreamingAssistant = 8
)

授权类型常量

View Source
const (
	// InfoTypeAuthorized 授权成功事件
	// 当公众号/服务号/小程序/微信小店/带货助手/视频号助手对第三方平台进行授权时触发
	InfoTypeAuthorized = "authorized"

	// InfoTypeUnauthorized 取消授权事件
	// 当公众号/服务号/小程序/微信小店/带货助手/视频号助手取消对第三方平台的授权时触发
	InfoTypeUnauthorized = "unauthorized"

	// InfoTypeUpdateAuthorized 授权更新事件
	// 当授权方更新授权时触发。如果更新授权时,授权的权限集没有发生变化,将不会触发授权更新通知
	InfoTypeUpdateAuthorized = "updateauthorized"

	// InfoTypeComponentVerifyTicket 验证票据推送事件
	// 微信服务器每隔10分钟推送component_verify_ticket到第三方平台的消息接收URL
	// https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/component_verify_ticket.html
	InfoTypeComponentVerifyTicket = "component_verify_ticket"
)

授权变更事件类型常量 对应微信官方文档中的InfoType字段说明 https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/authorize_event.html

Variables

View Source
var (
	ErrInvalidURL        = errors.New("invalid URL format")
	ErrEmptyJSAPIList    = errors.New("JSAPI list cannot be empty")
	ErrEmptyAppID        = errors.New("authorizer AppID cannot be empty")
	ErrCacheMiss         = errors.New("cache miss or expired")
	ErrInvalidMaxRetries = errors.New("max retries must be greater than 0")
	ErrTicketFetchFailed = errors.New("failed to fetch JSAPI ticket")
	ErrAccessTokenFailed = errors.New("failed to get authorizer access token")
)

标准错误定义

Functions

This section is empty.

Types

type AddToTemplateRequest

type AddToTemplateRequest struct {
	DraftID      int64 `json:"draft_id"`
	TemplateType int   `json:"template_type"`
}

AddToTemplateRequest 将草稿添加到模板库请求

type Article

type Article struct {
	Title       string `json:"title"`
	Description string `json:"description"`
	URL         string `json:"url"`
	PicURL      string `json:"picurl"`
}

Article 图文消息文章

type AuthClient

type AuthClient struct {
	// contains filtered or unexported fields
}

AuthClient 授权相关客户端

func NewAuthClient

func NewAuthClient(client *Client) *AuthClient

NewAuthClient 创建授权客户端

func (*AuthClient) NewAuthorizerClient

func (c *AuthClient) NewAuthorizerClient(authorizerAppID string) *AuthorizerClient

NewAuthorizerClient 创建授权方API客户端

type AuthorizationEvent

type AuthorizationEvent struct {
	AppId                        string `xml:"AppId" json:"appid"`
	CreateTime                   int64  `xml:"CreateTime" json:"create_time"`
	InfoType                     string `xml:"InfoType" json:"info_type"`
	AuthorizerAppid              string `xml:"AuthorizerAppid" json:"authorizer_appid"`
	AuthorizationCode            string `xml:"AuthorizationCode,omitempty" json:"authorization_code,omitempty"`
	AuthorizationCodeExpiredTime int64  `xml:"AuthorizationCodeExpiredTime,omitempty" json:"authorization_code_expired_time,omitempty"`
	PreAuthCode                  string `xml:"PreAuthCode,omitempty" json:"pre_auth_code,omitempty"`
}

AuthorizationEvent 授权变更事件基础结构 对应微信官方文档中的授权变更通知推送格式 https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/authorize_event.html 所有授权变更事件共有的字段 接收POST请求后,只需直接返回字符串success 字段说明: - AppId: 第三方平台appid - CreateTime: 时间戳 - InfoType: 通知类型 - AuthorizerAppid: 公众号/服务号/小程序/微信小店/带货助手/视频号助手的appid - AuthorizationCode: 授权码,可用于获取授权信息(仅authorized和updateauthorized事件) - AuthorizationCodeExpiredTime: 授权码过期时间 单位秒(仅authorized和updateauthorized事件) - PreAuthCode: 预授权码(仅authorized和updateauthorized事件)

type AuthorizationInfo

type AuthorizationInfo struct {
	AuthorizerAppID        string     `json:"authorizer_appid"`
	AuthorizerAccessToken  string     `json:"authorizer_access_token"`
	ExpiresIn              int        `json:"expires_in"` // authorizer_access_token的有效期
	AuthorizerRefreshToken string     `json:"authorizer_refresh_token"`
	FuncInfo               []FuncInfo `json:"func_info"`
}

AuthorizationInfo 授权信息

type AuthorizedEvent

type AuthorizedEvent struct {
	AuthorizationEvent
}

AuthorizedEvent 授权成功事件 InfoType: authorized 当公众号/服务号/小程序/微信小店/带货助手/视频号助手对第三方平台进行授权时触发

type AuthorizerClient

type AuthorizerClient struct {
	// contains filtered or unexported fields
}

AuthorizerClient 授权方API客户端

func (*AuthorizerClient) CallAPI

func (c *AuthorizerClient) CallAPI(ctx context.Context, apiURL string, params interface{}) ([]byte, error)

CallAPI 代调用API(支持context)

func (*AuthorizerClient) CallAPIWithQuery

func (c *AuthorizerClient) CallAPIWithQuery(ctx context.Context, baseURL string, queryParams map[string]string, postData interface{}) ([]byte, error)

CallAPIWithQuery 支持查询参数的API调用

func (*AuthorizerClient) CallAPIWithRetry

func (c *AuthorizerClient) CallAPIWithRetry(ctx context.Context, apiURL string, params interface{}, maxRetries int) ([]byte, error)

CallAPIWithRetry 带重试的API调用

func (*AuthorizerClient) Create

Create 创建二维码

func (*AuthorizerClient) CreateConditionalMenu

func (c *AuthorizerClient) CreateConditionalMenu(ctx context.Context, menu *ConditionalMenu) error

CreateConditionalMenu 创建个性化菜单

func (*AuthorizerClient) CreateMenu

func (c *AuthorizerClient) CreateMenu(ctx context.Context, menu *Menu) error

CreateMenu 创建自定义菜单

func (*AuthorizerClient) DeleteConditionalMenu

func (c *AuthorizerClient) DeleteConditionalMenu(ctx context.Context, menuID string) error

DeleteConditionalMenu 删除个性化菜单

func (*AuthorizerClient) DeleteMenu

func (c *AuthorizerClient) DeleteMenu(ctx context.Context) error

DeleteMenu 删除自定义菜单

func (*AuthorizerClient) GetJSSDKManager

func (c *AuthorizerClient) GetJSSDKManager() *JSSDKManager

GetJSSDKManager 创建JS-SDK管理器

func (*AuthorizerClient) GetMedia

func (c *AuthorizerClient) GetMedia(ctx context.Context, mediaID string) ([]byte, error)

GetMedia 获取临时素材

func (*AuthorizerClient) GetMenu

func (c *AuthorizerClient) GetMenu(ctx context.Context) (*Menu, error)

GetMenu 获取菜单

func (*AuthorizerClient) GetMiniProgramClient

func (c *AuthorizerClient) GetMiniProgramClient() *MiniProgramClient

GetMiniProgramClient 创建小程序客户端

func (*AuthorizerClient) GetOAuthClient

func (c *AuthorizerClient) GetOAuthClient(redirectURI string) *OAuthClient

GetOAuthClient 创建OAuth客户端

func (*AuthorizerClient) GetQRCodeURL

func (c *AuthorizerClient) GetQRCodeURL(ticket string) (string, error)

GetQRCodeURL 获取二维码图片URL

func (*AuthorizerClient) GetUserInfo

func (c *AuthorizerClient) GetUserInfo(ctx context.Context, openID string) (*UserInfo, error)

GetUserInfo 获取用户信息

func (*AuthorizerClient) GetUserList

func (c *AuthorizerClient) GetUserList(ctx context.Context, nextOpenID string) (*UserList, error)

GetUserList 获取用户列表

func (*AuthorizerClient) SendCustomMessage

func (c *AuthorizerClient) SendCustomMessage(ctx context.Context, toUser string, message interface{}) error

SendCustomMessage 发送客服消息

func (*AuthorizerClient) SendImageMessage

func (c *AuthorizerClient) SendImageMessage(ctx context.Context, toUser, mediaID string) error

SendImageMessage 发送图片消息

func (*AuthorizerClient) SendNewsMessage

func (c *AuthorizerClient) SendNewsMessage(ctx context.Context, toUser string, articles []Article) error

SendNewsMessage 发送图文消息

func (*AuthorizerClient) SendTemplateMessage

SendTemplateMessage 发送模板消息

func (*AuthorizerClient) SendTextMessage

func (c *AuthorizerClient) SendTextMessage(ctx context.Context, toUser, content string) error

SendTextMessage 发送文本消息

func (*AuthorizerClient) UploadMedia

func (c *AuthorizerClient) UploadMedia(ctx context.Context, mediaType, filename string, data []byte) (*MediaResponse, error)

UploadMedia 上传临时素材

type AuthorizerInfo

type AuthorizerInfo struct {
	NickName        string           `json:"nick_name"`
	HeadImg         string           `json:"head_img"`
	ServiceTypeInfo ServiceTypeInfo  `json:"service_type_info"`
	VerifyTypeInfo  VerifyTypeInfo   `json:"verify_type_info"`
	UserName        string           `json:"user_name"`
	PrincipalName   string           `json:"principal_name"`
	BusinessInfo    BusinessInfo     `json:"business_info"`
	Alias           string           `json:"alias"`
	QrcodeURL       string           `json:"qrcode_url"`
	Signature       string           `json:"signature"`
	MiniProgramInfo *MiniProgramInfo `json:"MiniProgramInfo,omitempty"`
	RegisterType    int              `json:"register_type"`
	AccountStatus   int              `json:"account_status"`
	BasicConfig     *BasicConfigInfo `json:"basic_config,omitempty"`
	ChannelsInfo    *ChannelsInfo    `json:"channels_info,omitempty"`
}

AuthorizerInfo 授权方信息

type AuthorizerTokenRequest

type AuthorizerTokenRequest struct {
	ComponentAppID         string `json:"component_appid"`
	AuthorizerAppID        string `json:"authorizer_appid"`
	AuthorizerRefreshToken string `json:"authorizer_refresh_token"`
}

AuthorizerTokenRequest 刷新授权方token请求参数

type AuthorizerTokenResponse

type AuthorizerTokenResponse struct {
	core.APIResponse
	AuthorizerAccessToken  string `json:"authorizer_access_token"`
	ExpiresIn              int    `json:"expires_in"`
	AuthorizerRefreshToken string `json:"authorizer_refresh_token"`
}

AuthorizerTokenResponse 授权方token响应

type BasicConfigInfo

type BasicConfigInfo struct {
	IsPhoneConfigured bool `json:"is_phone_configured"`
	IsEmailConfigured bool `json:"is_email_configured"`
}

BasicConfigInfo 基础配置信息

type BusinessInfo

type BusinessInfo struct {
	OpenStore int `json:"open_store"`
	OpenScan  int `json:"open_scan"`
	OpenPay   int `json:"open_pay"`
	OpenCard  int `json:"open_card"`
	OpenShake int `json:"open_shake"`
}

BusinessInfo 商业功能开通情况

type Button

type Button struct {
	Type      string   `json:"type,omitempty"`
	Name      string   `json:"name"`
	Key       string   `json:"key,omitempty"`
	URL       string   `json:"url,omitempty"`
	SubButton []Button `json:"sub_button,omitempty"`
}

Button 菜单按钮

type CacheStats added in v0.0.5

type CacheStats struct {
	Hits       int64 // 缓存命中次数
	Misses     int64 // 缓存未命中次数
	Evictions  int64 // 缓存淘汰次数
	TotalItems int64 // 总缓存项数
}

CacheStats 缓存统计信息

type Category

type Category struct {
	First  string `json:"first"`
	Second string `json:"second"`
}

Category 小程序类目

type ChannelsInfo

type ChannelsInfo struct {
	ID int `json:"id"`
}

ChannelsInfo 视频号账号类型;如果该授权账号为视频号则返回该字段

type ClearComponentQuotaRequest

type ClearComponentQuotaRequest struct {
	ComponentAppID     string `json:"component_appid"`
	ComponentAppSecret string `json:"component_appsecret"`
}

ClearComponentQuotaRequest 使用AppSecret重置第三方平台API调用次数请求

type ClearQuotaRequest

type ClearQuotaRequest struct {
	ComponentAppID string `json:"component_appid"`
}

ClearQuotaRequest 重置API调用次数请求

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client API客户端

func NewClient

func NewClient(config *Config, opt ...any) (apiClient *Client)

NewClient 创建新的API客户端(使用默认文件存储) @param config *Config 开放平台配置信息 @param opt ...any 可选参数,支持以下类型:

  • debugger.LoggerInterface: 自定义日志器
  • HTTPClient: 自定义HTTP客户端
  • EventHandler: 自定义事件处理器

@return *Client API客户端实例

func NewClientWithStorage

func NewClientWithStorage(config *Config, storage storage.TokenStorage, opt ...any) *Client

NewClientWithStorage 创建新的API客户端(使用自定义存储)

func (*Client) AddToTemplate

func (c *Client) AddToTemplate(ctx context.Context, draftID int64, templateType int) (*core.APIResponse, error)

AddToTemplate 将草稿添加到模板库

func (*Client) ClearComponentQuota

func (c *Client) ClearComponentQuota(ctx context.Context) (*core.APIResponse, error)

ClearComponentQuota 使用AppSecret重置第三方平台API调用次数

func (*Client) ClearQuota

func (c *Client) ClearQuota(ctx context.Context) (*core.APIResponse, error)

ClearQuota 重置API调用次数

func (*Client) DecryptMessage

func (c *Client) DecryptMessage(encryptedMsg, msgSignature, timestamp, nonce string) ([]byte, error)

DecryptMessage 解密消息(用于处理加密的授权事件)

func (*Client) DeleteTemplate

func (c *Client) DeleteTemplate(ctx context.Context, templateID int64) (*core.APIResponse, error)

DeleteTemplate 删除代码模板

func (*Client) GenerateAuthURL

func (c *Client) GenerateAuthURL(preAuthCode string, authType int, bizAppID string, platform string) string

GenerateAuthURL 生成授权链接 authType: 授权类型 (1:手机端仅展示公众号, 2:仅展示小程序, 3:公众号和小程序都展示, 4:小程序推客账号, 5:视频号账号, 6:全部, 8:带货助手账号) platform: 平台类型 ("pc": PC端, "mobile": 移动端)

func (*Client) GenerateMobileAuthURL

func (c *Client) GenerateMobileAuthURL(preAuthCode string, authType int, bizAppID string) string

GenerateMobileAuthURL 生成移动端授权链接

func (*Client) GeneratePcAuthURL

func (c *Client) GeneratePcAuthURL(preAuthCode string, authType int, bizAppID string) string

GeneratePcAuthURL 生成PC端授权链接

func (*Client) GetAllAuthorizers

func (c *Client) GetAllAuthorizers(ctx context.Context) (allAuthorizers []struct {
	AuthorizerAppID string `json:"authorizer_appid"`
	RefreshToken    string `json:"refresh_token,omitempty"` // 虽然文档写了,但是实际上获取不到
	AuthTime        int64  `json:"auth_time"`
}, err error)

GetAllAuthorizers 获取所有授权方列表,自动处理分页 该方法会循环调用GetAuthorizerList,直到获取所有授权方数据 返回所有授权方信息的切片和可能的错误

func (*Client) GetApiQuota

func (c *Client) GetApiQuota(ctx context.Context, authorizerAppID string) (*GetApiQuotaResponse, error)

GetApiQuota 查询API调用额度

func (*Client) GetAuthorizerAccessToken

func (c *Client) GetAuthorizerAccessToken(ctx context.Context, authorizerAppID string) (string, error)

GetAuthorizerAccessToken 获取授权方access_token

func (*Client) GetAuthorizerInfo

func (c *Client) GetAuthorizerInfo(ctx context.Context, authorizerAppID string) (*GetAuthorizerInfoResponse, error)

GetAuthorizerInfo 获取授权方信息

func (*Client) GetAuthorizerList

func (c *Client) GetAuthorizerList(ctx context.Context, offset, count int) (*GetAuthorizerListResponse, error)

GetAuthorizerList 获取授权方列表

func (*Client) GetAuthorizerOption

func (c *Client) GetAuthorizerOption(ctx context.Context, authorizerAppID, optionName string) (*GetAuthorizerOptionResponse, error)

GetAuthorizerOption 获取授权方选项信息

func (*Client) GetComponentAccessToken

func (c *Client) GetComponentAccessToken(ctx context.Context, verifyTicket string) (*storage.ComponentAccessToken, error)

GetComponentAccessToken 获取第三方平台access_token

func (*Client) GetComponentToken

func (c *Client) GetComponentToken(ctx context.Context) (*storage.ComponentAccessToken, error)

GetComponentToken 获取开放平台令牌 @param ctx context.Context 上下文 @return *storage.ComponentAccessToken 组件访问令牌,包含令牌内容和有效期信息 @return error 错误信息,如果令牌获取失败或自动刷新失败则返回错误

func (*Client) GetComponentVerifyTicket

func (c *Client) GetComponentVerifyTicket(ctx context.Context) (*storage.ComponentVerifyTicket, error)

GetComponentVerifyTicket 获取验证票据 @param ctx context.Context 上下文 @return *storage.ComponentVerifyTicket 验证票据结构,包含票据内容和有效期信息 @return error 错误信息

func (*Client) GetConfig

func (c *Client) GetConfig() *Config

GetConfig 获取配置信息

func (*Client) GetEventHandler

func (c *Client) GetEventHandler() EventHandler

GetEventHandler 获取事件处理器

func (*Client) GetLogger

func (c *Client) GetLogger() logger.LoggerInterface

GetLogger 获取日志器

func (*Client) GetPreAuthCode

func (c *Client) GetPreAuthCode(ctx context.Context) (*storage.PreAuthCode, error)

GetPreAuthCode 获取预授权码

func (*Client) GetPreAuthCodeFromAPI

func (c *Client) GetPreAuthCodeFromAPI(ctx context.Context) (*PreAuthCodeResponse, error)

GetPreAuthCodeFromAPI 从微信API获取预授权码

func (*Client) GetRidInfo

func (c *Client) GetRidInfo(ctx context.Context, rid string) (*GetRidInfoResponse, error)

GetRidInfo 查询rid信息

func (*Client) GetTemplateDraftList

func (c *Client) GetTemplateDraftList(ctx context.Context) (*GetTemplateDraftListResponse, error)

GetTemplateDraftList 获取草稿箱列表

func (*Client) GetTemplateList

func (c *Client) GetTemplateList(ctx context.Context) (*GetTemplateListResponse, error)

GetTemplateList 获取模板列表

func (*Client) HandleAuthorizationEvent

func (c *Client) HandleAuthorizationEvent(ctx context.Context, xmlData []byte, msgSignature, timestamp, nonce, encryptType string) (string, error)

HandleAuthorizationEvent 处理微信开放平台授权事件 支持明文和加密两种消息格式 根据微信官方文档<mcreference link="https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/authorize_event.html" index="0">0</mcreference>, 接收POST请求后只需直接返回字符串"success"

func (*Client) QueryAuth

func (c *Client) QueryAuth(ctx context.Context, authorizationCode string) (*QueryAuthResponse, error)

QueryAuth 使用授权码换取授权信息

func (*Client) RefreshAuthorizerToken

func (c *Client) RefreshAuthorizerToken(ctx context.Context, authorizerAppID, refreshToken string) (*AuthorizationInfo, error)

RefreshAuthorizerToken 刷新授权方access_token

func (*Client) SaveComponentVerifyTicket

func (c *Client) SaveComponentVerifyTicket(ctx context.Context, ticket string) error

SaveComponentVerifyTicket 保存验证票据 @param ctx context.Context 上下文 @param ticket string 票据内容 @return error 错误信息

func (*Client) SetAuthorizerOption

func (c *Client) SetAuthorizerOption(ctx context.Context, authorizerAppID, optionName, optionValue string) (*core.APIResponse, error)

SetAuthorizerOption 设置授权方选项信息

func (*Client) SetAuthorizerToken

func (c *Client) SetAuthorizerToken(authorizerAppID, accessToken, refreshToken string, expiresIn int) error

SetAuthorizerToken 设置授权方token信息

func (*Client) SetComponentToken

func (c *Client) SetComponentToken(token *storage.ComponentAccessToken) error

SetComponentToken 设置开放平台令牌

func (*Client) SetEventHandler

func (c *Client) SetEventHandler(handler EventHandler)

SetEventHandler 设置事件处理器

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(client core.HTTPClient)

SetHTTPClient 设置自定义HTTP客户端

func (*Client) SetLogger

func (c *Client) SetLogger(log any)

SetLogger 设置日志器

func (*Client) SetPreAuthCode

func (c *Client) SetPreAuthCode(ctx context.Context, preAuthCode *storage.PreAuthCode) error

SetPreAuthCode 设置预授权码

type ComponentTokenRequest

type ComponentTokenRequest struct {
	ComponentAppID        string `json:"component_appid"`
	ComponentAppSecret    string `json:"component_appsecret"`
	ComponentVerifyTicket string `json:"component_verify_ticket"`
}

ComponentTokenRequest 获取component_access_token请求参数

type ComponentVerifyTicketEvent

type ComponentVerifyTicketEvent struct {
	AuthorizationEvent
	ComponentVerifyTicket string `xml:"ComponentVerifyTicket" json:"component_verify_ticket"`
}

ComponentVerifyTicketEvent 验证票据推送事件 InfoType: component_verify_ticket 微信服务器每隔10分钟推送component_verify_ticket到第三方平台的消息接收URL 根据微信官方文档<mcreference link="https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/component_verify_ticket.html" index="0">0</mcreference>, 接收POST请求后只需直接返回字符串"success"

type ConditionalMenu

type ConditionalMenu struct {
	Button    []Button `json:"button"`
	MatchRule struct {
		TagID              string `json:"tag_id,omitempty"`
		Sex                string `json:"sex,omitempty"`
		Country            string `json:"country,omitempty"`
		Province           string `json:"province,omitempty"`
		City               string `json:"city,omitempty"`
		ClientPlatformType string `json:"client_platform_type,omitempty"`
		Language           string `json:"language,omitempty"`
	} `json:"matchrule"`
}

ConditionalMenu 个性化菜单

type Config

type Config struct {
	ComponentAppID     string `json:"component_appid" ini:"component_appid"`         // 第三方平台appid
	ComponentAppSecret string `json:"component_appsecret" ini:"component_appsecret"` // 第三方平台appsecret
	ComponentToken     string `json:"component_token" ini:"component_token"`         // 消息校验Token
	EncodingAESKey     string `json:"encoding_aes_key" ini:"encoding_aes_key"`       // 消息加解密Key
	RedirectURI        string `json:"redirect_uri" ini:"redirect_uri"`               // 授权回调URI
}

Config 微信开放平台配置结构体

func (*Config) Validate

func (c *Config) Validate() error

Validate 验证配置的有效性

type ConfirmInfo

type ConfirmInfo struct {
	NeedConfirm    int `json:"need_confirm"`
	AlreadyConfirm int `json:"already_confirm"`
	CanConfirm     int `json:"can_confirm"`
}

type DefaultEventHandler

type DefaultEventHandler struct{}

DefaultEventHandler 默认事件处理器

func (*DefaultEventHandler) HandleAuthorized

func (h *DefaultEventHandler) HandleAuthorized(ctx context.Context, event *AuthorizedEvent) error

func (*DefaultEventHandler) HandleComponentVerifyTicket

func (h *DefaultEventHandler) HandleComponentVerifyTicket(ctx context.Context, event *ComponentVerifyTicketEvent) error

func (*DefaultEventHandler) HandleEncodingAESKeyChanged

func (h *DefaultEventHandler) HandleEncodingAESKeyChanged(ctx context.Context, event *EncodingAESKeyChangedEvent) error

func (*DefaultEventHandler) HandleUnauthorized

func (h *DefaultEventHandler) HandleUnauthorized(ctx context.Context, event *UnauthorizedEvent) error

func (*DefaultEventHandler) HandleUpdateAuthorized

func (h *DefaultEventHandler) HandleUpdateAuthorized(ctx context.Context, event *UpdateAuthorizedEvent) error

type DeleteTemplateRequest

type DeleteTemplateRequest struct {
	TemplateID int64 `json:"template_id"`
}

DeleteTemplateRequest 删除代码模板请求

type EncodingAESKeyChangedEvent

type EncodingAESKeyChangedEvent struct {
	AuthorizationEvent
	NewEncodingAESKey string `xml:"NewEncodingAESKey" json:"new_encoding_aes_key"`
}

EncodingAESKeyChangedEvent EncodingAESKey变更事件 InfoType: encoding_aes_key_changed 当第三方平台在微信开放平台后台修改EncodingAESKey时,微信服务器会推送此事件 根据微信官方规范<mcreference link="https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/Message_encryption_and_decryption.html" index="1">1</mcreference>, 需要保存上一次的EncodingAESKey以确保平滑过渡

type EventHandler

type EventHandler interface {
	// HandleAuthorized 处理授权成功事件
	HandleAuthorized(ctx context.Context, event *AuthorizedEvent) error

	// HandleUnauthorized 处理取消授权事件
	HandleUnauthorized(ctx context.Context, event *UnauthorizedEvent) error

	// HandleUpdateAuthorized 处理授权更新事件
	HandleUpdateAuthorized(ctx context.Context, event *UpdateAuthorizedEvent) error

	// HandleComponentVerifyTicket 处理验证票据推送事件
	// 根据微信官方文档<mcreference link="https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/component_verify_ticket.html" index="0">0</mcreference>,
	// 接收POST请求后只需直接返回字符串"success"
	HandleComponentVerifyTicket(ctx context.Context, event *ComponentVerifyTicketEvent) error

	// HandleEncodingAESKeyChanged 处理EncodingAESKey变更事件
	// 当第三方平台在微信开放平台后台修改EncodingAESKey时,微信服务器会推送此事件
	// 根据微信官方规范<mcreference link="https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/Message_encryption_and_decryption.html" index="1">1</mcreference>,
	// 需要保存上一次的EncodingAESKey以确保平滑过渡
	HandleEncodingAESKeyChanged(ctx context.Context, event *EncodingAESKeyChangedEvent) error
}

EventHandler 事件处理器接口

type FuncInfo

type FuncInfo struct {
	FuncScopeCategory FuncScopeCategory `json:"funcscope_category"`
	ConfirmInfo       ConfirmInfo       `json:"confirm_info,omitempty"`
}

type FuncScopeCategory

type FuncScopeCategory struct {
	Id int `json:"id"`
}

FuncScopeCategory 授权给开发者的权限集

type GetApiQuotaRequest

type GetApiQuotaRequest struct {
	ComponentAppID  string `json:"component_appid"`
	AuthorizerAppID string `json:"authorizer_appid"`
}

GetApiQuotaRequest 查询API调用额度请求

type GetApiQuotaResponse

type GetApiQuotaResponse struct {
	core.APIResponse
	Quota []QuotaItem `json:"quota"`
}

GetApiQuotaResponse 查询API调用额度响应

type GetAuthorizerInfoRequest

type GetAuthorizerInfoRequest struct {
	ComponentAppID  string `json:"component_appid"`
	AuthorizerAppID string `json:"authorizer_appid"`
}

GetAuthorizerInfoRequest 获取授权方信息请求参数

type GetAuthorizerInfoResponse

type GetAuthorizerInfoResponse struct {
	core.APIResponse
	AuthorizerInfo AuthorizerInfo `json:"authorizer_info"`
}

GetAuthorizerInfoResponse 授权方信息响应

type GetAuthorizerListRequest

type GetAuthorizerListRequest struct {
	ComponentAppID string `json:"component_appid"`
	Offset         int    `json:"offset"`
	Count          int    `json:"count"`
}

GetAuthorizerListRequest 获取授权方列表请求参数

type GetAuthorizerListResponse

type GetAuthorizerListResponse struct {
	core.APIResponse
	TotalCount int `json:"total_count"`
	List       []struct {
		AuthorizerAppID string `json:"authorizer_appid"`
		RefreshToken    string `json:"refresh_token,omitempty"` // 虽然文档写了,但是实际上获取不到
		AuthTime        int64  `json:"auth_time"`
	} `json:"list"`
}

GetAuthorizerListResponse 获取授权方列表响应

type GetAuthorizerOptionRequest

type GetAuthorizerOptionRequest struct {
	ComponentAppID  string `json:"component_appid"`
	AuthorizerAppID string `json:"authorizer_appid"`
	OptionName      string `json:"option_name"`
}

GetAuthorizerOptionRequest 获取授权方选项信息请求

type GetAuthorizerOptionResponse

type GetAuthorizerOptionResponse struct {
	core.APIResponse
	AuthorizerAppID string `json:"authorizer_appid"`
	OptionName      string `json:"option_name"`
	OptionValue     string `json:"option_value"`
}

GetAuthorizerOptionResponse 获取授权方选项信息响应

type GetRidInfoRequest

type GetRidInfoRequest struct {
	RID string `json:"rid"`
}

GetRidInfoRequest 查询rid信息请求

type GetRidInfoResponse

type GetRidInfoResponse struct {
	core.APIResponse
	RidInfo RidInfo `json:"rid_info"`
}

GetRidInfoResponse 查询rid信息响应

type GetTemplateDraftListResponse

type GetTemplateDraftListResponse struct {
	core.APIResponse
	DraftList []TemplateDraft `json:"draft_list"`
}

GetTemplateDraftListResponse 获取草稿箱列表响应

type GetTemplateListResponse

type GetTemplateListResponse struct {
	core.APIResponse
	TemplateList []Template `json:"template_list"`
}

GetTemplateListResponse 获取模板列表响应

type ImageMessage

type ImageMessage struct {
	MediaID string `json:"media_id"`
}

ImageMessage 图片消息

type JSSDKCacher

type JSSDKCacher struct {
	// contains filtered or unexported fields
}

JSSDKCacher JS-SDK配置缓存器

func (*JSSDKCacher) CacheConfig

func (c *JSSDKCacher) CacheConfig(url string, jsAPIList []string, config *JSSDKConfig)

CacheConfig 缓存JS-SDK配置 - 带统计功能

func (*JSSDKCacher) CleanupExpired added in v0.0.5

func (c *JSSDKCacher) CleanupExpired()

CleanupExpired 清理过期缓存

func (*JSSDKCacher) GetCachedConfig

func (c *JSSDKCacher) GetCachedConfig(url string, jsAPIList []string) (*JSSDKConfig, error)

GetCachedConfig 获取缓存的JS-SDK配置 - 带统计功能

func (*JSSDKCacher) GetStats added in v0.0.5

func (c *JSSDKCacher) GetStats() CacheStats

GetStats 获取缓存统计信息

type JSSDKConfig

type JSSDKConfig struct {
	AppID     string   `json:"appId" ini:"app_id"`          // 公众号appid
	Timestamp int64    `json:"timestamp" ini:"timestamp"`   // 时间戳
	NonceStr  string   `json:"nonceStr" ini:"nonce_str"`    // 随机字符串
	Signature string   `json:"signature" ini:"signature"`   // 签名
	JSAPIList []string `json:"jsApiList" ini:"js_api_list"` // JS-SDK调用权限列表
}

JSSDKConfig JS-SDK配置结构

type JSSDKManager

type JSSDKManager struct {
	// contains filtered or unexported fields
}

JSSDKManager JS-SDK管理器

func (*JSSDKManager) GetConfig

func (jm *JSSDKManager) GetConfig(ctx context.Context, url string, jsAPIList []string) (*JSSDKConfig, error)

GetConfig 生成JS-SDK配置

func (*JSSDKManager) GetConfigOptimized

func (jm *JSSDKManager) GetConfigOptimized(ctx context.Context, url string, jsAPIList []string) (*JSSDKConfig, error)

GetConfigOptimized 优化后的JS-SDK配置获取

func (*JSSDKManager) GetConfigWithRetry

func (jm *JSSDKManager) GetConfigWithRetry(ctx context.Context, url string, jsAPIList []string, maxRetries int) (*JSSDKConfig, error)

GetConfigWithRetry 带重试的JS-SDK配置获取

type MediaResponse

type MediaResponse struct {
	core.APIResponse
	Type      string `json:"type"`
	MediaID   string `json:"media_id"`
	CreatedAt int64  `json:"created_at"`
}

MediaResponse 媒体文件响应

type Menu struct {
	Button []Button `json:"button"`
}

Menu 菜单结构

type MiniProgramClient

type MiniProgramClient struct {
	// contains filtered or unexported fields
}

MiniProgramClient 小程序客户端

func (*MiniProgramClient) GetWXACode

func (mpc *MiniProgramClient) GetWXACode(ctx context.Context, request *WXACodeRequest) (*WXACodeResponse, error)

GetWXACode 获取小程序码

type MiniProgramInfo

type MiniProgramInfo struct {
	Network     NetworkInfo `json:"network"`
	Categories  []Category  `json:"categories"`
	VisitStatus int         `json:"visit_status"`
}

MiniProgramInfo 小程序信息

type MusicMessage

type MusicMessage struct {
	Title        string `json:"title"`
	Description  string `json:"description"`
	MusicURL     string `json:"musicurl"`
	HQMusicURL   string `json:"hqmusicurl"`
	ThumbMediaID string `json:"thumb_media_id"`
}

MusicMessage 音乐消息

type NetworkInfo

type NetworkInfo struct {
	RequestDomain   []string `json:"RequestDomain"`
	WsRequestDomain []string `json:"WsRequestDomain"`
	UploadDomain    []string `json:"UploadDomain"`
	DownloadDomain  []string `json:"DownloadDomain"`
	BizDomain       []string `json:"BizDomain"`
	UDPDomain       []string `json:"UDPDomain"`
}

NetworkInfo 网络信息

type NewsMessage

type NewsMessage struct {
	Articles []Article `json:"articles"`
}

NewsMessage 图文消息

type OAuthClient

type OAuthClient struct {
	// contains filtered or unexported fields
}

OAuthClient 网页授权客户端

func (*OAuthClient) GetAccessToken

func (oc *OAuthClient) GetAccessToken(ctx context.Context, code string) (*OAuthToken, error)

GetAccessToken 使用授权码获取AccessToken

func (*OAuthClient) GetAuthorizeURL

func (oc *OAuthClient) GetAuthorizeURL(opts ...string) string

GetAuthorizeURL 生成授权页面URL

  • opts -- scope:授权类型,snsapi_base 静默授权,snsapi_userinfo 授权并获取用户信息 -- state:用于保持请求和回调的状态,授权请求后原样带回给第三方。 -- forcePopup 强制此次授权需要用户弹窗确认;默认为false;需要注意的是,若用户命中了特殊场景下的静默授权逻辑,则此参数不生效

func (*OAuthClient) GetBaseAuthorizeURL

func (oc *OAuthClient) GetBaseAuthorizeURL(state string) string

GetBaseAuthorizeURL 生成静默授权URL

func (*OAuthClient) GetUserInfo

func (oc *OAuthClient) GetUserInfo(ctx context.Context, accessToken, openID string) (*official_account.OAuthUserInfoResponse, error)

GetUserInfo 获取用户信息

func (*OAuthClient) GetUserInfoAuthorizeURL

func (oc *OAuthClient) GetUserInfoAuthorizeURL(state string) string

GetUserInfoAuthorizeURL 生成用户信息授权URL

func (*OAuthClient) RefreshToken

func (oc *OAuthClient) RefreshToken(ctx context.Context, refreshToken string) (*OAuthToken, error)

RefreshToken 刷新AccessToken

type OAuthComponentAccessTokenRequest

type OAuthComponentAccessTokenRequest struct {
	ComponentAppID       string `json:"component_appid"`        // 第三方平台appid
	ComponentAppSecret   string `json:"component_appsecret"`    // 第三方平台appsecret
	AppID                string `json:"appid"`                  // 授权公众号appid
	Code                 string `json:"code"`                   // 填写第一步获取的code参数
	GrantType            string `json:"grant_type"`             // 填写为authorization_code
	ComponentAccessToken string `json:"component_access_token"` // 第三方平台component_access_token
}

OAuthComponentAccessTokenRequest 第三方平台代公众号获取网页授权access_token请求参数

type OAuthComponentRefreshTokenRequest

type OAuthComponentRefreshTokenRequest struct {
	ComponentAppID       string `json:"component_appid"`        // 第三方平台appid
	AppID                string `json:"appid"`                  // 授权公众号appid
	RefreshToken         string `json:"refresh_token"`          // 填写通过access_token获取到的refresh_token参数
	GrantType            string `json:"grant_type"`             // 填写为refresh_token
	ComponentAccessToken string `json:"component_access_token"` // 第三方平台component_access_token
}

OAuthComponentRefreshTokenRequest 第三方平台代公众号刷新网页授权access_token请求参数

type OAuthToken

type OAuthToken struct {
	core.APIResponse
	AccessToken  string `json:"access_token"`
	ExpiresIn    int64  `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	OpenID       string `json:"openid"`
	Scope        string `json:"scope"`
}

OAuthToken 网页授权Token

type PreAuthCodeRequest

type PreAuthCodeRequest struct {
	ComponentAppID string `json:"component_appid"`
}

PreAuthCodeRequest 获取预授权码请求参数

type PreAuthCodeResponse

type PreAuthCodeResponse struct {
	core.APIResponse
	PreAuthCode string `json:"pre_auth_code"`
	ExpiresIn   int    `json:"expires_in"`
}

PreAuthCodeResponse 预授权码响应

type QueryAuthRequest

type QueryAuthRequest struct {
	ComponentAppID    string `json:"component_appid"`
	AuthorizationCode string `json:"authorization_code"`
}

QueryAuthRequest 使用授权码换取授权信息请求参数

type QueryAuthResponse

type QueryAuthResponse struct {
	core.APIResponse
	AuthorizationInfo AuthorizationInfo `json:"authorization_info"`
}

QueryAuthResponse 授权信息响应

type QuotaItem

type QuotaItem struct {
	API            string `json:"api"`
	DailyQuota     int    `json:"daily_quota"`
	DailyUsed      int    `json:"daily_used"`
	DailyRemaining int    `json:"daily_remaining"`
}

QuotaItem API调用额度项

type RidInfo

type RidInfo struct {
	Request struct {
		InvokeTime  string `json:"invoke_time"`
		CostInMs    int    `json:"cost_in_ms"`
		RequestURL  string `json:"request_url"`
		RequestBody string `json:"request_body"`
		Response    string `json:"response"`
		ClientIP    string `json:"client_ip"`
	} `json:"request"`
}

RidInfo rid信息

type ServiceTypeInfo

type ServiceTypeInfo struct {
	ID int `json:"id"`
}

ServiceTypeInfo 账号类型

type SetAuthorizerOptionRequest

type SetAuthorizerOptionRequest struct {
	ComponentAppID  string `json:"component_appid"`
	AuthorizerAppID string `json:"authorizer_appid"`
	OptionName      string `json:"option_name"`
	OptionValue     string `json:"option_value"`
}

SetAuthorizerOptionRequest 设置授权方选项信息请求

type Template

type Template struct {
	CreateTime  int64  `json:"create_time"`
	UserVersion string `json:"user_version"`
	UserDesc    string `json:"user_desc"`
	TemplateID  int64  `json:"template_id"`
}

Template 模板库模板

type TemplateDraft

type TemplateDraft struct {
	CreateTime  int64  `json:"create_time"`
	UserVersion string `json:"user_version"`
	UserDesc    string `json:"user_desc"`
	DraftID     int64  `json:"draft_id"`
}

TemplateDraft 草稿箱模板

type TextMessage

type TextMessage struct {
	Content string `json:"content"`
}

TextMessage 文本消息

type UnauthorizedEvent

type UnauthorizedEvent struct {
	AuthorizationEvent
}

UnauthorizedEvent 取消授权事件 InfoType: unauthorized 当公众号/服务号/小程序/微信小店/带货助手/视频号助手取消对第三方平台的授权时触发

type UpdateAuthorizedEvent

type UpdateAuthorizedEvent struct {
	AuthorizationEvent
}

UpdateAuthorizedEvent 授权更新事件 InfoType: updateauthorized 当授权方更新授权时触发。如果更新授权时,授权的权限集没有发生变化,将不会触发授权更新通知

type UserInfo

type UserInfo struct {
	core.APIResponse
	Subscribe      int    `json:"subscribe"`
	OpenID         string `json:"openid"`
	Nickname       string `json:"nickname"`
	Sex            int    `json:"sex"`
	Language       string `json:"language"`
	City           string `json:"city"`
	Province       string `json:"province"`
	Country        string `json:"country"`
	HeadImgURL     string `json:"headimgurl"`
	SubscribeTime  int64  `json:"subscribe_time"`
	UnionID        string `json:"unionid,omitempty"`
	Remark         string `json:"remark"`
	GroupID        int    `json:"groupid"`
	TagIDList      []int  `json:"tagid_list"`
	SubscribeScene string `json:"subscribe_scene"`
	QRScene        int    `json:"qr_scene"`
	QRSceneStr     string `json:"qr_scene_str"`
}

UserInfo 用户信息

type UserList

type UserList struct {
	core.APIResponse
	Total int `json:"total"`
	Count int `json:"count"`
	Data  struct {
		OpenID []string `json:"openid"`
	} `json:"data"`
	NextOpenID string `json:"next_openid"`
}

UserList 用户列表

type VerifyTypeInfo

type VerifyTypeInfo struct {
	ID int `json:"id"`
}

VerifyTypeInfo 认证类型

type VideoMessage

type VideoMessage struct {
	MediaID     string `json:"media_id"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
}

VideoMessage 视频消息

type VoiceMessage

type VoiceMessage struct {
	MediaID string `json:"media_id"`
}

VoiceMessage 语音消息

type WXACodeRequest

type WXACodeRequest struct {
	Path  string `json:"path"`
	Width int    `json:"width,omitempty"`
}

WXACodeRequest 小程序码请求

type WXACodeResponse

type WXACodeResponse struct {
	core.APIResponse
	ContentType string `json:"contentType"`
	Buffer      []byte `json:"buffer"`
}

WXACodeResponse 小程序码响应

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL