miniprogram

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2025 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Code2SessionURL code2session 接口地址
	Code2SessionPath = "/sns/jscode2session"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AccessToken

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

AccessToken 小程序 AccessToken 管理

func NewAccessToken

func NewAccessToken(appID, appSecret string, cache core.Cache, httpClient *http.Client, logger *slog.Logger) *AccessToken

NewAccessToken 创建 AccessToken 实例

func (*AccessToken) GetToken

func (at *AccessToken) GetToken(ctx context.Context) (string, error)

GetToken 获取 AccessToken(优先从缓存获取)

func (*AccessToken) RefreshToken

func (at *AccessToken) RefreshToken(ctx context.Context) (string, error)

RefreshToken 强制刷新 AccessToken

type Code2SessionRequest added in v1.1.0

type Code2SessionRequest struct {
	// JSCode 登录时获取的 code,可通过 wx.login 获取
	JSCode string
}

Code2SessionRequest code2session 请求参数

type Code2SessionResponse added in v1.1.0

type Code2SessionResponse struct {
	// OpenID 用户唯一标识
	OpenID string `json:"openid"`
	// SessionKey 会话密钥
	SessionKey string `json:"session_key"`
	// UnionID 用户在开放平台的唯一标识符
	// 若当前小程序已绑定到微信开放平台帐号下会返回
	UnionID string `json:"unionid,omitempty"`
}

Code2SessionResponse code2session 响应结果

type Config

type Config struct {
	// AppID 小程序 AppID(必填)
	AppID string
	// AppSecret 小程序 AppSecret(必填)
	AppSecret string
	// Cache 缓存实现(可选,默认使用内存缓存)
	Cache core.Cache
	// HTTPClient 自定义 HTTP 客户端(可选)
	HTTPClient *http.Client
	// Logger 日志记录器(可选,默认使用 slog.Default())
	Logger *slog.Logger
}

Config 小程序配置

type GetPhoneNumberRequest added in v1.2.0

type GetPhoneNumberRequest struct {
	// code 是通过 wx.getPhoneNumber 获取到的用户手机号对应的 code
	Code string `json:"code"`
}

type GetPhoneNumberResponse added in v1.2.0

type GetPhoneNumberResponse struct {
	// PhoneInfo 用户手机号信息
	PhoneInfo PhoneInfo `json:"phone_info"`
}

GetPhoneNumberResponse 获取用户手机号响应结果

type MiniProgram

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

MiniProgram 小程序实例

func New

func New(cfg *Config) *MiniProgram

New 创建小程序实例

func (*MiniProgram) Code2Session added in v1.1.0

func (mp *MiniProgram) Code2Session(ctx context.Context, req *Code2SessionRequest) (*Code2SessionResponse, error)

Code2Session 通过登录凭证 code 获取 session_key 和 openid 接口文档: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html

参数:

  • ctx: 上下文
  • req: 请求参数,包含 JSCode

返回:

  • *Code2SessionResponse: 响应结果,包含 openid, session_key, unionid 等
  • error: 可能的错误

错误:

  • 40029: code 无效(js_code 无效)
  • 45011: API 调用太频繁,请稍候再试
  • 40226: code 被封禁(高风险等级用户,小程序登录拦截)
  • -1: 系统繁忙,此时请开发者稍候再试

示例:

resp, err := mp.Code2Session(ctx, &miniprogram.Code2SessionRequest{
    JSCode: "081aBZ000X0pJt1WjY200zWDKK1aBZ0J",
})
if err != nil {
    // 处理错误(包括微信 API 错误)
    return err
}
fmt.Println("OpenID:", resp.OpenID)
fmt.Println("SessionKey:", resp.SessionKey)

func (*MiniProgram) Get added in v1.1.0

func (mp *MiniProgram) Get(ctx context.Context, path string, query map[string]string, result any) error

Get 发送 GET 请求并解析响应到 result(带 access_token) 用于调用 SDK 尚未封装的新 API

参数:

  • ctx: 上下文
  • path: 请求路径,如 "/cgi-bin/user/info"
  • query: 查询参数
  • result: 结果指针,响应将解析到此变量

示例:

var userInfo UserInfo
err := mp.Get(ctx, "/cgi-bin/user/info", map[string]string{
    "openid": "xxx",
}, &userInfo)

func (*MiniProgram) GetAccessToken

func (mp *MiniProgram) GetAccessToken() *AccessToken

GetAccessToken 获取 AccessToken 管理器 用于手动管理 token(如强制刷新)

func (*MiniProgram) GetClient

