wechatpay

package module
v3.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2021 License: Apache-2.0 Imports: 18 Imported by: 6

README

WechatPay GO(v3)

License CI codecov GoDoc Go Report Card

Introduction

Wechat Pay SDK(V3) Write by Go. API V3 of Office document is here.

Features

  • Signature/Verify messages
  • Encrypt/Decrypt cert
  • APIv3 Endpoints
  • None third-party dependency package

When developing, you can use the Makefile for doing the following operations:

Endpoint Description supported
pay Merchant send the payment transaction
query Merchant query payment transactions
close Merchant close the payment transaction
notify WeChat Pay notifies the merchant of the user's payment status
certificate obtain the platform cert and decrypt it to public key
tradebill obtain the download url of trade bill
fundflowbill obtain the download url of trade bill
refund Merchant send the refund transaction
refundquery Merchant query payment transactions
refundnotify WeChat Pay notifies the merchant of the refund status
combine pay Merchant send the combine payment, includes some sub transcation
combine close Merchant close the combine payment transactions
combine query Merchant query the combine payment transaction

Getting Started

Prepare your wechatp pay information, it includes App Id/Mech Id/Apiv3 Secret/Serial Number/Private Key Cert. You can find a getting started guide as shown below:

  1. import package
import "github.com/gunsluo/wechatpay-go/v3"
  1. use wechatpay-go package
// create a client of wechat pay
client, err := wechatpay.NewClient(
    wechatpay.Config{
       ...
    })

// create a pay request
req := &wechatpay.PayRequest{
    AppId:       appId,
    MchId:       mchId,
    Description: "for testing",
        ...
    TradeType: wechatpay.Native,
}

resp, err := req.Do(r.Context(), client)
if err != nil {
    // do something
}
codeUrl := resp.CodeUrl
Config

Click Wechat Pay and apply your account and configuration.

wechatpay.Config{
    AppId:       appId,
    MchId:       mchId,
    Apiv3Secret: apiv3Secret,
    Cert: wechatpay.CertSuite{
        SerialNo:       serialNo,
        PrivateKeyPath: privateKeyPath,
    },
}
Payment

Create a pay request and send it to wechat pay service.

req := &wechatpay.PayRequest{
    Description: "for testing",
    OutTradeNo:  tradeNo,
    TimeExpire:  time.Now().Add(10 * time.Minute),
    Attach:      "cipher code",
    NotifyUrl:   notifyURL,
    Amount: wechatpay.PayAmount{
        Total:    int(amount * 100),
        Currency: "CNY",
    },
    TradeType: wechatpay.Native,
}

resp, err := req.Do(r.Context(), payClient)
if err != nil {
    e := &wechatpay.Error{}
    if errors.As(err, &e) {
        fmt.Println("status", e.Status, "code:", e.Code, "message:", e.Message)
    }
    return
}
codeUrl := resp.CodeUrl
// use this code url to generate qr code
Notify

Receive the notification from wechat pay, use ParseHttpRequest or Parse to get notification information.

func notifyForPay(w http.ResponseWriter, r *http.Request) {
    notification := &wechatpay.PayNotification{}
    trans, err := notification.ParseHttpRequest(payClient, r)

    ...
}

func notifyForRefund(w http.ResponseWriter, r *http.Request) {
    notification := &wechatpay.RefundNotification{}
    trans, err := notification.ParseHttpRequest(payClient, r)

    ...
}

There is a full example for wechatpay-go.

Download

download bill and unpack data. Download get the decrypted byte array, UnmarshalDownload get a struct data.

req := wechatpay.TradeBillRequest{
    BillDate: billDate,
    BillType: wechatpay.AllBill,
    TarType:  wechatpay.GZIP,
}

ctx := context.Background()
data, err := req.Download(ctx, payClient)
//resp, err := req.UnmarshalDownload(ctx, payClient)

Contributing

See the contributing documentation.

Documentation

Overview

Package wechatpay implements V3 endpoints for wechat pay. It is general SDK and provides the featrues, such as pay/query/close/notify transaction, refund/download bill.

As a quick start:

client, err := NewClient(Config{})
// check error

If you want to apply a pay request, use PayRequest

// create a pay request
req := &.PayRequest{
	AppId:       appId,
	MchId:       mchId,
	Description: "for testing",
	TradeType: .Native,
}

resp, err := req.Do(r.Context(), client)
if err != nil {
	// do something
}
codeUrl := resp.CodeUrl

Index

Examples

Constants

