feat: add wechat pay

This commit is contained in:
Rogee
2025-01-14 14:42:08 +08:00
parent 52c17b63bb
commit 9cd7659d14
32 changed files with 1431 additions and 110 deletions

View File

@@ -0,0 +1,30 @@
package pay
import (
"git.ipao.vip/rogeecn/atom/container"
"git.ipao.vip/rogeecn/atom/utils/opt"
)
const DefaultPrefix = "Pay"
func DefaultProvider() container.ProviderContainer {
return container.ProviderContainer{
Provider: Provide,
Options: []opt.Option{
opt.Prefix(DefaultPrefix),
},
}
}
type Config struct {
WeChat *wechatPay
}
type wechatPay struct {
AppId string
MechID string
SubMechID string
SerialNo string
ApiV3Key string
PrivateKey string
}

View File

@@ -0,0 +1,48 @@
package pay
import (
"backend/providers/app"
"git.ipao.vip/rogeecn/atom/container"
"git.ipao.vip/rogeecn/atom/utils/opt"
"github.com/go-pay/gopay"
"github.com/go-pay/gopay/wechat/v3"
)
func Provide(opts ...opt.Option) error {
o := opt.New(opts...)
var config Config
if err := o.UnmarshalConfig(&config); err != nil {
return err
}
return container.Container.Provide(func(app *app.Config) (*Client, error) {
wechatPay, err := wechat.NewClientV3(
config.WeChat.MechID,
config.WeChat.SerialNo,
config.WeChat.ApiV3Key,
config.WeChat.PrivateKey,
)
if err != nil {
return nil, err
}
if err := wechatPay.AutoVerifySign(); err != nil {
return nil, err
}
if app.IsDevMode() {
wechatPay.DebugSwitch = gopay.DebugOn
}
return &Client{
conf: &config,
WeChat: wechatPay,
}, nil
}, o.DiOptions()...)
}
type Client struct {
conf *Config
WeChat *wechat.ClientV3
}

View File

@@ -0,0 +1,49 @@
package pay
import (
"context"
"errors"
"time"
"github.com/go-pay/gopay"
"github.com/go-pay/gopay/wechat/v3"
)
// get js pay prepay id
func (client *Client) WeChat_JSApiPayRequest(ctx context.Context, payerOpenID, orderNo, title string, price, amount int64, notifyUrl string) (*wechat.JSAPIPayParams, error) {
expire := time.Now().Add(10 * time.Minute).Format(time.RFC3339)
// 初始化 BodyMap
bm := make(gopay.BodyMap)
bm.
Set("sp_appid", client.conf.WeChat.AppId).
Set("sp_mchid", client.conf.WeChat.MechID).
Set("sub_mchid", client.conf.WeChat.SubMechID).
Set("description", title).
Set("out_trade_no", orderNo).
Set("time_expire", expire).
Set("notify_url", notifyUrl).
SetBodyMap("amount", func(bm gopay.BodyMap) {
if amount == 0 {
amount = 1
}
bm.
Set("total", amount).
Set("currency", "CNY")
}).
SetBodyMap("payer", func(bm gopay.BodyMap) {
bm.Set("sp_openid", payerOpenID)
})
resp, err := client.WeChat.V3TransactionJsapi(ctx, bm)
if err != nil {
return nil, err
}
if resp.Code != 0 {
return nil, errors.New("获取预支付ID失败")
}
return client.WeChat.PaySignOfJSAPI(client.conf.WeChat.AppId, resp.Response.PrepayId)
}