func (mp *MiniProgram) GetClient() *core.Client

GetClient 获取 HTTP 客户端 用于调用任意微信 API

func (*MiniProgram) GetConfig

func (mp *MiniProgram) GetConfig() *Config

GetConfig 获取配置

func (*MiniProgram) GetPhoneNumber added in v1.2.0

GetPhoneNumber 该接口用于将code换取用户手机号。 说明,每个code只能使用一次,code的有效期为5min。 接口文档: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html

参数:

  • ctx: 上下文
  • GetPhoneNumberRequest : 请求参数

返回:

  • *GetPhoneNumberResponse: 响应结果
  • error: 可能的错误

func (*MiniProgram) GetRaw added in v1.1.0

func (mp *MiniProgram) GetRaw(ctx context.Context, path string, query map[string]string, withToken bool) ([]byte, error)

GetRaw 获取原始响应(高级用法,用于特殊场景) 返回原始字节数据,由调用方自行处理

func (*MiniProgram) GetWithoutToken added in v1.1.0

func (mp *MiniProgram) GetWithoutToken(ctx context.Context, path string, query map[string]string, result any) error

GetWithoutToken 发送 GET 请求(不带 access_token)并解析响应到 result

func (*MiniProgram) Post added in v1.1.0

func (mp *MiniProgram) Post(ctx context.Context, path string, reqBody any, result any) error

Post 发送 POST 请求并解析响应到 result(带 access_token) 用于调用 SDK 尚未封装的新 API

参数:

  • ctx: 上下文
  • path: 请求路径,如 "/cgi-bin/message/custom/send"
  • reqBody: 请求体
  • result: 结果指针,响应将解析到此变量

示例:

var result SendMessageResult
err := mp.Post(ctx, "/cgi-bin/message/send", map[string]any{
    "touser":  "openid",
    "msgtype": "text",
    "text": map[string]string{"content": "Hello"},
}, &result)

func (*MiniProgram) PostRaw added in v1.1.0

func (mp *MiniProgram) PostRaw(ctx context.Context, path string, body any, withToken bool) ([]byte, error)

PostRaw 发送 POST 请求获取原始响应(高级用法)

func (*MiniProgram) PostWithQuery added in v1.1.0

func (mp *MiniProgram) PostWithQuery(ctx context.Context, path string, query map[string]string, reqBody any, result any) error

PostWithQuery 发送带查询参数的 POST 请求(带 access_token)并解析响应到 result

type PhoneInfo added in v1.2.0

type PhoneInfo struct {
	// PhoneNumber 用户手机号
	PhoneNumber string `json:"phoneNumber"`
	// PurePhoneNumber 没有区号的手机号
	PurePhoneNumber string `json:"purePhoneNumber"`
	//CountryCode 区号
	CountryCode int `json:"countryCode"`
	// Watermark 水印
	Watermark Watermark `json:"watermark"`
}

type Response

type Response[T any] struct {
	Body []byte
	Data T
	// contains filtered or unexported fields
}

Response 小程序 API 响应封装

func NewResponse

func NewResponse[T any](body []byte) *Response[T]

NewResponse 创建响应实例

func (*Response[T]) Decode added in v1.1.0

func (r *Response[T]) Decode() (T, error)

Decode 一次性完成: 1. 先探测 errcode/errmsg 2. 再解析到业务模型 T

func (*Response[T]) DecodeInto added in v1.1.0

func (r *Response[T]) DecodeInto(v any) error

DecodeInto 解析响应到指定的变量(用于非泛型场景) 先检查微信错误,再解析到目标变量

示例:

var userInfo UserInfo
resp := NewResponse[any](body)
err := resp.DecodeInto(&userInfo)

func (*Response[T]) Error

func (r *Response[T]) Error() error

Error 检查响应是否包含微信错误 如果响应不是有效 JSON,返回 ResponseParseError 如果 errcode != 0,返回 WechatError

func (*Response[T]) IsSuccess

func (r *Response[T]) IsSuccess() bool

IsSuccess 判断响应是否成功

func (*Response[T]) Map

func (r *Response[T]) Map() (map[string]any, error)

Map 解析响应为 map

func (*Response[T]) String

func (r *Response[T]) String() string

String 返回响应字符串

type Watermark added in v1.2.0

type Watermark struct {
	// AppID 小程序 AppID
	AppID string `json:"appid"`
	// Timestamp 获取手机号操作的时间戳
	Timestamp int64 `json:"timestamp"`
}

Jump to

Keyboard shortcuts

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