diff --git a/constants/pay.go b/constants/pay.go new file mode 100644 index 00000000..cd39d457 --- /dev/null +++ b/constants/pay.go @@ -0,0 +1,8 @@ +package constants + +type PayMethod int64 + +const ( + PAYMETHOD_STRIPE PayMethod = 1 + PAYMETHOD_PAYPAL PayMethod = 2 +) diff --git a/model/gmodel/fs_order_logic.go b/model/gmodel/fs_order_logic.go index 93f37a94..16c9a527 100755 --- a/model/gmodel/fs_order_logic.go +++ b/model/gmodel/fs_order_logic.go @@ -136,6 +136,27 @@ func (m *FsOrderModel) FindCount(ctx context.Context, countBuilder *gorm.DB, fil } } +// 事务 +func (m *FsOrderModel) Trans(ctx context.Context, fn func(ctx context.Context, connGorm *gorm.DB) error) error { + tx := m.db.Table(m.name).WithContext(ctx).Begin() + defer func() { + if r := recover(); r != nil { + tx.Rollback() + } + }() + + if err := tx.Error; err != nil { + return err + } + + if err := fn(ctx, tx); err != nil { + tx.Rollback() + return err + } + + return tx.Commit().Error +} + func (m *FsOrderModel) TableName() string { return m.name } diff --git a/model/gmodel/fs_pay_logic.go b/model/gmodel/fs_pay_logic.go index b8de697d..885c7dbc 100644 --- a/model/gmodel/fs_pay_logic.go +++ b/model/gmodel/fs_pay_logic.go @@ -14,3 +14,25 @@ func (p *FsPayModel) GetOrderPayList(ctx context.Context, sn string, payStatus i err = p.db.WithContext(ctx).Model(&FsPay{}).Where("`order_number` = ? and `pay_status` = ? and `is_refund` = ?", sn, payStatus, isRefund).Find(&resp).Error return resp, err } + +func (p *FsPayModel) GetListByOrderNumberStage(ctx context.Context, sn string, stage int64) (resp *FsPay, err error) { + err = p.db.Table(p.name).WithContext(ctx).Model(&FsPay{}).Where("`order_number` = ? ", sn).Where("`pay_stage` = ? ", stage).Take(&resp).Error + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *FsPayModel) CreateOrUpdate(ctx context.Context, req *FsPay) (resp *FsPay, err error) { + rowBuilder := p.db.Table(p.name).WithContext(ctx) + if req.Id > 0 { + err = rowBuilder.Save(req).Error + } else { + err = rowBuilder.Create(req).Error + } + return req, err +} + +func (m *FsPayModel) TableName() string { + return m.name +} diff --git a/server/home-user-auth/internal/handler/routes.go b/server/home-user-auth/internal/handler/routes.go index 75ac9d8f..91852e0d 100644 --- a/server/home-user-auth/internal/handler/routes.go +++ b/server/home-user-auth/internal/handler/routes.go @@ -82,6 +82,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { Path: "/api/user/order-list", Handler: UserOrderListHandler(serverCtx), }, + { + Method: http.MethodGet, + Path: "/api/user/order-delete", + Handler: UserOrderDeleteHandler(serverCtx), + }, { Method: http.MethodGet, Path: "/api/user/order-cancel", diff --git a/server/home-user-auth/internal/handler/userorderdeletehandler.go b/server/home-user-auth/internal/handler/userorderdeletehandler.go new file mode 100644 index 00000000..4b4ca392 --- /dev/null +++ b/server/home-user-auth/internal/handler/userorderdeletehandler.go @@ -0,0 +1,35 @@ +package handler + +import ( + "net/http" + "reflect" + + "fusenapi/utils/basic" + + "fusenapi/server/home-user-auth/internal/logic" + "fusenapi/server/home-user-auth/internal/svc" + "fusenapi/server/home-user-auth/internal/types" +) + +func UserOrderDeleteHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var req types.UserOrderDeleteReq + userinfo, err := basic.RequestParse(w, r, svcCtx, &req) + if err != nil { + return + } + + // 创建一个业务逻辑层实例 + l := logic.NewUserOrderDeleteLogic(r.Context(), svcCtx) + + rl := reflect.ValueOf(l) + basic.BeforeLogic(w, r, rl) + + resp := l.UserOrderDelete(&req, userinfo) + + if !basic.AfterLogic(w, r, rl, resp) { + basic.NormalAfterLogic(w, r, resp) + } + } +} diff --git a/server/home-user-auth/internal/logic/userorderdeletelogic.go b/server/home-user-auth/internal/logic/userorderdeletelogic.go new file mode 100644 index 00000000..0842b983 --- /dev/null +++ b/server/home-user-auth/internal/logic/userorderdeletelogic.go @@ -0,0 +1,78 @@ +package logic + +import ( + "errors" + "fusenapi/constants" + "fusenapi/model/gmodel" + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "context" + + "fusenapi/server/home-user-auth/internal/svc" + "fusenapi/server/home-user-auth/internal/types" + + "github.com/zeromicro/go-zero/core/logx" + "gorm.io/gorm" +) + +type UserOrderDeleteLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewUserOrderDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserOrderDeleteLogic { + return &UserOrderDeleteLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +// 处理进入前逻辑w,r +// func (l *UserOrderDeleteLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { +// } + +// 处理逻辑后 w,r 如:重定向, resp 必须重新处理 +// func (l *UserOrderDeleteLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { +// // httpx.OkJsonCtx(r.Context(), w, resp) +// } + +func (l *UserOrderDeleteLogic) UserOrderDelete(req *types.UserOrderDeleteReq, userinfo *auth.UserInfo) (resp *basic.Response) { + // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) + // userinfo 传入值时, 一定不为null + + if userinfo == nil || userinfo.UserId == 0 { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + } + + orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) + orderInfo, err := orderModel.FindOne(l.ctx, userinfo.UserId, req.ID) + + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + } + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") + } + + updateStatusMap := make(map[constants.Order]struct{}, 4) + updateStatusMap[constants.STATUS_NEW_COMPLETED] = struct{}{} + updateStatusMap[constants.STATUS_NEW_CANCEL] = struct{}{} + updateStatusMap[constants.STATUS_NEW_REFUNDED] = struct{}{} + updateStatusMap[constants.STATUS_NEW_CLOSE] = struct{}{} + if _, ok := updateStatusMap[constants.Order(*orderInfo.Status)]; !ok { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + } + *orderInfo.Status = int64(constants.STATUS_NEW_DELETE) + *orderInfo.IsDeleted = 1 + err = orderModel.Update(l.ctx, orderInfo) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "fail to delete") + } + + return resp.SetStatus(basic.CodeOK) +} diff --git a/server/home-user-auth/internal/types/types.go b/server/home-user-auth/internal/types/types.go index ef269467..81011e49 100644 --- a/server/home-user-auth/internal/types/types.go +++ b/server/home-user-auth/internal/types/types.go @@ -5,6 +5,13 @@ import ( "fusenapi/utils/basic" ) +type UserOrderDeleteReq struct { + ID int64 `form:"id"` //订单id +} + +type UserOrderDeleteRes struct { +} + type UserOrderCancelReq struct { ID int64 `form:"id"` //订单id RefundReasonId int64 `form:"refund_reason_id"` //退款配置id diff --git a/server/pay/etc/pay.yaml b/server/pay/etc/pay.yaml new file mode 100644 index 00000000..dcc6a6fe --- /dev/null +++ b/server/pay/etc/pay.yaml @@ -0,0 +1,13 @@ +Name: pay +Host: 0.0.0.0 +Port: 9915 +SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest +Auth: + AccessSecret: fusen2023 + AccessExpire: 2592000 + RefreshAfter: 1592000 +PayConfig: + Stripe: + Key: "sk_test_51IisojHygnIJZeghPVSBhkwySfcyDV4SoAduIxu3J7bvSJ9cZMD96LY1LO6SpdbYquLJX5oKvgEBB67KT9pecfCy00iEC4pp9y" + SuccessURL: "http://www.baidu.com" + CancelURL: "http://www.baidu.com" \ No newline at end of file diff --git a/server/pay/internal/config/config.go b/server/pay/internal/config/config.go new file mode 100644 index 00000000..d032023a --- /dev/null +++ b/server/pay/internal/config/config.go @@ -0,0 +1,21 @@ +package config + +import ( + "fusenapi/server/pay/internal/types" + + "github.com/zeromicro/go-zero/rest" +) + +type Config struct { + rest.RestConf + SourceMysql string + Auth types.Auth + + PayConfig struct { + Stripe struct { + Key string + SuccessURL string + CancelURL string + } + } +} diff --git a/server/pay/internal/handler/orderpaymentintenthandler.go b/server/pay/internal/handler/orderpaymentintenthandler.go new file mode 100644 index 00000000..d252d73c --- /dev/null +++ b/server/pay/internal/handler/orderpaymentintenthandler.go @@ -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 OrderPaymentIntentHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var req types.OrderPaymentIntentReq + userinfo, err := basic.RequestParse(w, r, svcCtx, &req) + if err != nil { + return + } + + // 创建一个业务逻辑层实例 + l := logic.NewOrderPaymentIntentLogic(r.Context(), svcCtx) + + rl := reflect.ValueOf(l) + basic.BeforeLogic(w, r, rl) + + resp := l.OrderPaymentIntent(&req, userinfo) + + if !basic.AfterLogic(w, r, rl, resp) { + basic.NormalAfterLogic(w, r, resp) + } + } +} diff --git a/server/pay/internal/handler/routes.go b/server/pay/internal/handler/routes.go new file mode 100644 index 00000000..13f9ba4c --- /dev/null +++ b/server/pay/internal/handler/routes.go @@ -0,0 +1,22 @@ +// Code generated by goctl. DO NOT EDIT. +package handler + +import ( + "net/http" + + "fusenapi/server/pay/internal/svc" + + "github.com/zeromicro/go-zero/rest" +) + +func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { + server.AddRoutes( + []rest.Route{ + { + Method: http.MethodPost, + Path: "/api/pay/payment-intent", + Handler: OrderPaymentIntentHandler(serverCtx), + }, + }, + ) +} diff --git a/server/pay/internal/logic/orderpaymentintentlogic.go b/server/pay/internal/logic/orderpaymentintentlogic.go new file mode 100644 index 00000000..98c5f0d0 --- /dev/null +++ b/server/pay/internal/logic/orderpaymentintentlogic.go @@ -0,0 +1,183 @@ +package logic + +import ( + "errors" + "fusenapi/constants" + "fusenapi/model/gmodel" + "fusenapi/utils/auth" + "fusenapi/utils/basic" + "fusenapi/utils/pay" + "time" + + "context" + + "fusenapi/server/pay/internal/svc" + "fusenapi/server/pay/internal/types" + + "github.com/zeromicro/go-zero/core/logx" + "gorm.io/gorm" +) + +type OrderPaymentIntentLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewOrderPaymentIntentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderPaymentIntentLogic { + return &OrderPaymentIntentLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +// 处理进入前逻辑w,r +// func (l *OrderPaymentIntentLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { +// } + +// 处理逻辑后 w,r 如:重定向, resp 必须重新处理 +// func (l *OrderPaymentIntentLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { +// // httpx.OkJsonCtx(r.Context(), w, resp) +// } + +func (l *OrderPaymentIntentLogic) OrderPaymentIntent(req *types.OrderPaymentIntentReq, userinfo *auth.UserInfo) (resp *basic.Response) { + // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) + // userinfo 传入值时, 一定不为null + + if userinfo == nil || userinfo.UserId == 0 { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + } + + // 查询订单数据 + orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) + orderInfo, err := orderModel.FindOneBySn(l.ctx, userinfo.UserId, req.Sn) + + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + } + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") + } + + // 校验订单状态 + if *orderInfo.IsCancel == 1 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "order cancelled") + } + + // 校验地址信息 + addressModel := gmodel.NewFsAddressModel(l.svcCtx.MysqlConn) + _, err = addressModel.GetOne(l.ctx, req.AddressId, userinfo.UserId) + + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "address not found") + } + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get address info") + } + + // 校验订单支付信息 + if *orderInfo.IsPayCompleted == 1 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "order is pay completed") + } + + // 判断订单状态以及该支付金额 + // 未支付 + var payAmount int64 + if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) { + payAmount = *orderInfo.TotalAmount / 2 + *orderInfo.DeliveryMethod = req.DeliveryMethod + *orderInfo.AddressId = req.AddressId + *orderInfo.PayMethod = req.PayMethod + } else { + payAmount = *orderInfo.TotalAmount - *orderInfo.TotalAmount/2 + } + + payConfig := &pay.Config{} + var generatePrepaymentReq = &pay.GeneratePrepaymentReq{ + ProductName: "aa", + Amount: payAmount, + Currency: "eur", + Quantity: 1, + ProductDescription: "ddddddddddddddddddddddd", + } + if constants.PayMethod(req.PayMethod) == constants.PAYMETHOD_STRIPE { + payConfig.Stripe.Key = l.svcCtx.Config.PayConfig.Stripe.Key + generatePrepaymentReq.SuccessURL = l.svcCtx.Config.PayConfig.Stripe.SuccessURL + generatePrepaymentReq.CancelURL = l.svcCtx.Config.PayConfig.Stripe.CancelURL + } + payDriver := pay.NewPayDriver(req.PayMethod, payConfig) + + var resData types.OrderPaymentIntentRes + // 事务处理 + err = orderModel.Trans(l.ctx, func(ctx context.Context, connGorm *gorm.DB) error { + // 支付预付--生成 + prepaymentRes, err := payDriver.GeneratePrepayment(generatePrepaymentReq) + if err != nil { + return err + } + resData.RedirectUrl = prepaymentRes.URL + + // 订单信息--修改 + err = gmodel.NewFsOrderModel(connGorm).Update(ctx, orderInfo) + if err != nil { + return err + } + + // 支付记录--处理 //支付记录改为一条订单多条,分首款尾款 + var createdAt int64 = time.Now().Unix() + var payStatus int64 = 0 + var orderSource int64 = 1 + var payStage int64 + var fspay *gmodel.FsPay + newFsPayModel := gmodel.NewFsPayModel(connGorm) + if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) { + fspay, err = newFsPayModel.GetListByOrderNumberStage(ctx, *orderInfo.Sn, 1) + if err != nil { + if !errors.Is(err, gorm.ErrRecordNotFound) { + return err + } + } + payStage = 1 + } else { + fspay, err = newFsPayModel.GetListByOrderNumberStage(ctx, *orderInfo.Sn, 2) + if err != nil { + if !errors.Is(err, gorm.ErrRecordNotFound) { + return err + } + } + payStage = 2 + } + if fspay == nil { + fspay = &gmodel.FsPay{ + UserId: orderInfo.UserId, + OrderNumber: orderInfo.Sn, + CreatedAt: &createdAt, + } + } else { + fspay.UpdatedAt = &createdAt + } + fspay.PayAmount = &payAmount + fspay.PayStage = &payStage + fspay.TradeNo = &prepaymentRes.TradeNo + fspay.PaymentMethod = &req.PayMethod + fspay.OrderSource = &orderSource + fspay.PayStatus = &payStatus + + _, err = newFsPayModel.CreateOrUpdate(ctx, fspay) + if err != nil { + return err + } + + return nil + }) + + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to make payment") + } + + return resp.SetStatusWithMessage(basic.CodeOK, "success", resData) +} diff --git a/server/pay/internal/svc/servicecontext.go b/server/pay/internal/svc/servicecontext.go new file mode 100644 index 00000000..e94ec174 --- /dev/null +++ b/server/pay/internal/svc/servicecontext.go @@ -0,0 +1,61 @@ +package svc + +import ( + "errors" + "fmt" + "fusenapi/server/pay/internal/config" + "net/http" + + "fusenapi/initalize" + "fusenapi/model/gmodel" + + "github.com/golang-jwt/jwt" + "gorm.io/gorm" +) + +type ServiceContext struct { + Config config.Config + + MysqlConn *gorm.DB + AllModels *gmodel.AllModelsGen +} + +func NewServiceContext(c config.Config) *ServiceContext { + + return &ServiceContext{ + Config: c, + MysqlConn: initalize.InitMysql(c.SourceMysql), + AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)), + } +} + +func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) { + AuthKey := r.Header.Get("Authorization") + if AuthKey == "" { + return nil, nil + } + AuthKey = AuthKey[7:] + + if len(AuthKey) <= 50 { + return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey))) + } + + token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) { + // 检查签名方法是否为 HS256 + if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + } + // 返回用于验证签名的密钥 + return []byte(svcCtx.Config.Auth.AccessSecret), nil + }) + if err != nil { + return nil, errors.New(fmt.Sprint("Error parsing token:", err)) + } + + // 验证成功返回 + if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { + return claims, nil + } + + return nil, errors.New(fmt.Sprint("Invalid token", err)) +} diff --git a/server/pay/internal/types/types.go b/server/pay/internal/types/types.go new file mode 100644 index 00000000..13a18778 --- /dev/null +++ b/server/pay/internal/types/types.go @@ -0,0 +1,86 @@ +// Code generated by goctl. DO NOT EDIT. +package types + +import ( + "fusenapi/utils/basic" +) + +type OrderPaymentIntentReq struct { + Sn string `form:"sn"` //订单编号 + DeliveryMethod int64 `form:"delivery_method"` //发货方式 + AddressId int64 `form:"address_id"` //地址id + PayMethod int64 `form:"pay_method"` //支付方式 +} + +type OrderPaymentIntentRes struct { + RedirectUrl string `json:"redirect_url"` +} + +type Request struct { +} + +type Response struct { + Code int `json:"code"` + Message string `json:"msg"` + Data interface{} `json:"data"` +} + +type Auth struct { + AccessSecret string `json:"accessSecret"` + AccessExpire int64 `json:"accessExpire"` + RefreshAfter int64 `json:"refreshAfter"` +} + +type File struct { + Filename string `fsfile:"filename"` + Header map[string][]string `fsfile:"header"` + Size int64 `fsfile:"size"` + Data []byte `fsfile:"data"` +} + +type Meta struct { + TotalCount int64 `json:"totalCount"` + PageCount int64 `json:"pageCount"` + CurrentPage int `json:"currentPage"` + PerPage int `json:"perPage"` +} + +// Set 设置Response的Code和Message值 +func (resp *Response) Set(Code int, Message string) *Response { + return &Response{ + Code: Code, + Message: Message, + } +} + +// Set 设置整个Response +func (resp *Response) SetWithData(Code int, Message string, Data interface{}) *Response { + return &Response{ + Code: Code, + Message: Message, + Data: Data, + } +} + +// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) *Response { + newResp := &Response{ + Code: sr.Code, + } + if len(data) == 1 { + newResp.Data = data[0] + } + return newResp +} + +// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) *Response { + newResp := &Response{ + Code: sr.Code, + Message: msg, + } + if len(data) == 1 { + newResp.Data = data[0] + } + return newResp +} diff --git a/server/pay/pay.go b/server/pay/pay.go new file mode 100644 index 00000000..08c53e12 --- /dev/null +++ b/server/pay/pay.go @@ -0,0 +1,36 @@ +package main + +import ( + "flag" + "fmt" + "net/http" + "time" + + "fusenapi/utils/auth" + + "fusenapi/server/pay/internal/config" + "fusenapi/server/pay/internal/handler" + "fusenapi/server/pay/internal/svc" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/pay.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + c.Timeout = int64(time.Second * 15) + server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { + })) + defer server.Stop() + + ctx := svc.NewServiceContext(c) + handler.RegisterHandlers(server, ctx) + + fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port) + server.Start() +} diff --git a/server/pay/pay_test.go b/server/pay/pay_test.go new file mode 100644 index 00000000..d035c13a --- /dev/null +++ b/server/pay/pay_test.go @@ -0,0 +1,12 @@ +package main + +import ( + "testing" +) + +// var configFile = flag.String("f", "etc/home-user-auth.yaml", "the config file") + +func TestMain(t *testing.T) { + // log.Println(model.RawFieldNames[FsCanteenType]()) + main() +} diff --git a/server/websocket/internal/config/config.go b/server/websocket/internal/config/config.go index b24bb7d7..3ed0e8c4 100644 --- a/server/websocket/internal/config/config.go +++ b/server/websocket/internal/config/config.go @@ -1,6 +1,10 @@ package config -import "github.com/zeromicro/go-zero/rest" +import ( + "fusenapi/server/websocket/internal/types" + + "github.com/zeromicro/go-zero/rest" +) type Config struct { rest.RestConf diff --git a/server_api/home-user-auth.api b/server_api/home-user-auth.api index f3a19304..bc07a158 100644 --- a/server_api/home-user-auth.api +++ b/server_api/home-user-auth.api @@ -60,12 +60,24 @@ service home-user-auth { @handler UserOrderListHandler get /api/user/order-list (UserOrderListReq) returns (response); + //删除订单 + @handler UserOrderDeleteHandler + get /api/user/order-delete (UserOrderDeleteReq) returns (response); + //取消订单 @handler UserOrderCancelHandler get /api/user/order-cancel (UserOrderCancelReq) returns (response); } +type ( + UserOrderDeleteReq { + ID int64 `form:"id"` //订单id + } + UserOrderDeleteRes { + } +) + //取消订单 type ( UserOrderCancelReq { diff --git a/server_api/pay.api b/server_api/pay.api new file mode 100644 index 00000000..f94d77a9 --- /dev/null +++ b/server_api/pay.api @@ -0,0 +1,29 @@ +syntax = "v1" + +info ( + title: 支付模块 + desc: 支付相关 + author: "" + email: "" +) + +import "basic.api" + +service pay { + + @handler OrderPaymentIntentHandler + post /api/pay/payment-intent(OrderPaymentIntentReq) returns (response); +} + +// 生成预付款 +type ( + OrderPaymentIntentReq { + Sn string `form:"sn"` //订单编号 + DeliveryMethod int64 `form:"delivery_method"` //发货方式 + AddressId int64 `form:"address_id"` //地址id + PayMethod int64 `form:"pay_method"` //支付方式 + } + OrderPaymentIntentRes { + RedirectUrl string `json:"redirect_url"` + } +) \ No newline at end of file diff --git a/utils/pay/pay.go b/utils/pay/pay.go new file mode 100644 index 00000000..005d700d --- /dev/null +++ b/utils/pay/pay.go @@ -0,0 +1,40 @@ +package pay + +import "fusenapi/constants" + +type Config struct { + // stripe支付 + Stripe Stripe +} + +// NewPayDriver 实例化方法 +func NewPayDriver(PayMethod int64, config *Config) Pay { + switch PayMethod { + case int64(constants.PAYMETHOD_STRIPE): + return &Stripe{Key: config.Stripe.Key} + default: + return &Stripe{Key: config.Stripe.Key} + } + +} + +// Pay 支付集成接口 +type Pay interface { + GeneratePrepayment(req *GeneratePrepaymentReq) (res *GeneratePrepaymentRes, err error) +} + +type GeneratePrepaymentReq struct { + Amount int64 `json:"amount"` // 支付金额 + Currency string `json:"currency"` // 支付货币 + ProductName string `json:"product_name"` // 商品名称 + ProductDescription string `json:"product_description"` // 商品描述 + ProductImages []*string `json:"product_imageso"` // 商品照片 + Quantity int64 `json:"quantity"` //数量 + SuccessURL string `json:"success_url"` // 支付成功回调 + CancelURL string `json:"cancel_url"` // 支付取消回调 +} + +type GeneratePrepaymentRes struct { + URL string `json:"url"` // 支付重定向地址 + TradeNo string `json:"trade_no"` //交易ID +} diff --git a/utils/pay/stripe.go b/utils/pay/stripe.go new file mode 100644 index 00000000..9dc5a2cf --- /dev/null +++ b/utils/pay/stripe.go @@ -0,0 +1,58 @@ +package pay + +import ( + "github.com/stripe/stripe-go/v74" + "github.com/stripe/stripe-go/v74/checkout/session" +) + +type Stripe struct { + Key string `json:"key"` +} + +// 生成预付款 +func (stripePay *Stripe) GeneratePrepayment(req *GeneratePrepaymentReq) (res *GeneratePrepaymentRes, err error) { + var productData stripe.CheckoutSessionLineItemPriceDataProductDataParams + + if req.ProductName != "" { + productData.Name = stripe.String(req.ProductName) + } + + if req.ProductDescription != "" { + productData.Description = stripe.String(req.ProductDescription) + } + + if len(req.ProductImages) > 0 { + productData.Images = req.ProductImages + } + // var images = make([]*string, 1) + // var image string = "https://img2.woyaogexing.com/2023/07/25/133132a32b9f79cfad84965a4bea57e0.jpg" + // images[0] = stripe.String(image) + // productData.Images = images + stripe.Key = stripePay.Key + + params := &stripe.CheckoutSessionParams{ + LineItems: []*stripe.CheckoutSessionLineItemParams{ + { + PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{ + Currency: stripe.String(req.Currency), + ProductData: &productData, + UnitAmount: stripe.Int64(req.Amount), + }, + Quantity: stripe.Int64(req.Quantity), + }, + }, + Mode: stripe.String(string(stripe.CheckoutSessionModePayment)), + SuccessURL: stripe.String(req.SuccessURL), + CancelURL: stripe.String(req.CancelURL), + } + result, err := session.New(params) + + if err != nil { + return nil, err + } + + return &GeneratePrepaymentRes{ + URL: result.URL, + TradeNo: result.ID, + }, err +}