---
url: "https://pay.weixin.qq.com/doc/v3/merchant/4012486942-go.md"
title: "查询代金券详情-请求示例-go"
doc_id: 4012486942
example_lang: "go"
---

## Go


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

```
package main

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

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 := &QueryCouponRequest{
		CouponId: wxpay_utility.String("9856888"),
		Appid:    wxpay_utility.String("Appid_example"),
		Openid:   wxpay_utility.String("Openid_example"),
	}

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

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

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

	reqUrl, err := url.Parse(fmt.Sprintf("%s%s", host, path))
	if err != nil {
		return nil, err
	}
	reqUrl.Path = strings.Replace(reqUrl.Path, "{coupon_id}", url.PathEscape(*request.CouponId), -1)
	reqUrl.Path = strings.Replace(reqUrl.Path, "{openid}", url.PathEscape(*request.Openid), -1)
	query := reqUrl.Query()
	if request.Appid != nil {
		query.Add("appid", *request.Appid)
	}
	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 := &Coupon{}
		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 QueryCouponRequest struct {
	CouponId *string `json:"coupon_id,omitempty"`
	Appid    *string `json:"appid,omitempty"`
	Openid   *string `json:"openid,omitempty"`
}

func (o *QueryCouponRequest) MarshalJSON() ([]byte, error) {
	type Alias QueryCouponRequest
	a := &struct {
		CouponId *string `json:"coupon_id,omitempty"`
		Appid    *string `json:"appid,omitempty"`
		Openid   *string `json:"openid,omitempty"`
		*Alias
	}{
		// 序列化时移除非 Body 字段
		CouponId: nil,
		Appid:    nil,
		Openid:   nil,
		Alias:    (*Alias)(o),
	}
	return json.Marshal(a)
}

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 BusinessType string

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

const (
	BUSINESSTYPE_MULTIUSE BusinessType = "MULTIUSE"
)

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

```
