---
url: "https://pay.weixin.qq.com/doc/v3/partner/4012476113-go.md"
title: "申请资金出境-请求示例-go"
doc_id: 4012476113
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"
)

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 := &CreateOrderRequest{
		OutOrderId:      wxpay_utility.String("merchant_1123123"),
		SubMchid:        wxpay_utility.String("123456"),
		TransactionId:   wxpay_utility.String("4208450740201411110007820472"),
		Amount:          wxpay_utility.Int64(10),
		ForeignCurrency: wxpay_utility.String("USD"),
		GoodsInfo: []GoodsInfo{GoodsInfo{
			GoodsName:      wxpay_utility.String("橘子"),
			GoodsCategory:  wxpay_utility.String("家用电器"),
			GoodsUnitPrice: wxpay_utility.Int64(1),
			GoodsQuantity:  wxpay_utility.Int64(1),
		}},
		SellerInfo: &SellerInfo{
			OverseaBusinessName: wxpay_utility.String("香港xxxx公司"),
			OverseaShopName:     wxpay_utility.String("香港xxx公司xxx店铺"),
			SellerId:            wxpay_utility.String("id2123123123"),
		},
		ExpressInfo: &ExpressInfo{
			CourierNumber:      wxpay_utility.String("curier_number_1231"),
			ExpressCompanyName: wxpay_utility.String("国际xxx物流"),
		},
		PayeeInfo: &PayeeInfo{
			PayeeId: wxpay_utility.String("ID123112312"),
		},
		PresaleInfo: &PresaleInfo{
			Type:                 PRESALEORDERTYPE_DEPOSIT.Ptr(),
			TotalAmount:          wxpay_utility.Int64(10),
			DepositTransactionId: wxpay_utility.String("4208450740201411110007820472"),
			BalanceTransactionId: wxpay_utility.String("4208450740201411110007820472"),
		},
	}

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

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

func CreateOrder(config *wxpay_utility.MchConfig, request *CreateOrderRequest) (response *Order, err error) {
	const (
		host   = "https://api.mch.weixin.qq.com"
		method = "POST"
		path   = "/v3/funds-to-oversea/orders"
	)

	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 := &Order{}
		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 CreateOrderRequest struct {
	OutOrderId      *string      `json:"out_order_id,omitempty"`
	SubMchid        *string      `json:"sub_mchid,omitempty"`
	TransactionId   *string      `json:"transaction_id,omitempty"`
	Amount          *int64       `json:"amount,omitempty"`
	ForeignCurrency *string      `json:"foreign_currency,omitempty"`
	GoodsInfo       []GoodsInfo  `json:"goods_info,omitempty"`
	SellerInfo      *SellerInfo  `json:"seller_info,omitempty"`
	ExpressInfo     *ExpressInfo `json:"express_info,omitempty"`
	PayeeInfo       *PayeeInfo   `json:"payee_info,omitempty"`
	PresaleInfo     *PresaleInfo `json:"presale_info,omitempty"`
}

type Order struct {
	OutOrderId               *string      `json:"out_order_id,omitempty"`
	SubMchid                 *string      `json:"sub_mchid,omitempty"`
	OrderId                  *string      `json:"order_id,omitempty"`
	Result                   *string      `json:"result,omitempty"`
	FailReason               *string      `json:"fail_reason,omitempty"`
	Amount                   *int64       `json:"amount,omitempty"`
	ForeignAmount            *int64       `json:"foreign_amount,omitempty"`
	ForeignCurrency          *string      `json:"foreign_currency,omitempty"`
	Rate                     *int64       `json:"rate,omitempty"`
	ExchangeRateTime         *string      `json:"exchange_rate_time,omitempty"`
	EstimateExchangeRateTime *string      `json:"estimate_exchange_rate_time,omitempty"`
	DepartureAmount          *int64       `json:"departure_amount,omitempty"`
	Fee                      *int64       `json:"fee,omitempty"`
	ChargeMchid              *string      `json:"charge_mchid,omitempty"`
	ChargeAccountType        *AccountType `json:"charge_account_type,omitempty"`
}

type GoodsInfo struct {
	GoodsName      *string `json:"goods_name,omitempty"`
	GoodsCategory  *string `json:"goods_category,omitempty"`
	GoodsUnitPrice *int64  `json:"goods_unit_price,omitempty"`
	GoodsQuantity  *int64  `json:"goods_quantity,omitempty"`
}

type SellerInfo struct {
	OverseaBusinessName *string `json:"oversea_business_name,omitempty"`
	OverseaShopName     *string `json:"oversea_shop_name,omitempty"`
	SellerId            *string `json:"seller_id,omitempty"`
}

type ExpressInfo struct {
	CourierNumber      *string `json:"courier_number,omitempty"`
	ExpressCompanyName *string `json:"express_company_name,omitempty"`
}

type PayeeInfo struct {
	PayeeId *string `json:"payee_id,omitempty"`
}

type PresaleInfo struct {
	Type                 *PresaleOrderType `json:"type,omitempty"`
	TotalAmount          *int64            `json:"total_amount,omitempty"`
	DepositTransactionId *string           `json:"deposit_transaction_id,omitempty"`
	BalanceTransactionId *string           `json:"balance_transaction_id,omitempty"`
}

type AccountType string

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

const (
	ACCOUNTTYPE_BASIC AccountType = "BASIC"
	ACCOUNTTYPE_FEES  AccountType = "FEES"
)

type PresaleOrderType string

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

const (
	PRESALEORDERTYPE_DEPOSIT PresaleOrderType = "DEPOSIT"
	PRESALEORDERTYPE_BALANCE PresaleOrderType = "BALANCE"
)

```
