payment

package
v1.0.1-alpha Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Overview

Package payment 微信支付 V3 - 商家转账(用户确认收款模式,单笔) 参考:

Index

Constants

View Source
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"

	// PayCodePayURL 付款码支付下单地址(收银员扫顾客付款码,B扫C)
	// 提交后立即返回订单结果:trade_state=SUCCESS 为扣款成功;USERPAYING 表示用户支付中,
	// 需轮询查单确认最终状态;USERPAYING 长期未成功时用撤销接口终止交易
	PayCodePayURL = "https://api.mch.weixin.qq.com/v3/pay/transactions/codepay"

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

	// PayReverseOrderURL 撤销订单地址(需格式化 out_trade_no,付款码支付配套:
	// USERPAYING 在途交易无法用关单接口终止,只能撤销)
	PayReverseOrderURL = "https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/%s/reverse"

	// 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 地址

View Source
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 地址与常量

View Source
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 地址

View Source
const (
	// MchTransferCreateURL 发起转账(需用户确认收款)地址
	MchTransferCreateURL = "https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills"

	// MchTransferTransferURL 用户授权后转账地址(用户完成授权后实际出款)
	MchTransferTransferURL = "https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills/transfer"

	// MchTransferCancelURL 撤销转账地址(需格式化 out_bill_no,仅用户确认收款前可撤销)
	MchTransferCancelURL = "https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills/out-bill-no/%s/cancel"

	// MchTransferQueryByOutBillNoURL 按商户单号查询转账单地址(需格式化 out_bill_no)
	MchTransferQueryByOutBillNoURL = "https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills/out-bill-no/%s"

	// MchTransferQueryByBillNoURL 按微信转账单号查询转账单地址(需格式化 transfer_bill_no)
	MchTransferQueryByBillNoURL = "https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills/transfer-bill-no/%s"

	// MchTransferElecsignApplyByOutBillNoURL 按商户单号申请电子回单地址
	MchTransferElecsignApplyByOutBillNoURL = "https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/elecsign/out-bill-no"

	// MchTransferElecsignQueryByOutBillNoURL 按商户单号查询电子回单地址(需格式化 out_bill_no)
	MchTransferElecsignQueryByOutBillNoURL = "https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/elecsign/out-bill-no/%s"

	// MchTransferElecsignApplyByBillNoURL 按微信转账单号申请电子回单地址
	MchTransferElecsignApplyByBillNoURL = "https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/elecsign/transfer-bill-no"

	// MchTransferElecsignQueryByBillNoURL 按微信转账单号查询电子回单地址(需格式化 transfer_bill_no)
	MchTransferElecsignQueryByBillNoURL = "https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/elecsign/transfer-bill-no/%s"
)

微信支付商家转账(用户确认收款模式)相关 API 地址 参考:https://pay.weixin.qq.com/doc/v3/merchant/4012716434

View Source
const (
	TransferStateAccepted        = "ACCEPTED"          // 转账已受理(非终态,可原单重试)
	TransferStateProcessing      = "PROCESSING"        // 转账处理中,结果尚未明确(建议检查账户余额)
	TransferStateWaitUserConfirm = "WAIT_USER_CONFIRM" // 待收款用户确认(可拉起收款确认页)
	TransferStateTransfering     = "TRANSFERING"       // 转账结果尚未明确(可拉起收款确认页重试确认)
	TransferStateSuccess         = "SUCCESS"           // 转账成功
	TransferStateFail            = "FAIL"              // 转账失败
	TransferStateCanceling       = "CANCELING"         // 撤销请求受理成功,撤销中
	TransferStateCancelled       = "CANCELLED"         // 撤销完成
)

转账单据状态(TransferBillResponse.State / TransferBillCreateResponse.State)

View Source
const (
	TransferElecsignStateGenerating = "GENERATING" // 电子回单受理成功,处理中
	TransferElecsignStateFinished   = "FINISHED"   // 电子回单处理完成(返回 hash 与下载地址)
	TransferElecsignStateFailed     = "FAILED"     // 电子回单生成失败(fail_reason 返回原因)
)

电子回单申请单状态(TransferElecsignResponse.State)

View Source
const (
	// PublicKeyIDPrefix 微信支付公钥 ID 前缀
	//
	// 说明:
	//   - 微信支付应答与回调的响应头 Wechatpay-Serial 携带该前缀时,表示本次签名使用微信支付公钥
	//   - 未携带该前缀时表示使用平台证书,商户需据此选择对应的验签密钥
	PublicKeyIDPrefix = "PUB_KEY_ID_"

	// PublicKeyHeader 告知微信支付本次请求期望使用的验签/加密密钥的请求头
	PublicKeyHeader = "Wechatpay-Serial"

	// JSAPISignType JSAPI 调起支付的签名类型
	JSAPISignType = "RSA"

	// AppPayPackageValue App 调起支付的 package 固定值
	AppPayPackageValue = "Sign=WXPay"
)

微信支付验签模式相关常量

View Source
const (
	TradeStateSuccess    = "SUCCESS"    // 支付成功
	TradeStateRefund     = "REFUND"     // 转入退款
	TradeStateNotPay     = "NOTPAY"     // 未支付
	TradeStateClosed     = "CLOSED"     // 已关闭
	TradeStateRevoked    = "REVOKED"    // 已撤销(付款码支付)
	TradeStateUserPaying = "USERPAYING" // 用户支付中(付款码支付)
	TradeStatePayError   = "PAYERROR"   // 支付失败
)

支付订单状态(Order.TradeState)

View Source
const (
	RefundStatusSuccess  = "SUCCESS"  // 退款成功
	RefundStatusClosed   = "CLOSED"   // 退款关闭
	RefundStatusAbnormal = "ABNORMAL" // 退款异常
)

退款状态(RefundResponse.Status)

View Source
const (
	ProfitSharingStateProcessing = "PROCESSING" // 分账处理中
	ProfitSharingStateFinished   = "FINISHED"   // 分账处理完成
)

分账状态(ProfitSharingResponse.State)

View Source
const (
	ProfitSharingResultPending = "PENDING" // 待分账
	ProfitSharingResultSuccess = "SUCCESS" // 分账成功
	ProfitSharingResultClosed  = "CLOSED"  // 分账失败已关闭
)

