feat(hardlink): unify kiosk payments and finalize legacy cleanup
This commit is contained in:
+93
-3
@@ -13,13 +13,16 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
PrintReceipt func(string)
|
||||
BaseURL string
|
||||
APIKey string
|
||||
SoftwareHouseID string
|
||||
@@ -28,6 +31,7 @@ type Config struct {
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
printReceipt func(string)
|
||||
baseURL string
|
||||
apiKey string
|
||||
version string
|
||||
@@ -91,6 +95,7 @@ func NewClient(cfg Config) (*Client, error) {
|
||||
}
|
||||
|
||||
return &Client{
|
||||
printReceipt: cfg.PrintReceipt,
|
||||
baseURL: strings.TrimRight(cfg.BaseURL, "/"),
|
||||
apiKey: cfg.APIKey,
|
||||
version: cfg.Version,
|
||||
@@ -104,7 +109,49 @@ func (c *Client) Sale(
|
||||
ctx context.Context,
|
||||
req paymentsvc.SaleRequest,
|
||||
onStatus paymentsvc.StatusHandler,
|
||||
) (*paymentsvc.Result, error) {
|
||||
) (returned *paymentsvc.Result, resultErr error) {
|
||||
stage := "create_payment_intent"
|
||||
var intentID, sessionID, transactionID string
|
||||
observeSession := func(session *terminalSessionResponse) {
|
||||
if session != nil {
|
||||
if session.ID != "" {
|
||||
sessionID = session.ID
|
||||
}
|
||||
if session.PaymentDetails != nil && session.PaymentDetails.TransactionID != "" {
|
||||
transactionID = session.PaymentDetails.TransactionID
|
||||
}
|
||||
}
|
||||
}
|
||||
defer func() {
|
||||
if returned != nil {
|
||||
returned.Terminal = dojoTerminalResult(returned)
|
||||
if c.printReceipt != nil {
|
||||
c.printReceipt(returned.CustomerReceipt)
|
||||
}
|
||||
}
|
||||
if resultErr != nil || (returned != nil && returned.Terminal.Outcome == "unknown") {
|
||||
fields := log.Fields{
|
||||
"provider": "dojo", "operation": "sale", "stage": stage,
|
||||
"request_id": req.RequestID, "transaction_reference": req.RequestID,
|
||||
"error_category": paymentsvc.SafeErrorCategory(resultErr),
|
||||
}
|
||||
if intentID != "" {
|
||||
fields["payment_intent_id"] = intentID
|
||||
}
|
||||
if sessionID != "" {
|
||||
fields["terminal_session_id"] = sessionID
|
||||
}
|
||||
if transactionID != "" {
|
||||
fields["provider_transaction_id"] = transactionID
|
||||
}
|
||||
var responseError *httpResponseError
|
||||
if errors.As(resultErr, &responseError) {
|
||||
fields["http_status"] = responseError.StatusCode
|
||||
fields["error_category"] = "http_error"
|
||||
}
|
||||
log.WithFields(fields).Warn("Dojo payment requires reconciliation")
|
||||
}
|
||||
}()
|
||||
if req.Currency == "" {
|
||||
req.Currency = "GBP"
|
||||
}
|
||||
@@ -115,7 +162,12 @@ func (c *Client) Sale(
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
intentID = intent.ID
|
||||
if intent.PaymentDetails != nil {
|
||||
transactionID = intent.PaymentDetails.TransactionID
|
||||
}
|
||||
|
||||
stage = "create_terminal_session"
|
||||
session, err := c.createTerminalSession(ctx, intent.ID)
|
||||
if err != nil {
|
||||
var responseErr *httpResponseError
|
||||
@@ -125,6 +177,8 @@ func (c *Client) Sale(
|
||||
"operation": "createTerminalSession",
|
||||
"status": responseErr.StatusCode,
|
||||
"terminal_unavailable": true,
|
||||
"request_id": req.RequestID, "transaction_reference": req.RequestID,
|
||||
"payment_intent_id": intentID,
|
||||
}).Warn(dojoTerminalUnavailableMessage)
|
||||
|
||||
sendPaymentStatus(onStatus, paymentstatus.TerminalUnavailable)
|
||||
@@ -135,18 +189,24 @@ func (c *Client) Sale(
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
observeSession(session)
|
||||
|
||||
session, err = c.waitForTerminalSession(ctx, session.ID, onStatus)
|
||||
stage = "read_terminal_session"
|
||||
session, err = c.waitForTerminalSession(ctx, session.ID, onStatus, observeSession)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch strings.ToLower(session.Status) {
|
||||
case types.ResultCaptured, types.ResultSignatureAccepted:
|
||||
stage = "read_payment_intent"
|
||||
intent, err = c.getPaymentIntent(ctx, intent.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if intent.PaymentDetails != nil && intent.PaymentDetails.TransactionID != "" {
|
||||
transactionID = intent.PaymentDetails.TransactionID
|
||||
}
|
||||
if strings.ToLower(intent.Status) != types.ResultCaptured {
|
||||
return nil, fmt.Errorf("Dojo terminal session is %s but payment intent is %s", session.Status, intent.Status)
|
||||
}
|
||||
@@ -215,6 +275,7 @@ func (c *Client) waitForTerminalSession(
|
||||
ctx context.Context,
|
||||
terminalSessionID string,
|
||||
onStatus paymentsvc.StatusHandler,
|
||||
observeSession func(*terminalSessionResponse),
|
||||
) (*terminalSessionResponse, error) {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
@@ -230,7 +291,9 @@ func (c *Client) waitForTerminalSession(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Println("session status:", session.Status)
|
||||
observeSession(&session.terminalSessionResponse)
|
||||
log.WithFields(log.Fields{"provider": "dojo", "terminal_session_id": terminalSessionID,
|
||||
"status": mapDojoSessionStatus(session.Status)}).Info("Dojo terminal session observed")
|
||||
|
||||
emitNewTerminalSessionEvents(
|
||||
session,
|
||||
@@ -273,6 +336,7 @@ func (c *Client) waitForTerminalSession(
|
||||
signatureRejected = true
|
||||
|
||||
if rejectedSession != nil {
|
||||
observeSession(rejectedSession)
|
||||
rejectedStatus := strings.ToLower(
|
||||
rejectedSession.Status,
|
||||
)
|
||||
@@ -672,3 +736,29 @@ func normalizeReceiptText(value string) string {
|
||||
|
||||
return replacer.Replace(value)
|
||||
}
|
||||
|
||||
func (*Client) ValidatePreauth(paymentsvc.SaleRequest) error { return paymentsvc.ErrPreauthUnsupported }
|
||||
func (*Client) Preauth(context.Context, paymentsvc.SaleRequest, paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||
return nil, paymentsvc.ErrPreauthUnsupported
|
||||
}
|
||||
|
||||
func dojoTerminalResult(r *paymentsvc.Result) paymentapi.Result {
|
||||
final := paymentapi.Result{Outcome: "unknown", HTTPStatus: http.StatusOK, Provider: "dojo", AmountMinor: r.Amount, CurrencyCode: r.Currency, TransactionReference: r.RequestID, CardType: r.CardType, MaskedCardNumber: creditcall.MaskedCardNumber(r.CardNumber), ExpiryDate: r.ExpiryDate, CardHash: r.CardHash, CardReference: r.CardReference, AuthorizationCode: r.AuthCode, LastFour: r.LastFourDigits, Message: "Payment outcome uncertain; contact reception"}
|
||||
if r.Success && strings.EqualFold(r.Status, "APPROVED") {
|
||||
final.Outcome, final.Message = "approved", "Payment approved"
|
||||
return final
|
||||
}
|
||||
switch strings.ToUpper(r.Status) {
|
||||
case "DECLINED":
|
||||
final.Outcome, final.Retryable, final.Message = "declined", true, "Transaction declined"
|
||||
case "CANCELLED", "CANCELED":
|
||||
final.Outcome, final.Retryable, final.Message = "cancelled", true, "Transaction cancelled"
|
||||
case "SIGNATUREVERIFICATIONREJECTED", "SIGNATURE_VERIFICATION_REJECTED":
|
||||
final.Outcome, final.Reason, final.Message = "declined", "signature_verification", "Signature verification declined"
|
||||
final.Retryable = true
|
||||
case dojoTerminalUnavailableStatus:
|
||||
final.Outcome, final.Reason, final.Message = "error", "terminal_unavailable", dojoTerminalUnavailableMessage
|
||||
final.Retryable = true
|
||||
}
|
||||
return final
|
||||
}
|
||||
|
||||
@@ -86,6 +86,9 @@ func TestSaleMapsCreateTerminalSessionConflictToTerminalUnavailable(t *testing.T
|
||||
if result.Status != dojoTerminalUnavailableStatus || result.ErrorMessage != dojoTerminalUnavailableMessage {
|
||||
t.Fatalf("terminal-unavailable result = %+v", result)
|
||||
}
|
||||
if !result.Terminal.Retryable || result.Terminal.Reason != "terminal_unavailable" || result.Terminal.Outcome != "error" {
|
||||
t.Errorf("Sale(session conflict) terminal=%+v, want safely retryable pre-dispatch unavailability", result.Terminal)
|
||||
}
|
||||
if result.RequestID != request.RequestID ||
|
||||
result.Operation != "SALE" ||
|
||||
result.Amount != request.Amount ||
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package dojo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||
log "github.com/sirupsen/logrus"
|
||||
logtest "github.com/sirupsen/logrus/hooks/test"
|
||||
)
|
||||
|
||||
type diagnosticTransport func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f diagnosticTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
|
||||
func dojoDiagnosticLog(t *testing.T) *logtest.Hook {
|
||||
t.Helper()
|
||||
logger := log.StandardLogger()
|
||||
oldOutput := logger.Out
|
||||
oldHooks := logger.ReplaceHooks(make(log.LevelHooks))
|
||||
hook := logtest.NewGlobal()
|
||||
log.SetOutput(io.Discard)
|
||||
t.Cleanup(func() { log.SetOutput(oldOutput); logger.ReplaceHooks(oldHooks) })
|
||||
return hook
|
||||
}
|
||||
|
||||
func TestDojoFailureDiagnosticsKeepIdentityWithoutRawErrors(t *testing.T) {
|
||||
for _, failure := range []string{"transport", "lost", "malformed", "http", "expired"} {
|
||||
t.Run(failure, func(t *testing.T) {
|
||||
hook := dojoDiagnosticLog(t)
|
||||
financialPosts := 0
|
||||
client, err := NewClient(Config{BaseURL: "https://synthetic.invalid", APIKey: "SYNTH-CREDENTIAL", SoftwareHouseID: "SYNTH-HOUSE", TerminalID: "SYNTH-PED"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client.httpClient = &http.Client{Transport: diagnosticTransport(func(r *http.Request) (*http.Response, error) {
|
||||
body := ""
|
||||
switch {
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/payment-intents":
|
||||
financialPosts++
|
||||
if failure == "transport" {
|
||||
return nil, errors.New("SYNTH-RAW-SECRET https://user:password@private.invalid")
|
||||
}
|
||||
body = `{"id":"SYNTH-INTENT"}`
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/terminal-sessions":
|
||||
body = `{"id":"SYNTH-SESSION","paymentDetails":{"transactionId":"SYNTH-PROVIDER-TXN"}}`
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/terminal-sessions/SYNTH-SESSION":
|
||||
switch failure {
|
||||
case "lost":
|
||||
return nil, io.ErrUnexpectedEOF
|
||||
case "malformed":
|
||||
body = `{"SYNTH-RAW-SECRET":nope}`
|
||||
case "http":
|
||||
return &http.Response{StatusCode: 502, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("SYNTH-RAW-SECRET card 4111111111111111"))}, nil
|
||||
case "expired":
|
||||
body = `{"id":"SYNTH-SESSION","status":"Expired","paymentDetails":{"transactionId":"SYNTH-PROVIDER-TXN"}}`
|
||||
default:
|
||||
t.Errorf("unexpected poll for %s", failure)
|
||||
}
|
||||
default:
|
||||
t.Errorf("Dojo Sale requested unexpected %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
request := paymentsvc.SaleRequest{RequestID: "SYNTH-REQUEST", Reference: "SYNTH-BOOK", Amount: 2500, Currency: "GBP"}
|
||||
result, err := client.Sale(context.Background(), request, nil)
|
||||
if failure == "expired" {
|
||||
if err != nil || result == nil || result.Terminal.Outcome != "unknown" || result.Terminal.Retryable {
|
||||
t.Fatalf("Sale(expired)=%+v/%v, want unchanged nonretryable unknown", result, err)
|
||||
}
|
||||
} else if err == nil || result != nil {
|
||||
t.Fatalf("Sale(%s)=%+v/%v, want original nil-result error", failure, result, err)
|
||||
}
|
||||
if failure == "http" && !strings.Contains(err.Error(), "SYNTH-RAW-SECRET") {
|
||||
t.Error("Sale(http) changed the existing returned error")
|
||||
}
|
||||
if financialPosts != 1 {
|
||||
t.Errorf("Sale(%s) financial posts=%d, want one", failure, financialPosts)
|
||||
}
|
||||
var diagnostic *log.Entry
|
||||
for _, entry := range hook.AllEntries() {
|
||||
data, _ := json.Marshal(entry.Data)
|
||||
for _, secret := range []string{"SYNTH-CREDENTIAL", "SYNTH-RAW-SECRET", "4111111111111111", "user:password"} {
|
||||
if strings.Contains(string(data)+entry.Message, secret) {
|
||||
t.Errorf("Sale(%s) logged sensitive marker %q", failure, secret)
|
||||
}
|
||||
}
|
||||
if entry.Message == "Dojo payment requires reconciliation" {
|
||||
diagnostic = entry
|
||||
}
|
||||
}
|
||||
if diagnostic == nil {
|
||||
t.Fatal("Sale failure emitted no reconciliation diagnostic")
|
||||
}
|
||||
for key, want := range map[string]any{"provider": "dojo", "request_id": "SYNTH-REQUEST", "transaction_reference": "SYNTH-REQUEST"} {
|
||||
if diagnostic.Data[key] != want {
|
||||
t.Errorf("Sale(%s) diagnostic[%s]=%v, want %v", failure, key, diagnostic.Data[key], want)
|
||||
}
|
||||
}
|
||||
wantStage, wantCategory := "read_terminal_session", "unresolved_result"
|
||||
switch failure {
|
||||
case "transport":
|
||||
wantStage, wantCategory = "create_payment_intent", "connection_failure"
|
||||
case "lost":
|
||||
wantCategory = "response_lost"
|
||||
case "malformed":
|
||||
wantCategory = "invalid_response"
|
||||
case "http":
|
||||
wantCategory = "http_error"
|
||||
}
|
||||
if diagnostic.Data["stage"] != wantStage || diagnostic.Data["error_category"] != wantCategory {
|
||||
t.Errorf("Sale(%s) diagnostic=%v, want stage=%s category=%s", failure, diagnostic.Data, wantStage, wantCategory)
|
||||
}
|
||||
if failure != "transport" {
|
||||
for key, want := range map[string]string{"payment_intent_id": "SYNTH-INTENT", "terminal_session_id": "SYNTH-SESSION", "provider_transaction_id": "SYNTH-PROVIDER-TXN"} {
|
||||
if diagnostic.Data[key] != want {
|
||||
t.Errorf("Sale(%s) diagnostic[%s]=%v, want %s", failure, key, diagnostic.Data[key], want)
|
||||
}
|
||||
}
|
||||
}
|
||||
if failure == "http" && diagnostic.Data["http_status"] != 502 {
|
||||
t.Errorf("Sale(http) status=%v, want 502", diagnostic.Data["http_status"])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDojoPollFailureRetainsLastObservedTransactionIdentity(t *testing.T) {
|
||||
hook := dojoDiagnosticLog(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
client, err := NewClient(Config{BaseURL: "https://synthetic.invalid", APIKey: "SYNTH", SoftwareHouseID: "SYNTH", TerminalID: "SYNTH"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client.httpClient = &http.Client{Transport: diagnosticTransport(func(r *http.Request) (*http.Response, error) {
|
||||
body := `{"id":"SYNTH-INTENT"}`
|
||||
if strings.HasPrefix(r.URL.Path, "/terminal-sessions") {
|
||||
body = `{"id":"SYNTH-SESSION"}`
|
||||
}
|
||||
if r.Method == "GET" {
|
||||
body = `{"id":"SYNTH-SESSION","status":"Initiated","paymentDetails":{"transactionId":"SYNTH-POLL-TXN"}}`
|
||||
cancel()
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
result, err := client.Sale(ctx, paymentsvc.SaleRequest{RequestID: "SYNTH-REQUEST", Amount: 2500}, nil)
|
||||
if result != nil || !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Sale(cancel after poll)=%+v/%v, want unchanged cancellation", result, err)
|
||||
}
|
||||
for _, entry := range hook.AllEntries() {
|
||||
if entry.Message == "Dojo payment requires reconciliation" {
|
||||
if entry.Data["provider_transaction_id"] != "SYNTH-POLL-TXN" || entry.Data["error_category"] != "cancelled" {
|
||||
t.Errorf("Sale(cancel after poll) diagnostic=%v, want last observed transaction and cancellation", entry.Data)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("Sale(cancel after poll) emitted no diagnostic; entries=%d", len(hook.AllEntries()))
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package dojo
|
||||
|
||||
import (
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTerminalResultKeepsExistingIdentityAndOnlyRealMetadata(t *testing.T) {
|
||||
raw := &paymentsvc.Result{Success: true, Status: "APPROVED", RequestID: "SYNTH-REQUEST", TransactionID: "SYNTH-PROVIDER-ID", Amount: 1234, Currency: "EUR", CardNumber: "************1133", CardType: "Visa", ExpiryDate: "1228", AuthCode: "SYNTH-AUTH"}
|
||||
result := dojoTerminalResult(raw)
|
||||
if result.Outcome != "approved" || result.TransactionReference != "SYNTH-REQUEST" || result.MaskedCardNumber != raw.CardNumber || result.ExpiryDate != "1228" || result.CardHash != "" || result.CardReference != "" {
|
||||
t.Errorf("dojoTerminalResult(%+v)=%+v, want current request identity and only supplied card data", raw, result)
|
||||
}
|
||||
raw.CardNumber = "4111111111111111"
|
||||
if got := dojoTerminalResult(raw).MaskedCardNumber; got != "" {
|
||||
t.Errorf("dojoTerminalResult(unmasked PAN) masked=%q, want omitted", got)
|
||||
}
|
||||
}
|
||||
func TestExpiredTerminalResultIsUncertain(t *testing.T) {
|
||||
result := dojoTerminalResult(&paymentsvc.Result{Status: "EXPIRED"})
|
||||
if result.Outcome != "unknown" || result.Retryable {
|
||||
t.Errorf("dojoTerminalResult(EXPIRED)=%+v, want nonretryable unknown", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmedSignatureRejectionRemainsRetryable(t *testing.T) {
|
||||
result := dojoTerminalResult(&paymentsvc.Result{Status: "SIGNATUREVERIFICATIONREJECTED"})
|
||||
if result.Outcome != "declined" || result.Reason != "signature_verification" || !result.Retryable {
|
||||
t.Errorf("dojoTerminalResult(signature rejected)=%+v, want safely retryable confirmed rejection", result)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user