wxpay

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2020 License: Apache-2.0 Imports: 13 Imported by: 0

README

wxpay

微信支付Golang sdk v2版

使用方法:

支付

统一下单 UnifiedOrder
cfg := &wxpay.Config{
		AppID:      "wx11111111111",       // 微信分配的公众账号ID(企业号corpid即为此appId)
		MchID:      "138888888",           // 微信支付分配的商户号
		TradeType:  wxpay.TradeTypeNative, // 支付方式
		AppSecret:  "66666666666666666",   // APP密钥
		NotifyURL:  "www.example.com",     // 接收微信支付异步通知回调地址
		ServerAddr: "192.168.1.101",       // 当前服务器ip地址
	}

resp, err := wxpay.UnifiedOrder(cfg, "统一下单测试", "110000000001", 1, "", "")
APP支付 AppTrade
cfg := &wxpay.Config{
		AppID:      "wx11111111111",     // 微信分配的公众账号ID(企业号corpid即为此appId)
		MchID:      "138888888",         // 微信支付分配的商户号
		TradeType:  wxpay.TradeTypeApp,  // 支付方式
		AppSecret:  "66666666666666666", // APP密钥
		NotifyURL:  "www.example.com",   // 接收微信支付异步通知回调地址
		ServerAddr: "192.168.1.101",     // 当前服务器ip地址
	}

prepayID, err := wxpay.AppTrade(cfg, "APP支付测试", "100000000001", 1, "114.114.114.114")
公众号支付 JSAPITrade
cfg := &wxpay.Config{
		AppID:      "wx11111111111",      // 微信分配的公众账号ID(企业号corpid即为此appId)
		MchID:      "138888888",          // 微信支付分配的商户号
		TradeType:  wxpay.TradeTypeJSAPI, // 支付方式
		AppSecret:  "66666666666666666",  // APP密钥
		NotifyURL:  "www.example.com",    // 接收微信支付异步通知回调地址
		ServerAddr: "192.168.1.101",      // 当前服务器ip地址
	}

prepayID, err := wxpay.JSAPITrade(cfg, "公众号支付测试", "100000000001", 1, "xxxxxxxxxx", "114.114.114.114")
扫码支付 NativeTrade
cfg := &wxpay.Config{
		AppID:      "wx11111111111",     // 微信分配的公众账号ID(企业号corpid即为此appId)
		MchID:      "138888888",         // 微信支付分配的商户号
		TradeType:  wxpay.TradeTypeNative, // 支付方式
		AppSecret:  "66666666666666666", // APP密钥
		NotifyURL:  "www.example.com",   // 接收微信支付异步通知回调地址
		ServerAddr: "127.0.0.1",         // 当前服务器ip地址
	}

codeURL, err := wxpay.NativeTrade(cfg, "扫码支付测试", "100000000001")

Documentation

Index

Constants

View Source
const (
	// TradeTypeJSAPI 公众号支付
	TradeTypeJSAPI = "JSAPI"

	// TradeTypeNative 扫码支付
	TradeTypeNative = "NATIVE"

	// TradeTypeApp App支付
	TradeTypeApp = "APP"
)
View Source
const (
	// TradeStateSuccess 支付成功
	TradeStateSuccess = "SUCCESS"

	// TradeStateRefund 转入退款
	TradeStateRefund = "REFUND"

	// TradeStateNotPay 未支付
	TradeStateNotPay = "NOTPAY"

	// TradeStateSuccess 已关闭
	TradeStateClosed = "CLOSED"

	// TradeStateRevoked 已撤销(刷卡支付)
	TradeStateRevoked = "REVOKED"

	// TradeStateUserPaying 用户支付中
	TradeStateUserPaying = "USERPAYING"

	// TradeStateUserPayError 支付失败(其他原因,如银行返回失败)
	TradeStateUserPayError = "PAYERROR"
)
View Source
const (
	// UnifiedOrderAPI 统一下单接口
	UnifiedOrderAPI = "https://api.mch.weixin.qq.com/pay/unifiedorder"

	// OrderQueryAPI 查询订单接口
	OrderQueryAPI = "https://api.mch.weixin.qq.com/pay/orderquery"
)

Variables

View Source
var (
	RandChar          = []byte("abcdefghijklmnopqrstuvwxyz0123456789")
	RandCharLen int32 = 36
)

Functions

func AppTrade

func AppTrade(cfg *Config, body string, outTradeNo string, totalFee int, clientIP string) (string, error)