分账接收方结果(ProfitSharingReceiverResult.Result)

View Source
const (
	ProfitSharingReturnProcessing = "PROCESSING" // 回退处理中
	ProfitSharingReturnSuccess    = "SUCCESS"    // 回退成功
	ProfitSharingReturnFailed     = "FAILED"     // 回退失败
)

分账回退结果(ProfitSharingReturnResponse.Result)

View Source
const (
	// NotificationAckCodeFail 处理失败应答的 code 值(官方唯一取值)
	NotificationAckCodeFail = "FAIL"
)

回调应答相关常量

说明:

  • 商户处理回调成功后必须应答 HTTP 204 + 空响应体(官方规范,勿返回 {"code":"SUCCESS"} 之类 JSON), 否则微信会按 15s/15s/30s/3m/10m/20m/30m/30m/30m/60m/3h/3h/3h/6h/6h/6h 的频率重试 15 次, 应答构造见 NotificationSuccess / NotificationFail
  • 处理失败需返回 4xx/5xx,响应体仅允许 {"code":"FAIL","message":"..."}(FAIL 为唯一取值)

Variables

View Source
var (
	// ErrNoEncryptKey 未配置微信支付公钥且无法获取平台证书,无法加密敏感信息
	ErrNoEncryptKey = errors.New("未配置微信支付公钥且无法获取平台证书,无法加密敏感信息")

	// ErrCertDownloadFailed 平台证书下载或解密失败
	ErrCertDownloadFailed = errors.New("平台证书下载失败")

	// ErrSignatureHeaderMissing 响应缺少微信支付签名头
	ErrSignatureHeaderMissing = errors.New("缺少微信支付响应签名头")

	// ErrAppIDNotSpecified 请求级与配置默认值都取不到 AppID
	// Config.AppID 是可选的(一个商户号可关联多个 AppID),所以每个需要 appid 的接口
	// 都必须在调用前解析出非空值,不能静默发空值给微信
	ErrAppIDNotSpecified = errors.New("AppID未指定:请在请求中传入 AppID 或在配置中设置 AppID")
)

微信支付模块预定义错误,业务可使用 errors.Is 判断

Functions

func EncryptSensitiveWithPublicKey

func EncryptSensitiveWithPublicKey(pubKey *rsa.PublicKey, plaintext string) (string, error)

EncryptSensitiveWithPublicKey 使用指定公钥加密敏感信息

参数:

  • pubKey: 微信支付公钥或平台证书公钥
  • plaintext: 明文

返回:

  • string: Base64 编码的密文
  • error: 明文为空或加密失败时返回错误

使用示例:

  • cipher, err := payment.EncryptSensitiveWithPublicKey(pubKey, "张三")

func IsAPIError

func IsAPIError(err error) bool

IsAPIError 判断错误是否为微信支付业务错误

参数:

  • err: 待判断的错误

返回:

  • bool: 是微信支付 APIError 时返回 true

func NotificationFail added in v0.2.0

func NotificationFail(w http.ResponseWriter, statusCode int, message string)

NotificationFail 写出微信支付回调处理失败的应答

参数:

  • w: HTTP 响应写入器
  • statusCode: HTTP 状态码(4xx/5xx,如 http.StatusInternalServerError)
  • message: 失败原因描述

说明:

  • 官方规范:失败应答体仅允许 {"code":"FAIL","message":"..."},FAIL 为唯一合法取值

使用示例:

  • payment.NotificationFail(w, http.StatusInternalServerError, "验签失败")

func NotificationSuccess added in v0.2.0

func NotificationSuccess(w http.ResponseWriter)

NotificationSuccess 写出微信支付回调处理成功的应答

参数:

  • w: HTTP 响应写入器

说明:

  • 官方规范:处理成功应答为 HTTP 204 + 空响应体,不要返回 {"code":"SUCCESS"} 之类的 JSON
  • 未按规范应答时,微信会按固定频率重试通知(最多 15 次)

使用示例:

  • payment.NotificationSuccess(w)

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

func AsAPIError(err error) (*APIError, bool)

AsAPIError 从错误链中提取微信支付业务错误

参数:

  • err: 待提取的错误

返回:

  • *APIError: 提取到的业务错误,非微信支付错误时返回 nil
  • bool: 是否提取成功

使用示例:

  • if apiErr, ok := payment.AsAPIError(err); ok { log.Println(apiErr.Code) }

func (*APIError) Error

func (e *APIError) Error() string

Error 实现 error 接口

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is 支持 errors.Is 按错误码比较

使用示例:

  • if errors.Is(err, &payment.APIError{Code: "ORDER_PAID"}) { ... }

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"` // 出错位置
}

APIErrorDetail 微信支付错误明细

type Amount

type Amount struct {
	Total         int    `json:"total"`                    // 订单总金额,单位为分
	Currency      string `json:"currency,omitempty"`       // 货币类型,默认 CNY
	PayerTotal    int    `json:"payer_total,omitempty"`    // 用户支付金额,单位为分(应答字段)
	PayerCurrency string `json:"payer_currency,omitempty"` // 用户支付货币类型(应答字段)
}

Amount 订单金额

说明:

  • 下单时仅需 Total(可附 Currency),PayerTotal/PayerCurrency 用于接收查单与 付款码支付同步返回中的实付金额(使用优惠券时 payer_total = total - 优惠金额)

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 端调起支付所需的参数

说明:

  • 字段名为官方 APIv3 要求的驼峰式,大小写敏感,需与微信开放平台 SDK 要求一致
  • Package 官方暂固定为 Sign=WXPay

type AppRequest

