使用 Go SDK

更新时间:2025.05.29

在本教程中,你将简要了解微信支付的 Go SDK。在学习过程中,你将

  • 掌握如何安装 Go SDK

  • 了解请求微信支付需要哪些密钥和证书

  • 了解如何使用 Go SDK 请求微信支付

环境要求

  • Go 1.16+

安装

使用 Go Modules 安装最新版本 SDK:

1go get github.com/wechatpay-apiv3/wechatpay-go

你可以在 GitHub 找到 Go SDK 的源代码、使用说明和最新版本信息。

必需的证书和密钥

运行 SDK 必需以下的证书和密钥:

发起请求

以 Native 支付为例,向微信支付发起你的第一个请求。

1package main
2import (
3	"context"
4	"log"
5	"time"
6	"github.com/wechatpay-apiv3/wechatpay-go/core"
7	"github.com/wechatpay-apiv3/wechatpay-go/core/option"
8	"github.com/wechatpay-apiv3/wechatpay-go/services/partnerpayments/native"
9	"github.com/wechatpay-apiv3/wechatpay-go/utils"
10)
11func main() {
12    var (
13        mchID string = "190000****" // 商户号
14        mchCertificateSerialNumber string = "3775B6A45ACD588826D15E583A95F5DD********" // 商户证书序列号
15        mchAPIv3Key string = "2ab9****************************" // 商户APIv3密钥
16    )
17    // 使用 utils 提供的函数从本地文件中加载商户私钥,商户私钥会用来生成请求的签名
18    mchPrivateKey, err: = utils.LoadPrivateKeyWithPath("/path/to/merchant/apiclient_key.pem")
19    if err != nil {
20        log.Fatal("load merchant private key error")
21    }
22    ctx: = context.Background()
23    // 使用商户私钥等初始化 client,并使它具有自动定时获取微信支付平台证书的能力
24    opts: = [] core.ClientOption {
25        option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key),
26    }
27    client, err: = core.NewClient(ctx, opts...)
28    if err != nil {
29        log.Fatalf("new wechat pay client err:%s", err)
30    }
31    // 以 Native 支付为例
32    svc := native.NativeApiService{Client: client}
33    // 发送请求
34    resp, result, err: = svc.Prepay(ctx,
35        native.PrepayRequest{
36			SpAppid: core.String("wxd678efh567hg6787"),
37			SpMchid: core.String("1230000109"),
38			SubAppid: core.String("wxd678efh567hg6787"),
39			SubMchid: core.String("1230000109"),
40			Description: core.String("Image形象店-深圳腾大-QQ公仔"),
41			OutTradeNo: core.String("1217752501201407033233368018"),
42			NotifyUrl: core.String("https://www.weixin.qq.com/wxpay/pay.php"),
43            Amount: & native.Amount {
44                Total: core.Int64(100),
45            },
46        },
47    )
48    // 使用微信扫描 resp.code_url 对应的二维码,即可体验Native支付
49    log.Printf("status=%d resp=%s", result.Response.StatusCode, resp)
50}

联系 SDK 团队获取帮助

接下来阅读

通过这个快速介绍,你已经安装了 Go SDK 并学习了一些基础知识。接下来,你可以阅读具体的产品文档,学习如何接入微信支付。

 

反馈
咨询
目录
置顶