Files
online-backend/internal/payment/visamasterpay/handler.go
GuwandykA 599c12ef87
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled
add some
2026-09-19 04:47:43 +05:00

182 lines
6.1 KiB
Go

package visamasterpay
import (
"errors"
"fmt"
"net/http"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/visa-master-payment-orders"
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
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)
// 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
// its own group with no JwtTokenCheck. See rbac.isPublicAdminPath,
// which must also list this path.
router.Group(baseURL).GET("/callback", h.callback)
}
// quote godoc
// @Summary Quote a visa/master/sber payment
// @Description Returns the current rate, configured fees, and max payable amount for an order's payout
// @Tags visa-master-payment-orders
// @Produce json
// @Security BearerAuth
// @Param id path int true "Visa/master payment order ID"
// @Success 200 {object} PaymentQuoteDTO
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /visa-master-payment-orders/{id}/quote [get]
func (h *handler) quote(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.Quote(c.Request.Context(), id)
if h.handleError(c, err, "quote") {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// pay godoc
// @Summary Start a visa/master/sber payout
// @Description Registers the payment with GBÜS and returns the hosted-payment-page URL to complete it on. The final outcome is only known once GBÜS redirects back to the callback, which verifies and finalizes it.
// @Tags visa-master-payment-orders
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Visa/master payment order ID"
// @Param body body PayOrderDTO true "Payment payload"
// @Success 200 {object} PaymentInitResultDTO
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /visa-master-payment-orders/{id}/pay [post]
func (h *handler) pay(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
}
var dto PayOrderDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if userID, ok := rbac.CurrentUserID(c); ok {
dto.CreatedBy = &userID
}
result, err := h.repository.Pay(c.Request.Context(), id, dto)
if h.handleError(c, err, "pay") {
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
// @Param paymentId query int true "Payment attempt ID"
// @Success 200 {string} string "html"
// @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.")))
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ň.")))
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.")))
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(`<!DOCTYPE html><html lang="tk"><head><meta charset="utf-8"><title>%s</title></head>
<body style="font-family:sans-serif;text-align:center;padding:48px;"><h2>%s</h2><p>%s</p></body></html>`, title, title, message)
}
func (h *handler) guardOrder(c *gin.Context, id int64) bool {
if rbac.SkipRecordGuard(c) {
return true
}
userID, branchID, err := h.repository.OwnerInfo(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardOrder(c, userID, branchID)
}
// handleError writes the appropriate response for a Quote/Pay error and
// reports whether the caller should stop (true) or continue with a
// successful result (false).
func (h *handler) handleError(c *gin.Context, err error, action string) bool {
if err == nil {
return false
}
switch {
case errors.Is(err, pgx.ErrNoRows):
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
case errors.Is(err, ErrAlreadyPaid), errors.Is(err, ErrAmountNotSet), errors.Is(err, ErrAmountExceedsMax), errors.Is(err, ErrPaymentWindowClosed):
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
default:
h.logger.Errorf("%s visa master payment order failed: %v", action, err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
}
return true
}