---
url: "https://pay.weixin.qq.com/doc/v3/partner/4012494237-go.md"
title: "根据商户号查用户的券-请求示例-go"
doc_id: 4012494237
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"
	"strings"
)

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 := &ListCouponsByFilterRequest{
		Openid:         wxpay_utility.String("Openid_example"),
		Appid:          wxpay_utility.String("Appid_example"),
		StockId:        wxpay_utility.String("9865000"),
		Status:         wxpay_utility.String("USED"),
		BusinessType:   BUSINESSTYPE_MULTIUSE.Ptr(),
		CreatorMchid:   wxpay_utility.String("9865002"),
		AvailableMchid: wxpay_utility.String("9865000"),
		Offset:         wxpay_utility.Int64(0),
		Limit:          wxpay_utility.Int64(20),
	}

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

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

func ListCouponsByFilter(config *wxpay_utility.MchConfig, request *ListCouponsByFilterRequest) (response *CouponCollection, err error) {
	const (
		host   = "https://api.mch.weixin.qq.com"
		method = "GET"
		path   = "/v3/marketing/favor/users/{openid}/coupons"
	)

	reqUrl, err := url.Parse(fmt.Sprintf("%s%s", host, path))
	if err != nil {
		return nil, err
	}
	reqUrl.Path = strings.Replace(reqUrl.Path, "{openid}", url.PathEscape(*request.Openid), -1)
	query := reqUrl.Query()
	if request.Appid != nil {
		query.Add("appid", *request.Appid)
	}
	if request.StockId != nil {
		query.Add("stock_id", *request.StockId)
	}
	if request.Status != nil {
		query.Add("status", *request.Status)
	}
	if request.BusinessType != nil {
		query.Add("business_type", fmt.Sprintf("%v", *request.BusinessType))
	}
	if request.CreatorMchid != nil {
		query.Add("creator_mchid", *request.CreatorMchid)
	}
	if request.AvailableMchid != nil {
		query.Add("available_mchid", *request.AvailableMchid)
	}
	if request.Offset != nil {
		query.Add("offset", fmt.Sprintf("%v", *request.Offset))
	}
	if request.Limit != nil {
		query.Add("limit", fmt.Sprintf("%v", *request.Limit))
	}
	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 := &CouponCollection{}
		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 ListCouponsByFilterRequest struct {
	Openid         *string       `json:"openid,omitempty"`
	Appid          *string       `json:"appid,omitempty"`
	StockId        *string       `json:"stock_id,omitempty"`
	Status         *string       `json:"status,omitempty"`
	CreatorMchid   *string       `json:"creator_mchid,omitempty"`
	AvailableMchid *string       `json:"available_mchid,omitempty"`
	Offset         *int64        `json:"offset,omitempty"`
	Limit          *int64        `json:"limit,omitempty"`
	BusinessType   *BusinessType `json:"business_type,omitempty"`
}

func (o *ListCouponsByFilterRequest) MarshalJSON() ([]byte, error) {
	type Alias ListCouponsByFilterRequest
	a := &struct {
		Openid         *string       `json:"openid,omitempty"`
		Appid          *string       `json:"appid,omitempty"`
		StockId        *string       `json:"stock_id,omitempty"`
		Status         *string       `json:"status,omitempty"`
		CreatorMchid   *string       `json:"creator_mchid,omitempty"`
		AvailableMchid *string       `json:"available_mchid,omitempty"`
		Offset         *int64        `json:"offset,omitempty"`
		Limit          *int64        `json:"limit,omitempty"`
		BusinessType   *BusinessType `json:"business_type,omitempty"`
		*Alias
	}{
		// 序列化时移除非 Body 字段
		Openid:         nil,
		Appid:          nil,
		StockId:        nil,
		Status:         nil,
		CreatorMchid:   nil,
		AvailableMchid: nil,
		Offset:         nil,
		Limit:          nil,
		BusinessType:   nil,
		Alias:          (*Alias)(o),
	}
	return json.Marshal(a)
}

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

type BusinessType string

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

const (
	BUSINESSTYPE_MULTIUSE BusinessType = "MULTIUSE"
)

type Coupon struct {
	StockCreatorMchid       *string             `json:"stock_creator_mchid,omitempty"`
	StockId                 *string             `json:"stock_id,omitempty"`
	CouponId                *string             `json:"coupon_id,omitempty"`
	CutToMessage            *CutTypeMsg         `json:"cut_to_message,omitempty"`
	CouponName              *string             `json:"coupon_name,omitempty"`
	Status                  *string             `json:"status,omitempty"`
	Description             *string             `json:"description,omitempty"`
	CreateTime              *string             `json:"create_time,omitempty"`
	CouponType              *string             `json:"coupon_type,omitempty"`
	NoCash                  *bool               `json:"no_cash,omitempty"`
	AvailableBeginTime      *string             `json:"available_begin_time,omitempty"`
	AvailableEndTime        *string             `json:"available_end_time,omitempty"`
	Singleitem              *bool               `json:"singleitem,omitempty"`
	NormalCouponInformation *FixedValueStockMsg `json:"normal_coupon_information,omitempty"`
	OutRequestNo            *string             `json:"out_request_no,omitempty"`
	AvailableBalance        *int64              `json:"available_balance,omitempty"`
	BusinessType            *BusinessType       `json:"business_type,omitempty"`
	DiscountMsg             *DiscountMsg        `json:"discount_msg,omitempty"`
}

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

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

type DiscountMsg struct {
	DiscountAmountMax  *int64 `json:"discount_amount_max,omitempty"`
	DiscountPercent    *int64 `json:"discount_percent,omitempty"`
	TransactionMinimum *int64 `json:"transaction_minimum,omitempty"`
}

```
