---
url: "https://pay.weixin.qq.com/doc/v3/partner/4012534537-go.md"
title: "创建代金券批次-请求示例-go"
doc_id: 4012534537
example_lang: "go"
---

## Go


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

```
package main

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

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

	request := &CreateCouponStockRequest{
		StockName:          wxpay_utility.String("微信支付代金券批次"),
		Comment:            wxpay_utility.String("零售批次"),
		BelongMerchant:     wxpay_utility.String("98568865"),
		AvailableBeginTime: wxpay_utility.String("2015-05-20T13:29:35.120+08:00"),
		AvailableEndTime:   wxpay_utility.String("2015-05-20T13:29:35.120+08:00"),
		StockUseRule: &StockRule{
			MaxCoupons:         wxpay_utility.Int64(100),
			MaxAmount:          wxpay_utility.Int64(5000),
			MaxAmountByDay:     wxpay_utility.Int64(400),
			MaxCouponsPerUser:  wxpay_utility.Int64(3),
			NaturalPersonLimit: wxpay_utility.Bool(false),
			PreventApiAbuse:    wxpay_utility.Bool(false),
		},
		PatternInfo: &PatternInfo{
			Description:      wxpay_utility.String("微信支付营销代金券"),
			MerchantLogo:     wxpay_utility.String("CDN地址"),
			MerchantName:     wxpay_utility.String("微信支付"),
			BackgroundColor:  BACKGROUNDCOLOR_COLOR010.Ptr(),
			CouponImage:      wxpay_utility.String("https://qpic.cn/xxx"),
			JumpTarget:       JUMPTARGET_PAYMENT_CODE.Ptr(),
			MiniProgramAppid: wxpay_utility.String("wx23232232323"),
			MiniProgramPath:  wxpay_utility.String("/path/index/index"),
		},
		CouponUseRule: &CouponRule{
			CouponAvailableTime: &FavorAvailableTime{
				FixAvailableTime: &FixedAvailableTime{
					AvailableWeekDay: []int64{int64(1)},
					BeginTime:        wxpay_utility.Int64(0),
					EndTime:          wxpay_utility.Int64(3600),
				},
				SecondDayAvailable:        wxpay_utility.Bool(false),
				AvailableTimeAfterReceive: wxpay_utility.Int64(7),
			},
			FixedNormalCoupon: &FixedValueStockMsg{
				CouponAmount:       wxpay_utility.Int64(100),
				TransactionMinimum: wxpay_utility.Int64(100),
			},
			GoodsTag:           []string{"123321"},
			TradeType:          []TradeType{TRADETYPE_MICROAPP},
			CombineUse:         wxpay_utility.Bool(false),
			AvailableItems:     []string{"123321"},
			UnavailableItems:   []string{"789987"},
			AvailableMerchants: []string{"9856000"},
			LimitCard: &CardLimitation{
				Name: wxpay_utility.String("精粹白金"),
				Bin:  []string{"62542688"},
			},
		},
		NoCash:       wxpay_utility.Bool(false),
		StockType:    wxpay_utility.String("NORMAL"),
		OutRequestNo: wxpay_utility.String("example_out_request_no"),
		ExtInfo:      wxpay_utility.String("{'exinfo1':'1234','exinfo2':'3456'}"),
	}

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

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

func CreateCouponStock(config *wxpay_utility.MchConfig, request *CreateCouponStockRequest) (response *CreateCouponStockResponse, err error) {
	const (
		host   = "https://api.mch.weixin.qq.com"
		method = "POST"
		path   = "/v3/marketing/favor/coupon-stocks"
	)

	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 := &CreateCouponStockResponse{}
		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 CreateCouponStockRequest struct {
	StockName          *string      `json:"stock_name,omitempty"`
	Comment            *string      `json:"comment,omitempty"`
	BelongMerchant     *string      `json:"belong_merchant,omitempty"`
	AvailableBeginTime *string      `json:"available_begin_time,omitempty"`
	AvailableEndTime   *string      `json:"available_end_time,omitempty"`
	StockUseRule       *StockRule   `json:"stock_use_rule,omitempty"`
	PatternInfo        *PatternInfo `json:"pattern_info,omitempty"`
	CouponUseRule      *CouponRule  `json:"coupon_use_rule,omitempty"`
	NoCash             *bool        `json:"no_cash,omitempty"`
	StockType          *string      `json:"stock_type,omitempty"`
	OutRequestNo       *string      `json:"out_request_no,omitempty"`
	ExtInfo            *string      `json:"ext_info,omitempty"`
}

type CreateCouponStockResponse struct {
	StockId    *string `json:"stock_id,omitempty"`
	CreateTime *string `json:"create_time,omitempty"`
}

type StockRule struct {
	MaxCoupons         *int64 `json:"max_coupons,omitempty"`
	MaxAmount          *int64 `json:"max_amount,omitempty"`
	MaxAmountByDay     *int64 `json:"max_amount_by_day,omitempty"`
	MaxCouponsPerUser  *int64 `json:"max_coupons_per_user,omitempty"`
	NaturalPersonLimit *bool  `json:"natural_person_limit,omitempty"`
	PreventApiAbuse    *bool  `json:"prevent_api_abuse,omitempty"`
}

type PatternInfo struct {
	Description      *string          `json:"description,omitempty"`
	MerchantLogo     *string          `json:"merchant_logo,omitempty"`
	MerchantName     *string          `json:"merchant_name,omitempty"`
	BackgroundColor  *BackgroundColor `json:"background_color,omitempty"`
	CouponImage      *string          `json:"coupon_image,omitempty"`
	JumpTarget       *JumpTarget      `json:"jump_target,omitempty"`
	MiniProgramAppid *string          `json:"mini_program_appid,omitempty"`
	MiniProgramPath  *string          `json:"mini_program_path,omitempty"`
}

type CouponRule struct {
	CouponAvailableTime *FavorAvailableTime `json:"coupon_available_time,omitempty"`
	FixedNormalCoupon   *FixedValueStockMsg `json:"fixed_normal_coupon,omitempty"`
	GoodsTag            []string            `json:"goods_tag,omitempty"`
	TradeType           []TradeType         `json:"trade_type,omitempty"`
	CombineUse          *bool               `json:"combine_use,omitempty"`
	AvailableItems      []string            `json:"available_items,omitempty"`
	UnavailableItems    []string            `json:"unavailable_items,omitempty"`
	AvailableMerchants  []string            `json:"available_merchants,omitempty"`
	LimitCard           *CardLimitation     `json:"limit_card,omitempty"`
}

type BackgroundColor string

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

const (
	BACKGROUNDCOLOR_COLOR010 BackgroundColor = "COLOR010"
	BACKGROUNDCOLOR_COLOR020 BackgroundColor = "COLOR020"
	BACKGROUNDCOLOR_COLOR030 BackgroundColor = "COLOR030"
	BACKGROUNDCOLOR_COLOR040 BackgroundColor = "COLOR040"
	BACKGROUNDCOLOR_COLOR050 BackgroundColor = "COLOR050"
	BACKGROUNDCOLOR_COLOR060 BackgroundColor = "COLOR060"
	BACKGROUNDCOLOR_COLOR070 BackgroundColor = "COLOR070"
	BACKGROUNDCOLOR_COLOR080 BackgroundColor = "COLOR080"
	BACKGROUNDCOLOR_COLOR081 BackgroundColor = "COLOR081"
	BACKGROUNDCOLOR_COLOR082 BackgroundColor = "COLOR082"
	BACKGROUNDCOLOR_COLOR090 BackgroundColor = "COLOR090"
	BACKGROUNDCOLOR_COLOR100 BackgroundColor = "COLOR100"
	BACKGROUNDCOLOR_COLOR101 BackgroundColor = "COLOR101"
	BACKGROUNDCOLOR_COLOR102 BackgroundColor = "COLOR102"
)

type JumpTarget string

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

const (
	JUMPTARGET_PAYMENT_CODE JumpTarget = "PAYMENT_CODE"
	JUMPTARGET_MINI_PROGRAM JumpTarget = "MINI_PROGRAM"
	JUMPTARGET_DEFAULT_PAGE JumpTarget = "DEFAULT_PAGE"
)

type FavorAvailableTime struct {
	FixAvailableTime          *FixedAvailableTime `json:"fix_available_time,omitempty"`
	SecondDayAvailable        *bool               `json:"second_day_available,omitempty"`
	AvailableTimeAfterReceive *int64              `json:"available_time_after_receive,omitempty"`
}

type FixedValueStockMsg struct {
	CouponAmount       *int64 `json:"coupon_amount,omitempty"`
	TransactionMinimum *int64 `json:"transaction_minimum,omitempty"`
}

type TradeType string

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

const (
	TRADETYPE_MICROAPP TradeType = "MICROAPP"
	TRADETYPE_APPPAY   TradeType = "APPPAY"
	TRADETYPE_PPAY     TradeType = "PPAY"
	TRADETYPE_CARD     TradeType = "CARD"
	TRADETYPE_FACE     TradeType = "FACE"
	TRADETYPE_OTHER    TradeType = "OTHER"
)

type CardLimitation struct {
	Name *string  `json:"name,omitempty"`
	Bin  []string `json:"bin,omitempty"`
}

type FixedAvailableTime struct {
	AvailableWeekDay []int64 `json:"available_week_day,omitempty"`
	BeginTime        *int64  `json:"begin_time,omitempty"`
	EndTime          *int64  `json:"end_time,omitempty"`
}

```
