---
url: "https://pay.weixin.qq.com/doc/v3/merchant/4012534352-go.md"
title: "扣费受理-请求示例-go"
doc_id: 4012534352
example_lang: "go"
---

## Go


需配合微信支付工具库 wxpay\_utility 使用，请参考 [Go](https://pay.weixin.qq.com/doc/v3/merchant/4015119334.md)

```
package main

import (
	"bytes"
	"demo/wxpay_utility" // 引用微信支付工具库，参考 https://pay.weixin.qq.com/doc/v3/merchant/4015119334
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"time"
)

func main() {
	// TODO: 请准备商户开发必要参数，参考：https://pay.weixin.qq.com/doc/v3/merchant/4013070756
	config, err := wxpay_utility.CreateMchConfig(
		"19xxxxxxxx",                 // 商户号，是由微信支付系统生成并分配给每个商户的唯一标识符，商户号获取方式参考 https://pay.weixin.qq.com/doc/v3/merchant/4013070756
		"1DDE55AD98Exxxxxxxxxx",      // 商户API证书序列号，如何获取请参考 https://pay.weixin.qq.com/doc/v3/merchant/4013053053
		"/path/to/apiclient_key.pem", // 商户API证书私钥文件路径，本地文件路径
		"PUB_KEY_ID_xxxxxxxxxxxxx",   // 微信支付公钥ID，如何获取请参考 https://pay.weixin.qq.com/doc/v3/merchant/4013038816
		"/path/to/wxp_pub.pem",       // 微信支付公钥文件路径，本地文件路径
	)
	if err != nil {
		fmt.Println(err)
		return
	}

	request := &CreateTransactionRequest{
		Appid:         wxpay_utility.String("wxcbda96de0b165486"),
		Description:   wxpay_utility.String("停车场扣费"),
		Attach:        wxpay_utility.String("深圳分店"),
		OutTradeNo:    wxpay_utility.String("20150806125346"),
		TradeScene:    wxpay_utility.String("PARKING"),
		GoodsTag:      wxpay_utility.String("WXG"),
		NotifyUrl:     wxpay_utility.String("https://www.weixin.qq.com/wxpay/pay.php"),
		ProfitSharing: wxpay_utility.String("Y"),
		Amount: &OrderAmount{
			Total:    wxpay_utility.Int64(888),
			Currency: wxpay_utility.String("CNY"),
		},
		ParkingInfo: &ParkingTradeScene{
			ParkingId:        wxpay_utility.String("5K8264ILTKCH16CQ250"),
			PlateNumber:      wxpay_utility.String("粤B888888"),
			PlateColor:       PLATECOLOR_BLUE.Ptr(),
			StartTime:        wxpay_utility.Time(time.Now()),
			EndTime:          wxpay_utility.Time(time.Now()),
			ParkingName:      wxpay_utility.String("欢乐海岸停车场"),
			ChargingDuration: wxpay_utility.Int64(3600),
			DeviceId:         wxpay_utility.String("12313"),
		},
	}

	response, err := CreateTransaction(config, request)
	if err != nil {
		fmt.Printf("请求失败: %+v\n", err)
		// TODO: 请求失败，根据状态码执行不同的处理
		return
	}

	// TODO: 请求成功，继续业务逻辑
	fmt.Printf("请求成功: %+v\n", response)
}

func CreateTransaction(config *wxpay_utility.MchConfig, request *CreateTransactionRequest) (response *Transaction, err error) {
	const (
		host   = "https://api.mch.weixin.qq.com"
		method = "POST"
		path   = "/v3/vehicle/transactions/parking"
	)

	reqUrl, err := url.Parse(fmt.Sprintf("%s%s", host, path))
	if err != nil {
		return nil, err
	}
	reqBody, err := json.Marshal(request)
	if err != nil {
		return nil, err
	}
	httpRequest, err := http.NewRequest(method, reqUrl.String(), bytes.NewReader(reqBody))
	if err != nil {
		return nil, err
	}
	httpRequest.Header.Set("Accept", "application/json")
	httpRequest.Header.Set("Wechatpay-Serial", config.WechatPayPublicKeyId())
	httpRequest.Header.Set("Content-Type", "application/json")
	authorization, err := wxpay_utility.BuildAuthorization(config.MchId(), config.CertificateSerialNo(), config.PrivateKey(), method, reqUrl.RequestURI(), reqBody)
	if err != nil {
		return nil, err
	}
	httpRequest.Header.Set("Authorization", authorization)

	client := &http.Client{}
	httpResponse, err := client.Do(httpRequest)
	if err != nil {
		return nil, err
	}
	respBody, err := wxpay_utility.ExtractResponseBody(httpResponse)
	if err != nil {
		return nil, err
	}
	if httpResponse.StatusCode >= 200 && httpResponse.StatusCode < 300 {
		// 2XX 成功，验证应答签名
		err = wxpay_utility.ValidateResponse(
			config.WechatPayPublicKeyId(),
			config.WechatPayPublicKey(),
			&httpResponse.Header,
			respBody,
		)
		if err != nil {
			return nil, err
		}
		response := &Transaction{}
		if err := json.Unmarshal(respBody, response); err != nil {
			return nil, err
		}

		return response, nil
	} else {
		return nil, wxpay_utility.NewApiException(
			httpResponse.StatusCode,
			httpResponse.Header,
			respBody,
		)
	}
}

type CreateTransactionRequest struct {
	Appid         *string            `json:"appid,omitempty"`
	Description   *string            `json:"description,omitempty"`
	Attach        *string            `json:"attach,omitempty"`
	OutTradeNo    *string            `json:"out_trade_no,omitempty"`
	TradeScene    *string            `json:"trade_scene,omitempty"`
	GoodsTag      *string            `json:"goods_tag,omitempty"`
	NotifyUrl     *string            `json:"notify_url,omitempty"`
	ProfitSharing *string            `json:"profit_sharing,omitempty"`
	Amount        *OrderAmount       `json:"amount,omitempty"`
	ParkingInfo   *ParkingTradeScene `json:"parking_info,omitempty"`
}

type Transaction struct {
	Appid                 *string            `json:"appid,omitempty"`
	SpMchid               *string            `json:"sp_mchid,omitempty"`
	Description           *string            `json:"description,omitempty"`
	CreateTime            *time.Time         `json:"create_time,omitempty"`
	OutTradeNo            *string            `json:"out_trade_no,omitempty"`
	TransactionId         *string            `json:"transaction_id,omitempty"`
	TradeState            *string            `json:"trade_state,omitempty"`
	TradeStateDescription *string            `json:"trade_state_description,omitempty"`
	SuccessTime           *time.Time         `json:"success_time,omitempty"`
	BankType              *string            `json:"bank_type,omitempty"`
	UserRepaid            *string            `json:"user_repaid,omitempty"`
	Attach                *string            `json:"attach,omitempty"`
	TradeScene            *string            `json:"trade_scene,omitempty"`
	ParkingInfo           *ParkingTradeScene `json:"parking_info,omitempty"`
	Payer                 *Payer             `json:"payer,omitempty"`
	Amount                *QueryOrderAmount  `json:"amount,omitempty"`
	PromotionDetail       []PromotionDetail  `json:"promotion_detail,omitempty"`
}

type OrderAmount struct {
	Total    *int64  `json:"total,omitempty"`
	Currency *string `json:"currency,omitempty"`
}

type ParkingTradeScene struct {
	ParkingId        *string     `json:"parking_id,omitempty"`
	PlateNumber      *string     `json:"plate_number,omitempty"`
	PlateColor       *PlateColor `json:"plate_color,omitempty"`
	StartTime        *time.Time  `json:"start_time,omitempty"`
	EndTime          *time.Time  `json:"end_time,omitempty"`
	ParkingName      *string     `json:"parking_name,omitempty"`
	ChargingDuration *int64      `json:"charging_duration,omitempty"`
	DeviceId         *string     `json:"device_id,omitempty"`
}

type Payer struct {
	Openid *string `json:"openid,omitempty"`
}

type QueryOrderAmount struct {
	Total         *int64  `json:"total,omitempty"`
	Currency      *string `json:"currency,omitempty"`
	PayerTotal    *int64  `json:"payer_total,omitempty"`
	DiscountTotal *int64  `json:"discount_total,omitempty"`
}

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

type PlateColor string

func (e PlateColor) Ptr() *PlateColor {
	return &e
}

const (
	PLATECOLOR_BLUE      PlateColor = "BLUE"
	PLATECOLOR_GREEN     PlateColor = "GREEN"
	PLATECOLOR_YELLOW    PlateColor = "YELLOW"
	PLATECOLOR_BLACK     PlateColor = "BLACK"
	PLATECOLOR_WHITE     PlateColor = "WHITE"
	PLATECOLOR_LIMEGREEN PlateColor = "LIMEGREEN"
)

```
