---
url: "https://pay.weixin.qq.com/doc/v3/partner/4012460518-go.md"
title: "条件查询批次列表-请求示例-go"
doc_id: 4012460518
example_lang: "go"
---

## Go


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

```
package main

import (
	"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 := &ListStocksRequest{
		Offset:            wxpay_utility.Int64(1),
		Limit:             wxpay_utility.Int64(8),
		StockCreatorMchid: wxpay_utility.String("9856888"),
		CreateStartTime:   wxpay_utility.String("2015-05-20T13:29:35.120+08:00"),
		CreateEndTime:     wxpay_utility.String("2015-05-20T13:29:35.120+08:00"),
		Status:            wxpay_utility.String("paused"),
	}

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

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

func ListStocks(config *wxpay_utility.MchConfig, request *ListStocksRequest) (response *StockCollection, err error) {
	const (
		host   = "https://api.mch.weixin.qq.com"
		method = "GET"
		path   = "/v3/marketing/favor/stocks"
	)

	reqUrl, err := url.Parse(fmt.Sprintf("%s%s", host, path))
	if err != nil {
		return nil, err
	}
	query := reqUrl.Query()
	if request.Offset != nil {
		query.Add("offset", fmt.Sprintf("%v", *request.Offset))
	}
	if request.Limit != nil {
		query.Add("limit", fmt.Sprintf("%v", *request.Limit))
	}
	if request.StockCreatorMchid != nil {
		query.Add("stock_creator_mchid", *request.StockCreatorMchid)
	}
	if request.CreateStartTime != nil {
		query.Add("create_start_time", *request.CreateStartTime)
	}
	if request.CreateEndTime != nil {
		query.Add("create_end_time", *request.CreateEndTime)
	}
	if request.Status != nil {
		query.Add("status", *request.Status)
	}
	reqUrl.RawQuery = query.Encode()
	httpRequest, err := http.NewRequest(method, reqUrl.String(), nil)
	if err != nil {
		return nil, err
	}
	httpRequest.Header.Set("Accept", "application/json")
	httpRequest.Header.Set("Wechatpay-Serial", config.WechatPayPublicKeyId())
	authorization, err := wxpay_utility.BuildAuthorization(config.MchId(), config.CertificateSerialNo(), config.PrivateKey(), method, reqUrl.RequestURI(), nil)
	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 := &StockCollection{}
		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 ListStocksRequest struct {
	Offset            *int64  `json:"offset,omitempty"`
	Limit             *int64  `json:"limit,omitempty"`
	StockCreatorMchid *string `json:"stock_creator_mchid,omitempty"`
	CreateStartTime   *string `json:"create_start_time,omitempty"`
	CreateEndTime     *string `json:"create_end_time,omitempty"`
	Status            *string `json:"status,omitempty"`
}

func (o *ListStocksRequest) MarshalJSON() ([]byte, error) {
	type Alias ListStocksRequest
	a := &struct {
		Offset            *int64  `json:"offset,omitempty"`
		Limit             *int64  `json:"limit,omitempty"`
		StockCreatorMchid *string `json:"stock_creator_mchid,omitempty"`
		CreateStartTime   *string `json:"create_start_time,omitempty"`
		CreateEndTime     *string `json:"create_end_time,omitempty"`
		Status            *string `json:"status,omitempty"`
		*Alias
	}{
		// 序列化时移除非 Body 字段
		Offset:            nil,
		Limit:             nil,
		StockCreatorMchid: nil,
		CreateStartTime:   nil,
		CreateEndTime:     nil,
		Status:            nil,
		Alias:             (*Alias)(o),
	}
	return json.Marshal(a)
}

type StockCollection struct {
	TotalCount *int64  `json:"total_count,omitempty"`
	Data       []Stock `json:"data,omitempty"`
	Limit      *int64  `json:"limit,omitempty"`
	Offset     *int64  `json:"offset,omitempty"`
}

type Stock struct {
	StockId               *string       `json:"stock_id,omitempty"`
	StockCreatorMchid     *string       `json:"stock_creator_mchid,omitempty"`
	StockName             *string       `json:"stock_name,omitempty"`
	Status                *string       `json:"status,omitempty"`
	CreateTime            *string       `json:"create_time,omitempty"`
	Description           *string       `json:"description,omitempty"`
	StockUseRule          *StockUseRule `json:"stock_use_rule,omitempty"`
	AvailableBeginTime    *string       `json:"available_begin_time,omitempty"`
	AvailableEndTime      *string       `json:"available_end_time,omitempty"`
	DistributedCoupons    *int64        `json:"distributed_coupons,omitempty"`
	NoCash                *bool         `json:"no_cash,omitempty"`
	StartTime             *string       `json:"start_time,omitempty"`
	StopTime              *string       `json:"stop_time,omitempty"`
	CutToMessage          *CutTypeMsg   `json:"cut_to_message,omitempty"`
	Singleitem            *bool         `json:"singleitem,omitempty"`
	StockType             *string       `json:"stock_type,omitempty"`
	CardId                *string       `json:"card_id,omitempty"`
	BusinessType          *BusinessType `json:"business_type,omitempty"`
	AvailableRegionList   []RegionInfo  `json:"available_region_list,omitempty"`
	AvailableIndustryList []string      `json:"available_industry_list,omitempty"`
}

type StockUseRule struct {
	MaxCoupons          *int64              `json:"max_coupons,omitempty"`
	MaxAmount           *int64              `json:"max_amount,omitempty"`
	MaxAmountByDay      *int64              `json:"max_amount_by_day,omitempty"`
	FixedNormalCoupon   *FixedValueStockMsg `json:"fixed_normal_coupon,omitempty"`
	MaxCouponsPerUser   *int64              `json:"max_coupons_per_user,omitempty"`
	CouponType          *string             `json:"coupon_type,omitempty"`
	GoodsTag            []string            `json:"goods_tag,omitempty"`
	TradeType           []TradeType         `json:"trade_type,omitempty"`
	CombineUse          *bool               `json:"combine_use,omitempty"`
	FixedDiscountCoupon *DiscountMsg        `json:"fixed_discount_coupon,omitempty"`
}

type CutTypeMsg struct {
	SinglePriceMax *int64 `json:"single_price_max,omitempty"`
	CutToPrice     *int64 `json:"cut_to_price,omitempty"`
}

type BusinessType string

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

const (
	BUSINESSTYPE_MULTIUSE BusinessType = "MULTIUSE"
)

type RegionInfo struct {
	Type     *RegionType `json:"type,omitempty"`
	Province *string     `json:"province,omitempty"`
	City     *string     `json:"city,omitempty"`
	District *string     `json:"district,omitempty"`
	Country  *string     `json:"country,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 DiscountMsg struct {
	DiscountAmountMax  *int64 `json:"discount_amount_max,omitempty"`
	DiscountPercent    *int64 `json:"discount_percent,omitempty"`
	TransactionMinimum *int64 `json:"transaction_minimum,omitempty"`
}

type RegionType string

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

const (
	REGIONTYPE_PROVINCE RegionType = "PROVINCE"
	REGIONTYPE_CITY     RegionType = "CITY"
	REGIONTYPE_DISTRICT RegionType = "DISTRICT"
	REGIONTYPE_COUNTRY  RegionType = "COUNTRY"
)

```
