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/services/refunddomestic" "github.com/wechatpay-apiv3/wechatpay-go/utils" "hospital-open-api/config" "path/filepath" ) type RefundRequest struct { TransactionId string `json:"transaction_id" comment:"微信订单号"` OutTradeNo string `json:"out_trade_no" comment:"商户订单号"` OutRefundNo string `json:"out_refund_no" comment:"退款订单号"` Reason string `json:"reason" comment:"退款原因"` PaymentAmountTotal int64 `json:"payment_amount_total" comment:"退款金额"` NotifyUrl string `json:"notify_url" comment:"回调地址"` } // Refund 退款 func (r RefundRequest) Refund() (*refunddomestic.Refund, error) { // 使用 utils 提供的函数从本地文件中加载商户私钥,商户私钥会用来生成请求的签名 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(config.C.Wechat.MchId, config.C.Wechat.MchCertificateSerialNumber, mchPrivateKey, config.C.Wechat.V3ApiSecret), } client, err := core.NewClient(ctx, opts...) if err != nil { return nil, errors.New(err.Error()) } refundRequest := refunddomestic.CreateRequest{ TransactionId: core.String(r.TransactionId), OutTradeNo: core.String(r.OutTradeNo), OutRefundNo: core.String(r.OutRefundNo), Reason: core.String(r.Reason), NotifyUrl: core.String(r.NotifyUrl), Amount: &refunddomestic.AmountReq{ Currency: core.String("CNY"), Refund: core.Int64(r.PaymentAmountTotal), Total: core.Int64(r.PaymentAmountTotal), }, } svc := refunddomestic.RefundsApiService{Client: client} resp, _, err := svc.Create(ctx, refundRequest) if err != nil { return nil, errors.New(err.Error()) } return resp, nil }