View Source
const (
	UserPaying           = "USERPAYING"
	TradeError           = "TRADE_ERROR"
	SystemError          = "SYSTEMERROR"
	SignError            = "SIGN_ERROR"
	RuleLimit            = "RULELIMIT"
	ParamError           = "PARAM_ERROR"
	OutTradeNoUsed       = "OUT_TRADE_NO_USED"
	OrderNotExist        = "ORDERNOTEXIST"
	OrderClosed          = "ORDER_CLOSED"
	OpenidMismatch       = "OPENID_MISMATCH"
	NotEnough            = "NOTENOUGH"
	NoAuth               = "NOAUTH"
	MchNotExists         = "MCH_NOT_EXISTS"
	InvalidTransactionid = "INVALID_TRANSACTIONID"
	InvalidRequest       = "INVALID_REQUEST"
	FrequencyLimited     = "FREQUENCY_LIMITED"
	BankError            = "BANKERROR"
	AppidMchidNotMatch   = "APPID_MCHID_NOT_MATCH"
	AccountError         = "ACCOUNTERROR"
)
View Source
const (
	TradeStateSuccess    = "SUCCESS"
	TradeStateRefund     = "REFUND"
	TradeStateNotPay     = "NOTPAY"
	TradeStateClosed     = "CLOSED"
	TradeStateRevoked    = "REVOKED"
	TradeStateUserPaying = "USERPAYING"
	TradeStatePayError   = "PAYERROR"
	TradeStateAccept     = "ACCEPT"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AccountType

type AccountType string

AccountType is account type.

const (
	BasicAccount     AccountType = "BASIC"
	OperationAccount AccountType = "OPERATION"
	FEESAccount      AccountType = "FEES"
)

type AllTradeBill

type AllTradeBill struct {
	TradeTime          string
	AppId              string
	MchId              string
	SpecialMechId      string
	DeviceId           string
	TransactionId      string
	OutTradeNo         string
	OpenId             string
	TardeType          string
	TradeState         string
	BankType           string
	Currency           string
	SettlementTotalFee float64
	CouponAmount       float64
	PayerRefundId      string
	MerchantRefundId   string
	RefundAmount       float64
	CouponRefundAmount float64
	RefundType         string
	RefundStatus       string
	GoodName           string
	Attach             string
	CommissionFee      float64
	Rate               string
	Amount             float64
	RefundApplyAmount  float64
	RateComment        string
}

AllTradeBill is data for all trade bill.

func UnmarshalAllTradeBill

func UnmarshalAllTradeBill(values []string) (*AllTradeBill, error)

UnmarshalAllTradeBill parses the bill data and stores the result in the bill.

type BillType

type BillType string

BillType is bill type

const (
	AllBill     BillType = "ALL"
	SuccessBill BillType = "SUCCESS"
	RefundBill  BillType = "REFUND"
)

type CertSuite

type CertSuite struct {
	SerialNo       string
	PrivateKeyTxt  string
	PrivateKeyPath string
}

CertSuite is the suite for api cert.

type Certificate

type Certificate struct {
	SerialNo      string             `json:"serial_no"`
	EffectiveTime string             `json:"effective_time"`
	ExpireTime    string             `json:"expire_time"`
	Encrypt       EncryptCertificate `json:"encrypt_certificate"`
}

Certificate is certificate information

type CertificatesRequest

type CertificatesRequest struct {
}

CertificatesRequest is the request for certificates.

func (*CertificatesRequest) Do

Do get certificates from wechat pay.

type CertificatesResponse

type CertificatesResponse struct {
	Certificates []Certificate `json:"data"`
}

CertificatesResponse is the response for certificates.

type Client

type Client interface {
	Config() *Config
	Do(context.Context, string, string, ...interface{}) *Result
	ParseNotification(context.Context, *Result) (*Notification, []byte, error)
	Download(ctx context.Context, u *FileUrl) ([]byte, error)
}

client is wechat pay client for api v3.

func NewClient

func NewClient(cfg Config, opts ...Option) (Client, error)

NewClient creates a new client with configuration from cfg. Config includes App Id/Mech Id/Apiv3 Secret/Serial Number and Private Key Cert. Create a new client:

client, err := NewClient(Config{})
// check error
Example
appId := "wxd678efh567hg6787"
mchId := "1230000109"
apiv3Secret := "AES256Key-32Characters1234567890"
serialNo := "477ED0046A54F0360A72A63A8F2816312AAEAB53"
privateKeyTxt := `-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCprsmcXPHqLtnP
oPDGUoMULK2WOo5FW8c72Svnqn/4aXPaJhlOtPxtX2frqIhTjwcOs6hNm3XFTGBL
MrdB94YQvj+Q7P12GNmxXG+9Ms+uUyJToYjlYDAG6UFKE10Jkm9cDGuLSkekU1Ao
rKE1G1wndH37w4AzVXoGBQ3NIiyW8jIm8Zi3/WNCVpHUoXYUuyhFEZ23fXytnps4
hARgg6NvPncIKtWvlUh85ZVOSsqc1T8dFaeDRXaj7r3jdJJ74tsGRMvZyUipJXyE
3uR2QkrGyia+0phDpC6zeMMpP+MQO9ohh+xQWBCeyvQjjnOPAlGThl+ThfXImU30
HL17oHdBAgMBAAECggEADm6FSz1Efgx6DgS8NcHy0BZ0tSBJ1XBW46o2579Cnxgo
+FbhNCaEibDhn9N3tNOnYAK7v84HGD7EueCYYY3x4x6rPWJKtG6spT8dadQWgdck
RkSo5glmTFAuc2RuN1AzFHsh8njg2wMTAEKee2vWTKzFwlIAZ11PwY9Qey/65uOT
Bi8q1Rssu6xofNadO5MbqMJ1Tl8DDIaLGnzTzbHrk9thBUo1FwFjJWTVI7nz2En4
Yc/G1/LQJfiQ31F+lkL3j6ABRJqtsgb07r9H/hT6+fd1hGDt2qKuS+E1mLDp9fHw
n6UyS4HyB7DA/XtFZ9z0VtAlmcGoUkyJLtXjEmwsGQKBgQDeCtE3spULpC7VPqk1
xv034C6zybZ7y8kSKwRvyYwkzdgSRgVaKsTVb8RNYor8hoGrVgdXFqQUI8O/v1cN
9wFoGYJT0LHre/YzOg31TkQkBfHHCFH/L50uOJcIQueftctz5Bwj6bJO/ih5iIAK
yjrHse4PdIiEJfz2D9hc4wnxrwKBgQDDogrWlUCTj2fvmZfkWR3Hbs0kIHd7zjIk
bJJONGtD8gE4i562tajC1mKoQEwt4YSwWsBkGAw1LhvMROQFT6AOaIIhHNex1Z3t
c2gAdEeWOMmzZnnhwWzTiYJomixrFkmEwT3EJK89GO3E0FH5S+G1P1tNXq38Vpty
1YVqOgMSDwKBgFrzuWGEQDMljJ2C7lL98KlbpiW1AY/SGMndXxLfTw2gV9qcXgLi
NABtqM4+CEqKWkExmw4cUxeA0uUPXnx06lmW4WCtwsN/4oh3RlJuPdE3siLiEJxk
B5FwUsVqinBMSktta+12A7kBuNiXhkNlNRCpnKcuB+GBog20zd62jVM3AoGBALcA
zFazQ7dFfRq7eUUYwCyhT7Et1dewqWM9VRdnHbhvmAjHQu7zvCyW069Ehn6c6bz3
B+YaQME2orZQ82SsebNAvAoxquwmQhevz2gtXhH+iWASyo0Onbi8d4tWPZrnPFq9
UgQ7tNnYigOEREqKW1drLwOPP/4/Hicr6iPWpKytAoGAEQ6J/RB/olEAC46ACoFo
FBgA+GUbDB0xBcA2inEt3q//208YMkjnKM871n89HpAgms5xrK32T69lduebk7Ar
9wWvkJVUwI9VDXomCFQqtiGzHlTl1Xq31BfeIDyq1ayQmTkRpRqIagbDZVtM+ha/
0I2SEzTObt07wcYcYG2Chvg=
-----END PRIVATE KEY-----`
client, _ := NewClient(
	Config{
		AppId:       appId,
		MchId:       mchId,
		Apiv3Secret: apiv3Secret,
		Cert: CertSuite{
			SerialNo:      serialNo,
			PrivateKeyTxt: privateKeyTxt,
		},
	})

fmt.Println(client != nil)
Output:

true

type CloseRequest

type CloseRequest struct {
	MchId      string `json:"mchid"`
	OutTradeNo string `json:"-"`
}

CloseRequest is the request for close transaction.

func (*CloseRequest) Do

func (r *CloseRequest) Do(ctx context.Context, c Client) error

Do send the request of close transaction.

type CloseSubOrder added in v3.1.0

type CloseSubOrder struct {
	MchId      string `json:"mchid"`
	OutTradeNo string `json:"out_trade_no"`
}

CloseSubOrder is the order under the combine close transcation

type CombineCloseRequest added in v3.1.0

type CombineCloseRequest struct {
	AppId      string          `json:"combine_appid"`
	OutTradeNo string          `json:"combine_out_trade_no"`
	Orders     []CloseSubOrder `json:"sub_orders,omitempty"`
}

CombineCloseRequest is the request for close transaction.

func (*CombineCloseRequest) Do added in v3.1.0

Do send the request of combine close transaction.

type CombinePayAmount added in v3.1.0

type CombinePayAmount struct {
	Total    int    `json:"total_amount"`
	Currency string `json:"currency,omitempty"`
}

CombinePayAmount is total amount paid, have total and currency.

type CombinePayRequest added in v3.1.0

type CombinePayRequest struct {
	AppId      string        `json:"combine_appid"`
	MchId      string        `json:"combine_mchid"`
	OutTradeNo string        `json:"combine_out_trade_no"`
	TimeStart  time.Time     `json:"time_start,omitempty"`
	TimeExpire time.Time     `json:"time_expire,omitempty"`
	NotifyUrl  string        `json:"notify_url"`
	SceneInfo  *PaySceneInfo `json:"scene_info,omitempty"`
	Payer      *Payer        `json:"combine_payer_info,omitempty"`
	Orders     []SubOrder    `json:"sub_orders,omitempty"`
	TradeType  TradeType     `json:"-"`
}

CombinePayRequest is request when send a combin payment.

func (*CombinePayRequest) Do added in v3.1.0

Do send a transaction and invoke wechat payment.

type CombinePayResponse added in v3.1.0

type CombinePayResponse struct {
	// The CodeUrl is returned when the merchant used Native
	CodeUrl string `json:"code_url"`
	// The CodeUrl is returned when the merchant used JSAPI APP
	PrepayId string `json:"prepay_id"`
	// The CodeUrl is returned when the merchant used H5
	H5Url string `json:"h5_url"`
}

CombinePayResponse is response when send a combine payment.

type CombineQueryRequest added in v3.1.0

type CombineQueryRequest struct {
	OutTradeNo string `json:"combine_out_trade_no"`
}

CombineQueryRequest is the request for query transaction.

func (*CombineQueryRequest) Do added in v3.1.0

Do send the request of query transaction.

type CombineQueryResponse added in v3.1.0

type CombineQueryResponse struct {
	AppId      string                `json:"combine_appid"`
	MchId      string                `json:"combine_mchid"`
	OutTradeNo string                `json:"combine_out_trade_no"`
	SceneInfo  *TransactionSceneInfo `json:"scene_info,omitempty"`
	Orders     []QuerySubOrder       `json:"sub_orders,omitempty"`
	Payer      *Payer                `json:"combine_payer_info,omitempty"`
}

CombineQueryResponse is the response for query transaction.

type CombineSubOrderAmount added in v3.1.0

type CombineSubOrderAmount struct {
	Total         int    `json:"total_amount,omitempty"`
	PayerTotal    int    `json:"payer_total,omitempty"`
	Currency      string `json:"currency,omitempty"`
	PayerCurrency string `json:"payer_currency,omitempty"`
}

CombineSubOrderAmount is tatal amount paid, have total and currency.

type Config

type Config struct {
	AppId string
	MchId string
	Cert  CertSuite

	Apiv3Secret string
	// contains filtered or unexported fields
}

Config is config for wechat pay, all fields is required.

func (*Config) Options

func (c *Config) Options() *options

Options return the options

type EncryptCertificate

type EncryptCertificate struct {
	Algorithm  string `json:"algorithm"`
	Nonce      string `json:"nonce"`
	Associated string `json:"associated_data"`
	CipherText string `json:"ciphertext"`
}

EncryptCertificate is the information of encrypt certificate.

type Error

type Error struct {
	Status  int    `json:"status"`
	Code    string `json:"code"`
	Message string `json:"message"`
}

Error is more detail error of wechat pay.

func (*Error) Error

func (e *Error) Error() string

Error implement Error function for err.

type FileUrl

type FileUrl struct {
	HashType    string `json:"hash_type"`
	HashValue   string `json:"hash_value"`
	DownloadUrl string `json:"download_url"`
}

FileUrl is url of the file, it is used download file.

type FundFlowBill

type FundFlowBill struct {
	AccountingTime      string
	TransactionId       string
	OrderNo             string
	BusinessName        string
	BusinessType        string
	InOutcomeType       string
	InOutcomeAmount     float64
	AccountBalance      float64
	FundChangeApplicant string
	Remark              string
	BusinessNumber      string
}

FundFlowBill is data for fund flow.

func UnmarshalFundFlowBill

func UnmarshalFundFlowBill(values []string) (*FundFlowBill, error)

UnmarshalFundFlowBill parses the bill data and stores the result in the bill.

type FundFlowBillRequest

type FundFlowBillRequest struct {
	BillDate    string      `json:"-"`
	AccountType AccountType `json:"-"`
	TarType     TarType     `json:"-"`
}

FundFlowBillRequest is the request for trade bill.

func (*FundFlowBillRequest) Do

Do send the request of downloading fundflow bill.

func (*FundFlowBillRequest) Download

func (r *FundFlowBillRequest) Download(ctx context.Context, c Client) ([]byte, error)

Download download plain text of fundflow bill.

func (*FundFlowBillRequest) UnmarshalDownload

func (r *FundFlowBillRequest) UnmarshalDownload(ctx context.Context, c Client) (*FundFlowBillResponse, error)

UnmarshalDownload download and unmarshal the data of fundflow bill.

type FundFlowBillResponse

type FundFlowBillResponse struct {
	Summary FundFlowBillSummary
	Bill    []*FundFlowBill
}

FundFlowBillResponse is the response for trade bill.

func UnmarshalFundFlowBillResponse

func UnmarshalFundFlowBillResponse(accountType AccountType, data []byte) (*FundFlowBillResponse, error)

UnmarshalFundFlowBillResponse parses the bill data and stores the result in this response.

type FundFlowBillSummary

type FundFlowBillSummary struct {
	TotalNumber          int
	TotalNumberOfIncome  int
	IncomeAomunt         float64
	TotalNumberOfOutcome int
	OutcomeAomunt        float64
}

FundFlowBill is summary fundflow.

func UnmarshalFundFlowBillSummary

func UnmarshalFundFlowBillSummary(values []string) (*FundFlowBillSummary, error)

UnmarshalFundFlowBillSummary parses the bill data and stores the result in the bill summary.

type GoodDetail

type GoodDetail struct {
	MerchantGoodsId  string `json:"merchant_goods_id"`
	WechatpayGoodsId string `json:"wechatpay_goods_id,omitempty"`
	GoodsName        string `json:"goods_name,omitempty"`
	Quantity         int    `json:"quantity"`
	UnitPrice        int    `json:"unit_price"`
}

GoodDetail is the good information about the transaction.

type GoodsDetail

type GoodsDetail struct {
	MerchantGoodsID  string `json:"merchant_goods_id"`
	WechatpayGoodsID string `json:"wechatpay_goods_id"`
	GoodsName        string `json:"goods_name"`
	UnitPrice        int    `json:"unit_price"`
	RefundAmount     int    `json:"refund_amount"`
	RefundQuantity   int    `json:"refund_quantity"`
}

GoodsDetail is a list of goods detail.

type Notification

type Notification struct {
	Id           string `json:"id"`
	CreateTime   string `json:"create_time"`
	EventType    string `json:"event_type"`
	ResourceType string `json:"resource_type"`
	Summary      string `json:"summary"`

	Resource NotificationResource `json:"resource"`
}

Notification is a notification from wechatpay.

type NotificationAnswer

type NotificationAnswer struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

NotificationAnswer is sent to wechat pay after processing the notification.

func (*NotificationAnswer) Bytes

func (a *NotificationAnswer) Bytes() []byte

Bytes return a json array bytes.

func (*NotificationAnswer) String

func (a *NotificationAnswer) String() string

String return a json string.

type NotificationResource

type NotificationResource struct {
	Algorithm    string `json:"algorithm"`
	CipherText   string `json:"ciphertext"`
	Associated   string `json:"associated_data"`
	OriginalType string `json:"original_type"`
	Nonce        string `json:"nonce"`
}

NotificationResource is the information of encrypt data.

type Option

type Option func(o *options)

Option is optional configuration for wechat pay.

func CertRefreshTime

func CertRefreshTime(refreshTime time.Duration) Option

CertRefreshTime set max cert refresh time, default value is 12h.

func Timeout

func Timeout(timeout time.Duration) Option

Timeout set timeout for http client.

func Transport

func Transport(transport http.RoundTripper) Option

Transport set transport to http client.

type PayAmount

type PayAmount struct {
	Total    int    `json:"total"`
	Currency string `json:"currency,omitempty"`
}

PayAmount is total amount paid, have total and currency.

type PayDetail

type PayDetail struct {
	CostPrice   int          `json:"cost_price,omitempty"`
	InvoiceId   string       `json:"invoice_id,omitempty"`
	GoodsDetail []GoodDetail `json:"goods_detail,omitempty"`
}

PayDetail is the promotion information about the transaction.

type PayNotification

type PayNotification struct {
	Notification
}

PayNotification is a paying notification from wechatpay.

func (*PayNotification) Parse

func (n *PayNotification) Parse(ctx context.Context, c Client, result *Result) (*PayNotifyTransaction, error)

Parse pasre the data from result and return a transaction.

func (*PayNotification) ParseHttpRequest

func (n *PayNotification) ParseHttpRequest(c Client, req *http.Request) (*PayNotifyTransaction, error)

ParseHttpRequest pasre the data that read from the http request. return a transaction.

type PayNotifyTransaction

type PayNotifyTransaction = QueryResponse

PayNotifyTransaction is the transaction after being decrypted.

type PayRequest

type PayRequest struct {
	AppId       string    `json:"appid"`
	MchId       string    `json:"mchid"`
	Description string    `json:"description"`
	OutTradeNo  string    `json:"out_trade_no"`
	TimeExpire  time.Time `json:"time_expire,omitempty"`
	Attach      string    `json:"attach,omitempty"`
	NotifyUrl   string    `json:"notify_url"`
	GoodsTag    string    `json:"goods_tag,omitempty"`
	Amount      PayAmount `json:"amount"`
	// Only set up Payer for JSAPI
	Payer     *Payer        `json:"payer,omitempty"`
	Detail    *PayDetail    `json:"detail,omitempty"`
	SceneInfo *PaySceneInfo `json:"scene_info,omitempty"`
	TradeType TradeType     `json:"-"`
}

PayRequest is request when send a payment.

func (*PayRequest) Do

func (r *PayRequest) Do(ctx context.Context, c Client) (*PayResponse, error)

Do send a transaction and invoke wechat payment.

type PayResponse

type PayResponse struct {
	// The CodeUrl is returned when the merchant used Native
	CodeUrl string `json:"code_url"`
	// The CodeUrl is returned when the merchant used JSAPI APP
	PrepayId string `json:"prepay_id"`
	// The CodeUrl is returned when the merchant used H5
	H5Url string `json:"h5_url"`
}

PayResponse is response when send a payment.

type PaySceneInfo

type PaySceneInfo struct {
	PayerClientIp string     `json:"payer_client_ip"`
	DeviceId      string     `json:"device_id,omitempty"`
	StoreInfo     *StoreInfo `json:"store_info,omitempty"`
}

PaySceneInfo is the scene information about the transaction.

type Payer

type Payer struct {
	OpenId string `json:"openid"`
}

Payer is the payer of the transaction.

type PromotionDetail

type PromotionDetail struct {
	CouponId            string `json:"coupon_id"`
	Name                string `json:"name,omitempty"`
	Scope               string `json:"scope,omitempty"`
	Type                string `json:"type,omitempty"`
	Amount              int    `json:"amount"`
	StockId             string `json:"stock_id,omitempty"`
	WechatpayContribute int    `json:"wechatpay_contribute,omitempty"`
	MerchantContribute  int    `json:"merchant_contribute,omitempty"`
	OtherContribute     int    `json:"other_contribute,omitempty"`
	Currency            string `json:"currency,omitempty"`

	GoodsDetail []TransactionGoodDetail `json:"goods_detail,omitempty"`
}

PromotionDetail is the promotion information about the transaction.

type QueryRequest

type QueryRequest struct {
	MchId         string `json:"-"`
	OutTradeNo    string `json:"-"`
	TransactionId string `json:"-"`
}

QueryRequest is the request for query transaction.

func (*QueryRequest) Do

Do send the request of query transaction.

type QueryResponse

type QueryResponse struct {
	AppId          string    `json:"appid"`
	MchId          string    `json:"mchid"`
	OutTradeNo     string    `json:"out_trade_no"`
	TransactionId  string    `json:"transaction_id,omitempty"`
	TradeType      TradeType `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"`
	Payer          Payer     `json:"payer"`

	Amount    TransactionAmount     `json:"amount,omitempty"`
	SceneInfo *TransactionSceneInfo `json:"scene_info,omitempty"`
	Promotion []*PromotionDetail    `json:"promotion_detail,omitempty"`
}

QueryResponse is the response for query transaction.

func (QueryResponse) IsSuccess

func (q QueryResponse) IsSuccess() bool

IsSuccess check if the transactions pay success.

type QuerySubOrder added in v3.1.0

type QuerySubOrder struct {
	MchId         string    `json:"mchid"`
	OutTradeNo    string    `json:"out_trade_no"`
	TradeType     TradeType `json:"trade_type,omitempty"`
	TradeState    string    `json:"trade_state"`
	BankType      string    `json:"bank_type,omitempty"`
	Attach        string    `json:"attach,omitempty"`
	SuccessTime   time.Time `json:"success_time,omitempty"`
	TransactionId string    `json:"transaction_id,omitempty"`

	Amount CombineSubOrderAmount `json:"amount,omitempty"`
}

QuerySubOrder is the order under the combine transcation

type RefundAmount

type RefundAmount struct {
	Refund   int    `json:"refund"`
	Total    int    `json:"total"`
	Currency string `json:"currency"`
}

RefundAmount is total amount refund, have total and currency.

type RefundAmountInNotify

type RefundAmountInNotify struct {
	Total       int `json:"total"`
	Refund      int `json:"refund"`
	PayerTotal  int `json:"payer_total"`
	PayerRefund int `json:"payer_refund"`
}

RefundAmountInNotify is total amount refund.

type RefundAmountInQueryResp

type RefundAmountInQueryResp struct {
	Total            int    `json:"total"`
	Refund           int    `json:"refund"`
	PayerTotal       int    `json:"payer_total"`
	PayerRefund      int    `json:"payer_refund"`
	SettlementTotal  int    `json:"settlement_total"`
	SettlementRefund int    `json:"settlement_refund"`
	DiscountRefund   int    `json:"discount_refund"`
	Currency         string `json:"currency"`
}

RefundAmountInQueryResp is total amount refund.

type RefundGoodDetail

type RefundGoodDetail struct {
	MerchantGoodsId  string `json:"merchant_goods_id"`
	WechatpayGoodsId string `json:"wechatpay_goods_id,omitempty"`
	GoodsName        string `json:"goods_name,omitempty"`
	UnitPrice        int    `json:"unit_price"`
	RefundAmount     int    `json:"refund_amount"`
	RefundQuantity   int    `json:"refund_quantity"`
}

RefundGoodDetail is the good information about refund transaction.

type RefundNotification

type RefundNotification struct {
	Notification
}

RefundNotification is a refund notification from wechatpay.

func (*RefundNotification) Parse

Parse pasre the data from result and return a refund transcation.

func (*RefundNotification) ParseHttpRequest

func (n *RefundNotification) ParseHttpRequest(c Client, req *http.Request) (*RefundNotifyTransaction, error)

ParseHttpRequest pasre the data that read from the http request. return a refund transaction.

type RefundNotifyTransaction

type RefundNotifyTransaction struct {
	MchId               string    `json:"mchid"`
	OutTradeNo          string    `json:"out_trade_no"`
	TransactionId       string    `json:"transaction_id"`
	OutRefundNo         string    `json:"out_refund_no"`
	RefundId            string    `json:"refund_id"`
	RefundStatus        string    `json:"refund_status"`
	SuccessTime         time.Time `json:"success_time,omitempty"`
	UserReceivedAccount string    `json:"user_received_account"`

	Amount RefundAmountInNotify `json:"amount"`
}

RefundNotifyTransaction is the transaction after being decrypted.

type RefundPromotionDetail

type RefundPromotionDetail struct {
	PromotionId  int    `json:"promotion_id"`
	Scope        string `json:"scope"`
	Type         string `json:"type"`
	Amount       int    `json:"amount"`
	RefundAmount int    `json:"refund_amount"`

	GoodsDetail []RefundGoodDetail `json:"goods_detail,omitempty"`
}

RefundPromotionDetail is the promotion information about refund transaction.

type RefundQueryAmount

type RefundQueryAmount struct {
	Total            int    `json:"total"`
	Refund           int    `json:"refund"`
	PayerTotal       int    `json:"payer_total"`
	PayerRefund      int    `json:"payer_refund"`
	SettlementRefund int    `json:"settlement_refund"`
	SettlementTotal  int    `json:"settlement_total"`
	DiscountRefund   int    `json:"discount_refund"`
	Currency         string `json:"currency"`
}

RefundQueryAmount is the amount of the refund transcation.

type RefundQueryPromotionDetail

type RefundQueryPromotionDetail struct {
	PromotionID  string        `json:"promotion_id"`
	Scope        string        `json:"scope"`
	Type         string        `json:"type"`
	Amount       int           `json:"amount"`
	RefundAmount int           `json:"refund_amount"`
	GoodsDetail  []GoodsDetail `json:"goods_detail"`
}

RefundQueryPromotionDetail is the promotion detail of refund.

type RefundQueryRequest

type RefundQueryRequest struct {
	OutRefundNo string `json:"-"`
}

RefundQueryRequest is the request for query transaction.

func (*RefundQueryRequest) Do

Do send the refund query result.

type RefundQueryResponse

type RefundQueryResponse 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"`
	SuccessTime         time.Time                    `json:"success_time"`
	CreateTime          time.Time                    `json:"create_time"`
	Status              string                       `json:"status"`
	FundsAccount        string                       `json:"funds_account"`
	Amount              *RefundQueryAmount           `json:"amount"`
	PromotionDetail     []RefundQueryPromotionDetail `json:"promotion_detail"`
}