type AppRequest struct {
	AppID       string     `json:"appid"`                // 应用 ID,空则回落 Config.AppID,两者皆空报错
	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"` // 场景信息

	TimeExpire    string       `json:"time_expire,omitempty"`    // 交易过期时间(RFC3339 格式,如 2018-06-08T10:34:56+08:00)
	SupportFapiao bool         `json:"support_fapiao,omitempty"` // 是否支持开发票(true 时支付成功页出现开票入口,需开通电子发票功能)
	SettleInfo    *SettleInfo  `json:"settle_info,omitempty"`    // 结算信息(下单时声明是否分账,官方明确支付成功后无法补设)
	Detail        *OrderDetail `json:"detail,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 NewClient deprecated

func NewClient(config *Config, opts ...any) *Client

NewClient 创建新的微信支付客户端(使用默认文件存储)

参数:

  • config: 支付配置信息
  • opts: 可选参数,支持 debugger.LoggerInterface 与 core.HTTPClient

返回:

  • *Client: 支付客户端实例

Deprecated: 配置或私钥非法时会直接 log.Panic 终止进程,依赖库不应越权决定宿主进程生死。 请改用 NewClientE 显式处理错误。

func NewClientE

func NewClientE(config *Config, opts ...any) (*Client, error)

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) ApplyForElecsignByBillNo added in v0.2.0

func (c *Client) ApplyForElecsignByBillNo(ctx context.Context, transferBillNo string) (*TransferElecsignResponse, error)

ApplyForElecsignByBillNo 按微信转账单号申请转账电子回单

参数:

  • ctx: 上下文
  • transferBillNo: 微信转账单号

返回:

  • *TransferElecsignResponse: 申请受理结果
  • error: 请求失败或微信返回错误时返回错误

文档:

func (*Client) ApplyForElecsignByOutBillNo added in v0.2.0

func (c *Client) ApplyForElecsignByOutBillNo(ctx context.Context, outBillNo string) (*TransferElecsignResponse, error)

ApplyForElecsignByOutBillNo 按商户单号申请转账电子回单

参数:

  • ctx: 上下文
  • outBillNo: 商户单号(须为转账成功的单据)

返回:

  • *TransferElecsignResponse: 申请受理结果
  • error: 请求失败或微信返回错误时返回错误

说明:

  • 需传入收款用户姓名的转账单才支持电子回单(官方申请条件:单据状态 SUCCESS、传入收款用户姓名、六个月内)

文档:

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(appID, prepayID string) (*AppPayParams, error)

BuildAppPayParams 生成 App 端调起支付所需的参数

参数:

  • appID: 本次调起使用的应用 ID,传空则回落到配置中的 Config.AppID
  • prepayID: AppPay 返回的预支付交易会话标识

返回:

  • *AppPayParams: 含 sign 的调起支付参数,可直接交给客户端 SDK
  • error: appID 与配置默认值均为空、prepayID 为空或签名失败时返回错误

说明:

  • 官方签名串为四行:appid\ntimestamp\nnoncestr\nprepayid\n,不包含 partnerid 与 package
  • 客户端字段名为 appid、partnerid、prepayid、package、noncestr、timestamp、sign,大小写敏感
  • appID 必须与 AppPay 下单时实际使用的 AppID 一致(一个商户号可关联多个 AppID), 否则客户端调起时微信会以签名与订单不同源拒绝

使用示例:

  • prepay, _ := client.AppPay(ctx, req)
  • params, err := client.BuildAppPayParams(req.AppID, prepay.PrepayID)

文档:

func (*Client) BuildJSAPIPayParams

func (c *Client) BuildJSAPIPayParams(appID, prepayID string) (*JSAPIPayParams, error)

BuildJSAPIPayParams 生成前端调起 JSAPI 支付所需的参数

参数:

  • appID: 本次调起使用的应用 ID,传空则回落到配置中的 Config.AppID
  • prepayID: JSAPIPay 返回的预支付交易会话标识

返回:

  • *JSAPIPayParams: 含 paySign 的调起支付参数,可直接交给小程序 wx.requestPayment 或公众号 JS-SDK
  • error: appID 与配置默认值均为空、prepayID 为空或签名失败时返回错误

说明:

  • 签名串格式为:appId\ntimeStamp\nnonceStr\npackage\n
  • 参数大小写需与微信要求一致,前端字段名为 appId、timeStamp、nonceStr、package、signType、paySign
  • appID 必须与 JSAPIPay 下单及 openid 所属的 AppID 同源(一个商户号可关联多个 AppID), 否则前端调起时微信报「参数错误」且无法定位原因

使用示例:

  • prepay, _ := client.JSAPIPay(ctx, req)
  • params, err := client.BuildJSAPIPayParams(req.AppID, prepay.PrepayID)

文档:

func (*Client) CancelTransferBill added in v0.2.0

func (c *Client) CancelTransferBill(ctx context.Context, outBillNo string) (*TransferBillCancelResponse, error)

CancelTransferBill 撤销转账(仅用户确认收款前可撤销,撤销为异步处理)

参数:

  • ctx: 上下文
  • outBillNo: 商户单号

返回:

  • *TransferBillCancelResponse: 返回成功仅表示撤销请求已受理,最终以查询单据状态为准
  • error: 请求失败或微信返回错误时返回错误

文档:

func (*Client) CloseOrder

func (c *Client) CloseOrder(ctx context.Context, outTradeNo string) error

CloseOrder 关闭未支付的订单

参数:

  • ctx: 上下文
  • outTradeNo: 商户订单号

返回:

  • error: 关单失败时返回错误

说明:

  • 适用于用户取消订单或订单超时未支付的场景
  • 接口成功时微信返回 204 No Content,无响应体

使用示例:

  • if err := client.CloseOrder(ctx, "ORDER_20240101_001"); err != nil { return err }

文档:

func (*Client) CodePay added in v0.1.1

func (c *Client) CodePay(ctx context.Context, req *CodePayRequest) (*Order, error)

CodePay 付款码支付下单(B扫C:收银员用扫码设备读取顾客展示的付款码收款)

参数:

  • ctx: 上下文
  • req: 付款码支付下单请求(Payer.AuthCode 为顾客付款码,必填)

返回:

  • *Order: 订单结果,与查单接口同构;TradeState=SUCCESS 表示扣款成功(TransactionID 有值), TradeState=USERPAYING 表示用户支付中,需用 QueryOrder 轮询最终状态
  • error: 请求失败时返回错误;扣款失败(如余额不足)返回 *APIError,业务码可据此判断是否换码重扫

使用示例:

  • order, err := client.CodePay(ctx, &payment.CodePayRequest{ OutTradeNo: "ORDER_001", Amount: payment.Amount{Total: 100}, Description: "商品", Payer: payment.CodePayer{AuthCode: "1345235315201154982642655744"}, SceneInfo: &payment.CodePaySceneInfo{StoreInfo: &payment.CodePayStoreInfo{ID: "0001"}}, })
  • if order.TradeState == payment.TradeStateUserPaying { /* 轮询查单 */ }

文档:

注意:

  • 官方文档中心「付款码支付」产品页提示该产品文档以 V2 为准,V3 接口文档本身已提供, 接入前建议在商户后台实测验证
  • 结果通过同步应答与查单获取,官方参数表无 notify_url,不走异步通知

func (*Client) CreateTransferBill added in v0.2.0

func (c *Client) CreateTransferBill(ctx context.Context, req *TransferBillCreateRequest) (*TransferBillCreateResponse, error)

CreateTransferBill 发起商家转账(用户确认收款模式)

参数:

  • ctx: 上下文
  • req: 转账请求参数(UserName 如传入须为 EncryptSensitiveData 加密后的密文)

返回:

  • *TransferBillCreateResponse: 含 package_info,用于引导用户确认收款
  • error: 请求失败或微信返回错误时返回错误

使用示例:

userName, _ := client.EncryptSensitiveData(ctx, "张三")
resp, err := client.CreateTransferBill(ctx, &payment.TransferBillCreateRequest{
	AppID: "wx123", OutBillNo: "B20261022001", TransferSceneID: "1005",
	OpenID: "oXyz...", UserName: userName, TransferAmount: 100,
	TransferRemark: "10月佣金", NotifyURL: "https://example.com/notify",
})

文档:

func (*Client) DecryptNotificationResource

func (c *Client) DecryptNotificationResource(resource *Resource) ([]byte, error)

DecryptNotificationResource 解密微信支付回调通知资源

参数:

  • resource: 通知资源对象

返回:

  • []byte: 解密后的 JSON 数据
  • error: 解密失败时返回错误

func (*Client) DownloadBill

func (c *Client) DownloadBill(ctx context.Context, downloadURL, hashValue string) ([]byte, error)

DownloadBill 下载账单文件并校验完整性

参数:

  • ctx: 上下文
  • downloadURL: 申请账单接口返回的下载地址,5 分钟内有效
  • hashValue: 申请账单接口返回的哈希值,传空字符串表示跳过校验

返回:

  • []byte: 账单文件原始字节,tar_type 为 GZIP 时为压缩流
  • error: 下载失败或哈希校验不一致时返回错误

说明:

  • 官方下载账单响应不含签名头,故跳过验签

使用示例:

  • data, err := client.DownloadBill(ctx, bill.DownloadURL, bill.HashValue)

文档:

func (*Client) EncryptSensitiveData

func (c *Client) EncryptSensitiveData(ctx context.Context, plaintext string) (string, error)

EncryptSensitiveData 加密微信支付要求的敏感信息

参数:

  • ctx: 上下文
  • plaintext: 明文,如分账接收方姓名、身份证号等

返回:

  • string: Base64 编码的密文,可直接作为接口字段值
  • error: 无可用密钥或加密失败时返回错误

说明:

  • 使用 RSAES-OAEP 算法(SHA-1 + MGF1-SHA1),与微信支付官方要求一致
  • 优先使用配置的微信支付公钥,未配置时使用最新平台证书

使用示例:

  • name, err := client.EncryptSensitiveData(ctx, "张三")

func (*Client) EncryptSerialNo

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

EncryptSerialNo 返回当前用于敏感信息加密的 Wechatpay-Serial 值

参数:

  • ctx: 上下文

返回:

  • string: 微信支付公钥 ID 或平台证书序列号
  • error: 无可用密钥时返回错误

使用示例:

  • serial, err := client.EncryptSerialNo(ctx)

func (*Client) GetConfig

func (c *Client) GetConfig() *Config

GetConfig 获取支付配置

返回:

  • *Config: 支付配置副本指针

func (*Client) GetLogger

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

GetLogger 获取日志器

返回:

  • logger.LoggerInterface: 日志器实例

func (*Client) H5Pay

func (c *Client) H5Pay(ctx context.Context, req *H5Request) (*H5Response, error)

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) QueryElecsignByBillNo added in v0.2.0

func (c *Client) QueryElecsignByBillNo(ctx context.Context, transferBillNo string) (*TransferElecsignResponse, error)

QueryElecsignByBillNo 按微信转账单号查询电子回单申请进度

参数:

  • ctx: 上下文
  • transferBillNo: 微信转账单号

返回:

  • *TransferElecsignResponse: FINISHED 时返回 hash_type/hash_value/download_url
  • error: 请求失败或微信返回错误时返回错误

文档:

func (*Client) QueryElecsignByOutBillNo added in v0.2.0

func (c *Client) QueryElecsignByOutBillNo(ctx context.Context, outBillNo string) (*TransferElecsignResponse, error)

QueryElecsignByOutBillNo 按商户单号查询电子回单申请进度

参数:

  • ctx: 上下文
  • outBillNo: 商户单号

返回:

  • *TransferElecsignResponse: FINISHED 时返回 hash_type/hash_value/download_url
  • error: 请求失败或微信返回错误时返回错误

使用示例:

resp, err := client.QueryElecsignByOutBillNo(ctx, "B20261022001")
if err == nil && resp.State == payment.TransferElecsignStateFinished {
	// 下载 resp.DownloadURL 对应文件,并用 resp.HashType/resp.HashValue 校验完整性
}

文档:

func (*Client) QueryOrder

func (c *Client) QueryOrder(ctx context.Context, outTradeNo string) (*Order, error)

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) QueryTransferBillByBillNo added in v0.2.0

func (c *Client) QueryTransferBillByBillNo(ctx context.Context, transferBillNo string) (*TransferBillResponse, error)

QueryTransferBillByBillNo 按微信转账单号查询转账单

参数:

  • ctx: 上下文
  • transferBillNo: 微信转账单号

返回:

  • *TransferBillResponse: 单据详情
  • error: 请求失败或微信返回错误时返回错误

文档:

func (*Client) QueryTransferBillByOutBillNo added in v0.2.0

func (c *Client) QueryTransferBillByOutBillNo(ctx context.Context, outBillNo string) (*TransferBillResponse, error)

QueryTransferBillByOutBillNo 按商户单号查询转账单

参数:

  • ctx: 上下文
  • outBillNo: 商户单号

返回:

  • *TransferBillResponse: 单据详情(含状态、金额、失败原因等)
  • error: 请求失败或微信返回错误时返回错误

文档:

func (*Client) Refund

func (c *Client) Refund(ctx context.Context, req *RefundRequest) (*RefundResponse, error)

Refund 申请退款

参数:

  • ctx: 上下文
  • req: 退款请求参数

返回:

  • *RefundResponse: 退款结果
  • error: 请求失败时返回错误

文档:

func (*Client) RefundQuery

func (c *Client) RefundQuery(ctx context.Context, outRefundNo string) (*RefundResponse, error)

RefundQuery 按商户退款单号查询退款结果

参数:

  • ctx: 上下文
  • outRefundNo: 商户退款单号

返回:

  • *RefundResponse: 退款结果,Status 为 SUCCESS 表示退款成功
  • error: 请求失败时返回错误

使用示例:

  • refund, err := client.RefundQuery(ctx, "REFUND_20240101_001")

文档:

func (*Client) ReverseOrder added in v0.1.1

func (c *Client) ReverseOrder(ctx context.Context, appID, outTradeNo string) error

ReverseOrder 撤销订单(付款码支付配套)

参数:

  • ctx: 上下文
  • appID: 撤销请求所属的应用 ID,须与付款码下单时一致,传空则回落到配置中的 Config.AppID
  • outTradeNo: 商户订单号

返回:

  • error: appID 与配置默认值均为空、商户订单号为空或撤销失败时返回错误

说明:

  • 支付交易返回失败或支付系统超时时调用;USERPAYING(用户支付中)在途交易无法用 CloseOrder 关闭,只能撤销
  • 官方语义:订单用户支付失败时微信侧将订单关闭;用户支付成功时微信侧将订单资金退还给用户
  • 接口成功时微信返回 200 OK,应答含 appid/mchid/out_trade_no
  • appid 为官方必填项:取不到时直接本地报错,不会静默发空值后被微信拒

使用示例:

  • if err := client.ReverseOrder(ctx, req.AppID, "ORDER_20240101_001"); err != nil { return err }

文档:

注意:

  • 官方文档中心提示本功能处于灰度测试阶段、暂未全量开放,接入前建议在商户后台实测验证

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) TransferAfterUserAuth added in v0.2.0

func (c *Client) TransferAfterUserAuth(ctx context.Context, req *TransferAfterUserAuthRequest) (*TransferBillResponse, error)

TransferAfterUserAuth 用户授权后转账(用户完成授权后实际出款)

参数:

  • ctx: 上下文
  • req: 转账请求参数(UserName 如传入须为加密后的密文;AuthorizationID 与 OutAuthorizationNo 二选一)

返回:

  • *TransferBillResponse: 含最新单据状态
  • error: 请求失败或微信返回错误时返回错误

文档:

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 CodePayRequest added in v0.1.1

type CodePayRequest struct {
	AppID         string            `json:"appid"`                    // 应用 ID,空则回落 Config.AppID,两者皆空报错
	MchID         string            `json:"mchid"`                    // 商户号
	Description   string            `json:"description"`              // 商品描述
	OutTradeNo    string            `json:"out_trade_no"`             // 商户订单号
	Amount        Amount            `json:"amount"`                   // 订单金额
	Payer         CodePayer         `json:"payer"`                    // 支付者信息(付款码)
	Attach        string            `json:"attach,omitempty"`         // 附加数据
	GoodsTag      string            `json:"goods_tag,omitempty"`      // 订单优惠标记
	SupportFapiao bool              `json:"support_fapiao,omitempty"` // 电子发票入口开放标识(true 时支付成功页出现开票入口,需开通电子发票功能)
	Detail        *OrderDetail      `json:"detail,omitempty"`         // 订单优惠信息(单品优惠)
	SettleInfo    *SettleInfo       `json:"settle_info,omitempty"`    // 结算信息(分账标识)
	SceneInfo     *CodePaySceneInfo `json:"scene_info"`               // 场景信息(必填,含门店信息)
}

CodePayRequest 付款码支付下单请求(B扫C)

说明:

  • amount.total 必须大于 0,付款码支付不支持 0 元下单
  • 提交后同步返回订单结果(结构与查单一致):trade_state=SUCCESS 表示扣款成功, USERPAYING 表示用户输入密码中,需用 QueryOrder 轮询最终状态
  • USERPAYING 超时不再等待时,需调用撤销接口终止交易,避免用户后续输入密码意外扣款
  • 不支持 time_expire:付款码支付为即时扣款,无支付窗口概念
  • 官方 V3 文档参数表无 notify_url,结果通过同步应答与查单获取,不走异步通知
  • scene_info 必填,其下 store_info 必填(ID 与 OutID 二选一)

type CodePaySceneInfo added in v0.1.1

type CodePaySceneInfo struct {
	DeviceID  string            `json:"device_id,omitempty"` // 商户端设备号(门店号或收银设备 ID)
	DeviceIP  string            `json:"device_ip,omitempty"` // 商户端设备 IP
	StoreInfo *CodePayStoreInfo `json:"store_info"`          // 商户门店信息(必填)
}

CodePaySceneInfo 付款码支付场景信息

说明:

  • 官方 V3 文档中 codepay 的 scene_info 为必填,其下 store_info 亦必填

type CodePayStoreInfo added in v0.1.1

type CodePayStoreInfo struct {
	ID       string `json:"id,omitempty"`        // 门店编号:微信支付线下场所 ID,纯数字,与 OutID 二选一必填
	OutID    string `json:"out_id,omitempty"`    // 商户自定义编码:商户系统门店编码,与 ID 二选一必填
	Name     string `json:"name,omitempty"`      // 门店名称
	AreaCode string `json:"area_code,omitempty"` // 门店所在地行政区划码
	Address  string `json:"address,omitempty"`   // 门店详细地址
}

CodePayStoreInfo 付款码支付门店信息

说明:

  • ID 与 OutID 二选一必填:有微信支付线下场所 ID 传 ID,否则传商户自有门店编码 OutID
  • 官方要求线下条码支付必须传入用户实际付款的场景信息(合规要求)

type CodePayer added in v0.1.1

type CodePayer struct {
	AuthCode string `json:"auth_code"` // 授权码:扫码设备读取的顾客付款码(即用户微信钱包展示的付款码,10~15 开头为微信付款码码段)
}

CodePayer 付款码支付支付者信息

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

func (c *Config) UsePublicKey() bool

UsePublicKey 判断当前配置是否启用微信支付公钥验签

返回:

  • bool: PublicKeyID 与 PublicKey 均已配置时返回 true

使用示例:

  • if cfg.UsePublicKey() { fmt.Println("公钥模式") }

func (*Config) Validate

func (c *Config) Validate() error

Validate 验证配置的有效性

返回:

  • error: 配置无效时返回错误

说明:

  • AppID 为可选:它只是「请求级 AppID 未覆盖时的默认值」,一个商户号可关联多个 AppID (公众号/小程序/H5 各一个),多应用商户号建客户端时无需固定其一; 下单与调起签名方法在请求级与配置级都取不到 AppID 时会明确报错,不会静默发空值

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 GoodsDetail added in v0.1.1

type GoodsDetail struct {
	MerchantGoodsID  string `json:"merchant_goods_id"`            // 商户侧商品编码
	WxpayGoodsID     string `json:"wxpay_goods_id,omitempty"`     // 微信支付商品编码(付款码支付接口拼写,官方统一商品编号,没有可不传)
	WechatpayGoodsID string `json:"wechatpay_goods_id,omitempty"` // 微信支付商品编码(JSAPI/Native/App/H5 下单接口拼写)
	GoodsName        string `json:"goods_name,omitempty"`         // 商品名称
	Quantity         int    `json:"quantity"`                     // 商品数量
	UnitPrice        int    `json:"unit_price"`                   // 商品单价,单位为分(如有优惠传优惠后单价)
}

GoodsDetail 单品优惠明细(OrderDetail.GoodsDetail 元素)

说明:

  • 微信侧商品编码字段在官方不同接口文档中拼写不同:付款码支付(codepay)为 wxpay_goods_id,JSAPI/Native/App/H5 等下单接口为 wechatpay_goods_id, 按所用接口选择其一传入

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,空则回落 Config.AppID,两者皆空报错
	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"` // 附加数据
	SceneInfo   *SceneInfo `json:"scene_info"`       // H5 场景信息必填

	TimeExpire    string       `json:"time_expire,omitempty"`    // 交易过期时间(RFC3339 格式,如 2018-06-08T10:34:56+08:00)
	SupportFapiao bool         `json:"support_fapiao,omitempty"` // 是否支持开发票(true 时支付成功页出现开票入口,需开通电子发票功能)
	SettleInfo    *SettleInfo  `json:"settle_info,omitempty"`    // 结算信息(下单时声明是否分账,官方明确支付成功后无法补设)
	Detail        *OrderDetail `json:"detail,omitempty"`         // 订单优惠信息(单品优惠)
}

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,空则回落 Config.AppID,两者皆空报错
	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"` // 场景信息

	TimeExpire    string       `json:"time_expire,omitempty"`    // 交易过期时间(RFC3339 格式,如 2018-06-08T10:34:56+08:00)
	SupportFapiao bool         `json:"support_fapiao,omitempty"` // 是否支持开发票(true 时支付成功页出现开票入口,需开通电子发票功能)
	SettleInfo    *SettleInfo  `json:"settle_info,omitempty"`    // 结算信息(下单时声明是否分账,官方明确支付成功后无法补设)
	Detail        *OrderDetail `json:"detail,omitempty"`         // 订单优惠信息(单品优惠)
}

