Files

277 lines
9.4 KiB
Go

// Package trustpayments implements bounded TRU Link calls without financial retries.
package trustpayments
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/google/uuid"
)
type Config struct {
BaseURL string
SiteID string
Password string
Terminal string
Currency string
Timezone string
// Transport is an explicit fixture seam; production leaves it nil.
Transport http.RoundTripper
}
type Client struct {
cfg Config
http *http.Client
}
func New(cfg Config) (*Client, error) {
u, err := url.Parse(cfg.BaseURL)
if err != nil || u.Scheme != "https" || u.User != nil || u.RawQuery != "" || u.Fragment != "" ||
(u.Host != "link.trustpayments.com" && u.Host != "sandbox.link.trustpayments.com") ||
strings.TrimRight(u.Path, "/") != "/trustpayments/rest" {
return nil, errors.New("invalid CMS ReservationSystem.PaymentGatewayURL for Trust")
}
for _, field := range []struct{ name, value string }{
{"ReservationSystem.PaymentGatewaySiteIDEPOS", cfg.SiteID},
{"ReservationSystem.PaymentGatewayPasswordEPOS", cfg.Password},
{"ReservationSystem.PDQs.Serial", cfg.Terminal},
} {
if strings.TrimSpace(field.value) == "" {
return nil, fmt.Errorf("CMS %s is required for Trust", field.name)
}
}
if _, err := time.LoadLocation(cfg.Timezone); err != nil || cfg.Timezone == "" || cfg.Timezone == "Local" {
return nil, errors.New("valid CMS ReservationSystem.TimeZone is required for Trust")
}
return &Client{cfg: cfg, http: &http.Client{Transport: cfg.Transport, Timeout: 300 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("Trust redirects prohibited") }}}, nil
}
func (c *Client) ValidRequest(request Request) bool {
return (request.Kind == "sale" || request.Kind == "preauth") && request.Amount > 0
}
// Process makes one financial request and at most one observational status call.
// Its reference exists for this attempt only; no restart recovery is provided.
func (c *Client) Process(ctx context.Context, request Request) (Result, error) {
if !c.ValidRequest(request) {
return Result{State: Unknown}, errors.New("invalid or unavailable Trust request")
}
op := Operation{Request: request, RefID: strings.ReplaceAll(uuid.NewString(), "-", ""), TxnDate: c.Timestamp(time.Now())}
ctx, cancel := context.WithTimeout(ctx, 315*time.Second)
defer cancel()
result, err := c.Execute(ctx, op, false)
if (result.State == Unknown || result.State == Pending) && ctx.Err() == nil {
return c.Execute(ctx, op, true)
}
return result, err
}
func (c *Client) Timestamp(t time.Time) string {
loc, _ := time.LoadLocation(c.cfg.Timezone)
return t.In(loc).Format("2006-01-02:15:04:05")
}
func Token(site, date, ref, password string) string {
h := sha256.Sum256([]byte(site + ":" + date + ":" + ref + ":" + password))
return hex.EncodeToString(h[:])
}
func Decimal(n int64) string { return fmt.Sprintf("%d.%02d", n/100, n%100) }
func ParseAmount(s string) (int64, error) {
if s == "" || strings.Trim(s, "0123456789.") != "" {
return 0, errors.New("invalid provider amount")
}
parts := strings.Split(s, ".")
if len(parts) != 2 || len(parts[0]) == 0 || len(parts[1]) != 2 {
return 0, errors.New("invalid provider amount scale")
}
n, err := strconv.ParseInt(parts[0]+parts[1], 10, 64)
if err != nil || n <= 0 {
return 0, errors.New("invalid provider amount range")
}
return n, nil
}
type response struct {
RefID string `json:"refid"`
Site string `json:"siteid"`
Terminal string `json:"terminalserialnumber"`
Kind string `json:"type"`
Result string `json:"resultcode"`
Amount string `json:"amount"`
Final string `json:"finalamount"`
Error json.RawMessage `json:"error"`
ErrorMessage string `json:"errormessage"`
Code json.RawMessage `json:"errorcode"`
Auth string `json:"authcode"`
Card string `json:"cardtype"`
Last string `json:"last4"`
Receipt string `json:"receipt"`
}
func safe(s string) string {
if len(s) > 80 || strings.Trim(s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -_./") != "" {
return ""
}
return s
}
func receiptFields(s string) (string, string) {
var receipt, sequence string
for _, line := range strings.Split(strings.ReplaceAll(s, "\r\n", "\n"), "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "Receipt:") {
receipt = safe(strings.TrimSpace(strings.TrimPrefix(line, "Receipt:")))
}
if strings.HasPrefix(line, "Sequence number:") {
sequence = safe(strings.TrimSpace(strings.TrimPrefix(line, "Sequence number:")))
}
}
return receipt, sequence
}
func (c *Client) Execute(ctx context.Context, op Operation, status bool) (Result, error) {
result := Result{State: Unknown, RefID: op.RefID}
if (op.Request.Kind != "sale" && op.Request.Kind != "preauth") || op.Request.Amount <= 0 || op.RefID == "" || op.TxnDate == "" {
return result, errors.New("invalid Trust operation context")
}
payload := map[string]string{"siteid": c.cfg.SiteID, "txndate": op.TxnDate, "refid": op.RefID}
endpoint := "status"
timeout := 15 * time.Second
if !status {
endpoint = op.Request.Kind
timeout = 300 * time.Second
payload["amount"] = Decimal(op.Request.Amount)
payload["type"] = op.Request.Kind
payload["terminalserialnumber"] = c.cfg.Terminal
payload["wait"] = "y"
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
b, err := json.Marshal(payload)
if err != nil {
return result, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(c.cfg.BaseURL, "/")+"/"+endpoint, bytes.NewReader(b))
if err != nil {
return result, errors.New("invalid Trust endpoint")
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("token", Token(c.cfg.SiteID, op.TxnDate, op.RefID, c.cfg.Password))
resp, err := c.http.Do(req)
if err != nil {
return result, errors.New("Trust transport outcome unavailable")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return result, fmt.Errorf("Trust HTTP status %d; financial outcome unknown", resp.StatusCode)
}
data, err := io.ReadAll(io.LimitReader(resp.Body, 1024*1024+1))
if err != nil || len(data) > 1024*1024 {
return result, errors.New("Trust result unreadable")
}
var r response
if err = json.Unmarshal(data, &r); err != nil {
return result, errors.New("Trust result invalid")
}
// Preserve bounded, parsed observations for operator reconciliation without
// representing mismatched values as admitted approval evidence.
if n, e := ParseAmount(r.Amount); e == nil {
result.ObservedAmount = n
result.ObservedAmountKnown = true
}
if n, e := ParseAmount(r.Final); e == nil {
result.ObservedFinalAmount = n
result.ObservedFinalKnown = true
}
code := strings.Trim(string(r.Code), `"`)
if code == "null" {
code = ""
}
if len(code) <= 6 && strings.Trim(code, "0123456789") == "" {
result.Code = code
}
// Duplicate identity, any error code and incomplete responses are never refusals.
if code != "" && code != "0" {
// This attempt never resubmits a financial POST. A duplicate on its first
// dispatch may belong to another owner; Status alone cannot prove that
// ownership when terminal/timestamp evidence is absent.
if code == "1008" || code == "1011" {
result.State = Review
}
return result, nil
}
if (len(r.Error) > 0 && string(r.Error) != "null" && string(r.Error) != "0" && string(r.Error) != "\"\"") || r.ErrorMessage != "" {
return result, nil
}
if r.RefID != op.RefID || r.Site != c.cfg.SiteID || (r.Terminal != "" && r.Terminal != c.cfg.Terminal) ||
(status && !strings.EqualFold(r.Kind, op.Request.Kind)) || (!status && r.Terminal != c.cfg.Terminal) ||
(r.Kind != "" && !strings.EqualFold(r.Kind, op.Request.Kind)) {
result.State = Review
return result, nil
}
switch strings.ToLower(r.Result) {
case "pending":
result.State = Pending
return result, nil
case "declined":
if r.Auth != "" {
result.State = Review
return result, nil
}
result.State = Declined
return result, nil
case "cancelled":
if r.Auth != "" {
result.State = Review
return result, nil
}
result.State = Cancelled
return result, nil
case "approved":
default:
return result, nil
}
amountText := r.Amount
if status {
amountText = r.Final
}
amount, err := ParseAmount(amountText)
if err != nil || amount != op.Request.Amount {
result.State = Review
return result, nil
}
if r.Final != "" {
final, e := ParseAmount(r.Final)
if e != nil || final != amount {
result.State = Review
return result, nil
}
}
result.State = Approved
result.Amount = amount
// Legacy TRU approval does not validate currency; this is CMS bookkeeping only.
result.Currency = c.cfg.Currency
receipt, sequence := receiptFields(r.Receipt)
result.Metadata = Metadata{Receipt: shortIdentifier(receipt), Sequence: shortIdentifier(sequence), AuthCode: shortIdentifier(r.Auth)}
if len(r.Card) <= 24 && strings.Trim(r.Card, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ") == "" {
result.Metadata.CardType = r.Card
}
if len(r.Last) == 4 && strings.Trim(r.Last, "0123456789") == "" {
result.Metadata.LastFour = r.Last
}
return result, nil
}
func shortIdentifier(s string) string {
if len(s) > 12 || strings.Trim(s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_/") != "" {
return ""
}
return s
}