RefundQueryResponse is the result for refund query.

type RefundRequest

type RefundRequest struct {
	TransactionId string `json:"transaction_id"`
	OutTradeNo    string `json:"out_trade_no"`
	OutRefundNo   string `json:"out_refund_no"`
	Reason        string `json:"reason,omitempty"`
	NotifyUrl     string `json:"notify_url,omitempty"`
	FundsAccount  string `json:"funds_account,omitempty"`

	Amount      RefundAmount       `json:"amount"`
	GoodsDetail []RefundGoodDetail `json:"goods_detail,omitempty"`
}

RefundRequest is request when apply refund, TransactionId and OutTradeNo is required.

func (*RefundRequest) Do

Do send the refund request and return refund response.

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"`
	SuccessTime         time.Time `json:"success_time,omitempty"`
	CreateTime          time.Time `json:"create_time"`
	Status              string    `json:"status"`
	FundsAccount        string    `json:"funds_account,omitempty"`

	Amount    RefundAmountInQueryResp  `json:"amount"`
	Promotion []*RefundPromotionDetail `json:"promotion_detail,omitempty"`
}

RefundResponse is the response for refund transaction.

type RefundTradeBill

type RefundTradeBill struct {
	TradeTime          string
	AppId              string
	MchId              string
	SpecialMechId      string
	DeviceId           string
	TransactionId      string
	OutTradeNo         string
	OpenId             string
	TardeType          string
	TradeState         string
	BankType           string
	Currency           string
	SettlementTotalFee float64
	CouponAmount       float64
	RefundApplyTime    string
	RefundSuccessTime  string
	PayerRefundId      string
	MerchantRefundId   string
	RefundAmount       float64
	CouponRefundAmount float64
	RefundType         string
	RefundStatus       string
	GoodName           string
	Attach             string
	CommissionFee      float64
	Rate               string
	Amount             float64
	RefundApplyAmount  float64
	RateComment        string
}