JSAPIRequest JSAPI 统一下单请求

type NativeRequest

type NativeRequest struct {
	AppID       string     `json:"appid"`                // 应用 ID,空则回落 Config.AppID,两者皆空报错
	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"` // 场景信息

	TimeExpire    string       `json:"time_expire,omitempty"`    // 交易过期时间(RFC3339 格式,如 2018-06-08T10:34:56+08:00)
	SupportFapiao bool         `json:"support_fapiao,omitempty"` // 是否支持开发票(true 时支付成功页出现开票入口,需开通电子发票功能)
	SettleInfo    *SettleInfo  `json:"settle_info,omitempty"`    // 结算信息(下单时声明是否分账,官方明确支付成功后无法补设)
	Detail        *OrderDetail `json:"detail,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"`            // 支付者信息
	PromotionDetail []PromotionDetail `json:"promotion_detail,omitempty"` // 优惠信息(走优惠活动时返回)
}

Order 查询订单响应

type OrderDetail added in v0.1.1

type OrderDetail struct {
	CostPrice   int           `json:"cost_price,omitempty"`   // 订单原价,单位为分(防止一张小票分多次支付套取优惠)
	InvoiceID   string        `json:"invoice_id,omitempty"`   // 商品小票 ID
	GoodsDetail []GoodsDetail `json:"goods_detail,omitempty"` // 单品列表,至少 1 条
}

