This commit is contained in:
Hiven
2023-07-28 19:03:36 +08:00
parent ae717f932e
commit 1225a4efdc
23 changed files with 403 additions and 18 deletions

View File

@@ -20,3 +20,10 @@ OAuth:
Stripe:
SK: "sk_test_51IisojHygnIJZeghPVSBhkwySfcyDV4SoAduIxu3J7bvSJ9cZMD96LY1LO6SpdbYquLJX5oKvgEBB67KT9pecfCy00iEC4pp9y"
PayConfig:
Stripe:
Key: "sk_test_51IisojHygnIJZeghPVSBhkwySfcyDV4SoAduIxu3J7bvSJ9cZMD96LY1LO6SpdbYquLJX5oKvgEBB67KT9pecfCy00iEC4pp9y"
EndpointSecret: "whsec_f5f9a121d43af3789db7459352f08cf523eb9e0fbf3381f91ba6c97c324c174d"
SuccessURL: "http://www.baidu.com"
CancelURL: "http://www.baidu.com"

View File

@@ -28,4 +28,13 @@ type Config struct {
Stripe struct {
SK string
}
PayConfig struct {
Stripe struct {
EndpointSecret string
Key string
CancelURL string
SuccessURL string
}
}
}

View File

@@ -6,11 +6,13 @@ import (
"fusenapi/model/gmodel"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"time"
"context"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
handlerUtils "fusenapi/utils/handler"
"github.com/zeromicro/go-zero/core/logx"
"gorm.io/gorm"
@@ -50,11 +52,76 @@ func (l *UserOrderCancelLogic) UserOrderCancel(req *types.UserOrderCancelReq, us
}
// 判断订单状态
if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) {
} else {
var notCancelStatusMap = make(map[constants.Order]struct{}, 3)
notCancelStatusMap[constants.STATUS_NEW_NOT_PAY] = struct{}{}
notCancelStatusMap[constants.STATUS_NEW_PART_PAY] = struct{}{}
notCancelStatusMap[constants.STATUS_NEW_PAY_COMPLETED] = struct{}{}
_, ok := notCancelStatusMap[constants.Order(*orderInfo.Status)]
if !ok {
return resp.SetStatusWithMessage(basic.CodeOrderNotCancelledErr, "the order status not cancle")
}
var cancelTime int64 = time.Now().Unix() - (*orderInfo.Ctime + int64(constants.CANCLE_ORDER_EXPIRE))
// 第一次支付成功后48小时后不能进行取消操作
if orderInfo.IsPayCompleted != nil && cancelTime > 0 {
return resp.SetStatusWithMessage(basic.CodeOrderNotCancelledErr, "The current order cannot be cancelled")
}
// 修改订单--取消状态和取消原因
*orderInfo.Status = int64(constants.STATUS_NEW_CANCEL)
*orderInfo.IsCancel = 1
orderInfo.RefundReasonId = &req.RefundReasonId
orderInfo.RefundReason = &req.RefundReason
var nowTime = time.Now().Unix()
var payList []handlerUtils.PayInfo
// 事务处理
err = orderModel.Trans(l.ctx, func(ctx context.Context, connGorm *gorm.DB) (err error) {
// 修改订单信息
orderModelTS := gmodel.NewFsOrderModel(connGorm)
err = orderModelTS.Update(ctx, orderInfo)
if err != nil {
return err
}
// 新增退款记录
var isRefund int64 = 0
refundReasonModelTS := gmodel.NewFsRefundReasonModel(connGorm)
refundReasonModelTS.CreateOrUpdate(ctx, &gmodel.FsRefundReason{
IsRefund: &isRefund,
RefundReasonId: &req.RefundReasonId,
RefundReason: &req.RefundReason,
OrderId: &orderInfo.Id,
CreatedAt: &nowTime,
})
// 退款申请
// 退款申请--查询支付信息
fsPayModelTS := gmodel.NewFsPayModel(connGorm)
rbFsPay := fsPayModelTS.RowSelectBuilder(nil).Where("order_number = ?", orderInfo.Sn).Where("pay_status =?", constants.PAYSTATUS_SUCCESS).Where("is_refund =?", 0)
payInfoList, err := fsPayModelTS.FindAll(ctx, rbFsPay, nil, "")
if err != nil {
return err
}
for _, payInfo := range payInfoList {
var key string
if *payInfo.PaymentMethod == int64(constants.PAYMETHOD_STRIPE) {
key = l.svcCtx.Config.PayConfig.Stripe.Key
}
payList = append(payList, handlerUtils.PayInfo{
TradeNo: *payInfo.TradeNo,
PaymentMethod: *payInfo.PaymentMethod,
Key: key,
})
}
return nil
})
// 退款申请--调取第三方接口发起退款
handlerUtils.PayRefundHandler(&handlerUtils.PayRefundHandlerReq{
PayInfoList: payList,
})
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeOrderCancelledNotOk, "the order cancle failed")
}
return resp.SetStatus(basic.CodeOK)
}