RefundTradeBill is data for refund trade bill.

func UnmarshalRefundTradeBill

func UnmarshalRefundTradeBill(values []string) (*RefundTradeBill, error)

UnmarshalRefundTradeBill parses the bill data and stores the result in the bill.

type Result

type Result struct {
	Body      []byte
	Timestamp int64
	Nonce     string
	Signature string
	SerialNo  string
	Err       error
}

Result is a result after call client.Do

func (*Result) Error

func (r *Result) Error() error

Error return the error.

func (*Result) Scan

func (r *Result) Scan(dest interface{}) error

Scan data from the response into the dest object.

type SettleInfo added in v3.1.0

type SettleInfo struct {
	ProfitSharing bool `json:"profit_sharing"`
	SubsidyAmount bool `json:"subsidy_amount"`
}

SettleInfo is settle information

type StoreInfo

type StoreInfo struct {
	Id       string `json:"id"`
	Name     string `json:"name,omitempty"`
	AreaCode string `json:"area_code,omitempty"`
	Address  string `json:"address,omitempty"`
}

StoreInfo the store information about the transaction.

type SubOrder added in v3.1.0

type SubOrder struct {
	MchId       string           `json:"mchid"`
	Attach      string           `json:"attach,omitempty"`
	Amount      CombinePayAmount `json:"amount"`
	OutTradeNo  string           `json:"out_trade_no"`
	Description string           `json:"description"`
}

