add pay
This commit is contained in:
@@ -18,4 +18,5 @@ minio:
|
||||
bucket: dev-minio
|
||||
use_ssl: false
|
||||
app_version: 0.0.1
|
||||
public_file_path: ./public
|
||||
public_file_path: ./public
|
||||
public_base_url: https://your-api-domain.example # used to build the GBÜS payment callback (returnUrl)
|
||||
@@ -1,18 +1,8 @@
|
||||
-- Reverse 20260918130000_add_payment_settings_and_visamaster_pay.up.sql
|
||||
DROP TABLE IF EXISTS visa_master_payment_logs;
|
||||
DROP TABLE IF EXISTS visa_master_order_payments;
|
||||
|
||||
ALTER TABLE visa_master_payment_orders
|
||||
DROP COLUMN IF EXISTS amount_usd,
|
||||
DROP COLUMN IF EXISTS exchange_rate,
|
||||
DROP COLUMN IF EXISTS exchange_rate_rub,
|
||||
DROP COLUMN IF EXISTS amount_tmt,
|
||||
DROP COLUMN IF EXISTS bank_fee_tmt,
|
||||
DROP COLUMN IF EXISTS gbus_fee_tmt,
|
||||
DROP COLUMN IF EXISTS tveb_fee_usd,
|
||||
DROP COLUMN IF EXISTS tveb_fee_tmt,
|
||||
DROP COLUMN IF EXISTS total_amount_tmt,
|
||||
DROP COLUMN IF EXISTS payment_period,
|
||||
DROP COLUMN IF EXISTS gateway_status,
|
||||
DROP COLUMN IF EXISTS gateway_reference,
|
||||
DROP COLUMN IF EXISTS gateway_response,
|
||||
DROP COLUMN IF EXISTS paid_at;
|
||||
DROP COLUMN IF EXISTS amount_usd;
|
||||
|
||||
DROP TABLE IF EXISTS payment_settings;
|
||||
|
||||
@@ -5,11 +5,22 @@
|
||||
-- orders use bank_fee_tmt + gbus_fee_tmt; Sber orders use their own
|
||||
-- sber_bank_fee_tmt plus a USD-denominated tveb_fee_usd (converted to
|
||||
-- TMT at payout time via the USD rate) - Sber has no GBÜS fee.
|
||||
-- 2. visa_master_payment_orders gains the requested USD amount plus the
|
||||
-- payout columns (rate(s), TMT amount, fees, total, gateway result)
|
||||
-- filled in once the order is paid out. The Sber-specific columns
|
||||
-- (exchange_rate_rub, tveb_fee_usd, tveb_fee_tmt) stay null for
|
||||
-- non-Sber orders, same as gbus_fee_tmt stays null for Sber ones.
|
||||
-- 2. visa_master_payment_orders gains only the requested USD amount
|
||||
-- (order data, set when the order is created). It already has `paid`.
|
||||
-- 3. visa_master_order_payments records every payout attempt for an
|
||||
-- order as its own row - kept as a full audit trail (including failed
|
||||
-- gateway attempts) rather than columns on the order itself, so a
|
||||
-- retry after a failure doesn't erase what the previous attempt did.
|
||||
-- The Sber-specific columns (exchange_rate_rub, tveb_fee_usd,
|
||||
-- tveb_fee_tmt) stay null for non-Sber attempts, same as
|
||||
-- gbus_fee_tmt stays null for Sber ones.
|
||||
-- 4. visa_master_payment_logs records every individual step taken while
|
||||
-- processing a payout (validated, rate fetched, gateway request sent,
|
||||
-- gateway response received, order marked paid/attempt recorded) as
|
||||
-- its own row, so there's a step-by-step, timestamped record of what
|
||||
-- actually happened for a given order - evidence if a payout is later
|
||||
-- disputed, independent of (and more granular than) the one summary
|
||||
-- row in visa_master_order_payments.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS payment_settings (
|
||||
id smallint PRIMARY KEY DEFAULT 1,
|
||||
@@ -29,17 +40,50 @@ VALUES (1, 100, 15, 100, 18)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
ALTER TABLE visa_master_payment_orders
|
||||
ADD COLUMN amount_usd numeric(18, 2),
|
||||
ADD COLUMN exchange_rate numeric(18, 8),
|
||||
ADD COLUMN exchange_rate_rub numeric(18, 8),
|
||||
ADD COLUMN amount_tmt numeric(18, 2),
|
||||
ADD COLUMN bank_fee_tmt numeric(12, 2),
|
||||
ADD COLUMN gbus_fee_tmt numeric(12, 2),
|
||||
ADD COLUMN tveb_fee_usd numeric(12, 2),
|
||||
ADD COLUMN tveb_fee_tmt numeric(12, 2),
|
||||
ADD COLUMN total_amount_tmt numeric(18, 2),
|
||||
ADD COLUMN payment_period date,
|
||||
ADD COLUMN gateway_status character varying(32) NOT NULL DEFAULT 'pending',
|
||||
ADD COLUMN gateway_reference character varying(255),
|
||||
ADD COLUMN gateway_response jsonb,
|
||||
ADD COLUMN paid_at TIMESTAMP;
|
||||
ADD COLUMN amount_usd numeric(18, 2);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS visa_master_order_payments (
|
||||
id bigserial PRIMARY KEY,
|
||||
order_id bigint NOT NULL,
|
||||
user_id bigint NOT NULL,
|
||||
payment_period date NOT NULL,
|
||||
exchange_rate_usd numeric(18, 8) NOT NULL,
|
||||
exchange_rate_rub numeric(18, 8),
|
||||
amount_tmt numeric(18, 2) NOT NULL,
|
||||
bank_fee_tmt numeric(12, 2) NOT NULL,
|
||||
gbus_fee_tmt numeric(12, 2),
|
||||
tveb_fee_usd numeric(12, 2),
|
||||
tveb_fee_tmt numeric(12, 2),
|
||||
total_amount_tmt numeric(18, 2) NOT NULL,
|
||||
gateway_status character varying(32) NOT NULL DEFAULT 'pending',
|
||||
gateway_reference character varying(255),
|
||||
gateway_response jsonb,
|
||||
created_by bigint,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
CONSTRAINT visa_master_order_payments_order_id_fkey
|
||||
FOREIGN KEY (order_id) REFERENCES visa_master_payment_orders(id),
|
||||
CONSTRAINT visa_master_order_payments_user_id_fkey
|
||||
FOREIGN KEY (user_id) REFERENCES users(id),
|
||||
CONSTRAINT visa_master_order_payments_created_by_fkey
|
||||
FOREIGN KEY (created_by) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS visa_master_order_payments_order_id_idx ON visa_master_order_payments (order_id);
|
||||
CREATE INDEX IF NOT EXISTS visa_master_order_payments_user_id_idx ON visa_master_order_payments (user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS visa_master_payment_logs (
|
||||
id bigserial PRIMARY KEY,
|
||||
order_id bigint NOT NULL,
|
||||
step character varying(100) NOT NULL,
|
||||
detail jsonb,
|
||||
created_by bigint,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
CONSTRAINT visa_master_payment_logs_order_id_fkey
|
||||
FOREIGN KEY (order_id) REFERENCES visa_master_payment_orders(id),
|
||||
CONSTRAINT visa_master_payment_logs_created_by_fkey
|
||||
FOREIGN KEY (created_by) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS visa_master_payment_logs_order_id_idx ON visa_master_payment_logs (order_id);
|
||||
|
||||
99
docs/docs.go
99
docs/docs.go
@@ -7110,6 +7110,35 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/visa-master-payment-orders/callback": {
|
||||
"get": {
|
||||
"description": "GBÜS redirects the browser here after payment; the real outcome is verified server-to-server before anything is finalized",
|
||||
"produces": [
|
||||
"text/html"
|
||||
],
|
||||
"tags": [
|
||||
"visa-master-payment-orders"
|
||||
],
|
||||
"summary": "GBÜS payment callback",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Payment attempt ID",
|
||||
"name": "paymentId",
|
||||
"in": "query",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "html",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/visa-master-payment-orders/{id}": {
|
||||
"get": {
|
||||
"security": [
|
||||
@@ -7281,7 +7310,7 @@ const docTemplate = `{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Charges the payment gateway and marks the order paid on success",
|
||||
"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.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -7291,7 +7320,7 @@ const docTemplate = `{
|
||||
"tags": [
|
||||
"visa-master-payment-orders"
|
||||
],
|
||||
"summary": "Pay out a visa/master/sber order",
|
||||
"summary": "Start a visa/master/sber payout",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
@@ -7314,7 +7343,7 @@ const docTemplate = `{
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/visamasterpay.PaymentResultDTO"
|
||||
"$ref": "#/definitions/visamasterpay.PaymentInitResultDTO"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
@@ -9843,6 +9872,17 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"visamasterpay.PaymentInitResultDTO": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"formUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"paymentId": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"visamasterpay.PaymentQuoteDTO": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -9871,59 +9911,6 @@ const docTemplate = `{
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"visamasterpay.PaymentResultDTO": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"amountTmt": {
|
||||
"type": "number"
|
||||
},
|
||||
"amountUsd": {
|
||||
"type": "number"
|
||||
},
|
||||
"bankFeeTmt": {
|
||||
"type": "number"
|
||||
},
|
||||
"exchangeRateRub": {
|
||||
"type": "number"
|
||||
},
|
||||
"exchangeRateUsd": {
|
||||
"type": "number"
|
||||
},
|
||||
"gatewayReference": {
|
||||
"type": "string"
|
||||
},
|
||||
"gatewayStatus": {
|
||||
"type": "string"
|
||||
},
|
||||
"gbusFeeTmt": {
|
||||
"type": "number"
|
||||
},
|
||||
"orderId": {
|
||||
"type": "integer"
|
||||
},
|
||||
"paid": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"paidAt": {
|
||||
"type": "string"
|
||||
},
|
||||
"paymentPeriod": {
|
||||
"type": "string"
|
||||
},
|
||||
"totalAmountTmt": {
|
||||
"type": "number"
|
||||
},
|
||||
"tvebFeeTmt": {
|
||||
"type": "number"
|
||||
},
|
||||
"tvebFeeUsd": {
|
||||
"type": "number"
|
||||
},
|
||||
"type": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"securityDefinitions": {
|
||||
|
||||
@@ -7104,6 +7104,35 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/visa-master-payment-orders/callback": {
|
||||
"get": {
|
||||
"description": "GBÜS redirects the browser here after payment; the real outcome is verified server-to-server before anything is finalized",
|
||||
"produces": [
|
||||
"text/html"
|
||||
],
|
||||
"tags": [
|
||||
"visa-master-payment-orders"
|
||||
],
|
||||
"summary": "GBÜS payment callback",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Payment attempt ID",
|
||||
"name": "paymentId",
|
||||
"in": "query",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "html",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/visa-master-payment-orders/{id}": {
|
||||
"get": {
|
||||
"security": [
|
||||
@@ -7275,7 +7304,7 @@
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Charges the payment gateway and marks the order paid on success",
|
||||
"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.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -7285,7 +7314,7 @@
|
||||
"tags": [
|
||||
"visa-master-payment-orders"
|
||||
],
|
||||
"summary": "Pay out a visa/master/sber order",
|
||||
"summary": "Start a visa/master/sber payout",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
@@ -7308,7 +7337,7 @@
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/visamasterpay.PaymentResultDTO"
|
||||
"$ref": "#/definitions/visamasterpay.PaymentInitResultDTO"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
@@ -9837,6 +9866,17 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"visamasterpay.PaymentInitResultDTO": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"formUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"paymentId": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"visamasterpay.PaymentQuoteDTO": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -9865,59 +9905,6 @@
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"visamasterpay.PaymentResultDTO": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"amountTmt": {
|
||||
"type": "number"
|
||||
},
|
||||
"amountUsd": {
|
||||
"type": "number"
|
||||
},
|
||||
"bankFeeTmt": {
|
||||
"type": "number"
|
||||
},
|
||||
"exchangeRateRub": {
|
||||
"type": "number"
|
||||
},
|
||||
"exchangeRateUsd": {
|
||||
"type": "number"
|
||||
},
|
||||
"gatewayReference": {
|
||||
"type": "string"
|
||||
},
|
||||
"gatewayStatus": {
|
||||
"type": "string"
|
||||
},
|
||||
"gbusFeeTmt": {
|
||||
"type": "number"
|
||||
},
|
||||
"orderId": {
|
||||
"type": "integer"
|
||||
},
|
||||
"paid": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"paidAt": {
|
||||
"type": "string"
|
||||
},
|
||||
"paymentPeriod": {
|
||||
"type": "string"
|
||||
},
|
||||
"totalAmountTmt": {
|
||||
"type": "number"
|
||||
},
|
||||
"tvebFeeTmt": {
|
||||
"type": "number"
|
||||
},
|
||||
"tvebFeeUsd": {
|
||||
"type": "number"
|
||||
},
|
||||
"type": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"securityDefinitions": {
|
||||
|
||||
@@ -1695,6 +1695,13 @@ definitions:
|
||||
format: date
|
||||
type: string
|
||||
type: object
|
||||
visamasterpay.PaymentInitResultDTO:
|
||||
properties:
|
||||
formUrl:
|
||||
type: string
|
||||
paymentId:
|
||||
type: integer
|
||||
type: object
|
||||
visamasterpay.PaymentQuoteDTO:
|
||||
properties:
|
||||
bankFeeTmt:
|
||||
@@ -1714,41 +1721,6 @@ definitions:
|
||||
type:
|
||||
type: string
|
||||
type: object
|
||||
visamasterpay.PaymentResultDTO:
|
||||
properties:
|
||||
amountTmt:
|
||||
type: number
|
||||
amountUsd:
|
||||
type: number
|
||||
bankFeeTmt:
|
||||
type: number
|
||||
exchangeRateRub:
|
||||
type: number
|
||||
exchangeRateUsd:
|
||||
type: number
|
||||
gatewayReference:
|
||||
type: string
|
||||
gatewayStatus:
|
||||
type: string
|
||||
gbusFeeTmt:
|
||||
type: number
|
||||
orderId:
|
||||
type: integer
|
||||
paid:
|
||||
type: boolean
|
||||
paidAt:
|
||||
type: string
|
||||
paymentPeriod:
|
||||
type: string
|
||||
totalAmountTmt:
|
||||
type: number
|
||||
tvebFeeTmt:
|
||||
type: number
|
||||
tvebFeeUsd:
|
||||
type: number
|
||||
type:
|
||||
type: string
|
||||
type: object
|
||||
host: localhost:5005
|
||||
info:
|
||||
contact: {}
|
||||
@@ -6429,7 +6401,9 @@ paths:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Charges the payment gateway and marks the order paid on success
|
||||
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.
|
||||
parameters:
|
||||
- description: Visa/master payment order ID
|
||||
in: path
|
||||
@@ -6448,7 +6422,7 @@ paths:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/visamasterpay.PaymentResultDTO'
|
||||
$ref: '#/definitions/visamasterpay.PaymentInitResultDTO'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
@@ -6463,7 +6437,7 @@ paths:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Pay out a visa/master/sber order
|
||||
summary: Start a visa/master/sber payout
|
||||
tags:
|
||||
- visa-master-payment-orders
|
||||
/visa-master-payment-orders/{id}/quote:
|
||||
@@ -6500,6 +6474,26 @@ paths:
|
||||
summary: Quote a visa/master/sber payment
|
||||
tags:
|
||||
- visa-master-payment-orders
|
||||
/visa-master-payment-orders/callback:
|
||||
get:
|
||||
description: GBÜS redirects the browser here after payment; the real outcome
|
||||
is verified server-to-server before anything is finalized
|
||||
parameters:
|
||||
- description: Payment attempt ID
|
||||
in: query
|
||||
name: paymentId
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- text/html
|
||||
responses:
|
||||
"200":
|
||||
description: html
|
||||
schema:
|
||||
type: string
|
||||
summary: GBÜS payment callback
|
||||
tags:
|
||||
- visa-master-payment-orders
|
||||
securityDefinitions:
|
||||
BearerAuth:
|
||||
in: header
|
||||
|
||||
@@ -16,6 +16,7 @@ type Config struct {
|
||||
Port string `yaml:"port" env-default:"8080"`
|
||||
} `yaml:"listen"`
|
||||
PublicFilePath string `yaml:"public_file_path" env-required:"true"`
|
||||
PublicBaseURL string `yaml:"public_base_url" env-required:"true"`
|
||||
Storage StorageConfig `yaml:"storage"`
|
||||
Minio MinioConfig `yaml:"minio"`
|
||||
JwtKey string `yaml:"jwt_key" env-required:"true"`
|
||||
|
||||
@@ -71,7 +71,7 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
|
||||
lending.Register(adminGroup, client, logger)
|
||||
cards.Register(adminGroup, client, logger)
|
||||
currencyRepo := currencydb.NewRepository(client, logger)
|
||||
payment.Register(adminGroup, client, logger, currencyRepo, paymentgateway.NewLogClient(logger))
|
||||
payment.Register(adminGroup, client, logger, currencyRepo, paymentGatewayClient(cfg, logger), cfg.PublicBaseURL)
|
||||
currency.NewHandler(logger, currencyRepo).Register(adminGroup)
|
||||
dashboard.NewHandler(logger, dashboarddb.NewRepository(client, logger)).Register(adminGroup)
|
||||
|
||||
@@ -86,3 +86,13 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
|
||||
|
||||
return router
|
||||
}
|
||||
|
||||
// paymentGatewayClient picks the real GBÜS client outside debug mode, and
|
||||
// the logging stub in debug mode, so local/dev runs never hit the live
|
||||
// bank gateway by accident.
|
||||
func paymentGatewayClient(cfg *config.Config, logger *logging.Logger) paymentgateway.Client {
|
||||
if cfg.IsDebug != nil && *cfg.IsDebug {
|
||||
return paymentgateway.NewLogClient(logger)
|
||||
}
|
||||
return paymentgateway.NewHTTPClient(logger)
|
||||
}
|
||||
|
||||
@@ -246,7 +246,8 @@ func isPublicAdminPath(path string) bool {
|
||||
adminPrefix + "/register",
|
||||
adminPrefix + "/register/verify",
|
||||
adminPrefix + "/forgot-password",
|
||||
adminPrefix + "/forgot-password/verify":
|
||||
adminPrefix + "/forgot-password/verify",
|
||||
adminPrefix + "/visa-master-payment-orders/callback":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
|
||||
@@ -19,16 +19,16 @@ import (
|
||||
)
|
||||
|
||||
// Register wires every payment module's handler onto router.
|
||||
func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger, currencyRepo currency.Repository, gateway paymentgateway.Client) {
|
||||
for _, h := range Handlers(client, logger, currencyRepo, gateway) {
|
||||
func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger, currencyRepo currency.Repository, gateway paymentgateway.Client, publicBaseURL string) {
|
||||
for _, h := range Handlers(client, logger, currencyRepo, gateway, publicBaseURL) {
|
||||
h.Register(router)
|
||||
}
|
||||
}
|
||||
|
||||
func Handlers(client postgresql.Client, logger *logging.Logger, currencyRepo currency.Repository, gateway paymentgateway.Client) []handlers.Handler {
|
||||
func Handlers(client postgresql.Client, logger *logging.Logger, currencyRepo currency.Repository, gateway paymentgateway.Client, publicBaseURL string) []handlers.Handler {
|
||||
settingsRepo := paymentsettingsdb.NewRepository(client, logger)
|
||||
return []handlers.Handler{
|
||||
paymentsettings.NewHandler(logger, settingsRepo),
|
||||
visamasterpay.NewHandler(logger, visamasterpaydb.NewRepository(client, logger, currencyRepo, settingsRepo, gateway)),
|
||||
visamasterpay.NewHandler(logger, visamasterpaydb.NewRepository(client, logger, currencyRepo, settingsRepo, gateway, publicBaseURL)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
@@ -16,21 +17,28 @@ import (
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/paymentgateway"
|
||||
|
||||
"github.com/jackc/pgconn"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
// orderTypeSber identifies Sber orders (case-insensitive, matched against
|
||||
// visa_master_payment_orders.type), which use a different fee/rate model
|
||||
// than the default Visa/Master orders: no GBÜS fee, their own bank fee,
|
||||
// and a USD-denominated TVEB fee, plus a RUB reference rate.
|
||||
// and their own MPI merchant credentials than the default Visa/Master
|
||||
// orders: no GBÜS fee, their own bank fee, and a USD-denominated TVEB fee,
|
||||
// plus a RUB reference rate.
|
||||
const orderTypeSber = "sber"
|
||||
|
||||
const paymentReturningColumns = `id, order_id, payment_period, exchange_rate_usd, exchange_rate_rub, amount_tmt,
|
||||
bank_fee_tmt, gbus_fee_tmt, tveb_fee_usd, tveb_fee_tmt, total_amount_tmt,
|
||||
gateway_status, gateway_reference, created_at, updated_at`
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
currencyRepo currency.Repository
|
||||
settingsRepo paymentsettings.Repository
|
||||
gateway paymentgateway.Client
|
||||
logger *logging.Logger
|
||||
client postgresql.Client
|
||||
currencyRepo currency.Repository
|
||||
settingsRepo paymentsettings.Repository
|
||||
gateway paymentgateway.Client
|
||||
publicBaseURL string
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(
|
||||
@@ -39,13 +47,15 @@ func NewRepository(
|
||||
currencyRepo currency.Repository,
|
||||
settingsRepo paymentsettings.Repository,
|
||||
gateway paymentgateway.Client,
|
||||
publicBaseURL string,
|
||||
) visamasterpay.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
currencyRepo: currencyRepo,
|
||||
settingsRepo: settingsRepo,
|
||||
gateway: gateway,
|
||||
logger: logger,
|
||||
client: client,
|
||||
currencyRepo: currencyRepo,
|
||||
settingsRepo: settingsRepo,
|
||||
gateway: gateway,
|
||||
publicBaseURL: strings.TrimRight(publicBaseURL, "/"),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,60 +122,71 @@ func (r *repository) Quote(ctx context.Context, orderID int64) (visamasterpay.Pa
|
||||
return quote, nil
|
||||
}
|
||||
|
||||
// Pay charges the gateway, then persists the result with a single atomic
|
||||
// UPDATE guarded by `paid = false`. No explicit transaction/row lock is
|
||||
// needed - unlike a running balance, this is a one-time state flip, so the
|
||||
// guarded UPDATE is itself the race check (zero rows affected means
|
||||
// someone else paid it first). A gateway failure is not returned as a Go
|
||||
// error: it's written into gateway_status and returned normally, matching
|
||||
// how this codebase already models order lifecycle via status columns.
|
||||
func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.PayOrderDTO) (visamasterpay.PaymentResultDTO, error) {
|
||||
// Pay registers the payout with GBÜS (mpi.gov.tm) and returns the hosted-
|
||||
// payment-page URL - GBÜS only confirms the real outcome later, via a
|
||||
// redirect to the callback URL embedded in the register request, verified
|
||||
// server-to-server in HandleCallback. The pending visa_master_order_payments
|
||||
// row is inserted before the gateway call so its own id can be embedded in
|
||||
// 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) {
|
||||
var orderType *string
|
||||
var amountUsd *float64
|
||||
var paid bool
|
||||
var senderAccount string
|
||||
var branchID int64
|
||||
var userID int64
|
||||
err := r.client.QueryRow(ctx,
|
||||
`SELECT type, amount_usd, paid, sender_deposit_account FROM visa_master_payment_orders WHERE id = $1 AND deleted_at IS NULL`,
|
||||
`SELECT type, amount_usd, paid, branch_id, user_id FROM visa_master_payment_orders WHERE id = $1 AND deleted_at IS NULL`,
|
||||
orderID,
|
||||
).Scan(&orderType, &amountUsd, &paid, &senderAccount)
|
||||
).Scan(&orderType, &amountUsd, &paid, &branchID, &userID)
|
||||
if err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
if paid {
|
||||
return visamasterpay.PaymentResultDTO{}, visamasterpay.ErrAlreadyPaid
|
||||
r.logStep(ctx, orderID, dto.CreatedBy, "rejected", map[string]string{"reason": "already_paid"})
|
||||
return visamasterpay.PaymentInitResultDTO{}, visamasterpay.ErrAlreadyPaid
|
||||
}
|
||||
if amountUsd == nil {
|
||||
return visamasterpay.PaymentResultDTO{}, visamasterpay.ErrAmountNotSet
|
||||
r.logStep(ctx, orderID, dto.CreatedBy, "rejected", map[string]string{"reason": "amount_not_set"})
|
||||
return visamasterpay.PaymentInitResultDTO{}, visamasterpay.ErrAmountNotSet
|
||||
}
|
||||
|
||||
usdRate, err := r.fetchRate(ctx, "USD")
|
||||
if err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
|
||||
settings, err := r.settingsRepo.Get(ctx)
|
||||
if err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
|
||||
maxAmountTmt := round2(*amountUsd * usdRate)
|
||||
amountTmt := maxAmountTmt
|
||||
if dto.AmountTmt != nil {
|
||||
if *dto.AmountTmt <= 0 || *dto.AmountTmt > maxAmountTmt {
|
||||
return visamasterpay.PaymentResultDTO{}, visamasterpay.ErrAmountExceedsMax
|
||||
r.logStep(ctx, orderID, dto.CreatedBy, "rejected", map[string]interface{}{
|
||||
"reason": "amount_exceeds_max", "requestedAmountTmt": *dto.AmountTmt, "maxAmountTmt": maxAmountTmt,
|
||||
})
|
||||
return visamasterpay.PaymentInitResultDTO{}, visamasterpay.ErrAmountExceedsMax
|
||||
}
|
||||
amountTmt = round2(*dto.AmountTmt)
|
||||
}
|
||||
|
||||
r.logStep(ctx, orderID, dto.CreatedBy, "validated", map[string]interface{}{
|
||||
"orderType": derefOrEmpty(orderType), "amountUsd": *amountUsd, "amountTmt": amountTmt, "exchangeRateUsd": usdRate,
|
||||
})
|
||||
|
||||
sber := isSber(orderType)
|
||||
var rubRate *float64
|
||||
var bankFeeTmt float64
|
||||
var gbusFeeTmt, tvebFeeUsd, tvebFeeTmt *float64
|
||||
var total float64
|
||||
|
||||
if isSber(orderType) {
|
||||
if sber {
|
||||
rate, err := r.fetchRate(ctx, "RUB")
|
||||
if err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
tveb := round2(settings.TvebFeeUsd * usdRate)
|
||||
|
||||
@@ -185,46 +206,198 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P
|
||||
period = dto.PaymentPeriod.Time()
|
||||
}
|
||||
|
||||
reference := fmt.Sprintf("vmo-%d-%d", orderID, time.Now().UnixNano())
|
||||
result, chargeErr := r.gateway.Charge(ctx, paymentgateway.ChargeRequest{
|
||||
Reference: reference,
|
||||
AccountNumber: senderAccount,
|
||||
AmountTmt: fmt.Sprintf("%.2f", amountTmt),
|
||||
r.logStep(ctx, orderID, dto.CreatedBy, "fees_calculated", map[string]interface{}{
|
||||
"bankFeeTmt": bankFeeTmt, "gbusFeeTmt": gbusFeeTmt, "tvebFeeUsd": tvebFeeUsd, "tvebFeeTmt": tvebFeeTmt,
|
||||
"exchangeRateRub": rubRate, "totalAmountTmt": total,
|
||||
})
|
||||
|
||||
status := "success"
|
||||
var gatewayRef *string
|
||||
if chargeErr != nil || result.Status != "success" {
|
||||
status = "failed"
|
||||
if r.logger != nil && chargeErr != nil {
|
||||
r.logger.Errorf("visa master payment gateway charge failed for order %d: %v", orderID, chargeErr)
|
||||
username, password, err := r.branchCredentials(ctx, branchID, sber)
|
||||
if err != nil {
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
|
||||
paymentID, err := insertPendingPayment(ctx, r.client, insertParams{
|
||||
orderID: orderID, userID: userID, period: period,
|
||||
rateUsd: usdRate, rateRub: rubRate, amountTmt: amountTmt,
|
||||
bankFeeTmt: bankFeeTmt, gbusFeeTmt: gbusFeeTmt, tvebFeeUsd: tvebFeeUsd, tvebFeeTmt: tvebFeeTmt,
|
||||
total: total, createdBy: dto.CreatedBy,
|
||||
})
|
||||
if err != nil {
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
|
||||
returnURL := fmt.Sprintf("%s/api/admin/visa-master-payment-orders/callback?paymentId=%d", r.publicBaseURL, paymentID)
|
||||
orderNumber := fmt.Sprintf("vmo-%d-%d", orderID, paymentID)
|
||||
description := "Visa/Master tölegi"
|
||||
if sber {
|
||||
description = "Sber tölegi"
|
||||
}
|
||||
registerReq := paymentgateway.RegisterRequest{
|
||||
OrderNumber: orderNumber,
|
||||
AmountMinor: int64(math.Round(amountTmt * 100)),
|
||||
ReturnURL: returnURL,
|
||||
Description: description,
|
||||
Username: username,
|
||||
Password: password,
|
||||
}
|
||||
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)
|
||||
|
||||
if regErr != nil || !result.Success() {
|
||||
if r.logger != nil && regErr != nil {
|
||||
r.logger.Errorf("visa master payment register failed for order %d payment %d: %v", orderID, paymentID, regErr)
|
||||
}
|
||||
r.logStep(ctx, orderID, dto.CreatedBy, "register_response", map[string]interface{}{
|
||||
"success": false, "errorCode": result.ErrorCode, "errorMessage": result.ErrorMessage,
|
||||
"error": errString(regErr), "rawResponse": rawJSON(result.RawResponse),
|
||||
})
|
||||
_ = updatePaymentGatewayResult(ctx, r.client, paymentID, "failed", nil, result.RawResponse)
|
||||
return visamasterpay.PaymentInitResultDTO{}, fmt.Errorf("payment gateway registration failed: %s", firstNonEmpty(result.ErrorMessage, errString(regErr)))
|
||||
}
|
||||
|
||||
r.logStep(ctx, orderID, dto.CreatedBy, "register_response", map[string]interface{}{
|
||||
"success": true, "gbusOrderId": result.OrderId, "formUrl": result.FormUrl, "rawResponse": rawJSON(result.RawResponse),
|
||||
})
|
||||
|
||||
ref := result.OrderId
|
||||
if err := updatePaymentGatewayResult(ctx, r.client, paymentID, "pending", &ref, result.RawResponse); err != nil {
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
|
||||
return visamasterpay.PaymentInitResultDTO{PaymentId: paymentID, FormUrl: result.FormUrl}, 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) {
|
||||
var orderID int64
|
||||
var gatewayStatus string
|
||||
var gatewayReference *string
|
||||
var createdBy *int64
|
||||
err := r.client.QueryRow(ctx,
|
||||
`SELECT order_id, gateway_status, gateway_reference, created_by FROM visa_master_order_payments WHERE id = $1 AND deleted_at IS NULL`,
|
||||
paymentID,
|
||||
).Scan(&orderID, &gatewayStatus, &gatewayReference, &createdBy)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return visamasterpay.PaymentResultDTO{}, visamasterpay.ErrPaymentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
|
||||
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 {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
|
||||
finish := func(item visamasterpay.PaymentResultDTO) visamasterpay.PaymentResultDTO {
|
||||
item.Type = derefOrEmpty(orderType)
|
||||
if amountUsd != nil {
|
||||
item.AmountUsd = *amountUsd
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
if gatewayStatus != "pending" {
|
||||
item, err := fetchPaymentByID(ctx, r.client, paymentID)
|
||||
if err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
item.Paid = item.GatewayStatus == "success"
|
||||
return finish(item), nil
|
||||
}
|
||||
|
||||
if gatewayReference == nil || *gatewayReference == "" {
|
||||
return visamasterpay.PaymentResultDTO{}, fmt.Errorf("payment %d has no gateway reference yet", paymentID)
|
||||
}
|
||||
|
||||
username, password, err := r.branchCredentials(ctx, branchID, isSber(orderType))
|
||||
if err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
|
||||
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})
|
||||
|
||||
status, err := r.gateway.CheckStatus(ctx, paymentgateway.StatusRequest{OrderId: *gatewayReference, Username: username, Password: password})
|
||||
if err != nil {
|
||||
r.logStep(ctx, orderID, createdBy, "status_check_response", map[string]interface{}{"error": errString(err)})
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
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),
|
||||
})
|
||||
|
||||
var item visamasterpay.PaymentResultDTO
|
||||
if status.Paid {
|
||||
tx, err := r.client.Begin(ctx)
|
||||
if err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
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 {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
if !lockedPaid {
|
||||
if _, err := tx.Exec(ctx,
|
||||
`UPDATE visa_master_payment_orders SET paid = true, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $1`,
|
||||
orderID,
|
||||
); err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
}
|
||||
|
||||
item, err = updatePaymentStatus(ctx, tx, paymentID, "success", status.RawResponse)
|
||||
if err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
} else {
|
||||
gatewayRef = nonEmptyRef(result.ProviderReference)
|
||||
item, err = updatePaymentStatus(ctx, r.client, paymentID, "failed", status.RawResponse)
|
||||
if err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
}
|
||||
paidNow := status == "success"
|
||||
|
||||
query := `
|
||||
UPDATE visa_master_payment_orders SET
|
||||
exchange_rate = $1, exchange_rate_rub = $2, amount_tmt = $3,
|
||||
bank_fee_tmt = $4, gbus_fee_tmt = $5, tveb_fee_usd = $6, tveb_fee_tmt = $7,
|
||||
total_amount_tmt = $8, payment_period = $9, gateway_status = $10, gateway_reference = $11,
|
||||
paid = $12, paid_at = CASE WHEN $12 THEN (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') ELSE paid_at END,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $13 AND paid = false
|
||||
RETURNING id, type, paid, amount_usd, exchange_rate, exchange_rate_rub, amount_tmt,
|
||||
bank_fee_tmt, gbus_fee_tmt, tveb_fee_usd, tveb_fee_tmt, total_amount_tmt,
|
||||
payment_period, gateway_status, gateway_reference, paid_at`
|
||||
r.logStep(ctx, orderID, createdBy, "payment_finalized", map[string]interface{}{"paymentId": paymentID, "paid": status.Paid})
|
||||
|
||||
item, err := scanResult(r.client.QueryRow(ctx, query,
|
||||
usdRate, rubRate, amountTmt,
|
||||
bankFeeTmt, gbusFeeTmt, tvebFeeUsd, tvebFeeTmt,
|
||||
total, period, status, gatewayRef, paidNow, orderID,
|
||||
))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return visamasterpay.PaymentResultDTO{}, visamasterpay.ErrAlreadyPaid
|
||||
item.Paid = status.Paid
|
||||
return finish(item), nil
|
||||
}
|
||||
|
||||
// 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) {
|
||||
var visaUser, visaPass, sberUser, sberPass string
|
||||
err = r.client.QueryRow(ctx,
|
||||
`SELECT billing_visa_master_username, billing_visa_master_password, billing_sber_username, billing_sber_password
|
||||
FROM branches WHERE id = $1`, branchID,
|
||||
).Scan(&visaUser, &visaPass, &sberUser, &sberPass)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return item, err
|
||||
if sber {
|
||||
return sberUser, sberPass, nil
|
||||
}
|
||||
return visaUser, visaPass, nil
|
||||
}
|
||||
|
||||
func (r *repository) fetchRate(ctx context.Context, from string) (float64, error) {
|
||||
@@ -249,21 +422,111 @@ func derefOrEmpty(s *string) string {
|
||||
return *s
|
||||
}
|
||||
|
||||
func scanResult(row pgx.Row) (visamasterpay.PaymentResultDTO, error) {
|
||||
// logStep records one step of processing a payout as its own row in
|
||||
// visa_master_payment_logs, so there's a step-by-step, timestamped record
|
||||
// of what happened for an order - evidence if a payout is later disputed.
|
||||
// It always writes through r.client (never the finalize transaction), so a
|
||||
// logging hiccup never blocks or rolls back a real payment, and a step is
|
||||
// still on record even if the surrounding transaction later fails.
|
||||
// Best-effort: a write failure here is logged, not propagated.
|
||||
func (r *repository) logStep(ctx context.Context, orderID int64, createdBy *int64, step string, detail interface{}) {
|
||||
payload, err := json.Marshal(detail)
|
||||
if err != nil {
|
||||
payload = []byte(`{}`)
|
||||
}
|
||||
if _, err := r.client.Exec(ctx,
|
||||
`INSERT INTO visa_master_payment_logs (order_id, step, detail, created_by) VALUES ($1, $2, $3, $4)`,
|
||||
orderID, step, payload, createdBy,
|
||||
); err != nil && r.logger != nil {
|
||||
r.logger.Errorf("visa master payment log write failed (order %d, step %s): %v", orderID, step, err)
|
||||
}
|
||||
}
|
||||
|
||||
// querier is satisfied by both postgresql.Client and pgx.Tx, so helpers
|
||||
// below can run either against the plain client or an open transaction.
|
||||
type querier interface {
|
||||
QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row
|
||||
}
|
||||
|
||||
// execer is the Exec-only counterpart of querier, for statements that
|
||||
// don't need RETURNING.
|
||||
type execer interface {
|
||||
Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error)
|
||||
}
|
||||
|
||||
type insertParams struct {
|
||||
orderID, userID int64
|
||||
period time.Time
|
||||
rateUsd float64
|
||||
rateRub *float64
|
||||
amountTmt float64
|
||||
bankFeeTmt float64
|
||||
gbusFeeTmt *float64
|
||||
tvebFeeUsd *float64
|
||||
tvebFeeTmt *float64
|
||||
total float64
|
||||
createdBy *int64
|
||||
}
|
||||
|
||||
// insertPendingPayment creates the attempt row before GBÜS is even called,
|
||||
// so its id can be embedded in the returnUrl - see Pay.
|
||||
func insertPendingPayment(ctx context.Context, q querier, p insertParams) (int64, error) {
|
||||
query := `
|
||||
INSERT INTO visa_master_order_payments (
|
||||
order_id, user_id, payment_period, exchange_rate_usd, exchange_rate_rub, amount_tmt,
|
||||
bank_fee_tmt, gbus_fee_tmt, tveb_fee_usd, tveb_fee_tmt, total_amount_tmt,
|
||||
gateway_status, created_by
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, 'pending', $12)
|
||||
RETURNING id`
|
||||
|
||||
var id int64
|
||||
err := q.QueryRow(ctx, query,
|
||||
p.orderID, p.userID, p.period, p.rateUsd, p.rateRub, p.amountTmt,
|
||||
p.bankFeeTmt, p.gbusFeeTmt, p.tvebFeeUsd, p.tvebFeeTmt, p.total, p.createdBy,
|
||||
).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
// updatePaymentGatewayResult records the outcome of the register.do call
|
||||
// itself (not the final payment outcome - that's updatePaymentStatus,
|
||||
// driven by the callback).
|
||||
func updatePaymentGatewayResult(ctx context.Context, q execer, paymentID int64, status string, reference *string, response []byte) error {
|
||||
_, err := q.Exec(ctx,
|
||||
`UPDATE visa_master_order_payments SET gateway_status = $1, gateway_reference = $2, gateway_response = $3,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $4`,
|
||||
status, reference, response, paymentID,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
// updatePaymentStatus records the verified final outcome (from
|
||||
// HandleCallback) and returns the updated row.
|
||||
func updatePaymentStatus(ctx context.Context, q querier, paymentID int64, status string, response []byte) (visamasterpay.PaymentResultDTO, error) {
|
||||
query := `
|
||||
UPDATE visa_master_order_payments SET gateway_status = $1, gateway_response = $2,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $3
|
||||
RETURNING ` + paymentReturningColumns
|
||||
|
||||
return scanPayment(q.QueryRow(ctx, query, status, response, paymentID))
|
||||
}
|
||||
|
||||
func fetchPaymentByID(ctx context.Context, q querier, paymentID int64) (visamasterpay.PaymentResultDTO, error) {
|
||||
query := `SELECT ` + paymentReturningColumns + ` FROM visa_master_order_payments WHERE id = $1 AND deleted_at IS NULL`
|
||||
return scanPayment(q.QueryRow(ctx, query, paymentID))
|
||||
}
|
||||
|
||||
func scanPayment(row pgx.Row) (visamasterpay.PaymentResultDTO, error) {
|
||||
var item visamasterpay.PaymentResultDTO
|
||||
var orderType *string
|
||||
var amountUsd *float64
|
||||
if err := row.Scan(
|
||||
&item.OrderId, &orderType, &item.Paid, &amountUsd, &item.ExchangeRateUsd, &item.ExchangeRateRub, &item.AmountTmt,
|
||||
&item.Id, &item.OrderId, &item.PaymentPeriod, &item.ExchangeRateUsd, &item.ExchangeRateRub, &item.AmountTmt,
|
||||
&item.BankFeeTmt, &item.GbusFeeTmt, &item.TvebFeeUsd, &item.TvebFeeTmt, &item.TotalAmountTmt,
|
||||
&item.PaymentPeriod, &item.GatewayStatus, &item.GatewayReference, &item.PaidAt,
|
||||
&item.GatewayStatus, &item.GatewayReference, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
item.Type = derefOrEmpty(orderType)
|
||||
if amountUsd != nil {
|
||||
item.AmountUsd = *amountUsd
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
@@ -271,9 +534,28 @@ func round2(v float64) float64 {
|
||||
return math.Round(v*100) / 100
|
||||
}
|
||||
|
||||
func nonEmptyRef(s string) *string {
|
||||
if s == "" {
|
||||
func errString(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, v := range values {
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
return &s
|
||||
return json.RawMessage(raw)
|
||||
}
|
||||
|
||||
@@ -23,35 +23,51 @@ type PaymentQuoteDTO struct {
|
||||
MaxAmountTmt float64 `json:"maxAmountTmt"`
|
||||
}
|
||||
|
||||
// PayOrderDTO submits a payout for a visa/master/sber order. AmountTmt is
|
||||
// optional: if omitted, the full requested amount (amount_usd * rate) is
|
||||
// paid; if provided (the modal's amount field is editable, capped at the
|
||||
// max), it's validated against that max instead. PaymentPeriod is
|
||||
// optional too - only the Visa/Master modal shows a payment-month picker;
|
||||
// Sber orders default to the current month when omitted.
|
||||
// PayOrderDTO starts a payout attempt for a visa/master/sber order.
|
||||
// AmountTmt is optional: if omitted, the full requested amount
|
||||
// (amount_usd * rate) is used; if provided (the modal's amount field is
|
||||
// editable, capped at the max), it's validated against that max instead.
|
||||
// PaymentPeriod is optional too - only the Visa/Master modal shows a
|
||||
// payment-month picker; Sber orders default to the current month when
|
||||
// omitted.
|
||||
type PayOrderDTO struct {
|
||||
PaymentPeriod *shared.FlexibleTime `json:"paymentPeriod" swaggertype:"string" format:"date"`
|
||||
AmountTmt *float64 `json:"amountTmt"`
|
||||
CreatedBy *int64 `json:"-"`
|
||||
}
|
||||
|
||||
// PaymentResultDTO is a flat, payment-focused view of the order's payout
|
||||
// state — deliberately not the full order+branch+user DTO owned by
|
||||
// cards/visamaster (fetch that separately via GET /visa-master-payment-orders/:id).
|
||||
type PaymentResultDTO struct {
|
||||
OrderId int64 `json:"orderId"`
|
||||
Type string `json:"type"`
|
||||
Paid bool `json:"paid"`
|
||||
AmountUsd float64 `json:"amountUsd"`
|
||||
ExchangeRateUsd float64 `json:"exchangeRateUsd"`
|
||||
ExchangeRateRub *float64 `json:"exchangeRateRub,omitempty"`
|
||||
AmountTmt float64 `json:"amountTmt"`
|
||||
BankFeeTmt float64 `json:"bankFeeTmt"`
|
||||
GbusFeeTmt *float64 `json:"gbusFeeTmt,omitempty"`
|
||||
TvebFeeUsd *float64 `json:"tvebFeeUsd,omitempty"`
|
||||
TvebFeeTmt *float64 `json:"tvebFeeTmt,omitempty"`
|
||||
TotalAmountTmt float64 `json:"totalAmountTmt"`
|
||||
PaymentPeriod *time.Time `json:"paymentPeriod,omitempty"`
|
||||
GatewayStatus string `json:"gatewayStatus"`
|
||||
GatewayReference *string `json:"gatewayReference,omitempty"`
|
||||
PaidAt *time.Time `json:"paidAt,omitempty"`
|
||||
// PaymentInitResultDTO is the immediate result of starting a payout:
|
||||
// GBÜS only registers the payment and hands back a hosted-payment-page URL
|
||||
// - the customer (or the operator, in-branch) must complete payment there.
|
||||
// The definitive outcome only becomes known once GBÜS redirects back to
|
||||
// our callback, which verifies and finalizes it - see PaymentResultDTO.
|
||||
type PaymentInitResultDTO struct {
|
||||
PaymentId int64 `json:"paymentId"`
|
||||
FormUrl string `json:"formUrl"`
|
||||
}
|
||||
|
||||
// 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
|
||||
// the full order+branch+user DTO owned by cards/visamaster (fetch that
|
||||
// separately via GET /visa-master-payment-orders/:id).
|
||||
type PaymentResultDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
OrderId int64 `json:"orderId"`
|
||||
Type string `json:"type"`
|
||||
Paid bool `json:"paid"`
|
||||
AmountUsd float64 `json:"amountUsd"`
|
||||
ExchangeRateUsd float64 `json:"exchangeRateUsd"`
|
||||
ExchangeRateRub *float64 `json:"exchangeRateRub,omitempty"`
|
||||
AmountTmt float64 `json:"amountTmt"`
|
||||
BankFeeTmt float64 `json:"bankFeeTmt"`
|
||||
GbusFeeTmt *float64 `json:"gbusFeeTmt,omitempty"`
|
||||
TvebFeeUsd *float64 `json:"tvebFeeUsd,omitempty"`
|
||||
TvebFeeTmt *float64 `json:"tvebFeeTmt,omitempty"`
|
||||
TotalAmountTmt float64 `json:"totalAmountTmt"`
|
||||
PaymentPeriod time.Time `json:"paymentPeriod"`
|
||||
GatewayStatus string `json:"gatewayStatus"`
|
||||
GatewayReference *string `json:"gatewayReference,omitempty"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package visamasterpay
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
@@ -29,6 +30,12 @@ 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
|
||||
@@ -55,7 +62,7 @@ func (h *handler) quote(c *gin.Context) {
|
||||
}
|
||||
|
||||
result, err := h.repository.Quote(c.Request.Context(), id)
|
||||
if h.handleQuoteOrPayError(c, err, "quote") {
|
||||
if h.handleError(c, err, "quote") {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -63,15 +70,15 @@ func (h *handler) quote(c *gin.Context) {
|
||||
}
|
||||
|
||||
// pay godoc
|
||||
// @Summary Pay out a visa/master/sber order
|
||||
// @Description Charges the payment gateway and marks the order paid on success
|
||||
// @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} PaymentResultDTO
|
||||
// @Success 200 {object} PaymentInitResultDTO
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
@@ -92,15 +99,52 @@ func (h *handler) pay(c *gin.Context) {
|
||||
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.handleQuoteOrPayError(c, err, "pay") {
|
||||
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
|
||||
@@ -117,10 +161,10 @@ func (h *handler) guardOrder(c *gin.Context, id int64) bool {
|
||||
return rbac.GuardOrder(c, userID, branchID)
|
||||
}
|
||||
|
||||
// handleQuoteOrPayError 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) handleQuoteOrPayError(c *gin.Context, err error, action string) bool {
|
||||
// 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
|
||||
}
|
||||
|
||||
@@ -16,10 +16,19 @@ var ErrAmountNotSet = errors.New("order has no requested amount")
|
||||
// what the order's amount_usd converts to at the current rate.
|
||||
var ErrAmountExceedsMax = errors.New("amount exceeds the order's requested amount")
|
||||
|
||||
// ErrPaymentNotFound is returned when a callback references a payment
|
||||
// attempt id that doesn't exist.
|
||||
var ErrPaymentNotFound = errors.New("payment attempt not found")
|
||||
|
||||
type Repository interface {
|
||||
// OwnerInfo returns the order's owner/branch so the handler can run
|
||||
// rbac.GuardOrder without importing cards/visamaster.
|
||||
OwnerInfo(ctx context.Context, orderID int64) (userID *int64, branchID int64, err error)
|
||||
Quote(ctx context.Context, orderID int64) (PaymentQuoteDTO, error)
|
||||
Pay(ctx context.Context, orderID int64, dto PayOrderDTO) (PaymentResultDTO, error)
|
||||
// Pay registers the payout with GBÜS and returns the hosted-payment-page
|
||||
// URL - it does not know the final outcome yet, see HandleCallback.
|
||||
Pay(ctx context.Context, orderID int64, dto PayOrderDTO) (PaymentInitResultDTO, error)
|
||||
// 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)
|
||||
}
|
||||
|
||||
@@ -1,38 +1,76 @@
|
||||
// Package paymentgateway talks to GBÜS (mpi.gov.tm), Turkmenistan's
|
||||
// national MPI, a "Сбербанк АС МПС"/PaymentGate-family gateway. Payment is
|
||||
// two-phase and redirect-based, not a synchronous debit: Register hands
|
||||
// back a hosted-payment-page URL for the customer to complete payment on,
|
||||
// and CheckStatus is the only source of truth for whether it was actually
|
||||
// paid - callers must never trust a browser redirect's query params alone.
|
||||
package paymentgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"online-back/pkg/logging"
|
||||
)
|
||||
|
||||
// ChargeRequest describes a single debit to submit to the external payment
|
||||
// gateway ("GBÜS") for a loan payment.
|
||||
type ChargeRequest struct {
|
||||
Reference string
|
||||
AccountNumber string
|
||||
AmountTmt string
|
||||
// RegisterRequest registers a new payment with the gateway (GBÜS register.do).
|
||||
type RegisterRequest struct {
|
||||
OrderNumber string // our own unique order reference
|
||||
AmountMinor int64 // amount in tetri (TMT * 100), matching the gateway's integer-minor-unit convention
|
||||
ReturnURL string
|
||||
Description string
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
// ChargeResult is the outcome of a Charge call.
|
||||
type ChargeResult struct {
|
||||
Status string // "success" or "failed"
|
||||
ProviderReference string
|
||||
RawResponse []byte
|
||||
// RegisterResult is the outcome of Register.
|
||||
type RegisterResult struct {
|
||||
OrderId string // the gateway's own order id - store this, it's what CheckStatus needs
|
||||
FormUrl string // where to send the customer to complete payment
|
||||
ErrorCode string
|
||||
ErrorMessage string
|
||||
RawResponse []byte
|
||||
}
|
||||
|
||||
// Client charges a customer's account through the external gateway. Plug
|
||||
// your real provider in by implementing this interface once GBÜS's API
|
||||
// contract (base URL, auth, request/response shape) is available.
|
||||
func (r RegisterResult) Success() bool {
|
||||
return r.OrderId != "" && r.FormUrl != "" && (r.ErrorCode == "" || r.ErrorCode == "0")
|
||||
}
|
||||
|
||||
// StatusRequest checks a previously registered payment's outcome (GBÜS
|
||||
// getOrderStatusExtended.do).
|
||||
type StatusRequest struct {
|
||||
OrderId string
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
// StatusResult is the outcome of CheckStatus. Paid is the only field
|
||||
// callers should act on; OrderStatus == 2 means fully paid/deposited per
|
||||
// the AS MPS convention, anything else is not (yet) paid.
|
||||
type StatusResult struct {
|
||||
Paid bool
|
||||
OrderStatus int
|
||||
ActionCode string
|
||||
ActionCodeDescription string
|
||||
ErrorCode string
|
||||
ErrorMessage string
|
||||
RawResponse []byte
|
||||
}
|
||||
|
||||
// Client is the gateway contract. Plug a real HTTPClient in once
|
||||
// credentials are configured; LogClient is a stand-in for local/dev use.
|
||||
type Client interface {
|
||||
Charge(ctx context.Context, req ChargeRequest) (ChargeResult, error)
|
||||
Register(ctx context.Context, req RegisterRequest) (RegisterResult, error)
|
||||
CheckStatus(ctx context.Context, req StatusRequest) (StatusResult, error)
|
||||
}
|
||||
|
||||
// LogClient is a stand-in used until a real GBÜS client is wired in. It
|
||||
// logs the charge and reports success so the loan payment flow is usable
|
||||
// end-to-end in the meantime.
|
||||
// LogClient is a stand-in used in debug mode so local/dev environments
|
||||
// never hit the real bank gateway by accident. Register logs the request
|
||||
// and returns a synthetic order id with no real form URL; CheckStatus
|
||||
// immediately reports the payment as paid, so the full register ->
|
||||
// callback -> finalize flow is exercisable end-to-end without real MPI
|
||||
// credentials.
|
||||
type LogClient struct {
|
||||
logger *logging.Logger
|
||||
}
|
||||
@@ -41,10 +79,24 @@ func NewLogClient(logger *logging.Logger) *LogClient {
|
||||
return &LogClient{logger: logger}
|
||||
}
|
||||
|
||||
func (c *LogClient) Charge(_ context.Context, req ChargeRequest) (ChargeResult, error) {
|
||||
reference := fmt.Sprintf("LOG-%s-%d", req.Reference, time.Now().UnixNano())
|
||||
func (c *LogClient) Register(_ context.Context, req RegisterRequest) (RegisterResult, error) {
|
||||
orderID := "LOG-" + req.OrderNumber
|
||||
if c.logger != nil {
|
||||
c.logger.Infof("payment gateway charge (stub): account=%s amount=%s reference=%s", req.AccountNumber, req.AmountTmt, reference)
|
||||
c.logger.Infof("payment gateway register (stub): orderNumber=%s amountMinor=%d orderId=%s", req.OrderNumber, req.AmountMinor, orderID)
|
||||
}
|
||||
return ChargeResult{Status: "success", ProviderReference: reference}, nil
|
||||
raw, _ := json.Marshal(map[string]interface{}{
|
||||
"stub": true, "note": "no real MPI client configured (debug mode) - pkg/paymentgateway.LogClient",
|
||||
"orderId": orderID, "orderNumber": req.OrderNumber, "amountMinor": req.AmountMinor, "processedAt": time.Now().UTC(),
|
||||
})
|
||||
return RegisterResult{OrderId: orderID, FormUrl: "", RawResponse: raw}, nil
|
||||
}
|
||||
|
||||
func (c *LogClient) CheckStatus(_ context.Context, req StatusRequest) (StatusResult, error) {
|
||||
if c.logger != nil {
|
||||
c.logger.Infof("payment gateway status check (stub): orderId=%s -> paid", req.OrderId)
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]interface{}{
|
||||
"stub": true, "orderId": req.OrderId, "orderStatus": 2, "processedAt": time.Now().UTC(),
|
||||
})
|
||||
return StatusResult{Paid: true, OrderStatus: 2, RawResponse: raw}, nil
|
||||
}
|
||||
|
||||
149
pkg/paymentgateway/http_client.go
Normal file
149
pkg/paymentgateway/http_client.go
Normal file
@@ -0,0 +1,149 @@
|
||||
package paymentgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"online-back/pkg/logging"
|
||||
)
|
||||
|
||||
// mpiBaseURL is GBÜS's fixed base URL - a national gateway, not something
|
||||
// that varies per environment, so it's a constant rather than a config field.
|
||||
const mpiBaseURL = "https://mpi.gov.tm/payment/rest/"
|
||||
|
||||
// HTTPClient is the real GBÜS integration, following the standard AS MPS
|
||||
// REST contract: register.do (GET, query params) to start a payment,
|
||||
// getOrderStatusExtended.do (POST, form-encoded body) to confirm its
|
||||
// outcome - the two calls intentionally use different HTTP shapes, mirroring
|
||||
// the gateway's own convention exactly rather than normalizing them.
|
||||
type HTTPClient struct {
|
||||
httpClient *http.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHTTPClient(logger *logging.Logger) *HTTPClient {
|
||||
return &HTTPClient{
|
||||
httpClient: &http.Client{Timeout: 20 * time.Second},
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
type registerResponse struct {
|
||||
OrderId string `json:"orderId"`
|
||||
FormUrl string `json:"formUrl"`
|
||||
ErrorCode string `json:"errorCode"`
|
||||
ErrorMessage string `json:"errorMessage"`
|
||||
}
|
||||
|
||||
func (c *HTTPClient) Register(ctx context.Context, req RegisterRequest) (RegisterResult, error) {
|
||||
query := url.Values{
|
||||
"orderNumber": {req.OrderNumber},
|
||||
"amount": {strconv.FormatInt(req.AmountMinor, 10)},
|
||||
"currency": {"934"}, // TMT, ISO 4217 numeric
|
||||
"language": {"ru"},
|
||||
"userName": {req.Username},
|
||||
"password": {req.Password},
|
||||
"returnUrl": {req.ReturnURL},
|
||||
"pageView": {"DESKTOP"},
|
||||
"description": {req.Description},
|
||||
}
|
||||
|
||||
body, err := c.do(ctx, http.MethodGet, mpiBaseURL+"register.do", query, nil)
|
||||
if err != nil {
|
||||
return RegisterResult{}, err
|
||||
}
|
||||
|
||||
var parsed registerResponse
|
||||
if err := json.Unmarshal(body, &parsed); err != nil {
|
||||
return RegisterResult{}, fmt.Errorf("register.do: decode response: %w", err)
|
||||
}
|
||||
|
||||
return RegisterResult{
|
||||
OrderId: parsed.OrderId, FormUrl: parsed.FormUrl,
|
||||
ErrorCode: parsed.ErrorCode, ErrorMessage: parsed.ErrorMessage,
|
||||
RawResponse: body,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type statusResponse struct {
|
||||
OrderStatus int `json:"orderStatus"`
|
||||
ActionCode string `json:"actionCode"`
|
||||
ActionCodeDescription string `json:"actionCodeDescription"`
|
||||
ErrorCode string `json:"errorCode"`
|
||||
ErrorMessage string `json:"errorMessage"`
|
||||
}
|
||||
|
||||
func (c *HTTPClient) CheckStatus(ctx context.Context, req StatusRequest) (StatusResult, error) {
|
||||
form := url.Values{
|
||||
"language": {"ru"},
|
||||
"orderId": {req.OrderId},
|
||||
"userName": {req.Username},
|
||||
"password": {req.Password},
|
||||
}
|
||||
|
||||
body, err := c.do(ctx, http.MethodPost, mpiBaseURL+"getOrderStatusExtended.do", nil, form)
|
||||
if err != nil {
|
||||
return StatusResult{}, err
|
||||
}
|
||||
|
||||
var parsed statusResponse
|
||||
if err := json.Unmarshal(body, &parsed); err != nil {
|
||||
return StatusResult{}, fmt.Errorf("getOrderStatusExtended.do: decode response: %w", err)
|
||||
}
|
||||
|
||||
return StatusResult{
|
||||
Paid: parsed.OrderStatus == 2,
|
||||
OrderStatus: parsed.OrderStatus,
|
||||
ActionCode: parsed.ActionCode,
|
||||
ActionCodeDescription: parsed.ActionCodeDescription,
|
||||
ErrorCode: parsed.ErrorCode,
|
||||
ErrorMessage: parsed.ErrorMessage,
|
||||
RawResponse: body,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// do issues either a GET with query params or a POST with a form-encoded
|
||||
// body (exactly one of query/form is non-nil) and returns the response body.
|
||||
func (c *HTTPClient) do(ctx context.Context, method, target string, query, form url.Values) ([]byte, error) {
|
||||
var req *http.Request
|
||||
var err error
|
||||
|
||||
if method == http.MethodGet {
|
||||
req, err = http.NewRequestWithContext(ctx, method, target+"?"+query.Encode(), nil)
|
||||
} else {
|
||||
req, err = http.NewRequestWithContext(ctx, method, target, strings.NewReader(form.Encode()))
|
||||
if err == nil {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s %s: %w", method, target, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s %s: read response: %w", method, target, err)
|
||||
}
|
||||
|
||||
if c.logger != nil {
|
||||
c.logger.Infof("payment gateway %s %s -> %d", method, target, resp.StatusCode)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("%s %s: unexpected status %d", method, target, resp.StatusCode)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
Reference in New Issue
Block a user