OrderDetail 订单优惠信息(下单时的 detail 字段)

说明:

  • 有单品优惠活动的商户需要上传,否则可能无法享受优惠
  • 整体序列化后(压缩空格换行)不能超过 6144 字节

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
	CreateTime    string                        `json:"create_time,omitempty"` // 分账创建时间(RFC3339)
	FinishTime    string                        `json:"finish_time,omitempty"` // 分账完成时间(RFC3339,分账单完成时返回)
	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"`         // 商户回退单号
	ReturnID    string `json:"return_id,omitempty"`   // 微信分账回退单号
	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"` // 回退失败原因
	CreateTime  string `json:"create_time,omitempty"` // 分账回退创建时间(RFC3339)
	FinishTime  string `json:"finish_time,omitempty"` // 分账回退完成时间(RFC3339)
}

ProfitSharingReturnResponse 分账回退请求与查询结果响应

type ProfitSharingUnfreezeRequest

type ProfitSharingUnfreezeRequest struct {
	TransactionID string `json:"transaction_id"` // 微信支付订单号
	OutOrderNo    string `json:"out_order_no"`   // 商户分账单号
	Description   string `json:"description"`    // 解冻描述
}

ProfitSharingUnfreezeRequest 解冻剩余资金参数

type PromotionDetail added in v0.1.1

