---
url: "https://pay.weixin.qq.com/doc/v3/merchant/4014551946-go.md"
title: "商户签名验签／加解密测试-请求示例-go"
doc_id: 4014551946
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/merchant/4015119334
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
)

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 := &EchoRequest{
		NotifyUrl:            wxpay_utility.String("https://www.weixin.qq.com/v3/test"),
		EchoMessage:          wxpay_utility.String("hello"),
		EncryptedEchoMessage: wxpay_utility.String("Fx9mh7K5sjqHxxQcgDVhnJ9QdS4nKfcUbuAOjMqetTOozwcJknYJK52SPZSYUCv2bqTTezwVzGPgZ52QL0rTA/ZU7jBY5vqmDj1knBbKIsmNjwtfL0fEAMf5gSzproHq+LBYIoCi91K5tyhp7kKSOxyOz4Hna6Up+IugfZNMbVMxkj7syUs2BOsJFPstvkNwHsJreR2y9cj5jSqtBaXuDK3X3sG1z/yt6mrE04MOEiO/INKdOUYtVfP1yBOazX/tSlXm6ndVswvjSm/61B1kjnNW9TZtPN6FhLqkvS9BVqnGxCYdhGoU2HYh/+pmuaHaO227Ur/D3u2bHux+NKa/qg=="), /*请传入wxpay_utility.EncryptOAEPWithPublicKey 加密结果*/
	}

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

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

func ApiSecurityEcho(config *wxpay_utility.MchConfig, request *EchoRequest) (response *EchoResponse, err error) {
	const (
		host   = "https://api.mch.weixin.qq.com"
		method = "POST"
		path   = "/v3/security/echo"
	)

	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 := &EchoResponse{}
		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 EchoRequest struct {
	NotifyUrl            *string `json:"notify_url,omitempty"`
	EchoMessage          *string `json:"echo_message,omitempty"`
	EncryptedEchoMessage *string `json:"encrypted_echo_message,omitempty"`
}

type EchoResponse struct {
	EchoMessage          *string `json:"echo_message,omitempty"`
	EncryptedEchoMessage *string `json:"encrypted_echo_message,omitempty"`
}

```