AppTrade App 支付

func JSAPITrade

func JSAPITrade(cfg *Config, body string, outTradeNo string, totalFee int, openID string, clientIP string) (string, error)

JSAPITrade 微信公众号支付

func NativeTrade

func NativeTrade(cfg *Config, body string, outTradeNo string, totalFee int) (string, error)

NativeTrade 扫码支付

func NewClient

func NewClient(cfg *Config) *http.Client

NewClient http 客户端

func NewRequest

func NewRequest(method string, urlStr string, param Parameter, key string) (*http.Request, error)

NewRequest 实例化一个request

func ParseResponse

func ParseResponse(response *http.Response, resp Responser, key string) error

ParseResponse 解析返回数据

func SendRequest

func SendRequest(client *http.Client, method string, urlStr string, param Parameter, resp Responser, key string) error

SendRequest 发送请求

Types

type Config

type Config struct {
	AppID      string        // 公众账号ID
	AppSecret  string        // AppSecret是APPID对应的接口密码
	MchID      string        // 商户号
	TradeType  string        // 交易类型
	NotifyURL  string        // 通知地址
	ServerAddr string        // 服务器地址
	TLSConfig  *tls.Config   // 证书
	Timeout    time.Duration // 请求超时时间
}

Config 配置

func (*Config) LoadTLSConfig

func (c *Config) LoadTLSConfig(crtFile, keyFile string) error

LoadTLSConfig 载入tls证书

type NotifyResponse

type NotifyResponse struct {
	Response `xml:",innerXml"`

	// OpenID 用户在商户appid下的唯一标识
	OpenID string `xml:"openid"`

	// IsSubscribe 用户是否关注公众账号,Y-关注,N-未关注,仅在公众账号类型支付有效
	IsSubscribe string `xml:"is_subscribe,omitempty"`

	// TradeType 调用接口提交的交易类型,取值如下:JSAPI,NATIVE,APP,MICROPAY,详细说明见参数规定
	TradeType string `xml:"trade_type"`

	// TradeState 交易状态 支付状态机请见下单API页面
	TradeState string `xml:"trade_state"`

	// BankType 银行类型,采用字符串类型的银行标识
	BankType string `xml:"bank_type"`

	// TotalFee 标价金额
	TotalFee int `xml:"total_fee"`

	// SettlementTotalFee 当订单使用了免充值型优惠券后返回该参数,应结订单金额=订单金额-免充值优惠券金额。
	SettlementTotalFee int `xml:"settlement_total_fee,omitempty"`

	// FeeType 货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
	FeeType string `xml:"fee_type,omitempty"`

	// CashFee 现金支付金额订单现金支付金额,详见支付金额
	CashFee int `xml:"cash_fee"`

	// CashFeeType 货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
	CashFeeType string `xml:"cash_fee_type,omitempty"`

	// CouponFee “代金券”金额<=订单金额,订单金额-“代金券”金额=现金支付金额,详见支付金额
	CouponFee int `xml:"coupon_fee"`

	// CouponCount 代金券使用数量
	CouponCount int `xml:"coupon_count"`

	// TransactionID 微信支付订单号
	TransactionID string `xml:"transaction_id"`

	// OutTradeNo 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@ ,且在同一个商户号下唯一。
	OutTradeNO string `xml:"out_trade_no"`

	// Attach 附加数据,原样返回
	Attach string `xml:"attach"`

	// TimeEnd 订单支付时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
	TimeEnd string `xml:"time_end"`

	// TradeStateDesc 对当前查询订单状态的描述和下一步操作的指引
	TradeStateDesc string `xml:"trade_state_desc"`
}

NotifyResponse 回调数据

func Notify

func Notify(cfg *Config, req *http.Request) (resp *NotifyResponse, err error)

Notify 异步回调

func (*NotifyResponse) IsPaid

func (r *NotifyResponse) IsPaid() bool

IsPaid 是否支付成功

type OrderQueryParam

type OrderQueryParam struct {
	Param `xml:",innerXml"`

	// TransactionID 微信的订单号,建议优先使用
	TransactionID string `xml:"transaction_id"`

	// OutTradeNo 商户订单号
	OutTradeNo string `xml:"out_trade_no"`
}

OrderQueryParam 查询订单参数

func (*OrderQueryParam) Valid

func (p *OrderQueryParam) Valid() error

Valid 参数校验

type OrderQueryResponse