type PromotionDetail struct {
	CouponID            string                 `json:"coupon_id"`                      // 券 ID
	Name                string                 `json:"name,omitempty"`                 // 优惠名称
	Scope               string                 `json:"scope,omitempty"`                // 优惠范围:GLOBAL 全场代金券 / SINGLE 单品优惠
	Type                string                 `json:"type,omitempty"`                 // 优惠类型:CASH 充值型 / NOCASH 免充值型
	Amount              int                    `json:"amount"`                         // 优惠券面额,单位为分
	StockID             string                 `json:"stock_id,omitempty"`             // 活动 ID(批次 ID)
	WechatpayContribute int                    `json:"wechatpay_contribute,omitempty"` // 微信出资,单位为分
	MerchantContribute  int                    `json:"merchant_contribute,omitempty"`  // 商户出资,单位为分
	OtherContribute     int                    `json:"other_contribute,omitempty"`     // 其他出资,单位为分
	Currency            string                 `json:"currency,omitempty"`             // 优惠货币类型
	GoodsDetail         []PromotionGoodsDetail `json:"goods_detail,omitempty"`         // 单品列表
}

PromotionDetail 订单优惠信息(应答字段,下单走优惠活动时返回)

type PromotionGoodsDetail added in v0.1.1

type PromotionGoodsDetail struct {
	GoodsID        string `json:"goods_id"`               // 商品编码
	Quantity       int    `json:"quantity"`               // 商品数量
	UnitPrice      int    `json:"unit_price"`             // 商品单价,单位为分
	DiscountAmount int    `json:"discount_amount"`        // 商品优惠金额,单位为分
	GoodsRemark    string `json:"goods_remark,omitempty"` // 商品备注
}

