add pluggable PayBridge and Dojo payment flow with CMS credentials
This commit is contained in:
@@ -0,0 +1,278 @@
|
||||
package creditcall
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
)
|
||||
|
||||
const (
|
||||
KeyErrors = "ERRORS"
|
||||
KeyVersionInformation = "VERSION_INFORMATION"
|
||||
KeyChipDnaStatus = "CHIPDNA_STATUS"
|
||||
KeyPaymentDeviceStatus = "PAYMENT_DEVICE_STATUS"
|
||||
KeyRequestQueueStatus = "REQUEST_QUEUE_STATUS"
|
||||
KeyTmsStatus = "TMS_STATUS"
|
||||
KeyPaymentPlatform = "PAYMENT_PLATFORM_STATUS"
|
||||
KeyPaymentDeviceModel = "PAYMENT_DEVICE_MODEL"
|
||||
KeyPaymentDeviceIdentifier = "PAYMENT_DEVICE_IDENTIFIER"
|
||||
KeyIsAvailable = "IS_AVAILABLE"
|
||||
KeyAvailabilityError = "AVAILABILITY_ERROR"
|
||||
KeyAvailabilityErrorInformation = "AVAILABILITY_ERROR_INFORMATION"
|
||||
)
|
||||
|
||||
type (
|
||||
ArrayOfParameter struct {
|
||||
Parameters []Parameter `xml:"Parameter" json:"Parameters"`
|
||||
}
|
||||
|
||||
Parameter struct {
|
||||
Key string `xml:"Key" json:"Key"`
|
||||
Value string `xml:"Value" json:"Value"`
|
||||
}
|
||||
|
||||
ServerStatus struct {
|
||||
IsProcessingTransaction bool `xml:"IsProcessingTransaction" json:"IsProcessingTransaction"`
|
||||
ChipDnaServerIssue string `xml:"ChipDnaServerIssue" json:"ChipDnaServerIssue"`
|
||||
}
|
||||
|
||||
ArrayOfPaymentDeviceStatus struct {
|
||||
Items []PaymentDeviceStatus `xml:"PaymentDeviceStatus" json:"Items"`
|
||||
}
|
||||
|
||||
PaymentDeviceStatus struct {
|
||||
ConfiguredDeviceId string `xml:"ConfiguredDeviceId" json:"ConfiguredDeviceId"`
|
||||
ConfiguredDeviceModel string `xml:"ConfiguredDeviceModel" json:"ConfiguredDeviceModel"`
|
||||
ProcessingTransaction bool `xml:"ProcessingTransaction" json:"ProcessingTransaction"`
|
||||
AvailabilityError string `xml:"AvailabilityError" json:"AvailabilityError"`
|
||||
AvailabilityErrorInformation string `xml:"AvailabilityErrorInformation" json:"AvailabilityErrorInformation"`
|
||||
ConfigurationState string `xml:"ConfigurationState" json:"ConfigurationState"`
|
||||
IsAvailable bool `xml:"IsAvailable" json:"IsAvailable"`
|
||||
BatteryPercentage int `xml:"BatteryPercentage" json:"BatteryPercentage"`
|
||||
BatteryChargingStatus string `xml:"BatteryChargingStatus" json:"BatteryChargingStatus"`
|
||||
BatteryStatusUpdateDateTime string `xml:"BatteryStatusUpdateDateTime" json:"BatteryStatusUpdateDateTime"`
|
||||
BatteryStatusUpdateDateTimeFormat string `xml:"BatteryStatusUpdateDateTimeFormat" json:"BatteryStatusUpdateDateTimeFormat"`
|
||||
}
|
||||
|
||||
RequestQueueStatus struct {
|
||||
CreditRequestCount int `xml:"CreditRequestCount" json:"CreditRequestCount"`
|
||||
CreditConfirmRequestCount int `xml:"CreditConfirmRequestCount" json:"CreditConfirmRequestCount"`
|
||||
CreditVoidRequestCount int `xml:"CreditVoidRequestCount" json:"CreditVoidRequestCount"`
|
||||
DebitRequestCount int `xml:"DebitRequestCount" json:"DebitRequestCount"`
|
||||
DebitConfirmRequestCount int `xml:"DebitConfirmRequestCount" json:"DebitConfirmRequestCount"`
|
||||
DebitVoidRequestCount int `xml:"DebitVoidRequestCount" json:"DebitVoidRequestCount"`
|
||||
}
|
||||
|
||||
TmsStatus struct {
|
||||
LastConfigUpdateDateTime string `xml:"LastConfigUpdateDateTime" json:"LastConfigUpdateDateTime"`
|
||||
DaysUntilConfigUpdateIsRequired int `xml:"DaysUntilConfigUpdateIsRequired" json:"DaysUntilConfigUpdateIsRequired"`
|
||||
RequiredConfigUpdateDateTime string `xml:"RequiredConfigUpdateDateTime" json:"RequiredConfigUpdateDateTime"`
|
||||
}
|
||||
|
||||
PaymentPlatformStatus struct {
|
||||
MachineLocalDateTime string `xml:"MachineLocalDateTime" json:"MachineLocalDateTime"`
|
||||
PaymentPlatformLocalDateTime string `xml:"PaymentPlatformLocalDateTime" json:"PaymentPlatformLocalDateTime"`
|
||||
PaymentPlatformLocalDateTimeFormat string `xml:"PaymentPlatformLocalDateTimeFormat" json:"PaymentPlatformLocalDateTimeFormat"`
|
||||
State string `xml:"State" json:"State"`
|
||||
}
|
||||
|
||||
ParsedStatus struct {
|
||||
Errors []string `json:"Errors"`
|
||||
VersionInfo map[string]string `json:"VersionInfo"`
|
||||
ChipDnaStatus *ServerStatus `json:"ChipDnaStatus"`
|
||||
PaymentDevices []PaymentDeviceStatus `json:"PaymentDevices"`
|
||||
RequestQueue *RequestQueueStatus `json:"RequestQueue"`
|
||||
TMS *TmsStatus `json:"TMS"`
|
||||
PaymentPlatform *PaymentPlatformStatus `json:"PaymentPlatform"`
|
||||
Unknown map[string]string `json:"Unknown"`
|
||||
}
|
||||
)
|
||||
|
||||
// ===========================
|
||||
// Parser
|
||||
// ===========================
|
||||
|
||||
func ParseStatusResult(data []byte) (*ParsedStatus, error) {
|
||||
var tr TransactionResultXML
|
||||
if err := tr.ParseTransactionResult(data); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal TransactionResult: %w", err)
|
||||
}
|
||||
|
||||
out := &ParsedStatus{
|
||||
VersionInfo: make(map[string]string),
|
||||
Unknown: make(map[string]string),
|
||||
}
|
||||
|
||||
for _, e := range tr.Entries {
|
||||
switch e.Key {
|
||||
|
||||
// Some responses return plain text (not escaped XML) for ERRORS.
|
||||
case KeyErrors:
|
||||
msg := html.UnescapeString(e.Value) // safe even if not escaped
|
||||
if msg != "" {
|
||||
out.Errors = append(out.Errors, msg)
|
||||
}
|
||||
|
||||
// Everything below is escaped XML inside <Value>
|
||||
case KeyVersionInformation:
|
||||
unescaped := html.UnescapeString(e.Value)
|
||||
|
||||
var a ArrayOfParameter
|
||||
if err := xml.Unmarshal([]byte(unescaped), &a); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s: %w", e.Key, err)
|
||||
}
|
||||
for _, p := range a.Parameters {
|
||||
out.VersionInfo[p.Key] = p.Value
|
||||
}
|
||||
|
||||
case KeyChipDnaStatus:
|
||||
unescaped := html.UnescapeString(e.Value)
|
||||
|
||||
var s ServerStatus
|
||||
if err := xml.Unmarshal([]byte(unescaped), &s); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s: %w", e.Key, err)
|
||||
}
|
||||
out.ChipDnaStatus = &s
|
||||
|
||||
case KeyPaymentDeviceStatus:
|
||||
unescaped := html.UnescapeString(e.Value)
|
||||
|
||||
var a ArrayOfPaymentDeviceStatus
|
||||
if err := xml.Unmarshal([]byte(unescaped), &a); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s: %w", e.Key, err)
|
||||
}
|
||||
out.PaymentDevices = append(out.PaymentDevices, a.Items...)
|
||||
|
||||
case KeyRequestQueueStatus:
|
||||
unescaped := html.UnescapeString(e.Value)
|
||||
|
||||
var s RequestQueueStatus
|
||||
if err := xml.Unmarshal([]byte(unescaped), &s); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s: %w", e.Key, err)
|
||||
}
|
||||
out.RequestQueue = &s
|
||||
|
||||
case KeyTmsStatus:
|
||||
unescaped := html.UnescapeString(e.Value)
|
||||
|
||||
var s TmsStatus
|
||||
if err := xml.Unmarshal([]byte(unescaped), &s); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s: %w", e.Key, err)
|
||||
}
|
||||
out.TMS = &s
|
||||
|
||||
case KeyPaymentPlatform:
|
||||
unescaped := html.UnescapeString(e.Value)
|
||||
|
||||
var s PaymentPlatformStatus
|
||||
if err := xml.Unmarshal([]byte(unescaped), &s); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal %s: %w", e.Key, err)
|
||||
}
|
||||
out.PaymentPlatform = &s
|
||||
|
||||
default:
|
||||
// Keep for logging / future additions. Unescape so it's readable XML if it was escaped.
|
||||
out.Unknown[e.Key] = html.UnescapeString(e.Value)
|
||||
}
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func fetchChipDNAStatus() (*ParsedStatus, error) {
|
||||
const op = logging.Op("fetchChipDNAStatus")
|
||||
|
||||
body := []byte{}
|
||||
client := &http.Client{Timeout: 300 * time.Second}
|
||||
response, err := client.Post(types.LinkChipDNAStatus, "text/xml", bytes.NewBuffer(body))
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "error fetching ChipDNA status", string(op), "", "", 0)
|
||||
return nil, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
body, err = io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Read response body error", string(op), "", "", 0)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result, err := ParseStatusResult(body)
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Parse ChipDNA status error", string(op), "", "", 0)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func ReadPdqStatus(hotel string, kiosk int) (PaymentDeviceStatus, error) {
|
||||
const op = logging.Op("readPdqStatus")
|
||||
|
||||
status, err := fetchChipDNAStatus()
|
||||
if err != nil {
|
||||
logging.Error(types.ServiceName, "pdq_unavailable", "Failed to fetch ChipDNA status: "+err.Error(), string(op), "", hotel, kiosk)
|
||||
return PaymentDeviceStatus{}, fmt.Errorf("error fetch ChipDNA status: %w", err)
|
||||
}
|
||||
|
||||
if len(status.Errors) > 0 {
|
||||
msg := strings.Join(status.Errors, "; ")
|
||||
logging.Error(types.ServiceName, "pdq_unavailable", "ChipDNA status errors: "+msg, string(op), "", hotel, kiosk)
|
||||
return PaymentDeviceStatus{}, fmt.Errorf("ChipDNA status errors: %s", msg)
|
||||
}
|
||||
|
||||
if len(status.PaymentDevices) == 0 {
|
||||
logging.Error(types.ServiceName, "pdq_unavailable", "ChipDNA status has no PAYMENT_DEVICE_STATUS items", string(op), "", hotel, kiosk)
|
||||
return PaymentDeviceStatus{}, fmt.Errorf("no payment devices returned")
|
||||
}
|
||||
|
||||
dev := status.PaymentDevices[0]
|
||||
if !dev.IsAvailable {
|
||||
logging.Error(types.ServiceName, "pdq_unavailable", "Payment device unavailable", string(op), "", hotel, kiosk)
|
||||
return dev, fmt.Errorf("device unavailable")
|
||||
}
|
||||
|
||||
return dev, nil
|
||||
}
|
||||
|
||||
func StartPdqHourlyCheck(ctx context.Context, hotel string, kiosk int) {
|
||||
// waitUntilNextHour(ctx)
|
||||
|
||||
// First execution exactly at round hour
|
||||
_, _ = ReadPdqStatus(hotel, kiosk)
|
||||
|
||||
ticker := time.NewTicker(10 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
_, _ = ReadPdqStatus(hotel, kiosk)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func waitUntilNextHour(ctx context.Context) {
|
||||
now := time.Now()
|
||||
next := now.Truncate(time.Hour).Add(time.Hour)
|
||||
d := time.Until(next)
|
||||
|
||||
timer := time.NewTimer(d)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package creditcall
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
_ "github.com/denisenkom/go-mssqldb"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// XML parsing structs
|
||||
type (
|
||||
TransactionRec struct {
|
||||
XMLName xml.Name `xml:"TransactionPayload"`
|
||||
AmountMinorUnits string `xml:"amount"`
|
||||
TransactionType string `xml:"transactionType"`
|
||||
}
|
||||
|
||||
TransactionResultXML struct {
|
||||
XMLName xml.Name `xml:"TransactionResult"`
|
||||
Entries []EntryXML `xml:"Entry"`
|
||||
}
|
||||
|
||||
EntryXML struct {
|
||||
Key string `xml:"Key"`
|
||||
Value string `xml:"Value"`
|
||||
}
|
||||
|
||||
TransactionConfirmation struct {
|
||||
XMLName xml.Name `xml:"TransactionConfirmation"`
|
||||
Result string `xml:"Result"`
|
||||
Errors string `xml:"Errors"`
|
||||
ErrorDescription string `xml:"ErrorDescription"`
|
||||
ReceiptDataCardholder string `xml:"ReceiptDataCardholder"`
|
||||
}
|
||||
|
||||
PaymentResult struct {
|
||||
Fields map[string]string
|
||||
CardholderReceipt string
|
||||
Status cmstypes.StatusRec
|
||||
}
|
||||
|
||||
TransactionInfo struct {
|
||||
transactionRes string
|
||||
transactionState string
|
||||
}
|
||||
|
||||
ConfirmTransactionRequest struct {
|
||||
XMLName xml.Name `xml:"ConfirmTransactionRequest"`
|
||||
Amount string `xml:"Amount"`
|
||||
Reference string `xml:"TransactionReference"`
|
||||
}
|
||||
)
|
||||
|
||||
// ParseTransactionResult parses the XML into entries.
|
||||
func (tr *TransactionResultXML) ParseTransactionResult(data []byte) error {
|
||||
if err := xml.Unmarshal(data, &tr); err != nil {
|
||||
return fmt.Errorf("XML unmarshal: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ti *TransactionInfo) FillFromTransactionResult(trResult TransactionResultXML) {
|
||||
for _, e := range trResult.Entries {
|
||||
switch e.Key {
|
||||
case types.TransactionResult:
|
||||
ti.transactionRes = e.Value
|
||||
case types.TransactionState:
|
||||
ti.transactionState = e.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *PaymentResult) FillFromTransactionResult(trResult TransactionResultXML) {
|
||||
r.Fields = make(map[string]string)
|
||||
|
||||
for _, e := range trResult.Entries {
|
||||
switch e.Key {
|
||||
case types.ReceiptData, types.ReceiptDataMerchant:
|
||||
// intentionally ignored
|
||||
|
||||
case types.ReceiptDataCardholder:
|
||||
r.CardholderReceipt = e.Value
|
||||
|
||||
case types.TransactionResult:
|
||||
r.Status.Message = e.Value
|
||||
r.Status.Code = http.StatusOK
|
||||
r.Fields[e.Key] = e.Value
|
||||
|
||||
default:
|
||||
r.Fields[e.Key] = e.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// BuildPaymentRedirectURL builds the redirect URL to send the guest to after payment.
|
||||
func BuildPaymentRedirectURL(result map[string]string) string {
|
||||
res := result[types.TransactionResult]
|
||||
|
||||
// Transaction approved?
|
||||
if strings.EqualFold(res, types.ResultApproved) {
|
||||
// Transaction confirmed?
|
||||
if strings.EqualFold(result[types.ConfirmResult], types.ResultApproved) {
|
||||
log.WithField(types.LogResult, result[types.ConfirmResult]).
|
||||
Info("Transaction approved and confirmed")
|
||||
|
||||
return BuildSuccessURL(result)
|
||||
}
|
||||
|
||||
// Not confirmed
|
||||
log.WithFields(log.Fields{types.LogFieldError: result[types.ConfirmResult], types.LogFieldDescription: result[types.ConfirmErrors]}).
|
||||
Error("Transaction approved but not confirmed")
|
||||
|
||||
return BuildFailureURL(result[types.ConfirmResult], result[types.ConfirmErrors])
|
||||
}
|
||||
|
||||
// Not approved
|
||||
return BuildFailureURL(res, result[types.Errors])
|
||||
}
|
||||
|
||||
func BuildPreauthRedirectURL(result map[string]string) (string, bool) {
|
||||
res := result[types.TransactionResult]
|
||||
tType := result[types.TransactionType]
|
||||
|
||||
// Transaction approved?
|
||||
if strings.EqualFold(res, types.ResultApproved) {
|
||||
switch {
|
||||
// Transaction type AccountVerification?
|
||||
case strings.EqualFold(tType, types.AccountVerificationType):
|
||||
log.WithField(types.LogResult, result[types.TransactionResult]).
|
||||
Info("Account verification approved")
|
||||
|
||||
return BuildSuccessURL(result), false
|
||||
|
||||
// Transaction type Sale?
|
||||
case strings.EqualFold(tType, types.SaleTransactionType):
|
||||
// Transaction confirmed?
|
||||
log.WithField(types.LogResult, result[types.ConfirmResult]).
|
||||
Info("Amount preauthorized successfully")
|
||||
|
||||
return BuildSuccessURL(result), true
|
||||
}
|
||||
}
|
||||
|
||||
// Not approved
|
||||
return BuildFailureURL(res, result[types.Errors]), false
|
||||
}
|
||||
|
||||
func BuildSuccessURL(result map[string]string) string {
|
||||
q := url.Values{}
|
||||
q.Set("CardNumber", hex.EncodeToString([]byte(result[types.PanMasked])))
|
||||
q.Set("CardType", hex.EncodeToString([]byte(result[types.CardType])))
|
||||
q.Set("ExpiryDate", hex.EncodeToString([]byte(result[types.ExpiryDate])))
|
||||
q.Set("TxnReference", result[types.Reference])
|
||||
q.Set("CardHash", hex.EncodeToString([]byte(result[types.CardHash])))
|
||||
q.Set("CardReference", hex.EncodeToString([]byte(result[types.CardReference])))
|
||||
return (&url.URL{
|
||||
Path: types.CheckinSuccessfulEndpoint,
|
||||
RawQuery: q.Encode(),
|
||||
}).String()
|
||||
}
|
||||
|
||||
func BuildFailureURL(msgType, description string) string {
|
||||
q := url.Values{}
|
||||
if msgType != "" {
|
||||
description = fmt.Sprintf("Transaction %s", strings.ToLower(msgType))
|
||||
}
|
||||
if description != "" {
|
||||
msgType = types.ResultError
|
||||
}
|
||||
|
||||
log.WithFields(log.Fields{types.LogFieldError: msgType, types.LogFieldDescription: description}).
|
||||
Error("Transaction failed")
|
||||
|
||||
q.Set("MsgType", msgType)
|
||||
q.Set("Description", description)
|
||||
return (&url.URL{
|
||||
Path: types.CheckinUnsuccessfulEndpoint,
|
||||
RawQuery: q.Encode(),
|
||||
}).String()
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package creditcall
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/db"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
httpTimeout = 120 * time.Second
|
||||
)
|
||||
|
||||
/* ==============================
|
||||
Public Entry Point
|
||||
============================== */
|
||||
|
||||
func ReleasePreauthorizations(database *sql.DB) error {
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
client := &http.Client{Timeout: httpTimeout}
|
||||
|
||||
preauths, err := fetchDuePreauths(ctx, database, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(preauths) == 0 {
|
||||
log.Info("No preauthorizations due for release")
|
||||
return nil
|
||||
} else {
|
||||
log.Infof("%d preauthorizations due for release", len(preauths))
|
||||
}
|
||||
|
||||
var failed []string
|
||||
var completed int
|
||||
for _, p := range preauths {
|
||||
if err := handlePreauthRelease(ctx, database, client, p, now); err != nil {
|
||||
log.Errorf("Preauth %s failed: %v", p.TxnReference, err)
|
||||
failed = append(failed, p.TxnReference)
|
||||
}
|
||||
completed++
|
||||
}
|
||||
log.Infof("Preauth release completed: %d processed, %d failed", completed, len(failed))
|
||||
|
||||
if len(failed) > 0 {
|
||||
return fmt.Errorf("preauth release incomplete, failed refs: %s", strings.Join(failed, ", "))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/* ==============================
|
||||
Core Business Logic
|
||||
============================== */
|
||||
|
||||
func handlePreauthRelease(
|
||||
ctx context.Context,
|
||||
dbConn *sql.DB,
|
||||
client *http.Client,
|
||||
preauth types.PreauthRec,
|
||||
now time.Time,
|
||||
) error {
|
||||
|
||||
ref := preauth.TxnReference
|
||||
log.Infof("Evaluating preauth %s", ref)
|
||||
|
||||
info, err := fetchTransactionInfo(ctx, client, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Infof("res=%s state=%s", info.transactionRes, info.transactionState)
|
||||
|
||||
// If already voided or declined → mark released
|
||||
if isAlreadyReleased(info) {
|
||||
return markReleased(ctx, dbConn, ref, now)
|
||||
}
|
||||
|
||||
// Only void approved + uncommitted
|
||||
if !isVoidable(info) {
|
||||
log.Infof("Preauth %s not eligible for void (res=%s state=%s)", ref, info.transactionRes, info.transactionState)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Void transaction
|
||||
if err := voidPreauth(ctx, client, ref); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Verify final state
|
||||
finalInfo, err := fetchTransactionInfo(ctx, client, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !isSuccessfullyVoided(finalInfo) {
|
||||
return fmt.Errorf("unexpected final state res=%s state=%s",
|
||||
finalInfo.transactionRes, finalInfo.transactionState)
|
||||
}
|
||||
|
||||
log.Infof("Preauth %s successfully voided", ref)
|
||||
return markReleased(ctx, dbConn, ref, now)
|
||||
}
|
||||
|
||||
/* ==============================
|
||||
State Evaluation Helpers
|
||||
============================== */
|
||||
|
||||
func isVoidable(info TransactionInfo) bool {
|
||||
return strings.EqualFold(info.transactionRes, types.ResultApproved) &&
|
||||
strings.EqualFold(info.transactionState, types.ResultStateUncommitted)
|
||||
}
|
||||
|
||||
func isAlreadyReleased(info TransactionInfo) bool {
|
||||
return strings.EqualFold(info.transactionState, types.ResultStateVoided) ||
|
||||
strings.EqualFold(info.transactionRes, types.ResultDeclined)
|
||||
}
|
||||
|
||||
func isSuccessfullyVoided(info TransactionInfo) bool {
|
||||
return strings.EqualFold(info.transactionRes, types.ResultDeclined) &&
|
||||
strings.EqualFold(info.transactionState, types.ResultStateVoided)
|
||||
}
|
||||
|
||||
/* ==============================
|
||||
External Operations
|
||||
============================== */
|
||||
|
||||
func fetchDuePreauths(
|
||||
ctx context.Context,
|
||||
dbConn *sql.DB,
|
||||
now time.Time,
|
||||
) ([]types.PreauthRec, error) {
|
||||
|
||||
return db.GetDuePreauths(ctx, dbConn, now, 0)
|
||||
}
|
||||
|
||||
func markReleased(
|
||||
ctx context.Context,
|
||||
dbConn *sql.DB,
|
||||
ref string,
|
||||
now time.Time,
|
||||
) error {
|
||||
|
||||
return db.MarkPreauthReleased(ctx, dbConn, ref, now)
|
||||
}
|
||||
|
||||
func fetchTransactionInfo(
|
||||
ctx context.Context,
|
||||
client *http.Client,
|
||||
ref string,
|
||||
) (TransactionInfo, error) {
|
||||
|
||||
var tr TransactionResultXML
|
||||
var info TransactionInfo
|
||||
|
||||
payload, _ := xml.Marshal(types.TransactionReferenceRequest{
|
||||
TransactionReference: ref,
|
||||
})
|
||||
|
||||
body, err := postXML(ctx, client, types.LinkTransactionInformation, payload)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
if err := tr.ParseTransactionResult(body); err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
info.FillFromTransactionResult(tr)
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func voidPreauth(
|
||||
ctx context.Context,
|
||||
client *http.Client,
|
||||
ref string,
|
||||
) error {
|
||||
|
||||
var tr TransactionResultXML
|
||||
var info TransactionInfo
|
||||
|
||||
payload, _ := xml.Marshal(types.TransactionReferenceRequest{
|
||||
TransactionReference: ref,
|
||||
})
|
||||
|
||||
body, err := postXML(ctx, client, types.LinkVoidTransaction, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tr.ParseTransactionResult(body); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
info.FillFromTransactionResult(tr)
|
||||
|
||||
if !strings.EqualFold(info.transactionRes, types.ResultApproved) {
|
||||
return fmt.Errorf("void rejected: %s", info.transactionRes)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/* ==============================
|
||||
Low-level HTTP
|
||||
============================== */
|
||||
|
||||
func postXML(
|
||||
ctx context.Context,
|
||||
client *http.Client,
|
||||
url string,
|
||||
payload []byte,
|
||||
) ([]byte, error) {
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/xml")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
Reference in New Issue
Block a user