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 baseURL string logger *logging.Logger } func NewHTTPClient(logger *logging.Logger) *HTTPClient { return &HTTPClient{ httpClient: &http.Client{Timeout: 20 * time.Second}, baseURL: mpiBaseURL, logger: logger, } } // base returns the configured gateway base URL, falling back to the fixed // GBÜS endpoint when the client was constructed without one. func (c *HTTPClient) base() string { if c.baseURL == "" { return mpiBaseURL } return c.baseURL } 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, c.base()+"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 flexibleString `json:"actionCode"` ActionCodeDescription string `json:"actionCodeDescription"` ErrorCode string `json:"errorCode"` ErrorMessage string `json:"errorMessage"` } // flexibleString unmarshals a JSON string or a JSON number into a Go // string. GBÜS is documented to send actionCode as a string, but some // deployments send it as a bare number, so decoding must accept either. type flexibleString string func (s *flexibleString) UnmarshalJSON(data []byte) error { if string(data) == "null" { *s = "" return nil } if len(data) > 0 && data[0] == '"' { var str string if err := json.Unmarshal(data, &str); err != nil { return err } *s = flexibleString(str) return nil } *s = flexibleString(data) return nil } 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, c.base()+"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: string(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 }