SubOrder is the order under the combine transcation

type SuccessTradeBill

type SuccessTradeBill struct {
	TradeTime          string
	AppId              string
	MchId              string
	SpecialMechId      string
	DeviceId           string
	TransactionId      string
	OutTradeNo         string
	OpenId             string
	TardeType          string
	TradeState         string
	BankType           string
	Currency           string
	SettlementTotalFee float64
	CouponAmount       float64
	GoodName           string
	Attach             string
	CommissionFee      float64
	Rate               string
	Amount             float64
	RateComment        string
}

SuccessTradeBill is data for success trade bill.

func UnmarshalSuccessTradeBill

func UnmarshalSuccessTradeBill(values []string) (*SuccessTradeBill, error)

UnmarshalSuccessTradeBill parses the bill data and stores the result in the bill.

type TarType

type TarType string

TarType is file tar type

const (
	DataStream TarType = ""
	GZIP       TarType = "GZIP"
)

type TradeBillRequest

type TradeBillRequest struct {
	BillDate string   `json:"-"`
	BillType BillType `json:"-"`
	TarType  TarType  `json:"-"`
}

TradeBillRequest is the request for trade bill.

func (*TradeBillRequest) Do

func (r *TradeBillRequest) Do(ctx context.Context, c Client) (*FileUrl, error)

