package weChat import ( "context" "errors" "github.com/wechatpay-apiv3/wechatpay-go/core" "github.com/wechatpay-apiv3/wechatpay-go/core/option" "github.com/wechatpay-apiv3/wechatpay-go/utils" "hepa-calc-api/config" "path/filepath" ) // 创建客户端 func createClient() (*core.Client, error) { mchId := config.C.Wechat.Pay1659662936.MchId // 商户号 mchCertificateSerialNumber := config.C.Wechat.Pay1659662936.MchCertificateSerialNumber // 商户证书序列号 v3ApiSecret := config.C.Wechat.Pay1659662936.V3ApiSecret // 商户APIv3密钥 if mchId == "" { return nil, errors.New("商户号错误") } // 使用 utils 提供的函数从本地文件中加载商户私钥,商户私钥会用来生成请求的签名 certsDir := filepath.Join("extend/weChat/certs", mchId, "/apiclient_key.pem") // certsDir := filepath.Join("extend/weChat/certs", "/1636644248/apiclient_key.pem") mchPrivateKey, err := utils.LoadPrivateKeyWithPath(certsDir) if err != nil { return nil, errors.New("微信签名生成失败") } ctx := context.Background() // 使用商户私钥等初始化 client,并使它具有自动定时获取微信支付平台证书的能力 opts := []core.ClientOption{ option.WithWechatPayAutoAuthCipher(mchId, mchCertificateSerialNumber, mchPrivateKey, v3ApiSecret), } client, err := core.NewClient(ctx, opts...) if err != nil { return nil, errors.New(err.Error()) } return client, nil }