View File

@@ -1,7 +1,6 @@
Name: pay
Host: 0.0.0.0
Port: 9915
Timeout: 15000
SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest
Auth:
AccessSecret: fusen2023

View File

@@ -0,0 +1,35 @@
package handler
import (
"net/http"
"reflect"
"fusenapi/utils/basic"
"fusenapi/server/pay/internal/logic"
"fusenapi/server/pay/internal/svc"
"fusenapi/server/pay/internal/types"
)
func OrderRefundHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.OrderRefundReq
userinfo, err := basic.RequestParse(w, r, svcCtx, &req)
if err != nil {
return
}
// 创建一个业务逻辑层实例
l := logic.NewOrderRefundLogic(r.Context(), svcCtx)
rl := reflect.ValueOf(l)
basic.BeforeLogic(w, r, rl)
resp := l.OrderRefund(&req, userinfo)
if !basic.AfterLogic(w, r, rl, resp) {
basic.NormalAfterLogic(w, r, resp)
}
}
}

View File

@@ -17,6 +17,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/api/pay/payment-intent",
Handler: OrderPaymentIntentHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/api/pay/refund",
Handler: OrderRefundHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/api/pay/stripe-webhook",

View File

@@ -30,6 +30,15 @@ func StripeWebhookHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
// return
// }
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
req.RemoteAddr = IPAddress
req.Payload = payload
req.StripeSignature = r.Header.Get("Stripe-Signature")

View File

