feat(hardlink): unify kiosk payments and finalize legacy cleanup
This commit is contained in:
@@ -0,0 +1,276 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package trustpayments
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type transportFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f transportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
func fixtureConfig() Config {
|
||||
return Config{BaseURL: "https://sandbox.link.trustpayments.com/trustpayments/rest/", SiteID: "site", Password: "test-secret", Terminal: "terminal", Currency: "GBP", Timezone: "Europe/London"}
|
||||
}
|
||||
func TestTrustSigningMoneyAndConfiguration(t *testing.T) {
|
||||
if got := Token("123456", "2020-03-01:10:20:05", "7876547", "tv%61w%5"); got != "990bc7bb7efee9e383a96f6f929fd00c90f4ec94f4344270c1552e4d5d4d80c5" {
|
||||
t.Errorf("Token=%s", got)
|
||||
}
|
||||
for _, s := range []string{"", "0.00", "-1.00", "1.001", "1", "NaN", "92233720368547758.08", "1e2"} {
|
||||
if _, e := ParseAmount(s); e == nil {
|
||||
t.Errorf("ParseAmount(%q) accepted", s)
|
||||
}
|
||||
}
|
||||
if n, e := ParseAmount("123456.78"); e != nil || Decimal(n) != "123456.78" {
|
||||
t.Fatalf("money=%d/%v", n, e)
|
||||
}
|
||||
for _, url := range []string{"", "http://link.trustpayments.com/trustpayments/rest/", "https://other.invalid/trustpayments/rest/", "https://link.trustpayments.com:443/trustpayments/rest/", "https://link.trustpayments.com/trustpayments/rest/?x=1"} {
|
||||
cfg := fixtureConfig()
|
||||
cfg.BaseURL = url
|
||||
if _, e := New(cfg); e == nil {
|
||||
t.Errorf("New(%q) accepted", url)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestTrustFinancialEvidenceAndUncertainErrors(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
change func(map[string]any)
|
||||
status bool
|
||||
state string
|
||||
}{
|
||||
{"sale", nil, false, Approved}, {"status", nil, true, Approved},
|
||||
{"adjusted", func(r map[string]any) { r["finalamount"] = "11.00" }, false, Review},
|
||||
{"wrongAmount", func(r map[string]any) { r["amount"] = "9.00" }, false, Review},
|
||||
{"providerCurrencyIgnored", func(r map[string]any) { r["currency"] = "EUR" }, false, Approved},
|
||||
{"wrongRef", func(r map[string]any) { r["refid"] = "other" }, false, Review},
|
||||
{"wrongSite", func(r map[string]any) { r["siteid"] = "other" }, true, Review},
|
||||
{"wrongType", func(r map[string]any) { r["type"] = "preauth" }, true, Review},
|
||||
{"noAmount", func(r map[string]any) { delete(r, "finalamount") }, true, Review},
|
||||
{"declined", func(r map[string]any) { r["resultcode"] = "Declined"; delete(r, "authcode") }, false, Declined},
|
||||
{"cancelled", func(r map[string]any) { r["resultcode"] = "Cancelled"; delete(r, "authcode") }, false, Cancelled},
|
||||
{"pending", func(r map[string]any) { r["resultcode"] = "Pending" }, false, Pending},
|
||||
{"2003", func(r map[string]any) { r["errorcode"] = 2003 }, false, Unknown},
|
||||
{"2005", func(r map[string]any) { r["errorcode"] = "2005" }, false, Unknown},
|
||||
{"2006", func(r map[string]any) { r["errorcode"] = 2006 }, false, Unknown},
|
||||
{"1011", func(r map[string]any) { r["errorcode"] = 1011 }, false, Review},
|
||||
{"1008", func(r map[string]any) { r["errorcode"] = 1008 }, false, Review},
|
||||
{"offline", func(r map[string]any) { r["resultcode"] = "Terminal Busy" }, false, Unknown},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := fixtureConfig()
|
||||
calls := 0
|
||||
cfg.Transport = transportFunc(func(req *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
var input map[string]string
|
||||
if e := json.NewDecoder(req.Body).Decode(&input); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if input["txndate"] != "2026-10-23:12:00:00" || req.Header.Get("token") != Token(cfg.SiteID, input["txndate"], "ref", cfg.Password) {
|
||||
t.Error("signing context changed")
|
||||
}
|
||||
if !tc.status && (input["wait"] != "y" || input["amount"] != "10.00") {
|
||||
t.Error("incorrect financial payload")
|
||||
}
|
||||
r := map[string]any{"refid": "ref", "siteid": "site", "terminalserialnumber": "terminal", "type": "sale", "amount": "10.00", "finalamount": "10.00", "resultcode": "Approved", "receipt": "Sequence number: 42\r\nReceipt: 31\r\nPAN: 4111111111111111", "authcode": "123456", "cardtype": "Visa", "last4": "1133"}
|
||||
if tc.change != nil {
|
||||
tc.change(r)
|
||||
}
|
||||
b, _ := json.Marshal(r)
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(b)))}, nil
|
||||
})
|
||||
c, e := New(cfg)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
result, e := c.Execute(context.Background(), Operation{RefID: "ref", TxnDate: "2026-10-23:12:00:00", Request: Request{Kind: "sale", Amount: 1000, Currency: "GBP"}}, tc.status)
|
||||
if e != nil || result.State != tc.state || calls != 1 {
|
||||
t.Fatalf("Execute=%+v/%v, calls=%d, want %s/1", result, e, calls, tc.state)
|
||||
}
|
||||
if result.State == Approved && (result.Metadata.Receipt != "31" || result.Metadata.Sequence != "42" || result.Metadata.LastFour != "1133") {
|
||||
t.Error("metadata lost")
|
||||
}
|
||||
if result.State == Approved && result.Currency != cfg.Currency {
|
||||
t.Errorf("currency metadata=%q, want CMS currency %q", result.Currency, cfg.Currency)
|
||||
}
|
||||
if tc.name == "adjusted" && (!result.ObservedFinalKnown || result.ObservedFinalAmount != 1100 || result.Amount != 0) {
|
||||
t.Fatal("financial mismatch evidence was lost or admitted")
|
||||
}
|
||||
b, _ := json.Marshal(result)
|
||||
if strings.Contains(string(b), "4111111111111111") || strings.Contains(string(b), cfg.Password) {
|
||||
t.Error("sensitive data escaped")
|
||||
}
|
||||
})
|
||||
}
|
||||
cfg := fixtureConfig()
|
||||
c, _ := New(cfg)
|
||||
r, e := c.Execute(context.Background(), Operation{}, false)
|
||||
if e == nil || r.State == Approved {
|
||||
t.Fatal("invalid operation admitted")
|
||||
}
|
||||
}
|
||||
func TestTrustTransportHTTPAndMalformedResultsRemainUnknown(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, body string
|
||||
status int
|
||||
}{{"http500", `{"resultcode":"Approved"}`, 500}, {"http401", "", 401}, {"malformed", "{", 200}, {"empty", "{}", 200}, {"unexpectedError", `{"resultcode":"Approved","error":"private-token"}`, 200}} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := fixtureConfig()
|
||||
calls := 0
|
||||
cfg.Transport = transportFunc(func(*http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
return &http.Response{StatusCode: tc.status, Body: io.NopCloser(strings.NewReader(tc.body))}, nil
|
||||
})
|
||||
c, e := New(cfg)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
r, _ := c.Execute(context.Background(), Operation{RefID: "ref", TxnDate: "2026-10-23:12:00:00", Request: Request{Kind: "sale", Amount: 1000, Currency: "GBP"}}, false)
|
||||
if r.State == Approved || r.State == Declined || calls != 1 {
|
||||
t.Fatalf("uncertain=%+v calls=%d", r, calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package trustpayments
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLegacyTrustCurrencyDoesNotDetermineApproval(t *testing.T) {
|
||||
for _, providerCurrency := range []any{nil, "", "GBP", "EUR", "NOT-AN-ISO-CODE", 123, map[string]any{"unexpected": "value"}} {
|
||||
t.Run(fmt.Sprint("provider=", providerCurrency), func(t *testing.T) {
|
||||
cfg := fixtureConfig()
|
||||
cfg.Transport = transportFunc(func(r *http.Request) (*http.Response, error) {
|
||||
var input map[string]string
|
||||
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, exists := input["currency"]; exists {
|
||||
t.Error("TRU request gained a currency field")
|
||||
}
|
||||
body, _ := json.Marshal(map[string]any{"refid": "SYNTH-REF", "siteid": cfg.SiteID, "terminalserialnumber": cfg.Terminal, "type": "sale", "resultcode": "Approved", "amount": "25.00", "currency": providerCurrency})
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(body)))}, nil
|
||||
})
|
||||
client, err := New(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
op := Operation{RefID: "SYNTH-REF", TxnDate: "2026-11-03:12:00:00", Request: Request{Kind: "sale", Amount: 2500, Currency: "REQUEST-CURRENCY-IS-NOT-A-GATE"}}
|
||||
result, err := client.Execute(context.Background(), op, false)
|
||||
if err != nil || result.State != Approved || result.Amount != 2500 || result.Currency != cfg.Currency {
|
||||
t.Fatalf("Execute(provider currency %v)=%+v/%v, want approval and CMS bookkeeping only", providerCurrency, result, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCMSCurrencyIsMetadataNotAClientValidationFlag(t *testing.T) {
|
||||
for _, currency := range []string{"", "GBP", "NOT-AN-ISO-CODE"} {
|
||||
cfg := fixtureConfig()
|
||||
cfg.Currency = currency
|
||||
client, err := New(cfg)
|
||||
if err != nil {
|
||||
t.Errorf("New(CMS currency %q)=%v, want no Trust currency gate", currency, err)
|
||||
continue
|
||||
}
|
||||
if !client.ValidRequest(Request{Kind: "preauth", Amount: 2500, Currency: "different"}) {
|
||||
t.Errorf("ValidRequest(CMS currency %q) imposed currency validation", currency)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package trustpayments
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTrustProcessOneFinancialPostAndBoundedStatus(t *testing.T) {
|
||||
for _, first := range []string{"Approved", "Declined", "Cancelled", "Pending", "2003", "2005", "2006", "transport", "1011", "mismatch"} {
|
||||
t.Run(first, func(t *testing.T) {
|
||||
cfg := fixtureConfig()
|
||||
var ref, timestamp string
|
||||
financial, status := 0, 0
|
||||
cfg.Transport = transportFunc(func(r *http.Request) (*http.Response, error) {
|
||||
var input map[string]string
|
||||
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lookup := strings.HasSuffix(r.URL.Path, "/status")
|
||||
deadline, ok := r.Context().Deadline()
|
||||
remaining := time.Until(deadline)
|
||||
if !lookup {
|
||||
financial++
|
||||
ref, timestamp = input["refid"], input["txndate"]
|
||||
if !ok || remaining > 300*time.Second || remaining < 299*time.Second || input["wait"] != "y" {
|
||||
t.Errorf("financial deadline/payload=%s/%v", remaining, input)
|
||||
}
|
||||
} else {
|
||||
status++
|
||||
if input["refid"] != ref || input["txndate"] != timestamp || !ok || remaining > 15*time.Second || remaining < 14*time.Second || input["amount"] != "" {
|
||||
t.Errorf("status changed identity/budget/payload=%s/%v", remaining, input)
|
||||
}
|
||||
}
|
||||
if !lookup && first == "transport" {
|
||||
return nil, errors.New("synthetic disconnected provider")
|
||||
}
|
||||
body := map[string]any{"refid": ref, "siteid": "site", "terminalserialnumber": "terminal", "type": "sale", "amount": "10.00", "finalamount": "10.00", "resultcode": "Approved", "authcode": "123456"}
|
||||
if !lookup {
|
||||
switch first {
|
||||
case "Declined", "Cancelled":
|
||||
body["resultcode"], body["authcode"] = first, ""
|
||||
case "Pending":
|
||||
body["resultcode"] = first
|
||||
case "2003", "2005", "2006", "1011":
|
||||
body["errorcode"] = first
|
||||
case "mismatch":
|
||||
body["amount"] = "9.00"
|
||||
}
|
||||
}
|
||||
encoded, _ := json.Marshal(body)
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(encoded)))}, nil
|
||||
})
|
||||
client, err := New(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := client.Process(context.Background(), Request{Kind: "sale", Amount: 1000, Currency: "GBP"})
|
||||
wantStatus := 0
|
||||
if first == "Pending" || first == "transport" || first == "2003" || first == "2005" || first == "2006" {
|
||||
wantStatus = 1
|
||||
}
|
||||
want := Approved
|
||||
if first == "Declined" {
|
||||
want = Declined
|
||||
}
|
||||
if first == "Cancelled" {
|
||||
want = Cancelled
|
||||
}
|
||||
if first == "1011" || first == "mismatch" {
|
||||
want = Review
|
||||
}
|
||||
if err != nil || financial != 1 || status != wantStatus || result.State != want || len(ref) != 32 {
|
||||
t.Fatalf("Process(%s) state/error/posts/status=%s/%v/%d/%d, want %s/nil/1/%d", first, result.State, err, financial, status, want, wantStatus)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrustProcessStatusStillUnknownAndPreauth(t *testing.T) {
|
||||
for _, kind := range []string{"sale", "preauth"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
cfg := fixtureConfig()
|
||||
calls := 0
|
||||
cfg.Transport = transportFunc(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if calls == 1 && !strings.HasSuffix(r.URL.Path, "/"+kind) {
|
||||
t.Errorf("provider endpoint=%s", r.URL.Path)
|
||||
}
|
||||
if calls == 2 && !strings.HasSuffix(r.URL.Path, "/status") {
|
||||
t.Errorf("second call=%s, want status", r.URL.Path)
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"errorcode":2003}`))}, nil
|
||||
})
|
||||
client, err := New(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := client.Process(context.Background(), Request{Kind: kind, Amount: 2500, Currency: "GBP"})
|
||||
if err != nil || result.State != Unknown || calls != 2 {
|
||||
t.Fatalf("unresolved result=%+v/%v calls=%d", result, err, calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package trustpayments
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/printer"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Processor owns Trust execution and terminal receipt printing.
|
||||
type Processor struct {
|
||||
Client *Client
|
||||
PrintReceipt func(string)
|
||||
}
|
||||
|
||||
func (p *Processor) ValidatePreauth(req paymentsvc.SaleRequest) error {
|
||||
if p.Client == nil || !p.Client.ValidRequest(Request{Kind: "preauth", Amount: req.Amount}) {
|
||||
return paymentsvc.ErrPreauthUnsupported
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (p *Processor) Sale(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||
return p.run(ctx, req, status, "sale")
|
||||
}
|
||||
func (p *Processor) Preauth(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||
return p.run(ctx, req, status, "preauth")
|
||||
}
|
||||
func (p *Processor) run(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler, kind string) (*paymentsvc.Result, error) {
|
||||
for _, code := range []string{paymentstatus.Starting, paymentstatus.RequestSent, paymentstatus.Processing} {
|
||||
if status != nil {
|
||||
status(paymentsvc.StatusUpdate{Code: code})
|
||||
}
|
||||
}
|
||||
result, err := p.Client.Process(ctx, Request{Kind: kind, Amount: req.Amount, Currency: req.Currency})
|
||||
final := paymentapi.Result{Outcome: "unknown", HTTPStatus: http.StatusOK, Provider: "TrustPayments", Message: "Payment outcome uncertain; contact reception", TransactionReference: result.RefID}
|
||||
switch result.State {
|
||||
case Approved:
|
||||
final.Outcome, final.Message = "approved", "Payment approved"
|
||||
final.AmountMinor, final.CurrencyCode = result.Amount, result.Currency
|
||||
m := result.Metadata
|
||||
final.ReceiptNumber, final.SequenceNumber, final.AuthorizationCode = m.Receipt, m.Sequence, m.AuthCode
|
||||
final.CardType, final.LastFour = m.CardType, m.LastFour
|
||||
receipt := fmt.Sprintf("Trust Payments\n%s %s\n%s\nCard ************%s", Decimal(result.Amount), result.Currency, m.Description(result.RefID), m.LastFour)
|
||||
if p.PrintReceipt != nil {
|
||||
p.PrintReceipt(receipt)
|
||||
} else {
|
||||
printer.PrintSaleReceipt(receipt)
|
||||
}
|
||||
case Declined:
|
||||
final.Outcome, final.Retryable, final.Message = "declined", true, "Transaction declined"
|
||||
case Cancelled:
|
||||
final.Outcome, final.Retryable, final.Message = "cancelled", true, "Transaction cancelled"
|
||||
}
|
||||
if final.Outcome != "unknown" {
|
||||
err = nil
|
||||
} else {
|
||||
fields := log.Fields{
|
||||
"provider": final.Provider, "operation": kind, "outcome": final.Outcome,
|
||||
"request_id": req.RequestID, "request_reference": req.Reference,
|
||||
"transaction_reference": result.RefID, "provider_state": result.State,
|
||||
"provider_code": result.Code, "error_category": paymentsvc.SafeErrorCategory(err),
|
||||
}
|
||||
if result.ObservedAmountKnown {
|
||||
fields["observed_amount_minor"] = result.ObservedAmount
|
||||
}
|
||||
if result.ObservedFinalKnown {
|
||||
fields["observed_final_amount_minor"] = result.ObservedFinalAmount
|
||||
}
|
||||
log.WithFields(fields).Warn("Trust payment outcome requires reception reconciliation")
|
||||
}
|
||||
return &paymentsvc.Result{Terminal: final}, err
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package trustpayments
|
||||
|
||||
// These are provider-call values, not persistent operations or kiosk sessions.
|
||||
const (
|
||||
Approved = "APPROVED_VALIDATED"
|
||||
Declined = "DECLINED"
|
||||
Cancelled = "CANCELLED"
|
||||
Pending = "PENDING"
|
||||
Unknown = "UNKNOWN"
|
||||
Review = "REVIEW_REQUIRED"
|
||||
)
|
||||
|
||||
type Request struct {
|
||||
Kind string
|
||||
Amount int64
|
||||
Currency string
|
||||
}
|
||||
|
||||
type Operation struct {
|
||||
Request Request
|
||||
RefID, TxnDate string
|
||||
}
|
||||
|
||||
type Metadata struct {
|
||||
Receipt, Sequence, AuthCode, CardType, LastFour string
|
||||
}
|
||||
|
||||
func (m Metadata) Description(ref string) string {
|
||||
s := "Tx " + ref
|
||||
for _, v := range [][2]string{{"Rec", m.Receipt}, {"Seq", m.Sequence}, {"Hash", m.AuthCode}, {"Ref", m.CardType + m.LastFour}} {
|
||||
if v[1] != "" {
|
||||
s += " " + v[0] + " " + v[1]
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
State, RefID, Currency, Code string
|
||||
Amount int64
|
||||
Metadata Metadata
|
||||
ObservedAmount, ObservedFinalAmount int64
|
||||
ObservedAmountKnown, ObservedFinalKnown bool
|
||||
}
|
||||
Reference in New Issue
Block a user