PromotionGoodsDetail 优惠活动单品明细(PromotionDetail.GoodsDetail 元素)

type RefundAmount

type RefundAmount struct {
	Refund   int    `json:"refund"`             // 退款金额,单位为分
	Total    int    `json:"total"`              // 原订单金额,单位为分
	Currency string `json:"currency,omitempty"` // 币种,官方默认 CNY(必填性官方文档与 SDK 模型存在出入,按可选处理)
}

RefundAmount 退款金额

type RefundRequest

type RefundRequest struct {
	OutTradeNo    string       `json:"out_trade_no,omitempty"`   // 商户订单号(与 TransactionID 二选一)
	TransactionID string       `json:"transaction_id,omitempty"` // 微信支付订单号(与 OutTradeNo 二选一)
	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 回调通知资源对象

type ReverseOrderRequest added in v0.1.1

type ReverseOrderRequest struct {
	AppID string `json:"appid"` // 应用 ID,由 ReverseOrder 用入参或 Config.AppID 填入
	MchID string `json:"mchid"` // 商户号
}

ReverseOrderRequest 撤销订单请求(付款码支付配套)

说明:

  • 官方 V3 文档中 appid 与 mchid 均为必填

type SceneInfo

type SceneInfo struct {
	PayerClientIP string          `json:"payer_client_ip"`      // 用户终端 IP
	H5Info        *H5Info         `json:"h5_info,omitempty"`    // H5 场景信息
	DeviceID      string          `json:"device_id,omitempty"`  // 商户端设备号(门店号或收银设备 ID)
	StoreInfo     *SceneStoreInfo `json:"store_info,omitempty"` // 商户门店信息
}

SceneInfo 支付场景信息

type SceneStoreInfo added in v0.2.0

type SceneStoreInfo struct {
	ID   string `json:"id,omitempty"`   // 门店编号,商户侧门店编号
	Name string `json:"name,omitempty"` // 门店名称
}

SceneStoreInfo 下单场景门店信息(SceneInfo.StoreInfo)

说明:

  • ID 为官方必填(商户侧门店编号),Name 选填
  • 与付款码支付的 CodePayStoreInfo 不同:下单接口门店信息无 out_id

type SettleInfo added in v0.1.1

type SettleInfo struct {
	ProfitSharing bool `json:"profit_sharing,omitempty"` // 是否指定分账
}

SettleInfo 结算信息(下单时的 settle_info 字段)

说明:

  • ProfitSharing=true 表示订单支付成功后资金冻结,可调用请求分账 API 分账; false 或不传则资金直接进入可用余额
  • 需要分账的订单必须在下单时声明,支付成功后无法补设

type TransferAfterUserAuthRequest added in v0.2.0

type TransferAfterUserAuthRequest struct {
	AppID                    string                    `json:"appid"`                                 // 商户 AppID(须与商户号绑定)
	OutBillNo                string                    `json:"out_bill_no"`                           // 商户单号(数字/大小写字母,商户系统内唯一)
	TransferSceneID          string                    `json:"transfer_scene_id"`                     // 转账场景 ID(如 1000 现金营销、1005 佣金报酬、1006 企业报销)
	UserName                 string                    `json:"user_name,omitempty"`                   // 收款用户姓名(RSA 加密后的密文)
	TransferAmount           int64                     `json:"transfer_amount"`                       // 转账金额(单位:分)
	TransferRemark           string                    `json:"transfer_remark"`                       // 转账备注(UTF8,最长 32 字符,用户可见)
	UserRecvPerception       string                    `json:"user_recv_perception,omitempty"`        // 用户收款感知(如 "佣金报酬"、"现金奖励")
	TransferSceneReportInfos []TransferSceneReportInfo `json:"transfer_scene_report_infos,omitempty"` // 转账场景报备信息
	AuthorizationID          string                    `json:"authorization_id,omitempty"`            // 微信授权单据号(与 out_authorization_no 二选一)
	OutAuthorizationNo       string                    `json:"out_authorization_no,omitempty"`        // 商户授权单号(与 authorization_id 二选一)
}

TransferAfterUserAuthRequest 用户授权后转账请求(POST /v3/fund-app/mch-transfer/transfer-bills/transfer)

适用场景:用户在转账授权页完成授权后,商户凭授权单据实际出款(请求体不含 openid/notify_url)。

注意:

  • authorization_id 与 out_authorization_no 二选一必填(标识用户授权单据)
  • user_name 为敏感字段,请先通过 EncryptSensitiveData 加密后再传入
  • transfer_scene_report_infos 官方标注必填,需按转账场景准确填写

type TransferBillCancelResponse added in v0.2.0

type TransferBillCancelResponse struct {
	OutBillNo      string `json:"out_bill_no"`      // 商户单号
	TransferBillNo string `json:"transfer_bill_no"` // 微信转账单号
	State          string `json:"state"`            // 单据状态(CANCELING 撤销中 / CANCELLED 撤销完成)
	UpdateTime     string `json:"update_time"`      // 最后一次单据状态变更时间(rfc3339)
}

TransferBillCancelResponse 撤销转账响应

返回成功仅表示撤销请求已受理,系统异步处理,最终以查询单据状态为准。

type TransferBillCreateRequest added in v0.2.0

type TransferBillCreateRequest struct {
	AppID                    string                    `json:"appid"`                                 // 商户 AppID(须与商户号绑定)
	OutBillNo                string                    `json:"out_bill_no"`                           // 商户单号(数字/大小写字母,商户系统内唯一)
	TransferSceneID          string                    `json:"transfer_scene_id"`                     // 转账场景 ID(如 1000 现金营销、1005 佣金报酬、1006 企业报销)
	OpenID                   string                    `json:"openid"`                                // 收款用户 OpenID(AppID 下)
	UserName                 string                    `json:"user_name,omitempty"`                   // 收款用户姓名(RSA 加密后的密文)
	TransferAmount           int64                     `json:"transfer_amount"`                       // 转账金额(单位:分)
	TransferRemark           string                    `json:"transfer_remark"`                       // 转账备注(UTF8,最长 32 字符,用户可见)
	NotifyURL                string                    `json:"notify_url,omitempty"`                  // 回调通知地址(https)
	UserRecvPerception       string                    `json:"user_recv_perception,omitempty"`        // 用户收款感知(如 "佣金报酬"、"现金奖励")
	UserRecvStyle            *UserRecvStyle            `json:"user_recv_style,omitempty"`             // 用户收款样式(收款确认页/红包,不传默认收款确认页)
	TransferSceneReportInfos []TransferSceneReportInfo `json:"transfer_scene_report_infos,omitempty"` // 转账场景报备信息
}

TransferBillCreateRequest 发起转账请求(POST /v3/fund-app/mch-transfer/transfer-bills)

注意:

  • 用户确认收款模式:创建转账单后需引导用户确认收款(package_info 用于拉起收款确认页)
  • user_name 为敏感字段,请先通过 EncryptSensitiveData 加密后再传入(金额 >= 2000 元必填)
  • transfer_scene_report_infos 官方标注必填,需按转账场景准确填写(参考 https://pay.weixin.qq.com/doc/v3/merchant/4013774588)

type TransferBillCreateResponse added in v0.2.0

type TransferBillCreateResponse struct {
	OutBillNo      string `json:"out_bill_no"`      // 商户单号
	TransferBillNo string `json:"transfer_bill_no"` // 微信转账单号
	State          string `json:"state"`            // 单据状态(见 TransferStateXxx 常量,创建后一般为 WAIT_USER_CONFIRM)
	PackageInfo    string `json:"package_info"`     // 跳转微信收款确认页的 package 信息
	CreateTime     string `json:"create_time"`      // 单据创建时间(rfc3339)
}

TransferBillCreateResponse 发起转账响应

type TransferBillResponse added in v0.2.0

type TransferBillResponse struct {
	MchID          string `json:"mch_id"`                // 商户号
	OutBillNo      string `json:"out_bill_no"`           // 商户单号
	TransferBillNo string `json:"transfer_bill_no"`      // 微信转账单号
	AppID          string `json:"appid"`                 // 商户 AppID
	State          string `json:"state"`                 // 单据状态(见 TransferStateXxx 常量)
	TransferAmount int64  `json:"transfer_amount"`       // 转账金额(单位:分)
	TransferRemark string `json:"transfer_remark"`       // 转账备注
	OpenID         string `json:"openid,omitempty"`      // 收款用户 OpenID
	UserName       string `json:"user_name,omitempty"`   // 收款用户姓名(密文)
	FailReason     string `json:"fail_reason,omitempty"` // 失败原因(FAIL/已退资金时返回)
	CreateTime     string `json:"create_time"`           // 单据创建时间(rfc3339)
	UpdateTime     string `json:"update_time"`           // 最后一次状态变更时间(rfc3339)
}

TransferBillResponse 查询转账单响应

user_name 为密文;成功/失败终态时 fail_reason 可能有值。

type TransferElecsignApplyRequest added in v0.2.0

type TransferElecsignApplyRequest struct {
	OutBillNo      string `json:"out_bill_no,omitempty"`      // 商户单号(与微信转账单号二选一)
	TransferBillNo string `json:"transfer_bill_no,omitempty"` // 微信转账单号(与商户单号二选一)
}

TransferElecsignApplyRequest 申请电子回单请求

type TransferElecsignResponse added in v0.2.0

type TransferElecsignResponse struct {
	State       string `json:"state"`                  // 申请单状态(见 TransferElecsignStateXxx 常量)
	CreateTime  string `json:"create_time"`            // 申请单创建时间(rfc3339)
	UpdateTime  string `json:"update_time"`            // 申请单更新时间(rfc3339)
	HashType    string `json:"hash_type,omitempty"`    // 回单文件摘要类型(SHA256/SM3),FINISHED 时返回
	HashValue   string `json:"hash_value,omitempty"`   // 回单文件摘要值(FINISHED 时返回,用于校验文件完整性)
	DownloadURL string `json:"download_url,omitempty"` // 回单文件下载地址(FINISHED 时返回,有效期 10 分钟)
}

TransferElecsignResponse 电子回单申请/查询响应

state=FINISHED 时返回 hash_type/hash_value/download_url; download_url 有效期 10 分钟,过期后重新查询获取,不要自行拼接。

type TransferSceneReportInfo added in v0.2.0

type TransferSceneReportInfo struct {
	InfoType    string `json:"info_type"`    // 报备信息类型(场景 ID 对应的报备信息名称)
	InfoContent string `json:"info_content"` // 报备信息内容
}

TransferSceneReportInfo 商家转账场景报备信息项

type UserRecvStyle added in v0.2.0

type UserRecvStyle struct {
	Type string `json:"type"` // 用户收款样式类型
}

UserRecvStyle 用户收款样式(发起转账 user_recv_style)

说明:

  • 官方为对象结构,仅含样式类型;不传时默认按收款确认页样式展示
  • Type 取值:CONFIRM_PAGE 收款确认页样式 / RED_PACKET 红包样式 (红包单笔金额需 ≤200 元,仅部分转账场景可用,取值可能新增需兼容)

Jump to

Keyboard shortcuts

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