type OrderQueryResponse struct {
	Response `xml:",innerXml"`

	// OpenID 用户在商户appid下的唯一标识
	OpenID string `xml:"openid"`

	// IsSubscribe 用户是否关注公众账号,Y-关注,N-未关注,仅在公众账号类型支付有效
	IsSubscribe string `xml:"is_subscribe,omitempty"`

	// TradeType 调用接口提交的交易类型,取值如下:JSAPI,NATIVE,APP,MICROPAY,详细说明见参数规定
	TradeType string `xml:"trade_type"`

	// TradeState 交易状态 支付状态机请见下单API页面
	TradeState string `xml:"trade_state"`

	// BankType 银行类型,采用字符串类型的银行标识
	BankType string `xml:"bank_type"`

	// TotalFee 标价金额
	TotalFee int `xml:"total_fee"`

	// SettlementTotalFee 当订单使用了免充值型优惠券后返回该参数,应结订单金额=订单金额-免充值优惠券金额。
	SettlementTotalFee int `xml:"settlement_total_fee,omitempty"`

	// FeeType 货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
	FeeType string `xml:"fee_type,omitempty"`

	// CashFee 现金支付金额订单现金支付金额,详见支付金额
	CashFee int `xml:"cash_fee"`

	// CashFeeType 货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
	CashFeeType string `xml:"cash_fee_type,omitempty"`

	// CouponFee “代金券”金额<=订单金额,订单金额-“代金券”金额=现金支付金额,详见支付金额
	CouponFee int `xml:"coupon_fee"`

	// CouponCount 代金券使用数量
	CouponCount int `xml:"coupon_count"`

	// TransactionID 微信支付订单号
	TransactionID string `xml:"transaction_id"`

	// OutTradeNo 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@ ,且在同一个商户号下唯一。
	OutTradeNO string `xml:"out_trade_no"`

	// Attach 附加数据,原样返回
	Attach string `xml:"attach"`

	// TimeEnd 订单支付时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
	TimeEnd string `xml:"time_end"`

	// TradeStateDesc 对当前查询订单状态的描述和下一步操作的指引
	TradeStateDesc string `xml:"trade_state_desc"`
}

OrderQueryParam 查询订单返回数据结构

func OrderQuery

func OrderQuery(cfg *Config, transactionID string, outTradeNo string) (resp *OrderQueryResponse, err error)

OrderQuery 查询订单

type Param

type Param struct {
	XMLName xml.Name `xml:"xml"`

	// AppID 微信支付分配的公众账号ID(企业号corpid即为此appId)
	AppID string `xml:"appid"`

	// MchID 微信支付分配的商户号
	MchID string `xml:"mch_id"`

	// DeviceInfo 自定义参数,可以为终端设备号(门店号或收银设备ID),PC网页或公众号内支付可以传"WEB"
	DeviceInfo string `xml:"device_info"`

	// NonceStr 随机字符串,长度要求在32位以内。推荐随机数生成算法
	NonceStr string `xml:"nonce_str"`

	// Sign 通过签名算法计算得出的签名值,详见签名生成算法
	Sign string `xml:"sign"`

	// SignType 签名类型,默认为MD5,支持HMAC-SHA256和MD5。
	SignType string `xml:"sign_type,omitempty"`
}

Param 参数

func NewParam

func NewParam(cfg *Config) Param

NewParam 参数

func (*Param) SetSign

func (p *Param) SetSign(sign string)

SetSign 设置Sign

func (*Param) Valid

func (p *Param) Valid() error

Valid 参数校验

type Parameter

type Parameter interface {
	Valid() error
	SetSign(sign string)
}

Parameter 接口

type Response

type Response struct {
	XMLName    xml.Name `xml:"xml"`
	ReturnCode string   `xml:"return_code"`
	ReturnMsg  string   `xml:"return_msg"`
	AppId      string   `xml:"appid"`        // 公众账号ID
	MchId      string   `xml:"mch_id"`       // 商户号
	DeviceInfo string   `xml:"device_info"`  // 设备号
	NonceStr   string   `xml:"nonce_str"`    // 随机字符串
	Sign       string   `xml:"sign"`         // 签名
	SignType   string   `xml:"sign_type"`    // 签名类型
	ResultCode string   `xml:"result_code"`  // 业务结果
	ErrCode    string   `xml:"err_code"`     // 错误码
	ErrCodeDes string   `xml:"err_code_des"` // 错误描述
}

Response 业务返回

func (Response) CheckReturn

func (r Response) CheckReturn() error