@@ -0,0 +1,43 @@
package logic
import (
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"context"
"fusenapi/server/pay/internal/svc"
"fusenapi/server/pay/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type OrderRefundLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewOrderRefundLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderRefundLogic {
return &OrderRefundLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 处理进入前逻辑w,r
// func (l *OrderRefundLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *OrderRefundLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }
func (l *OrderRefundLogic) OrderRefund(req *types.OrderRefundReq, userinfo *auth.UserInfo) (resp *basic.Response) {
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
// userinfo 传入值时, 一定不为null
return resp.SetStatus(basic.CodeOK)
}

View File

@@ -64,6 +64,21 @@ func (l *StripeWebhookLogic) StripeWebhook(req *types.StripeWebhookReq, userinfo
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "Webhook signature verification failed")
}
// 新增支付回调事件日志
var payMethod = int64(constants.PAYMETHOD_STRIPE)
var nowTime = time.Now().Unix()
var eventData = string(event.Data.Raw)
var fsPayEvent = &gmodel.FsPayEvent{
PayMethod: &payMethod,
EventId: &event.ID,
EventType: &event.Type,
EventData: &eventData,
EventCreated: &event.Created,
Ip: &req.RemoteAddr,
CreatedAt: &nowTime,
}
l.HandlePayEventCreate(fsPayEvent)
// Unmarshal the event data into an appropriate struct depending on its Type
switch event.Type {
case "charge.succeeded":
@@ -94,7 +109,7 @@ func (l *StripeWebhookLogic) StripeWebhook(req *types.StripeWebhookReq, userinfo
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_intent.succeeded")
}
err = l.handlePaymentIntentSucceeded(&paymentIntent)
err = l.HandlePaymentIntentSucceeded(&paymentIntent)
if err != nil {
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type Unhandled")
}
@@ -114,6 +129,12 @@ func (l *StripeWebhookLogic) StripeWebhook(req *types.StripeWebhookReq, userinfo
return resp.SetStatus(basic.CodeOK)
}
// 回调事件日志
func (l *StripeWebhookLogic) HandlePayEventCreate(fsPayEvent *gmodel.FsPayEvent) error {
_, err := gmodel.NewFsPayEventModel(l.svcCtx.MysqlConn).CreateOrUpdate(l.ctx, fsPayEvent)
return err
}
// session完成
// func (l *StripeWebhookLogic) handlePaymentSessionCompleted(sessionId string, tradeNo string) (err error) {
// // 查询支付记录
@@ -137,7 +158,7 @@ func (l *StripeWebhookLogic) StripeWebhook(req *types.StripeWebhookReq, userinfo
// }
// 成功的付款
func (l *StripeWebhookLogic) handlePaymentIntentSucceeded(paymentIntent *stripe.PaymentIntent) error {
func (l *StripeWebhookLogic) HandlePaymentIntentSucceeded(paymentIntent *stripe.PaymentIntent) error {
orderSn, ok := paymentIntent.Metadata["order_sn"]
if !ok || orderSn == "" {
return errors.New("order_sn not found")
@@ -146,14 +167,12 @@ func (l *StripeWebhookLogic) handlePaymentIntentSucceeded(paymentIntent *stripe.
// 查询支付记录
payModel := gmodel.NewFsPayModel(l.svcCtx.MysqlConn)
rsbPay := payModel.RowSelectBuilder(nil)
rsbPay = rsbPay.Where("order_number = ?", orderSn)
rsbPay = rsbPay.Where("order_number = ?", orderSn).Where("pay_status = ?", constants.PAYSTATUS_UNSUCCESS)
payInfo, err := payModel.FindOneByQuery(l.ctx, rsbPay, nil)
if err != nil {
return err
}
if *payInfo.PayStatus == 1 {
return errors.New("pay status 1")
}
//订单信息
orderDetailTemplateModel := gmodel.NewFsOrderDetailTemplateModel(l.svcCtx.MysqlConn)
orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
@@ -209,6 +228,7 @@ func (l *StripeWebhookLogic) handlePaymentIntentSucceeded(paymentIntent *stripe.
*payInfo.PayTime = nowTime
*payInfo.CardNo = card
*payInfo.Brand = brand
*payInfo.TradeNo = paymentIntent.ID
_, err = payModelT.CreateOrUpdate(ctx, payInfo)
if err != nil {
return err
@@ -244,12 +264,12 @@ func (l *StripeWebhookLogic) handlePaymentIntentSucceeded(paymentIntent *stripe.
// 支付记录是尾款
if *payInfo.PayStage == int64(constants.PAYSTAGE_REMAINING) {
if *orderInfo.Status < int64(constants.STATUS_NEW_PAY_COMPLETED) {
if *fsOrderRelInfo.Status < int64(constants.STATUS_NEW_PAY_COMPLETED) {
orderStatus = int64(constants.STATUS_NEW_PAY_COMPLETED)
}
orderIsPayCompleted = 1
orderInfo.IsPayCompleted = &orderIsPayCompleted
orderPayedAmount = *orderInfo.PayedAmount + paymentIntent.Amount
orderPayedAmount = *fsOrderRelInfo.PayedAmount + paymentIntent.Amount
}
// 更新订单信息

View File

@@ -5,6 +5,12 @@ import (
"fusenapi/utils/basic"
)
type OrderRefundReq struct {
}
type OrderRefundRes struct {
}
type OrderPaymentIntentReq struct {
Sn string `form:"sn"` //订单编号
DeliveryMethod int64 `form:"delivery_method"` //发货方式
@@ -20,6 +26,7 @@ type OrderPaymentIntentRes struct {
type StripeWebhookReq struct {
Payload []byte `json:"base_byte_slice,optional"`
StripeSignature string `json:"Stripe-Signature"`
RemoteAddr string `json:"remote_addr"`
}
type Request struct {