直接上代码,内容慢慢补
package main
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"net/http"
"os"
"time"
"github.com/wechatpay-apiv3/wechatpay-go/core"
)
var (
client *core.Client
ctx context.Context
)
func init() {
var err error
var (
mchID string = "1234567890" // 商户号
mchCertificateSerialNumber string = "4F00000000000000000000000000000000000021" // 商户API证书序列号
mchPrivateKey *rsa.PrivateKey // 商户API私钥
wechatPayCertList []*x509.Certificate // 微信支付平台证书
customHTTPClient *http.Client
customHTTPHeader http.Header
)
keyPEM, err := os.ReadFile("apiclient_key.pem")
if err != nil {
panic(err)
}
block, _ := pem.Decode([]byte(keyPEM))
if block == nil {
panic("failed to parse privateKey PEM")
}
privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
mchPrivateKey = privateKey.(*rsa.PrivateKey)
certPEM, err := os.ReadFile("apiclient_cert.pem")
if err != nil {
panic(err)
}
block, _ = pem.Decode([]byte(certPEM))
if block == nil {
panic("failed to parse certificate PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
panic(err)
}
wechatPayCertList = []*x509.Certificate{cert}
ctx = context.Background()
opts := []core.ClientOption{
core.WithMerchantCredential(mchID, mchCertificateSerialNumber, mchPrivateKey), // 必要,使用商户信息生成默认 WechatPayCredential
core.WithWechatPayValidator(wechatPayCertList), // 必要,使用微信支付平台证书列表生成默认 WechatPayValidator
core.WithHTTPClient(customHTTPClient), // 可选,设置自定义 HTTPClient 实例,不设置时使用默认 http.Client{}
core.WithTimeout(2 * time.Second), // 可选,设置自定义超时时间,不设置时使用 http.Client{} 默认超时
core.WithHeader(customHTTPHeader), // 可选,设置自定义请求头
}
client, err = core.NewClient(ctx, opts...)
if err != nil {
panic(err)
}
}
Q.E.D.