CheckReturn 此字段是通信标识,非交易标识,交易是否成功需要查看trade_state来判断

func (Response) IsResultOK

func (r Response) IsResultOK() bool

IsResultOK 返回成功

type Responser

type Responser interface {
	CheckReturn() error
}

Responser 验证

type SceneInfo

type SceneInfo struct {
	// ID 门店唯一标识
	ID string `json:"id"`

	// Name 门店名称
	Name string `json:"name"`

	// AreaCode 门店所在地行政区划码,详细见《最新县及县以上行政区划代码》
	AreaCode string `json:"areaCode"`

	// Address 门店详细地址
	Address string `json:"address"`
}

SceneInfo 场景信息

type UnifiedOrderParam

type UnifiedOrderParam struct {
	Param `xml:",innerXml"`

	// Body 商品简单描述,该字段请按照规范传递,具体请见参数规定
	Body string `xml:"body"`

	// Detail 商品详细描述,对于使用单品优惠的商户,改字段必须按照规范上传,详见“单品优惠参数说明”
	Detail string `xml:"detail"`

	// Attach 附加数据,在查询API和支付通知中原样返回,可作为自定义参数使用。
	Attach string `xml:"attach"`

	// OutTradeNo 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|* 且在同一个商户号下唯一。详见商户订单号
	OutTradeNo string `xml:"out_trade_no"`

	// FeeType 符合ISO 4217标准的三位字母代码,默认人民币:CNY,详细列表请参见货币类型
	FeeType string `xml:"fee_type"`

	// TotalFee 订单总金额,单位为分,详见支付金额
	TotalFee int `xml:"total_fee"` // 订单总金额,单位为分,详见支付金额

	// SpbillCreateIP APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP。
	SpbillCreateIP string `xml:"spbill_create_ip"`

	// TimeStart 订单生成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
	TimeStart string `xml:"time_start"`

	// TimeExpire 订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。
	// 订单失效时间是针对订单号而言的,由于在请求支付的时候有一个必传参数prepay_id只有两小时的有效期,所以在重入时间超过2小时的时候需要重新请求下单接口获取新的prepay_id。
	// 其他详见时间规则 建议:最短失效时间间隔大于1分钟
	TimeExpire string `xml:"time_expire"`

	// GoodsTag 订单优惠标记,使用代金券或立减优惠功能时需要的参数,说明详见代金券或立减优惠
	GoodsTag string `xml:"goods_tag"`

	// NotifyURL 异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。
	NotifyURL string `xml:"notify_url"`

	// TradeType 说明详见参数规定
	// JSAPI 公众号支付 NATIVE 扫码支付 APP APP支付
	TradeType string `xml:"trade_type"`

	// ProductID trade_type=NATIVE时(即扫码支付),此参数必传。此参数为二维码中包含的商品ID,商户自行定义。
	ProductID string `xml:"product_id"`

	// LimitPay 上传此参数no_credit--可限制用户不能使用信用卡支付
	LimitPay string `xml:"limit_pay"`

	// OpenID trade_type=JSAPI时(即公众号支付),此参数必传,此参数为微信用户在商户对应appid下的唯一标识。
	// openid如何获取,可参考【获取openid】。 企业号请使用【企业号OAuth2.0接口】获取企业号内成员userid,再调用【企业号userid转openid接口】进行转换
	OpenID string `xml:"openid"`

	// SceneInfo 该字段用于上报场景信息,目前支持上报实际门店信息。
	// 该字段为JSON对象数据,对象格式为{"store_info":{"id": "门店ID","name": "名称","area_code": "编码","address": "地址" }} ,字段详细说明请点击行前的展开
	SceneInfo string `xml:"scene_info"`
}

UnifiedOrderParam 参数

func (*UnifiedOrderParam) Valid

func (p *UnifiedOrderParam) Valid() error

Valid 验证

type UnifiedOrderResponse

type UnifiedOrderResponse struct {
	Response `xml:",innerXml"`

	TradeType string `xml:"trade_type"` // 交易类型
	PrepayID  string `xml:"prepay_id"`  // 预支付交易会话标识
	CodeURL   string `xml:"code_url"`   // 二维码链接
}

UnifiedOrderResponse 统一下单返回

func UnifiedOrder

func UnifiedOrder(cfg *Config, body string, outTradeNo string, totalFee int, openID string, clientIP string) (resp *UnifiedOrderResponse, err error)

UnifiedOrder 统一下单接口

Jump to

Keyboard shortcuts

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