add pay
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

This commit is contained in:
2026-09-19 03:54:40 +05:00
parent 848a07324f
commit 6c7c402390
16 changed files with 891 additions and 324 deletions

View File

@@ -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
}

View 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
}