---
url: "https://pay.weixin.qq.com/doc/v3/partner/4012476892-go.md"
title: "申请退款-请求示例-go"
doc_id: 4012476892
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/partner/4015119446
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"time"
)

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 := &CreateRefundRequest{
		SubMchid:             wxpay_utility.String("1900000109"),
		SpAppid:              wxpay_utility.String("wx8888888888888888"),
		SubAppid:             wxpay_utility.String("wx8888888888888888"),
		TransactionId:        wxpay_utility.String("1217752501201407033233368018"),
		OutTradeNo:           wxpay_utility.String("1217752501201407033233368018"),
		OutRefundNo:          wxpay_utility.String("1217752501201407033233368018"),
		Reason:               wxpay_utility.String("商品已售完"),
		Amount: &RefundReqAmount{
			Refund: wxpay_utility.Int64(888),
			From: []FundsFromItem{FundsFromItem{
				Account: wxpay_utility.String("AVAILABLE"),
				Amount:  wxpay_utility.Int64(444),
			}},
			Total:    wxpay_utility.Int64(888),
			Currency: wxpay_utility.String("CNY"),
		},
		NotifyUrl:     wxpay_utility.String("https://weixin.qq.com"),
		RefundAccount: wxpay_utility.String("REFUND_SOURCE_SUB_MERCHANT"),
		FundsAccount:  wxpay_utility.String("AVAILABLE"),
	}

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

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

func CreateRefund(config *wxpay_utility.MchConfig, request *CreateRefundRequest) (response *Refund4Create, err error) {
	const (
		host   = "https://api.mch.weixin.qq.com"
		method = "POST"
		path   = "/v3/ecommerce/refunds/apply"
	)

	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 := &Refund4Create{}
		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 CreateRefundRequest struct {
	SubMchid             *string          `json:"sub_mchid,omitempty"`
	SpAppid              *string          `json:"sp_appid,omitempty"`
	SubAppid             *string          `json:"sub_appid,omitempty"`
	TransactionId        *string          `json:"transaction_id,omitempty"`
	OutTradeNo           *string          `json:"out_trade_no,omitempty"`
	OutRefundNo          *string          `json:"out_refund_no,omitempty"`
	Reason               *string          `json:"reason,omitempty"`
	Amount               *RefundReqAmount `json:"amount,omitempty"`
	NotifyUrl            *string          `json:"notify_url,omitempty"`
	RefundAccount        *string          `json:"refund_account,omitempty"`
	FundsAccount         *string          `json:"funds_account,omitempty"`
}

type Refund4Create struct {
	RefundId        *string           `json:"refund_id,omitempty"`
	OutRefundNo     *string           `json:"out_refund_no,omitempty"`
	CreateTime      *time.Time        `json:"create_time,omitempty"`
	Amount          *RefundAmount     `json:"amount,omitempty"`
	PromotionDetail []PromotionDetail `json:"promotion_detail,omitempty"`
	RefundAccount   *string           `json:"refund_account,omitempty"`
}

type RefundReqAmount struct {
	Refund   *int64          `json:"refund,omitempty"`
	From     []FundsFromItem `json:"from,omitempty"`
	Total    *int64          `json:"total,omitempty"`
	Currency *string         `json:"currency,omitempty"`
}

type RefundAmount struct {
	Refund         *int64          `json:"refund,omitempty"`
	From           []FundsFromItem `json:"from,omitempty"`
	PayerRefund    *int64          `json:"payer_refund,omitempty"`
	DiscountRefund *int64          `json:"discount_refund,omitempty"`
	Currency       *string         `json:"currency,omitempty"`
	Advance        *int64          `json:"advance,omitempty"`
}

type PromotionDetail struct {
	PromotionId  *string `json:"promotion_id,omitempty"`
	Scope        *string `json:"scope,omitempty"`
	Type         *string `json:"type,omitempty"`
	Amount       *int64  `json:"amount,omitempty"`
	RefundAmount *int64  `json:"refund_amount,omitempty"`
}

type FundsFromItem struct {
	Account *string `json:"account,omitempty"`
	Amount  *int64  `json:"amount,omitempty"`
}
```
