Documentation
¶
Index ¶
- Constants
- Variables
- func EncryptSensitiveWithPublicKey(pubKey *rsa.PublicKey, plaintext string) (string, error)
- func IsAPIError(err error) bool
- type APIError
- type APIErrorDetail
- type Amount
- type AppPayParams
- type AppRequest
- type BillRequest
- type BillResponse
- type CertificateItem
- type CertificatesResponse
- type Client
- func NewClient(config *Config, opts ...any) *Clientdeprecated
- func NewClientE(config *Config, opts ...any) (*Client, error)
- func NewClientWithStorage(config *Config, storage storage.TokenStorage, opts ...any) *Clientdeprecated
- func NewClientWithStorageE(config *Config, storage storage.TokenStorage, opts ...any) (*Client, error)
- func (c *Client) AppPay(ctx context.Context, req *AppRequest) (*PrepayResponse, error)
- func (c *Client) ApplyFundFlowBill(ctx context.Context, req *BillRequest) (*BillResponse, error)
- func (c *Client) ApplyTradeBill(ctx context.Context, req *BillRequest) (*BillResponse, error)
- func (c *Client) BuildAppPayParams(prepayID string) (*AppPayParams, error)
- func (c *Client) BuildJSAPIPayParams(prepayID string) (*JSAPIPayParams, error)
- func (c *Client) CloseOrder(ctx context.Context, outTradeNo string) error
- func (c *Client) DecryptNotificationResource(resource *Resource) ([]byte, error)
- func (c *Client) DownloadBill(ctx context.Context, downloadURL, hashValue string) ([]byte, error)
- func (c *Client) EncryptSensitiveData(ctx context.Context, plaintext string) (string, error)
- func (c *Client) EncryptSerialNo(ctx context.Context) (string, error)
- func (c *Client) GetConfig() *Config
- func (c *Client) GetLogger() logger.LoggerInterface
- func (c *Client) H5Pay(ctx context.Context, req *H5Request) (*H5Response, error)
- func (c *Client) JSAPIPay(ctx context.Context, req *JSAPIRequest) (*PrepayResponse, error)
- func (c *Client) NativePay(ctx context.Context, req *NativeRequest) (*NativeResponse, error)
- func (c *Client) ProfitSharing(ctx context.Context, req *ProfitSharingRequest) (*ProfitSharingResponse, error)
- func (c *Client) ProfitSharingAmounts(ctx context.Context, transactionID string) (*ProfitSharingAmountsResponse, error)
- func (c *Client) ProfitSharingQuery(ctx context.Context, outOrderNo, transactionID string) (*ProfitSharingResponse, error)
- func (c *Client) ProfitSharingReturn(ctx context.Context, req *ProfitSharingReturnRequest) (*ProfitSharingReturnResponse, error)
- func (c *Client) ProfitSharingReturnQuery(ctx context.Context, outReturnNo, outOrderNo string) (*ProfitSharingReturnResponse, error)
- func (c *Client) ProfitSharingUnfreeze(ctx context.Context, req *ProfitSharingUnfreezeRequest) (*ProfitSharingResponse, error)
- func (c *Client) QueryOrder(ctx context.Context, outTradeNo string) (*Order, error)
- func (c *Client) QueryOrderByTransactionID(ctx context.Context, transactionID string) (*Order, error)
- func (c *Client) Refund(ctx context.Context, req *RefundRequest) (*RefundResponse, error)
- func (c *Client) RefundQuery(ctx context.Context, outRefundNo string) (*RefundResponse, error)
- func (c *Client) SetHTTPClient(client core.HTTPClient)
- func (c *Client) SetLogger(log debugger.LoggerInterface)
- func (c *Client) VerifyNotification(ctx context.Context, header http.Header, body []byte) (*Notification, []byte, error)
- func (c *Client) VerifyNotificationByHeaders(ctx context.Context, headers *NotificationHeaders, body []byte) (*Notification, []byte, error)
- type CloseOrderRequest
- type Config
- type EncryptCertificate
- type H5Info
- type H5Request
- type H5Response
- type JSAPIPayParams
- type JSAPIRequest
- type NativeRequest
- type NativeResponse
- type Notification
- type NotificationHeaders
- type Order
- type Payer
- type PrepayResponse
- type ProfitSharingAmountsResponse
- type ProfitSharingReceiver
- type ProfitSharingReceiverResult
- type ProfitSharingRequest
- type ProfitSharingResponse
- type ProfitSharingReturnRequest
- type ProfitSharingReturnResponse
- type ProfitSharingUnfreezeRequest
- type RefundAmount
- type RefundRequest
- type RefundResponse
- type Resource
- type SceneInfo
Constants ¶
const ( // PayJSAPIURL JSAPI 统一下单地址 PayJSAPIURL = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi" // PayH5URL H5 支付地址 PayH5URL = "https://api.mch.weixin.qq.com/v3/pay/transactions/h5" // PayNativeURL Native 支付下单地址 PayNativeURL = "https://api.mch.weixin.qq.com/v3/pay/transactions/native" // PayAppURL App 支付下单地址 PayAppURL = "https://api.mch.weixin.qq.com/v3/pay/transactions/app" // PayQueryOrderURL 按商户订单号查询订单地址(需格式化 out_trade_no) PayQueryOrderURL = "https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/%s" // PayQueryOrderByTransactionIDURL 按微信支付订单号查询订单地址(需格式化 transaction_id) PayQueryOrderByTransactionIDURL = "https://api.mch.weixin.qq.com/v3/pay/transactions/id/%s" // PayCloseOrderURL 关闭订单地址(需格式化 out_trade_no) PayCloseOrderURL = "https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/%s/close" // PayRefundURL 退款申请地址 PayRefundURL = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds" // PayRefundQueryURL 按商户退款单号查询退款地址(需格式化 out_refund_no) PayRefundQueryURL = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds/%s" // PayCertificatesURL 获取平台证书地址 PayCertificatesURL = "https://api.mch.weixin.qq.com/v3/certificates" )
微信支付 V3 相关 API 地址
const ( // BillTradeURL 申请交易账单地址 BillTradeURL = "https://api.mch.weixin.qq.com/v3/bill/tradebill" // BillFundFlowURL 申请资金账单地址 BillFundFlowURL = "https://api.mch.weixin.qq.com/v3/bill/fundflowbill" // BillHashTypeSHA1 账单哈希类型,官方固定为 SHA1 BillHashTypeSHA1 = "SHA1" )
微信支付账单相关 API 地址与常量
const ( // ProfitSharingOrderURL 请求分账地址 ProfitSharingOrderURL = "https://api.mch.weixin.qq.com/v3/profitsharing/orders" // ProfitSharingQueryURL 查询分账结果地址(需格式化 out_order_no) ProfitSharingQueryURL = "https://api.mch.weixin.qq.com/v3/profitsharing/orders/%s" // ProfitSharingUnfreezeURL 解冻剩余资金地址 ProfitSharingUnfreezeURL = "https://api.mch.weixin.qq.com/v3/profitsharing/orders/unfreeze" // ProfitSharingReturnURL 请求分账回退地址 ProfitSharingReturnURL = "https://api.mch.weixin.qq.com/v3/profitsharing/return-orders" // ProfitSharingReturnQueryURL 查询分账回退结果地址(需格式化 out_return_no) ProfitSharingReturnQueryURL = "https://api.mch.weixin.qq.com/v3/profitsharing/return-orders/%s" // ProfitSharingAmountsURL 查询剩余待分金额地址(需格式化 transaction_id) ProfitSharingAmountsURL = "https://api.mch.weixin.qq.com/v3/profitsharing/transactions/%s/amounts" )
微信支付分账相关 API 地址
const ( // PublicKeyIDPrefix 微信支付公钥 ID 前缀 // // 说明: // - 微信支付应答与回调的响应头 Wechatpay-Serial 携带该前缀时,表示本次签名使用微信支付公钥 // - 未携带该前缀时表示使用平台证书,商户需据此选择对应的验签密钥 PublicKeyIDPrefix = "PUB_KEY_ID_" // PublicKeyHeader 告知微信支付本次请求期望使用的验签/加密密钥的请求头 PublicKeyHeader = "Wechatpay-Serial" // JSAPISignType JSAPI 调起支付的签名类型 JSAPISignType = "RSA" // AppPayPackageValue App 调起支付的 package 固定值 AppPayPackageValue = "Sign=WXPay" )
微信支付验签模式相关常量
const ( TradeStateSuccess = "SUCCESS" // 支付成功 TradeStateRefund = "REFUND" // 转入退款 TradeStateNotPay = "NOTPAY" // 未支付 TradeStateClosed = "CLOSED" // 已关闭 TradeStateRevoked = "REVOKED" // 已撤销(付款码支付) TradeStateUserPaying = "USERPAYING" // 用户支付中(付款码支付) TradeStatePayError = "PAYERROR" // 支付失败 )
支付订单状态(Order.TradeState)
const ( RefundStatusSuccess = "SUCCESS" // 退款成功 RefundStatusClosed = "CLOSED" // 退款关闭 RefundStatusAbnormal = "ABNORMAL" // 退款异常 )
退款状态(RefundResponse.Status)
const ( ProfitSharingStateProcessing = "PROCESSING" // 分账处理中 ProfitSharingStateFinished = "FINISHED" // 分账处理完成 )
分账状态(ProfitSharingResponse.State)
const ( ProfitSharingResultPending = "PENDING" // 待分账 ProfitSharingResultSuccess = "SUCCESS" // 分账成功 ProfitSharingResultClosed = "CLOSED" // 分账失败已关闭 )
分账接收方结果(ProfitSharingReceiverResult.Result)
const ( ProfitSharingReturnProcessing = "PROCESSING" // 回退处理中 ProfitSharingReturnSuccess = "SUCCESS" // 回退成功 ProfitSharingReturnFailed = "FAILED" // 回退失败 )
分账回退结果(ProfitSharingReturnResponse.Result)
const ( // NotificationAckJSON 处理成功时推荐返回的应答体 NotificationAckJSON = `{"code":"SUCCESS","message":"成功"}` // NotificationAckCodeSuccess 处理成功应答的 code 值 NotificationAckCodeSuccess = "SUCCESS" // NotificationAckCodeFail 处理失败应答的 code 值 NotificationAckCodeFail = "FAIL" )
回调应答相关常量
说明:
- 商户处理回调成功后必须应答 200/204,否则微信会按 15s/15s/30s/3m/10m/20m/30m/30m/30m/60m/3h/3h/3h/6h/6h/6h 的频率重试 15 次
- 处理失败需返回 5xx 或 4xx 并带上 code/message,微信会据此重试
Variables ¶
var ( // ErrNoEncryptKey 未配置微信支付公钥且无法获取平台证书,无法加密敏感信息 ErrNoEncryptKey = errors.New("未配置微信支付公钥且无法获取平台证书,无法加密敏感信息") // ErrCertDownloadFailed 平台证书下载或解密失败 ErrCertDownloadFailed = errors.New("平台证书下载失败") // ErrSignatureHeaderMissing 响应缺少微信支付签名头 ErrSignatureHeaderMissing = errors.New("缺少微信支付响应签名头") )
微信支付模块预定义错误,业务可使用 errors.Is 判断
Functions ¶
func EncryptSensitiveWithPublicKey ¶
EncryptSensitiveWithPublicKey 使用指定公钥加密敏感信息
参数:
- pubKey: 微信支付公钥或平台证书公钥
- plaintext: 明文
返回:
- string: Base64 编码的密文
- error: 明文为空或加密失败时返回错误
使用示例:
- cipher, err := payment.EncryptSensitiveWithPublicKey(pubKey, "张三")
Types ¶
type APIError ¶
type APIError struct {
StatusCode int `json:"status_code"`
Code string `json:"code"`
Message string `json:"message"`
Detail *APIErrorDetail `json:"detail,omitempty"`
RawBody string `json:"raw_body,omitempty"`
Header http.Header `json:"-"`
}
APIError 微信支付 V3 接口返回的业务错误
字段说明:
- StatusCode: HTTP 状态码,如 400、401、403、404、429、500
- Code: 微信支付错误码,如 ORDER_PAID、SIGN_ERROR、NO_AUTH
- Message: 错误描述
- Detail: 详细的错误明细,可能为空
说明:
- 微信支付 V3 的错误响应体形如 {"code":"ORDER_PAID","message":"订单已支付","detail":{...}}
- 通过 IsAPIError / AsAPIError 判断与提取,便于业务层做差异化处理
使用示例:
- _, err := client.CloseOrder(ctx, "ORDER_001")
- if apiErr, ok := payment.AsAPIError(err); ok && apiErr.Code == "ORDERPAIDCLOSE" { ... }
func AsAPIError ¶
AsAPIError 从错误链中提取微信支付业务错误
参数:
- err: 待提取的错误
返回:
- *APIError: 提取到的业务错误,非微信支付错误时返回 nil
- bool: 是否提取成功
使用示例:
- if apiErr, ok := payment.AsAPIError(err); ok { log.Println(apiErr.Code) }
type APIErrorDetail ¶
type APIErrorDetail struct {
Field string `json:"field,omitempty"` // 出错字段名
Value string `json:"value,omitempty"` // 出错字段值
Issue string `json:"issue,omitempty"` // 具体问题
Location string `json:"location,omitempty"` // 出错位置
DetailList []string `json:"detail_list,omitempty"` // 补充说明
}
APIErrorDetail 微信支付错误明细
type Amount ¶
type Amount struct {
Total int `json:"total"` // 订单总金额,单位为分
Currency string `json:"currency,omitempty"` // 货币类型,默认 CNY
}
Amount 订单金额
type AppPayParams ¶
type AppPayParams struct {
AppID string `json:"appid"`
PartnerID string `json:"partnerid"`
PrepayID string `json:"prepayid"`
Package string `json:"package"`
NonceStr string `json:"noncestr"`
Timestamp string `json:"timestamp"`
Sign string `json:"sign"`
}
AppPayParams App 端调起支付所需的参数
说明:
- 字段名大小写敏感,需与微信开放平台 SDK 要求一致
- Package 官方暂固定为 Sign=WXPay
type AppRequest ¶
type AppRequest struct {
AppID string `json:"appid"` // 应用 ID
MchID string `json:"mchid"` // 商户号
Description string `json:"description"` // 商品描述
OutTradeNo string `json:"out_trade_no"` // 商户订单号
NotifyURL string `json:"notify_url"` // 通知地址
Amount Amount `json:"amount"` // 订单金额
Attach string `json:"attach,omitempty"` // 附加数据
GoodsTag string `json:"goods_tag,omitempty"` // 订单优惠标记
SceneInfo *SceneInfo `json:"scene_info,omitempty"` // 场景信息
}
AppRequest App 支付下单请求
type BillRequest ¶
type BillRequest struct {
BillDate string `json:"bill_date"` // 账单日期
BillType string `json:"bill_type,omitempty"` // 账单类型
TarType string `json:"tar_type,omitempty"` // 压缩类型
AccountType string `json:"account_type,omitempty"` // 资金账户类型
}
BillRequest 账单申请请求
字段说明:
- BillDate: 账单日期,格式 yyyy-MM-dd
- BillType: 账单类型,ALL / SUCCESS / REFUND,不填默认 ALL
- TarType: 压缩类型,GZIP,不填则不压缩
- AccountType: 资金账户类型,仅资金账单使用,BASIC / OPERATION / FEES
type BillResponse ¶
type BillResponse struct {
HashType string `json:"hash_type"` // 哈希类型,固定 SHA1
HashValue string `json:"hash_value"` // 账单文件哈希值,用于校验完整性
DownloadURL string `json:"download_url"` // 账单下载地址,5 分钟内有效
}
BillResponse 账单申请响应
type CertificateItem ¶
type CertificateItem struct {
SerialNo string `json:"serial_no"` // 证书序列号
EffectiveTime string `json:"effective_time"` // 生效时间
ExpireTime string `json:"expire_time"` // 过期时间
EncryptCertificate EncryptCertificate `json:"encrypt_certificate"` // 加密证书信息
}
CertificateItem 平台证书列表项
type CertificatesResponse ¶
type CertificatesResponse struct {
Data []CertificateItem `json:"data"` // 证书列表
}
CertificatesResponse 获取平台证书响应
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client 微信支付 V3 客户端
func NewClientE ¶
NewClientE 创建新的微信支付客户端并返回错误(使用默认文件存储)
参数:
- config: 支付配置信息
- opts: 可选参数,支持 debugger.LoggerInterface 与 core.HTTPClient
返回:
- *Client: 支付客户端实例
- error: 配置校验、存储创建或密钥解析失败时返回错误
说明:
- 默认存储目录为 ./runtime/wego_storage,需确保进程对该目录有读写权限
使用示例:
- client, err := payment.NewClientE(&payment.Config{AppID: "wx123", ...})
func NewClientWithStorage
deprecated
func NewClientWithStorage(config *Config, storage storage.TokenStorage, opts ...any) *Client
NewClientWithStorage 创建新的微信支付客户端(使用自定义存储)
参数:
- config: 支付配置信息
- storage: 自定义存储实例
- opts: 可选参数,支持 debugger.LoggerInterface 与 core.HTTPClient
返回:
- *Client: 支付客户端实例
Deprecated: 配置或私钥非法时会直接 log.Panic 终止进程,请改用 NewClientWithStorageE。
func NewClientWithStorageE ¶
func NewClientWithStorageE(config *Config, storage storage.TokenStorage, opts ...any) (*Client, error)
NewClientWithStorageE 创建新的微信支付客户端并返回错误(使用自定义存储)
参数:
- config: 支付配置信息
- storage: 自定义存储实例
- opts: 可选参数,支持 debugger.LoggerInterface 与 core.HTTPClient
返回:
- *Client: 支付客户端实例
- error: 配置校验或密钥解析失败时返回错误
使用示例:
- client, err := payment.NewClientWithStorageE(cfg, myStorage, myHTTPClient)
func (*Client) AppPay ¶
func (c *Client) AppPay(ctx context.Context, req *AppRequest) (*PrepayResponse, error)
AppPay App 支付下单
参数:
- ctx: 上下文
- req: App 下单请求参数
返回:
- *PrepayResponse: 包含 prepay_id 的响应,需再用 BuildAppPayParams 生成调起参数
- error: 请求失败时返回错误
使用示例:
- prepay, err := client.AppPay(ctx, &payment.AppRequest{OutTradeNo: "ORDER_001", Amount: payment.Amount{Total: 100}, Description: "商品"})
文档:
func (*Client) ApplyFundFlowBill ¶
func (c *Client) ApplyFundFlowBill(ctx context.Context, req *BillRequest) (*BillResponse, error)
ApplyFundFlowBill 申请资金账单
参数:
- ctx: 上下文
- req: 账单申请参数,BillDate 必填,AccountType 常用 BASIC / OPERATION / FEES
返回:
- *BillResponse: 含下载链接与哈希值的响应
- error: 参数缺失或请求失败时返回错误
使用示例:
- bill, err := client.ApplyFundFlowBill(ctx, &payment.BillRequest{BillDate: "2026-10-14", AccountType: "BASIC"})
文档:
func (*Client) ApplyTradeBill ¶
func (c *Client) ApplyTradeBill(ctx context.Context, req *BillRequest) (*BillResponse, error)
ApplyTradeBill 申请交易账单
参数:
- ctx: 上下文
- req: 账单申请参数,BillDate 必填,格式 yyyy-MM-dd
返回:
- *BillResponse: 含下载链接与哈希值的响应
- error: 参数缺失或请求失败时返回错误
说明:
- 微信在次日 9 点开始生成前一天的对账单,建议次日 10 点后获取
使用示例:
- bill, err := client.ApplyTradeBill(ctx, &payment.BillRequest{BillDate: "2026-10-14", BillType: "ALL"})
文档:
func (*Client) BuildAppPayParams ¶
func (c *Client) BuildAppPayParams(prepayID string) (*AppPayParams, error)
BuildAppPayParams 生成 App 端调起支付所需的参数
参数:
- prepayID: AppPay 返回的预支付交易会话标识
返回:
- *AppPayParams: 含 sign 的调起支付参数,可直接交给客户端 SDK
- error: prepayID 为空或签名失败时返回错误
说明:
- 官方签名串为四行:appid\ntimestamp\nnoncestr\nprepayid\n,不包含 partnerid 与 package
- 客户端字段名为 appid、partnerid、prepayid、package、noncestr、timestamp、sign,大小写敏感
使用示例:
- prepay, _ := client.AppPay(ctx, req)
- params, err := client.BuildAppPayParams(prepay.PrepayID)
文档:
func (*Client) BuildJSAPIPayParams ¶
func (c *Client) BuildJSAPIPayParams(prepayID string) (*JSAPIPayParams, error)
BuildJSAPIPayParams 生成前端调起 JSAPI 支付所需的参数
参数:
- prepayID: JSAPIPay 返回的预支付交易会话标识
返回:
- *JSAPIPayParams: 含 paySign 的调起支付参数,可直接交给小程序 wx.requestPayment 或公众号 JS-SDK
- error: prepayID 为空或签名失败时返回错误
说明:
- 签名串格式为:appId\ntimeStamp\nnonceStr\npackage\n
- 参数大小写需与微信要求一致,前端字段名为 appId、timeStamp、nonceStr、package、signType、paySign
使用示例:
- prepay, _ := client.JSAPIPay(ctx, req)
- params, err := client.BuildJSAPIPayParams(prepay.PrepayID)
文档:
func (*Client) CloseOrder ¶
CloseOrder 关闭未支付的订单
参数:
- ctx: 上下文
- outTradeNo: 商户订单号
返回:
- error: 关单失败时返回错误
说明:
- 适用于用户取消订单或订单超时未支付的场景
- 接口成功时微信返回 204 No Content,无响应体
使用示例:
- if err := client.CloseOrder(ctx, "ORDER_20240101_001"); err != nil { return err }
文档:
func (*Client) DecryptNotificationResource ¶
DecryptNotificationResource 解密微信支付回调通知资源
参数:
- resource: 通知资源对象
返回:
- []byte: 解密后的 JSON 数据
- error: 解密失败时返回错误
func (*Client) DownloadBill ¶
DownloadBill 下载账单文件并校验完整性
参数:
- ctx: 上下文
- downloadURL: 申请账单接口返回的下载地址,5 分钟内有效
- hashValue: 申请账单接口返回的哈希值,传空字符串表示跳过校验
返回:
- []byte: 账单文件原始字节,tar_type 为 GZIP 时为压缩流
- error: 下载失败或哈希校验不一致时返回错误
说明:
- 官方下载账单响应不含签名头,故跳过验签
使用示例:
- data, err := client.DownloadBill(ctx, bill.DownloadURL, bill.HashValue)
文档:
func (*Client) EncryptSensitiveData ¶
EncryptSensitiveData 加密微信支付要求的敏感信息
参数:
- ctx: 上下文
- plaintext: 明文,如分账接收方姓名、身份证号等
返回:
- string: Base64 编码的密文,可直接作为接口字段值
- error: 无可用密钥或加密失败时返回错误
说明:
- 使用 RSAES-OAEP 算法(SHA-1 + MGF1-SHA1),与微信支付官方要求一致
- 优先使用配置的微信支付公钥,未配置时使用最新平台证书
使用示例:
- name, err := client.EncryptSensitiveData(ctx, "张三")
func (*Client) EncryptSerialNo ¶
EncryptSerialNo 返回当前用于敏感信息加密的 Wechatpay-Serial 值
参数:
- ctx: 上下文
返回:
- string: 微信支付公钥 ID 或平台证书序列号
- error: 无可用密钥时返回错误
使用示例:
- serial, err := client.EncryptSerialNo(ctx)
func (*Client) GetLogger ¶
func (c *Client) GetLogger() logger.LoggerInterface
GetLogger 获取日志器
返回:
- logger.LoggerInterface: 日志器实例
func (*Client) H5Pay ¶
H5Pay H5 支付统一下单
参数:
- ctx: 上下文
- req: H5 下单请求参数
返回:
- *H5Response: 包含 h5_url 的响应
- error: 请求失败时返回错误
文档:
func (*Client) JSAPIPay ¶
func (c *Client) JSAPIPay(ctx context.Context, req *JSAPIRequest) (*PrepayResponse, error)
JSAPIPay JSAPI 统一下单
参数:
- ctx: 上下文
- req: JSAPI 下单请求参数
返回:
- *PrepayResponse: 包含 prepay_id 的响应
- error: 请求失败时返回错误
文档:
func (*Client) NativePay ¶
func (c *Client) NativePay(ctx context.Context, req *NativeRequest) (*NativeResponse, error)
NativePay Native 支付下单(扫码支付)
参数:
- ctx: 上下文
- req: Native 下单请求参数
返回:
- *NativeResponse: 包含 code_url 的响应,商户需将其转换为二维码
- error: 请求失败时返回错误
使用示例:
- resp, err := client.NativePay(ctx, &payment.NativeRequest{OutTradeNo: "ORDER_001", Amount: payment.Amount{Total: 100}, Description: "商品"})
文档:
func (*Client) ProfitSharing ¶
func (c *Client) ProfitSharing(ctx context.Context, req *ProfitSharingRequest) (*ProfitSharingResponse, error)
ProfitSharing 请求分账
参数:
- ctx: 上下文
- req: 分账请求参数,Receivers 中的 Name 需为加密后的密文
返回:
- *ProfitSharingResponse: 分账单受理结果,State 为 PROCESSING 时需继续查询
- error: 参数缺失、加密失败或请求失败时返回错误
说明:
- 接口为异步处理,最终分账结果需用 ProfitSharingQuery 查询
- 请求头 Wechatpay-Serial 会自动填充为实际加密所用的公钥 ID 或平台证书序列号
使用示例:
- name, _ := client.EncryptSensitiveData(ctx, "张三")
- resp, err := client.ProfitSharing(ctx, &payment.ProfitSharingRequest{
- TransactionID: "4200001234", OutOrderNo: "PS001", UnfreezeUnsplit: true,
- Receivers: []payment.ProfitSharingReceiver{{Type: "MERCHANT_ID", Account: "1900000109", Name: name, Amount: 100, Description: "分账"}},
- })
文档:
func (*Client) ProfitSharingAmounts ¶
func (c *Client) ProfitSharingAmounts(ctx context.Context, transactionID string) (*ProfitSharingAmountsResponse, error)
ProfitSharingAmounts 查询订单剩余待分金额
参数:
- ctx: 上下文
- transactionID: 微信支付订单号
返回:
- *ProfitSharingAmountsResponse: 含剩余待分金额的响应
- error: 请求失败时返回错误
使用示例:
- resp, err := client.ProfitSharingAmounts(ctx, "4200001234")
文档:
func (*Client) ProfitSharingQuery ¶
func (c *Client) ProfitSharingQuery(ctx context.Context, outOrderNo, transactionID string) (*ProfitSharingResponse, error)
ProfitSharingQuery 查询分账结果
参数:
- ctx: 上下文
- outOrderNo: 商户分账单号
- transactionID: 微信支付订单号
返回:
- *ProfitSharingResponse: 分账单结果,State 为 FINISHED 表示处理完毕
- error: 请求失败时返回错误
使用示例:
- resp, err := client.ProfitSharingQuery(ctx, "PS001", "4200001234")
文档:
func (*Client) ProfitSharingReturn ¶
func (c *Client) ProfitSharingReturn(ctx context.Context, req *ProfitSharingReturnRequest) (*ProfitSharingReturnResponse, error)
ProfitSharingReturn 请求分账回退
参数:
- ctx: 上下文
- req: 回退请求参数,OrderID 与 OutOrderNo 至少填一个
返回:
- *ProfitSharingReturnResponse: 回退受理结果
- error: 参数缺失或请求失败时返回错误
使用示例:
- resp, err := client.ProfitSharingReturn(ctx, &payment.ProfitSharingReturnRequest{OutOrderNo: "PS001", OutReturnNo: "RT001", ReturnMchID: "1900000109", Amount: 100, Description: "分账回退"})
文档:
func (*Client) ProfitSharingReturnQuery ¶
func (c *Client) ProfitSharingReturnQuery(ctx context.Context, outReturnNo, outOrderNo string) (*ProfitSharingReturnResponse, error)
ProfitSharingReturnQuery 查询分账回退结果
参数:
- ctx: 上下文
- outReturnNo: 商户回退单号
- outOrderNo: 商户分账单号
返回:
- *ProfitSharingReturnResponse: 回退结果,Result 为 SUCCESS 表示回退成功
- error: 请求失败时返回错误
使用示例:
- resp, err := client.ProfitSharingReturnQuery(ctx, "RT001", "PS001")
文档:
func (*Client) ProfitSharingUnfreeze ¶
func (c *Client) ProfitSharingUnfreeze(ctx context.Context, req *ProfitSharingUnfreezeRequest) (*ProfitSharingResponse, error)
ProfitSharingUnfreeze 解冻剩余未分账资金
参数:
- ctx: 上下文
- req: 解冻请求参数
返回:
- *ProfitSharingResponse: 解冻结果
- error: 参数缺失或请求失败时返回错误
使用示例:
- resp, err := client.ProfitSharingUnfreeze(ctx, &payment.ProfitSharingUnfreezeRequest{TransactionID: "4200001234", OutOrderNo: "PS001", Description: "解冻"})
文档:
func (*Client) QueryOrder ¶
QueryOrder 按商户订单号查询订单
参数:
- ctx: 上下文
- outTradeNo: 商户订单号
返回:
- *Order: 订单信息
- error: 请求失败时返回错误
文档:
func (*Client) QueryOrderByTransactionID ¶
func (c *Client) QueryOrderByTransactionID(ctx context.Context, transactionID string) (*Order, error)
QueryOrderByTransactionID 按微信支付订单号查询订单
参数:
- ctx: 上下文
- transactionID: 微信支付订单号
返回:
- *Order: 订单信息
- error: 请求失败时返回错误
使用示例:
- order, err := client.QueryOrderByTransactionID(ctx, "4200001234202401011234567890")
文档:
func (*Client) Refund ¶
func (c *Client) Refund(ctx context.Context, req *RefundRequest) (*RefundResponse, error)
Refund 申请退款
参数:
- ctx: 上下文
- req: 退款请求参数
返回:
- *RefundResponse: 退款结果
- error: 请求失败时返回错误
文档:
func (*Client) RefundQuery ¶
RefundQuery 按商户退款单号查询退款结果
参数:
- ctx: 上下文
- outRefundNo: 商户退款单号
返回:
- *RefundResponse: 退款结果,Status 为 SUCCESS 表示退款成功
- error: 请求失败时返回错误
使用示例:
- refund, err := client.RefundQuery(ctx, "REFUND_20240101_001")
文档:
func (*Client) SetHTTPClient ¶
func (c *Client) SetHTTPClient(client core.HTTPClient)
SetHTTPClient 设置自定义 HTTP 客户端
参数:
- client: 自定义 HTTP 客户端
func (*Client) SetLogger ¶
func (c *Client) SetLogger(log debugger.LoggerInterface)
SetLogger 设置自定义日志器
参数:
- log: 自定义日志器,nil 则使用默认日志器
func (*Client) VerifyNotification ¶
func (c *Client) VerifyNotification(ctx context.Context, header http.Header, body []byte) (*Notification, []byte, error)
VerifyNotification 验证微信支付回调通知签名并解密资源
参数:
- ctx: 上下文
- header: HTTP 请求头
- body: 请求体字节数组
返回:
- *Notification: 解密后的通知对象
- []byte: 解密后的资源 JSON 数据
- error: 验签或解密失败时返回错误
文档:
func (*Client) VerifyNotificationByHeaders ¶
func (c *Client) VerifyNotificationByHeaders(ctx context.Context, headers *NotificationHeaders, body []byte) (*Notification, []byte, error)
VerifyNotificationByHeaders 通过解析后的通知头验证回调通知
参数:
- ctx: 上下文
- headers: 通知头信息
- body: 请求体字节数组
返回:
- *Notification: 解密后的通知对象
- []byte: 解密后的资源 JSON 数据
- error: 验签或解密失败时返回错误
说明:
- 验签密钥由通知头 Wechatpay-Serial 决定:公钥 ID 走公钥,否则走平台证书
- 官方切换灰度期内回调由微信随机使用公钥或平台证书签名,两者均需支持
type CloseOrderRequest ¶
type CloseOrderRequest struct {
MchID string `json:"mchid"` // 商户号
}
CloseOrderRequest 关闭订单请求
type Config ¶
type Config struct {
AppID string `json:"app_id" ini:"app_id"` // 应用 ID(公众号/小程序 appid)
MchID string `json:"mch_id" ini:"mch_id"` // 商户号
APIV3Key string `json:"api_v3_key" ini:"api_v3_key"` // API V3 密钥(32 字节)
CertSerialNo string `json:"cert_serial_no" ini:"cert_serial_no"` // 商户 API 证书序列号,用于请求签名
PrivateKey string `json:"private_key" ini:"private_key"` // 商户私钥 PEM 字符串
NotifyURL string `json:"notify_url" ini:"notify_url"` // 支付结果通知 URL
PublicKeyID string `json:"public_key_id" ini:"public_key_id"` // 微信支付公钥 ID,形如 PUB_KEY_ID_xxx(官方推荐)
PublicKey string `json:"public_key" ini:"public_key"` // 微信支付公钥 PEM 字符串(官方推荐)
}
Config 微信支付 V3 配置结构体
验签模式说明(平台证书与微信支付公钥可任选其一,也可同时配置):
- 仅使用平台证书:不填 PublicKeyID 与 PublicKey,维持传统模式
- 仅使用微信支付公钥:填写 PublicKeyID 与 PublicKey,不再依赖平台证书下载
- 两者都配置:优先使用微信支付公钥,但应答/回调仍以响应头 Wechatpay-Serial 为准自动回退到平台证书
func (*Config) UsePublicKey ¶
UsePublicKey 判断当前配置是否启用微信支付公钥验签
返回:
- bool: PublicKeyID 与 PublicKey 均已配置时返回 true
使用示例:
- if cfg.UsePublicKey() { fmt.Println("公钥模式") }
type EncryptCertificate ¶
type EncryptCertificate struct {
Algorithm string `json:"algorithm"` // 加密算法
Nonce string `json:"nonce"` // 加密使用的随机串
AssociatedData string `json:"associated_data"` // 加密使用的附加数据
Ciphertext string `json:"ciphertext"` // Base64 编码的密文
}
EncryptCertificate 加密证书信息
type H5Info ¶
type H5Info struct {
Type string `json:"type"` // 场景类型,如 Wap、iOS、Android
AppName string `json:"app_name,omitempty"` // 应用名称
AppURL string `json:"app_url,omitempty"` // 网站 URL
BundleID string `json:"bundle_id,omitempty"` // iOS Bundle ID
PackageName string `json:"package_name,omitempty"` // Android 包名
}
H5Info H5 支付场景信息
type H5Request ¶
type H5Request struct {
AppID string `json:"appid"` // 应用 ID
MchID string `json:"mchid"` // 商户号
Description string `json:"description"` // 商品描述
OutTradeNo string `json:"out_trade_no"` // 商户订单号
NotifyURL string `json:"notify_url"` // 通知地址
Amount Amount `json:"amount"` // 订单金额
SceneInfo *SceneInfo `json:"scene_info"` // H5 场景信息必填
}
H5Request H5 支付请求
type H5Response ¶
type H5Response struct {
H5URL string `json:"h5_url"` // H5 支付跳转 URL
}
H5Response H5 支付响应
type JSAPIPayParams ¶
type JSAPIPayParams struct {
AppID string `json:"appId"`
TimeStamp string `json:"timeStamp"`
NonceStr string `json:"nonceStr"`
Package string `json:"package"`
SignType string `json:"signType"`
PaySign string `json:"paySign"`
}
JSAPIPayParams 前端调起 JSAPI 支付所需的参数
字段说明:
- AppID: 应用 ID(公众号/小程序 appid)
- TimeStamp: 时间戳,秒级字符串
- NonceStr: 随机字符串
- Package: 固定格式 prepay_id=xxx
- SignType: 签名类型,固定 RSA
- PaySign: 使用商户私钥对上述字段签名后的结果
使用示例:
- 小程序 wx.requestPayment 与公众号 JS-SDK chooseWXPay 均可直接使用
type JSAPIRequest ¶
type JSAPIRequest struct {
AppID string `json:"appid"` // 应用 ID
MchID string `json:"mchid"` // 商户号
Description string `json:"description"` // 商品描述
OutTradeNo string `json:"out_trade_no"` // 商户订单号
NotifyURL string `json:"notify_url"` // 通知地址
Amount Amount `json:"amount"` // 订单金额
Payer Payer `json:"payer"` // 支付者信息
Attach string `json:"attach,omitempty"` // 附加数据
SceneInfo *SceneInfo `json:"scene_info,omitempty"` // 场景信息
}
JSAPIRequest JSAPI 统一下单请求
type NativeRequest ¶
type NativeRequest struct {
AppID string `json:"appid"` // 应用 ID
MchID string `json:"mchid"` // 商户号
Description string `json:"description"` // 商品描述
OutTradeNo string `json:"out_trade_no"` // 商户订单号
NotifyURL string `json:"notify_url"` // 通知地址
Amount Amount `json:"amount"` // 订单金额
Attach string `json:"attach,omitempty"` // 附加数据
GoodsTag string `json:"goods_tag,omitempty"` // 订单优惠标记
SceneInfo *SceneInfo `json:"scene_info,omitempty"` // 场景信息
}
NativeRequest Native 支付下单请求
type NativeResponse ¶
type NativeResponse struct {
CodeURL string `json:"code_url"` // 二维码链接,商户需将其转换为二维码图片
}
NativeResponse Native 支付下单响应
type Notification ¶
type Notification struct {
ID string `json:"id"` // 通知 ID
CreateTime string `json:"create_time"` // 通知创建时间
EventType string `json:"event_type"` // 通知类型
ResourceType string `json:"resource_type"` // 资源类型
Resource Resource `json:"resource"` // 加密资源
Summary string `json:"summary"` // 回调摘要
}
Notification 回调通知结构
type NotificationHeaders ¶
type NotificationHeaders struct {
WechatpaySerial string
WechatpayNonce string
WechatpayTimestamp string
WechatpaySignature string
WechatpaySignatureType string
WechatpayRequestID string
}
NotificationHeaders 微信支付回调通知请求头
字段说明:
- WechatpaySerial: 平台证书序列号
- WechatpayNonce: 随机串
- WechatpayTimestamp: 时间戳
- WechatpaySignature: 签名
- WechatpaySignatureType: 签名类型
- WechatpayRequestID: 请求 ID
func ParseNotificationHeaders ¶
func ParseNotificationHeaders(header http.Header) *NotificationHeaders
ParseNotificationHeaders 从 HTTP 请求头中解析微信支付回调通知头
参数:
- header: HTTP 请求头
返回:
- *NotificationHeaders: 解析后的通知头
type Order ¶
type Order struct {
AppID string `json:"appid"` // 应用 ID
MchID string `json:"mchid"` // 商户号
OutTradeNo string `json:"out_trade_no"` // 商户订单号
TransactionID string `json:"transaction_id"` // 微信支付订单号
TradeType string `json:"trade_type,omitempty"` // 交易类型
TradeState string `json:"trade_state"` // 交易状态
TradeStateDesc string `json:"trade_state_desc"` // 交易状态描述
BankType string `json:"bank_type,omitempty"` // 付款银行
Attach string `json:"attach,omitempty"` // 附加数据
SuccessTime time.Time `json:"success_time,omitempty"` // 支付完成时间
Amount *Amount `json:"amount,omitempty"` // 订单金额
Payer *Payer `json:"payer,omitempty"` // 支付者信息
}
Order 查询订单响应
type Payer ¶
type Payer struct {
OpenID string `json:"openid"` // 用户在直连商户应用下的用户标示
}
Payer JSAPI 支付 payer 信息
type PrepayResponse ¶
type PrepayResponse struct {
PrepayID string `json:"prepay_id"` // 预支付交易会话标识
}
PrepayResponse JSAPI 统一下单响应
type ProfitSharingAmountsResponse ¶
type ProfitSharingAmountsResponse struct {
TransactionID string `json:"transaction_id"` // 微信支付订单号
UnsplitAmount int `json:"unsplit_amount"` // 剩余待分金额,单位为分
}
ProfitSharingAmountsResponse 查询剩余待分金额响应
type ProfitSharingReceiver ¶
type ProfitSharingReceiver struct {
Type string `json:"type"` // 分账接收方类型
Account string `json:"account"` // 分账接收方账号
Name string `json:"name,omitempty"` // 分账接收方姓名(需加密)
Amount int `json:"amount"` // 分账金额,单位为分
Description string `json:"description"` // 分账描述
}
ProfitSharingReceiver 分账接收方
说明:
- Name 为敏感字段,需使用微信支付公钥或平台证书加密后传入
- Type 取值:MERCHANT_ID(商户号)、PERSONAL_OPENID(个人 openid)
type ProfitSharingReceiverResult ¶
type ProfitSharingReceiverResult struct {
Amount int `json:"amount"` // 分账金额,单位为分
Description string `json:"description"` // 分账描述
Type string `json:"type"` // 接收方类型
Account string `json:"account"` // 接收方账号
Result string `json:"result"` // 分账结果,PENDING / SUCCESS / CLOSED
FailReason string `json:"fail_reason,omitempty"` // 分账失败原因
DetailID string `json:"detail_id,omitempty"` // 分账明细单号
}
ProfitSharingReceiverResult 分账接收方结果
type ProfitSharingRequest ¶
type ProfitSharingRequest struct {
AppID string `json:"appid,omitempty"` // 应用 ID,含个人接收方时必填
TransactionID string `json:"transaction_id"` // 微信支付订单号
OutOrderNo string `json:"out_order_no"` // 商户分账单号
Receivers []ProfitSharingReceiver `json:"receivers"` // 分账接收方列表
UnfreezeUnsplit bool `json:"unfreeze_unsplit"` // 是否解冻剩余未分账资金
}
ProfitSharingRequest 请求分账参数
type ProfitSharingResponse ¶
type ProfitSharingResponse struct {
TransactionID string `json:"transaction_id"` // 微信支付订单号
OutOrderNo string `json:"out_order_no"` // 商户分账单号
OrderID string `json:"order_id"` // 微信分账单号
State string `json:"state"` // 分账单状态,PROCESSING / FINISHED
Receivers []ProfitSharingReceiverResult `json:"receivers"` // 分账接收方结果列表
}
ProfitSharingResponse 分账请求与查询结果响应
type ProfitSharingReturnRequest ¶
type ProfitSharingReturnRequest struct {
OrderID string `json:"order_id,omitempty"` // 微信分账单号,与 OutOrderNo 二选一
OutOrderNo string `json:"out_order_no,omitempty"` // 商户分账单号
OutReturnNo string `json:"out_return_no"` // 商户回退单号
ReturnMchID string `json:"return_mchid"` // 回退商户号
Amount int `json:"amount"` // 回退金额,单位为分
Description string `json:"description"` // 回退描述
}
ProfitSharingReturnRequest 请求分账回退参数
type ProfitSharingReturnResponse ¶
type ProfitSharingReturnResponse struct {
OrderID string `json:"order_id,omitempty"` // 微信分账单号
OutOrderNo string `json:"out_order_no"` // 商户分账单号
OutReturnNo string `json:"out_return_no"` // 商户回退单号
ReturnMchID string `json:"return_mchid"` // 回退商户号
Amount int `json:"amount"` // 回退金额,单位为分
Description string `json:"description"` // 回退描述
Result string `json:"result"` // 回退结果,PROCESSING / SUCCESS / FAILED
FailReason string `json:"fail_reason,omitempty"` // 回退失败原因
}
ProfitSharingReturnResponse 分账回退请求与查询结果响应
type ProfitSharingUnfreezeRequest ¶
type ProfitSharingUnfreezeRequest struct {
TransactionID string `json:"transaction_id"` // 微信支付订单号
OutOrderNo string `json:"out_order_no"` // 商户分账单号
Description string `json:"description"` // 解冻描述
}
ProfitSharingUnfreezeRequest 解冻剩余资金参数
type RefundAmount ¶
type RefundAmount struct {
Refund int `json:"refund"` // 退款金额,单位为分
Total int `json:"total"` // 原订单金额,单位为分
}
RefundAmount 退款金额
type RefundRequest ¶
type RefundRequest struct {
OutTradeNo string `json:"out_trade_no"` // 商户订单号
OutRefundNo string `json:"out_refund_no"` // 商户退款单号
Reason string `json:"reason,omitempty"` // 退款原因
NotifyURL string `json:"notify_url,omitempty"` // 退款结果通知地址
Amount RefundAmount `json:"amount"` // 退款金额
}
RefundRequest 退款申请请求
type RefundResponse ¶
type RefundResponse struct {
RefundID string `json:"refund_id"` // 微信退款单号
OutRefundNo string `json:"out_refund_no"` // 商户退款单号
TransactionID string `json:"transaction_id"` // 微信支付订单号
OutTradeNo string `json:"out_trade_no"` // 商户订单号
Channel string `json:"channel"` // 退款渠道
UserReceivedAccount string `json:"user_received_account"` // 用户退款入账账户
CreateTime time.Time `json:"create_time,omitempty"` // 退款受理时间
SuccessTime time.Time `json:"success_time,omitempty"` // 退款成功时间
FundsAccount string `json:"funds_account,omitempty"` // 退款出资账户
Status string `json:"status"` // 退款状态
Amount RefundAmount `json:"amount"` // 退款金额
}
RefundResponse 退款申请与退款查询响应
说明:
- 申请退款接口仅返回部分字段,查询退款接口会额外返回 CreateTime、SuccessTime、FundsAccount
type Resource ¶
type Resource struct {
Algorithm string `json:"algorithm"` // 加密算法
Ciphertext string `json:"ciphertext"` // Base64 编码的密文
Nonce string `json:"nonce"` // 加密随机串
AssociatedData string `json:"associated_data"` // 加密附加数据
OriginalType string `json:"original_type"` // 原始类型
}
Resource 回调通知资源对象