hepa-calc-api/extend/weChat/weChatPay.go
2024-07-18 14:19:02 +08:00

80 lines
2.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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"
"hepa-calc-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:"退款原因"`
RefundAmount int64 `json:"refund_amount" comment:"退款金额"`
PaymentAmountTotal int64 `json:"payment_amount_total" comment:"支付金额"`
NotifyUrl string `json:"notify_url" comment:"回调地址"`
}
// Refund 退款
func (r RefundRequest) Refund() (*refunddomestic.Refund, error) {
mchId := ""
mchCertificateSerialNumber := ""
v3ApiSecret := ""
mchId = config.C.Wechat.Pay1636644248.MchId
mchCertificateSerialNumber = config.C.Wechat.Pay1636644248.MchCertificateSerialNumber
v3ApiSecret = config.C.Wechat.Pay1636644248.V3ApiSecret
if mchId == "" {
return nil, errors.New("商户号错误")
}
// certsDir := "extend/weChat/certs/" + mchId + "/apiclient_key.pem"
// 使用 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())
}
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.RefundAmount),
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
}