plugins/utils/weixin/client.go

43 lines
1.4 KiB
Go

package weixin
import (
"context"
"crypto/x509"
"fmt"
"github.com/wechatpay-apiv3/wechatpay-go/core"
"github.com/wechatpay-apiv3/wechatpay-go/core/option"
"github.com/wechatpay-apiv3/wechatpay-go/utils"
"os"
)
type Server struct {
MchID string `json:"mch_id"`
MchCertificateSerialNumber string `json:"mch_certificate_serial_number"`
MchAPIv3Key string `json:"mch_ap_iv_3_key"`
}
func newClient(ctx context.Context, c *Server) (*core.Client, error) {
dir, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("MchID[%s] get current dir error:%v", c.MchID, err)
}
filePath := fmt.Sprintf("%s/%s/%s/%s", dir, "cert", "wechat", c.MchID)
mchPrivateKey, err := utils.LoadPrivateKeyWithPath(fmt.Sprintf("%s/%s", filePath, "wechat_private_key.pem"))
if err != nil {
return nil, fmt.Errorf("MchID[%s] load merchant private key error:%v", c.MchID, err)
}
opts := []core.ClientOption{
option.WithWechatPayAutoAuthCipher(c.MchID, c.MchCertificateSerialNumber, mchPrivateKey, c.MchAPIv3Key),
}
payCert, err := utils.LoadCertificateWithPath(fmt.Sprintf("%s/%s", filePath, "wechat_cert.pem"))
if err != nil {
return nil, fmt.Errorf("MchID[%s] load pay certificate error:%v", c.MchID, err)
}
opts = append(opts, option.WithWechatPayCertificate([]*x509.Certificate{payCert}))
client, err := core.NewClient(ctx, opts...)
if err != nil {
return nil, fmt.Errorf("MchID[%s] %v", c.MchID, err)
}
return client, nil
}