fusenapi/server/pay/internal/logic/stripewebhooklogic.go
2023-07-26 19:23:16 +08:00

228 lines
7.0 KiB
Go

package logic
import (
"encoding/json"
"errors"
"fusenapi/constants"
"fusenapi/model/gmodel"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"io"
"net/http"
"time"
"context"
"fusenapi/server/pay/internal/svc"
"fusenapi/server/pay/internal/types"
"github.com/stripe/stripe-go/v74"
"github.com/zeromicro/go-zero/core/logx"
"gorm.io/gorm"
)
type StripeWebhookLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
Payload []byte
}
func NewStripeWebhookLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StripeWebhookLogic {
return &StripeWebhookLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 处理进入前逻辑w,r
func (l *StripeWebhookLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
const MaxBodyBytes = int64(65536)
r.Body = http.MaxBytesReader(w, r.Body, MaxBodyBytes)
defer r.Body.Close()
payload, err := io.ReadAll(r.Body)
if err != nil {
logx.Error(err)
w.WriteHeader(http.StatusServiceUnavailable)
return
}
l.Payload = payload
}
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *StripeWebhookLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }
func (l *StripeWebhookLogic) StripeWebhook(req *types.StripeWebhookReq, userinfo *auth.UserInfo) (resp *basic.Response) {
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
// userinfo 传入值时, 一定不为null
event := stripe.Event{}
if err := json.Unmarshal(l.Payload, &event); err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail")
}
// Unmarshal the event data into an appropriate struct depending on its Type
switch event.Type {
case "payment_intent.succeeded":
var paymentIntent stripe.PaymentIntent
err := json.Unmarshal(event.Data.Raw, &paymentIntent)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_intent.succeeded")
}
err = l.handlePaymentIntentSucceeded(&paymentIntent)
if err != nil {
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type Unhandled")
}
case "payment_method.attached":
var paymentMethod stripe.PaymentMethod
err := json.Unmarshal(event.Data.Raw, &paymentMethod)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_method.attached")
}
// ... handle other event types
default:
logx.Error("Unhandled event")
return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type Unhandled")
}
return resp.SetStatus(basic.CodeOK)
}
// 成功的付款
func (l *StripeWebhookLogic) handlePaymentIntentSucceeded(paymentIntent *stripe.PaymentIntent) error {
// 查询支付记录
payModel := gmodel.NewFsPayModel(l.svcCtx.MysqlConn)
rsbPay := payModel.RowSelectBuilder(nil)
rsbPay = rsbPay.Where("trade_no = ?", paymentIntent.ID)
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)
rsbOrder := orderModel.RowSelectBuilder(nil)
rsbOrder = rsbOrder.Where("trade_no =?", paymentIntent.ID).Preload("FsOrderDetails")
rsbOrder = rsbOrder.Preload("FsOrderDetails", func(dbPreload *gorm.DB) *gorm.DB {
return dbPreload.Table(orderModel.TableName()).Preload("FsOrderDetailTemplateInfo", func(dbPreload *gorm.DB) *gorm.DB {
return dbPreload.Table(orderDetailTemplateModel.TableName()).Preload("FsProductDesignInfo")
})
})
fsOrderRel, err := orderModel.FindOneByQuery(l.ctx, rsbOrder, nil)
if err != nil {
return err
}
var designIds []int64
var cartIds []int64
if len(fsOrderRel.FsOrderDetails) > 0 {
for _, fsOrderDetail := range fsOrderRel.FsOrderDetails {
if fsOrderDetail.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 {
designIds = append(designIds, fsOrderDetail.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id)
}
cartIds = append(cartIds, *fsOrderDetail.CartId)
}
}
var nowTime int64 = time.Now().Unix()
// 支付成功
if paymentIntent.Status == "succeeded" {
var card string = paymentIntent.LatestCharge.PaymentMethodDetails.Card.Last4
var brand string = string(paymentIntent.LatestCharge.PaymentMethodDetails.Card.Brand)
err = orderModel.Trans(l.ctx, func(ctx context.Context, connGorm *gorm.DB) (err error) {
// 更新支付信息
payModelT := gmodel.NewFsPayModel(connGorm)
*payInfo.PayStatus = 1
*payInfo.PayTime = nowTime
*payInfo.CardNo = card
*payInfo.Brand = brand
_, err = payModelT.CreateOrUpdate(ctx, payInfo)
if err != nil {
return err
}
// 更新设计数据
productDesignModelT := gmodel.NewFsProductDesignModel(connGorm)
var isPay int64 = 1
err = productDesignModelT.UpdateByIds(ctx, designIds, &gmodel.FsProductDesign{IsPay: &isPay})
if err != nil {
return err
}
var orderInfo = &gmodel.FsOrder{}
// 支付记录是首款
if *payInfo.PayStage == int64(constants.PAYSTAGE_DEPOSIT) {
*orderInfo.Status = int64(constants.STATUS_NEW_PART_PAY)
*orderInfo.IsPartPay = 1
*orderInfo.PayedAmount = paymentIntent.Amount
// 删除购物车
cartModelT := gmodel.NewFsCartModel(connGorm)
err = cartModelT.DeleteCartsByIds(ctx, cartIds)
if err != nil {
return err
}
}
// 支付记录是尾款
if *payInfo.PayStage == int64(constants.PAYSTAGE_REMAINING) {
if *orderInfo.Status < int64(constants.STATUS_NEW_PAY_COMPLETED) {
*orderInfo.Status = int64(constants.STATUS_NEW_PAY_COMPLETED)
}
*orderInfo.IsPayCompleted = 1
*orderInfo.PayedAmount = *orderInfo.PayedAmount + paymentIntent.Amount
}
// 更新订单信息
*orderInfo.Ptime = nowTime
orderModelT := gmodel.NewFsOrderModel(connGorm)
err = orderModelT.Update(ctx, orderInfo)
if err != nil {
return err
}
return err
})
if err != nil {
return err
}
//千人千面的处理
// $renderServer = (new RenderService());
// $renderServer->thousandsFacesV2($order->id);
// //清除用户最新的设计
// $cache = \Yii::$app->cache;
// $cache->delete(CacheConfigHelper::LAST_DESIGN . $order->user_id);
// //缓存最新订单编号
// $cache->set(CacheConfigHelper::USER_ORDERNO . $order->user_id, $order->sn);
// //查询用户邮箱信息
// $user = \api\models\User::find()->where(['id' => $order->user_id])->one();
// $redisData = [
// 'key' => 'receipt_download',
// 'param' => [
// 'email' => $user->email,
// 'order_id' => $order->id,
// 'pay_id' => $pay->id,
// 'type' => 1,//付款成功为1
// ]
// ];
// Email::timely($redisData);
}
// 订单记录
return nil
}