diff --git a/internal/payment/visamasterpay/db/postgresql.go b/internal/payment/visamasterpay/db/postgresql.go index 49f1563..fbd0bae 100644 --- a/internal/payment/visamasterpay/db/postgresql.go +++ b/internal/payment/visamasterpay/db/postgresql.go @@ -127,7 +127,6 @@ func (r *repository) Quote(ctx context.Context, orderID int64) (visamasterpay.Pa // that callback URL - the callback then never has to trust anything GBÜS // passes back except to look up our own row. func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.PayOrderDTO) (visamasterpay.PaymentInitResultDTO, error) { - println("[pay] step 1: loading order", orderID) var orderType *string var paid bool var branchID int64 @@ -137,46 +136,32 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P orderID, ).Scan(&orderType, &paid, &branchID, &userID) if err != nil { - println("[pay] step 1 FAILED: load order:", err.Error()) return visamasterpay.PaymentInitResultDTO{}, err } - println("[pay] step 1 ok: type=", derefOrEmpty(orderType), "paid=", paid, "branchId=", branchID, "userId=", userID) - println("[pay] step 2: checking payable day") if !isPayableDay(time.Now()) { - println("[pay] step 2 FAILED: payment window closed") r.logStep(ctx, orderID, dto.CreatedBy, "rejected", map[string]string{"reason": "payment_window_closed"}) return visamasterpay.PaymentInitResultDTO{}, visamasterpay.ErrPaymentWindowClosed } - println("[pay] step 3: checking already paid") if paid { - println("[pay] step 3 FAILED: already paid") r.logStep(ctx, orderID, dto.CreatedBy, "rejected", map[string]string{"reason": "already_paid"}) return visamasterpay.PaymentInitResultDTO{}, visamasterpay.ErrAlreadyPaid } - println("[pay] step 4: fetching USD rate") usdRate, err := r.fetchRate(ctx, "USD") if err != nil { - println("[pay] step 4 FAILED: fetch USD rate:", err.Error()) return visamasterpay.PaymentInitResultDTO{}, err } - println("[pay] step 4 ok: usdRate=", usdRate) - println("[pay] step 5: fetching payment settings") settings, err := r.settingsRepo.Get(ctx) if err != nil { - println("[pay] step 5 FAILED: fetch settings:", err.Error()) return visamasterpay.PaymentInitResultDTO{}, err } - println("[pay] step 5 ok: maxAmountUsd=", settings.MaxAmountUsd) - println("[pay] step 6: validating amount") maxAmountTmt := round2(settings.MaxAmountUsd * usdRate) amountTmt := maxAmountTmt if dto.AmountTmt != nil { if *dto.AmountTmt <= 0 || *dto.AmountTmt > maxAmountTmt { - println("[pay] step 6 FAILED: amount exceeds max, requested=", *dto.AmountTmt, "max=", maxAmountTmt) r.logStep(ctx, orderID, dto.CreatedBy, "rejected", map[string]interface{}{ "reason": "amount_exceeds_max", "requestedAmountTmt": *dto.AmountTmt, "maxAmountTmt": maxAmountTmt, }) @@ -184,13 +169,11 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P } amountTmt = round2(*dto.AmountTmt) } - println("[pay] step 6 ok: amountTmt=", amountTmt, "maxAmountTmt=", maxAmountTmt) r.logStep(ctx, orderID, dto.CreatedBy, "validated", map[string]interface{}{ "orderType": derefOrEmpty(orderType), "maxAmountUsd": settings.MaxAmountUsd, "amountTmt": amountTmt, "exchangeRateUsd": usdRate, }) - println("[pay] step 7: calculating fees") sber := isSber(orderType) var rubRate *float64 var bankFeeTmt float64 @@ -200,7 +183,6 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P if sber { rate, err := r.fetchRate(ctx, "RUB") if err != nil { - println("[pay] step 7 FAILED: fetch RUB rate:", err.Error()) return visamasterpay.PaymentInitResultDTO{}, err } tveb := round2(settings.TvebFeeUsd * usdRate) @@ -215,7 +197,6 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P gbusFeeTmt = &settings.GbusFeeTmt total = round2(amountTmt + bankFeeTmt + settings.GbusFeeTmt) } - println("[pay] step 7 ok: bankFeeTmt=", bankFeeTmt, "totalAmountTmt=", total) period := time.Now() if dto.PaymentPeriod != nil { @@ -227,15 +208,11 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P "exchangeRateRub": rubRate, "totalAmountTmt": total, }) - println("[pay] step 8: fetching branch credentials for branchId=", branchID) username, password, err := r.branchCredentials(ctx, branchID, sber) if err != nil { - println("[pay] step 8 FAILED: branch credentials:", err.Error()) return visamasterpay.PaymentInitResultDTO{}, err } - println("[pay] step 8 ok") - println("[pay] step 9: inserting pending payment row") paymentID, err := insertPendingPayment(ctx, r.client, insertParams{ orderID: orderID, userID: userID, period: period, rateUsd: usdRate, rateRub: rubRate, amountTmt: amountTmt, @@ -243,10 +220,8 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P total: total, createdBy: dto.CreatedBy, }) if err != nil { - println("[pay] step 9 FAILED: insert pending payment:", err.Error()) return visamasterpay.PaymentInitResultDTO{}, err } - println("[pay] step 9 ok: paymentId=", paymentID) returnURL := fmt.Sprintf("%s/api/admin/visa-master-payment-orders/callback?paymentId=%d", r.publicBaseURL, paymentID) orderNumber := fmt.Sprintf("vmo-%d-%d", orderID, paymentID) @@ -262,16 +237,13 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P Username: username, Password: password, } - println("[pay] step 10: sending register request to gateway, orderNumber=", orderNumber, "amountMinor=", registerReq.AmountMinor) r.logStep(ctx, orderID, dto.CreatedBy, "register_request", map[string]interface{}{ "paymentId": paymentID, "orderNumber": orderNumber, "amountMinor": registerReq.AmountMinor, "returnUrl": returnURL, }) result, regErr := r.gateway.Register(ctx, registerReq) - println("[pay] step 11: gateway register response received, success=", result.Success(), "errorCode=", result.ErrorCode, "errorMessage=", result.ErrorMessage) if regErr != nil || !result.Success() { - println("[pay] step 11 FAILED: register error:", errString(regErr)) if r.logger != nil && regErr != nil { r.logger.Errorf("visa master payment register failed for order %d payment %d: %v", orderID, paymentID, regErr) } @@ -287,26 +259,16 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P "success": true, "gbusOrderId": result.OrderId, "formUrl": result.FormUrl, "rawResponse": rawJSON(result.RawResponse), }) - println("[pay] step 12: updating gateway result to pending, gbusOrderId=", result.OrderId) ref := result.OrderId if err := updatePaymentGatewayResult(ctx, r.client, paymentID, "pending", &ref, result.RawResponse); err != nil { - println("[pay] step 12 FAILED:", err.Error()) return visamasterpay.PaymentInitResultDTO{}, err } - println("[pay] step 13 done: paymentId=", paymentID, "formUrl=", result.FormUrl, "successUrl=", returnURL) return visamasterpay.PaymentInitResultDTO{PaymentId: paymentID, OrderId: orderID, FormUrl: result.FormUrl, SuccessUrl: returnURL}, nil } -// HandleCallback is hit (unauthenticated - see rbac.isPublicAdminPath) when -// GBÜS redirects the customer's/operator's browser back after payment. It -// never trusts that request itself: it looks up the pending attempt by the -// paymentId we embedded in returnUrl, then verifies the real outcome with -// GBÜS server-to-server before ever marking anything paid. Idempotent: a -// replayed callback on an already-finalized attempt just returns its -// current state without calling GBÜS again. func (r *repository) HandleCallback(ctx context.Context, paymentID int64) (visamasterpay.PaymentResultDTO, error) { - println("[callback] step 1: loading payment", paymentID) + var orderID int64 var gatewayStatus string var gatewayReference *string @@ -316,26 +278,20 @@ func (r *repository) HandleCallback(ctx context.Context, paymentID int64) (visam paymentID, ).Scan(&orderID, &gatewayStatus, &gatewayReference, &createdBy) if errors.Is(err, pgx.ErrNoRows) { - println("[callback] step 1 FAILED: payment not found") return visamasterpay.PaymentResultDTO{}, visamasterpay.ErrPaymentNotFound } if err != nil { - println("[callback] step 1 FAILED: load payment:", err.Error()) return visamasterpay.PaymentResultDTO{}, err } - println("[callback] step 1 ok: orderId=", orderID, "gatewayStatus=", gatewayStatus) - println("[callback] step 2: loading order", orderID) var orderType *string var amountUsd *float64 var branchID int64 if err := r.client.QueryRow(ctx, `SELECT type, amount_usd, branch_id FROM visa_master_payment_orders WHERE id = $1 AND deleted_at IS NULL`, orderID, ).Scan(&orderType, &amountUsd, &branchID); err != nil { - println("[callback] step 2 FAILED: load order:", err.Error()) return visamasterpay.PaymentResultDTO{}, err } - println("[callback] step 2 ok: type=", derefOrEmpty(orderType), "branchId=", branchID) finish := func(item visamasterpay.PaymentResultDTO) visamasterpay.PaymentResultDTO { item.Type = derefOrEmpty(orderType) @@ -345,97 +301,70 @@ func (r *repository) HandleCallback(ctx context.Context, paymentID int64) (visam return item } - println("[callback] step 3: checking gateway status") if gatewayStatus != "pending" { - println("[callback] step 3: already finalized, gatewayStatus=", gatewayStatus) item, err := fetchPaymentByID(ctx, r.client, paymentID) if err != nil { - println("[callback] step 3 FAILED: fetch payment:", err.Error()) return visamasterpay.PaymentResultDTO{}, err } item.Paid = item.GatewayStatus == "success" - println("[callback] step 3 done: returning cached result, paid=", item.Paid) return finish(item), nil } - println("[callback] step 3 ok: still pending") - println("[callback] step 4: checking gateway reference") if gatewayReference == nil || *gatewayReference == "" { - println("[callback] step 4 FAILED: no gateway reference yet") return visamasterpay.PaymentResultDTO{}, fmt.Errorf("payment %d has no gateway reference yet", paymentID) } - println("[callback] step 4 ok: gbusOrderId=", *gatewayReference) - println("[callback] step 5: fetching branch credentials for branchId=", branchID) username, password, err := r.branchCredentials(ctx, branchID, isSber(orderType)) if err != nil { - println("[callback] step 5 FAILED: branch credentials:", err.Error()) return visamasterpay.PaymentResultDTO{}, err } - println("[callback] step 5 ok") r.logStep(ctx, orderID, createdBy, "callback_received", map[string]interface{}{"paymentId": paymentID}) r.logStep(ctx, orderID, createdBy, "status_check_request", map[string]interface{}{"gbusOrderId": *gatewayReference}) - println("[callback] step 6: sending status check request to gateway") status, err := r.gateway.CheckStatus(ctx, paymentgateway.StatusRequest{OrderId: *gatewayReference, Username: username, Password: password}) if err != nil { - println("[callback] step 6 FAILED: check status:", err.Error()) r.logStep(ctx, orderID, createdBy, "status_check_response", map[string]interface{}{"error": errString(err)}) return visamasterpay.PaymentResultDTO{}, err } - println("[callback] step 6 ok: paid=", status.Paid, "orderStatus=", status.OrderStatus, "actionCode=", status.ActionCode) + r.logStep(ctx, orderID, createdBy, "status_check_response", map[string]interface{}{ "paid": status.Paid, "orderStatus": status.OrderStatus, "actionCode": status.ActionCode, "actionCodeDescription": status.ActionCodeDescription, "rawResponse": rawJSON(status.RawResponse), }) - println("[callback] step 7: finalizing payment, paid=", status.Paid) var item visamasterpay.PaymentResultDTO if status.Paid { - println("[callback] step 7a: starting transaction") tx, err := r.client.Begin(ctx) if err != nil { - println("[callback] step 7a FAILED: begin tx:", err.Error()) return visamasterpay.PaymentResultDTO{}, err } defer tx.Rollback(ctx) - println("[callback] step 7b: locking order row") var lockedPaid bool if err := tx.QueryRow(ctx, `SELECT paid FROM visa_master_payment_orders WHERE id = $1 FOR UPDATE`, orderID).Scan(&lockedPaid); err != nil { - println("[callback] step 7b FAILED: lock order:", err.Error()) return visamasterpay.PaymentResultDTO{}, err } - println("[callback] step 7b ok: lockedPaid=", lockedPaid) if !lockedPaid { - println("[callback] step 7c: marking order paid and completed") if _, err := tx.Exec(ctx, `UPDATE visa_master_payment_orders SET paid = true, status = 'completed', updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $1`, orderID, ); err != nil { - println("[callback] step 7c FAILED: mark order paid:", err.Error()) return visamasterpay.PaymentResultDTO{}, err } } - println("[callback] step 7d: updating payment status to success") item, err = updatePaymentStatus(ctx, tx, paymentID, "success", status.RawResponse) if err != nil { - println("[callback] step 7d FAILED:", err.Error()) return visamasterpay.PaymentResultDTO{}, err } - println("[callback] step 7e: committing transaction") if err := tx.Commit(ctx); err != nil { - println("[callback] step 7e FAILED: commit tx:", err.Error()) return visamasterpay.PaymentResultDTO{}, err } } else { - println("[callback] step 7f: updating payment status to failed") item, err = updatePaymentStatus(ctx, r.client, paymentID, "failed", status.RawResponse) if err != nil { - println("[callback] step 7f FAILED:", err.Error()) return visamasterpay.PaymentResultDTO{}, err } } @@ -443,10 +372,29 @@ func (r *repository) HandleCallback(ctx context.Context, paymentID int64) (visam r.logStep(ctx, orderID, createdBy, "payment_finalized", map[string]interface{}{"paymentId": paymentID, "paid": status.Paid}) item.Paid = status.Paid - println("[callback] step 8 done: paymentId=", paymentID, "paid=", item.Paid) return finish(item), nil } +// Status re-checks orderID's latest payment attempt via HandleCallback - +// for when the frontend can't rely on GBÜS's redirect having reached the +// callback (e.g. the user closed the hosted payment page first). Safe to +// call repeatedly: HandleCallback only hits GBÜS while the attempt is still +// "pending" and otherwise just returns the already-finalized row. +func (r *repository) Status(ctx context.Context, orderID int64) (visamasterpay.PaymentResultDTO, error) { + var paymentID int64 + err := r.client.QueryRow(ctx, + `SELECT id FROM visa_master_order_payments WHERE order_id = $1 AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 1`, + orderID, + ).Scan(&paymentID) + if errors.Is(err, pgx.ErrNoRows) { + return visamasterpay.PaymentResultDTO{}, visamasterpay.ErrPaymentNotFound + } + if err != nil { + return visamasterpay.PaymentResultDTO{}, err + } + return r.HandleCallback(ctx, paymentID) +} + // branchCredentials picks the sber or visa/master MPI merchant credentials // for a branch, matching the type of order being paid. func (r *repository) branchCredentials(ctx context.Context, branchID int64, sber bool) (username, password string, err error) { @@ -475,17 +423,8 @@ func (r *repository) fetchRate(ctx context.Context, from string) (float64, error return strconv.ParseFloat(result.Currencies[0].Value.String(), 64) } -// ashgabatZone is Turkmenistan's fixed UTC+5 offset (no DST observed). var ashgabatZone = time.FixedZone("+05", 5*60*60) -// isPayableDay reports whether GBÜS payouts can be initiated on t's -// Ashgabat-local calendar day - false on Saturday/Sunday, since GBÜS/the -// bank does not process payouts on weekends. Because Saturday and Sunday -// are always adjacent, this alone also produces the right month-end cutoff -// (e.g. if the 31st is a Sunday, the 30th is a Saturday, so the 29th - -// Friday - is the last payable day) without any separate month-end logic. -// TODO: re-enable before deploying to prod - temporarily left open to allow -// testing the pay flow on weekends. const skipPayableDayCheck = true func isPayableDay(t time.Time) bool { @@ -635,9 +574,6 @@ func firstNonEmpty(values ...string) string { return "unknown error" } -// rawJSON re-encodes an already-JSON []byte as json.RawMessage so it nests -// as real JSON inside a logStep detail payload instead of being escaped as -// a base64 string; nil/empty stays nil. func rawJSON(raw []byte) json.RawMessage { if len(raw) == 0 { return nil diff --git a/internal/payment/visamasterpay/dto.go b/internal/payment/visamasterpay/dto.go index b5f99e9..169d65a 100644 --- a/internal/payment/visamasterpay/dto.go +++ b/internal/payment/visamasterpay/dto.go @@ -55,6 +55,15 @@ type PaymentInitResultDTO struct { SuccessUrl string `json:"successUrl"` } +// CallbackResultDTO is what the GBÜS callback responds with, once GBÜS +// redirects the browser back after payment. Paid reflects the verified +// server-to-server outcome (not merely that GBÜS redirected here), and Data +// is a Turkmen-language message describing the result for display. +type CallbackResultDTO struct { + Paid bool `json:"paid"` + Data string `json:"data"` +} + // PaymentResultDTO is one payout attempt's final, verified state, recorded // as its own row in visa_master_order_payments (a full audit trail - // failed attempts are kept, not overwritten by a retry) - deliberately not diff --git a/internal/payment/visamasterpay/handler.go b/internal/payment/visamasterpay/handler.go index dd0ad01..06e857c 100644 --- a/internal/payment/visamasterpay/handler.go +++ b/internal/payment/visamasterpay/handler.go @@ -2,7 +2,6 @@ package visamasterpay import ( "errors" - "fmt" "net/http" "online-back/internal/appresult" @@ -30,6 +29,7 @@ func (h *handler) Register(router *gin.RouterGroup) { group := router.Group(baseURL, appresult.JwtTokenCheck()) group.GET("/:id/quote", h.quote) group.POST("/:id/pay", h.pay) + group.GET("/:id/status", h.status) // callback is hit by the customer's/operator's browser after GBÜS // redirects back - it carries no Bearer token, so it's registered on @@ -111,38 +111,64 @@ func (h *handler) pay(c *gin.Context) { c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } +// status godoc +// @Summary Re-check a visa/master/sber order's latest payment attempt +// @Description For when the frontend can't rely on GBÜS's redirect having reached the callback (e.g. the user closed the hosted payment page first) - re-verifies the latest attempt with GBÜS server-to-server, the same way the callback does, and finalizes it if needed. Safe to call repeatedly. +// @Tags visa-master-payment-orders +// @Produce json +// @Security BearerAuth +// @Param id path int true "Visa/master payment order ID" +// @Success 200 {object} PaymentResultDTO +// @Failure 400 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /visa-master-payment-orders/{id}/status [get] +func (h *handler) status(c *gin.Context) { + id, ok := shared.ParseID(c.Param("id")) + if !ok { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + if !h.guardOrder(c, id) { + return + } + + result, err := h.repository.Status(c.Request.Context(), id) + if h.handleError(c, err, "status") { + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(result)) +} + // callback godoc // @Summary GBÜS payment callback // @Description GBÜS redirects the browser here after payment; the real outcome is verified server-to-server before anything is finalized // @Tags visa-master-payment-orders -// @Produce html +// @Produce json // @Param paymentId query int true "Payment attempt ID" -// @Success 200 {string} string "html" +// @Success 200 {object} CallbackResultDTO // @Router /visa-master-payment-orders/callback [get] func (h *handler) callback(c *gin.Context) { paymentID, ok := shared.ParseID(c.Query("paymentId")) if !ok { - c.Data(http.StatusBadRequest, "text/html; charset=utf-8", []byte(callbackPage("Ýalňyşlyk", "Töleg maglumaty tapylmady."))) + c.JSON(http.StatusBadRequest, CallbackResultDTO{Paid: false, Data: "Töleg maglumaty tapylmady."}) return } result, err := h.repository.HandleCallback(c.Request.Context(), paymentID) if err != nil { h.logger.Errorf("visa master payment callback failed (paymentId=%d): %v", paymentID, err) - c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(callbackPage("Ýalňyşlyk", "Tölegiň netijesini barlap bolmady. Operator bilen habarlaşyň."))) + c.JSON(http.StatusOK, CallbackResultDTO{Paid: false, Data: "Tölegiň netijesini barlap bolmady. Operator bilen habarlaşyň."}) return } if result.Paid { - c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(callbackPage("Töleg üstünlikli", "Töleg tamamlandy. Bu penjiräni ýapyp bilersiňiz."))) + c.JSON(http.StatusOK, CallbackResultDTO{Paid: true, Data: "Töleg amala aşyryldy."}) return } - c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(callbackPage("Töleg amala aşmady", "Töleg tamamlanmady ýa-da ret edildi. Operator bilen habarlaşyň."))) -} - -func callbackPage(title, message string) string { - return fmt.Sprintf(`%s -

%s

%s

`, title, title, message) + c.JSON(http.StatusOK, CallbackResultDTO{Paid: false, Data: "Töleg amala aşyrylmady."}) } func (h *handler) guardOrder(c *gin.Context, id int64) bool { @@ -169,7 +195,7 @@ func (h *handler) handleError(c *gin.Context, err error, action string) bool { return false } switch { - case errors.Is(err, pgx.ErrNoRows): + case errors.Is(err, pgx.ErrNoRows), errors.Is(err, ErrPaymentNotFound): c.JSON(http.StatusNotFound, appresult.ErrNotFound) case errors.Is(err, ErrAlreadyPaid), errors.Is(err, ErrAmountExceedsMax), errors.Is(err, ErrPaymentWindowClosed): c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable) diff --git a/internal/payment/visamasterpay/storage.go b/internal/payment/visamasterpay/storage.go index ace0f13..a988a5b 100644 --- a/internal/payment/visamasterpay/storage.go +++ b/internal/payment/visamasterpay/storage.go @@ -33,4 +33,10 @@ type Repository interface { // HandleCallback verifies a payment attempt's real outcome with GBÜS // (never trusting the callback request itself) and finalizes it. HandleCallback(ctx context.Context, paymentID int64) (PaymentResultDTO, error) + // Status re-checks the order's latest payment attempt the same way + // HandleCallback does - for the frontend to call (authenticated, + // order-scoped) when it can't rely on GBÜS having redirected the + // browser back to the callback, e.g. the user closed the hosted + // payment page before the redirect fired. + Status(ctx context.Context, orderID int64) (PaymentResultDTO, error) }