81 lines
2.1 KiB
Go
81 lines
2.1 KiB
Go
package globals
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"platform/pkg/env"
|
|
|
|
"github.com/wechatpay-apiv3/wechatpay-go/core"
|
|
"github.com/wechatpay-apiv3/wechatpay-go/core/auth/verifiers"
|
|
"github.com/wechatpay-apiv3/wechatpay-go/core/notify"
|
|
"github.com/wechatpay-apiv3/wechatpay-go/core/option"
|
|
"github.com/wechatpay-apiv3/wechatpay-go/services/partnerpayments/h5"
|
|
"github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
|
|
"github.com/wechatpay-apiv3/wechatpay-go/utils"
|
|
)
|
|
|
|
var WechatPay *WechatPayClient
|
|
|
|
type WechatPayClient struct {
|
|
Native *native.NativeApiService
|
|
H5 *h5.H5ApiService
|
|
Notify *notify.Handler
|
|
}
|
|
|
|
func initWechatPay() error {
|
|
|
|
// 加载商户私钥
|
|
private, err := base64.StdEncoding.DecodeString(env.WechatPayMchPrivateKey)
|
|
if err != nil {
|
|
return fmt.Errorf("加载微信支付商户私钥失败: %w", err)
|
|
}
|
|
|
|
appPrivateKey, err := utils.LoadPrivateKey(string(private))
|
|
if err != nil {
|
|
return fmt.Errorf("解析微信支付商户私钥失败: %w", err)
|
|
}
|
|
|
|
// 加载微信支付公钥
|
|
public, err := base64.StdEncoding.DecodeString(env.WechatPayPublicKey)
|
|
if err != nil {
|
|
return fmt.Errorf("加载微信支付公钥失败: %w", err)
|
|
}
|
|
|
|
wechatPublicKey, err := utils.LoadPublicKey(string(public))
|
|
if err != nil {
|
|
return fmt.Errorf("解析微信支付公钥失败: %w", err)
|
|
}
|
|
|
|
// 创建 WechatPay 客户端
|
|
client, err := core.NewClient(context.Background(),
|
|
option.WithWechatPayPublicKeyAuthCipher(
|
|
env.WechatPayMchId,
|
|
env.WechatPayMchPrivateKeySerial,
|
|
appPrivateKey,
|
|
env.WechatPayPublicKeyId,
|
|
wechatPublicKey,
|
|
),
|
|
)
|
|
if err != nil {
|
|
return fmt.Errorf("创建微信支付客户端失败: %w", err)
|
|
}
|
|
|
|
// 创建 WechatPay 通知处理器
|
|
handler, err := notify.NewRSANotifyHandler(env.WechatPayApiCert, verifiers.NewSHA256WithRSAPubkeyVerifier(
|
|
env.WechatPayPublicKeyId,
|
|
*wechatPublicKey,
|
|
))
|
|
if err != nil {
|
|
return fmt.Errorf("创建微信支付通知处理器失败: %w", err)
|
|
}
|
|
|
|
// 创建 WechatPay 服务
|
|
WechatPay = &WechatPayClient{
|
|
Native: &native.NativeApiService{Client: client},
|
|
H5: &h5.H5ApiService{Client: client},
|
|
Notify: handler,
|
|
}
|
|
return nil
|
|
}
|