64 lines
1.9 KiB
Go
64 lines
1.9 KiB
Go
package wechat
|
|
|
|
import (
|
|
"context"
|
|
"crypto/x509"
|
|
"fmt"
|
|
"github.com/go-playground/validator/v10"
|
|
"github.com/wechatpay-apiv3/wechatpay-go/core"
|
|
"github.com/wechatpay-apiv3/wechatpay-go/core/option"
|
|
"github.com/wechatpay-apiv3/wechatpay-go/utils"
|
|
"os"
|
|
putils "plugins/utils/helper"
|
|
)
|
|
|
|
type Server struct {
|
|
MchID string `validate:"required" json:"mch_id"`
|
|
MchCertificateSerialNumber string `validate:"required" json:"mch_certificate_serial_number"`
|
|
}
|
|
|
|
func (c *Server) Validate() error {
|
|
err := validator.New().Struct(c)
|
|
if err != nil {
|
|
for _, err = range err.(validator.ValidationErrors) {
|
|
return fmt.Errorf("配置有误:" + err.Error())
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
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)
|
|
if !putils.FileExists(filePath) {
|
|
return nil, fmt.Errorf("MchID[%s]微信密钥证书信息不存在,请联系技术人员处理", c.MchID)
|
|
}
|
|
// 商户相关配置,商户API私钥
|
|
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)
|
|
}
|
|
var client *core.Client
|
|
// 微信支付平台配置
|
|
wechatPayCertificate, err := utils.LoadCertificateWithPath(fmt.Sprintf("%s/%s", filePath, "wechat_cert.pem"))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("平台证书有误:%v", err)
|
|
}
|
|
client, err = core.NewClient(
|
|
ctx,
|
|
option.WithMerchantCredential(
|
|
c.MchID,
|
|
c.MchCertificateSerialNumber,
|
|
mchPrivateKey,
|
|
),
|
|
option.WithWechatPayCertificate([]*x509.Certificate{wechatPayCertificate}),
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("创建 Client 失败:%v", err)
|
|
}
|
|
return client, nil
|
|
}
|