Do send the request and get download url.

func (*TradeBillRequest) Download

func (r *TradeBillRequest) Download(ctx context.Context, c Client) ([]byte, error)

Download download plain text of trade bill.

func (*TradeBillRequest) UnmarshalDownload

func (r *TradeBillRequest) UnmarshalDownload(ctx context.Context, c Client) (*TradeBillResponse, error)

UnmarshalDownload download and unmarshal the data of trade bill.

type TradeBillResponse

type TradeBillResponse struct {
	Summary TradeBillSummary
	Refund  []*RefundTradeBill
	All     []*AllTradeBill
	Success []*SuccessTradeBill
}

TradeBillResponse is the response for trade bill.

func UnmarshalTradeBillResponse

func UnmarshalTradeBillResponse(billType BillType, data []byte) (*TradeBillResponse, error)

UnmarshalTradeBillResponse parses the bill data and stores the result in this response.

type TradeBillSummary

type TradeBillSummary struct {
	TotalNumberOfTransactions int
	TotalSettlementFee        float64
	TotalRefundFee            float64
	TotalCouponFee            float64
	TotalCommissionFee        float64
	TotalApplyRefundFee       float64
	TotalAmount               float64
}

TradeBillSummary is summary trade bill.

func UnmarshalTradeBillSummary

func UnmarshalTradeBillSummary(values []string) (*TradeBillSummary, error)

UnmarshalTradeBillSummary parses the bill data and stores the result in the bill summary.

type TradeType

type TradeType string

TradeType is trade type and defined by wechat pay.

const (
	JSAPI  TradeType = "JSAPI"
	APP    TradeType = "APP"
	H5     TradeType = "H5"
	Native TradeType = "NATIVE"
)

type TransactionAmount

type TransactionAmount struct {
	Total         int    `json:"total,omitempty"`
	PayerTotal    int    `json:"payer_total,omitempty"`
	Currency      string `json:"currency,omitempty"`
	PayerCurrency string `json:"payer_currency,omitempty"`
}

TransactionAmount is tatal amount paid, have total and currency.

type TransactionGoodDetail

type TransactionGoodDetail 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"`
}

TransactionGoodDetail is the good information about the transaction.

type TransactionSceneInfo

type TransactionSceneInfo struct {
	DeviceId string `json:"device_id,omitempty"`
}

TransactionSceneInfo is the scene information about the transaction.

Directories

Path Synopsis
Package sign implements signature and verify for wechat pay.
Package sign implements signature and verify for wechat pay.

Jump to

Keyboard shortcuts

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