Skip to main content

.NET (Stitch.Terminal)

Overview

The Stitch Terminal SDK is designed for POS systems and other merchant-facing applications to seamlessly connect to payment terminals that process payments on Stitch.

For an overview of how payments are processed and how card data is kept secure, see How payments flow.

You create a session on a terminal by calling terminal.StartSessionAsync(request, ...). The SDK returns a Task<TerminalSession> that completes when the session reaches a terminal state.

Requirements

The SDK targets .NET 8 or later. For applications that must remain on .NET Framework, use the Stitch.Terminal.Native package instead.

Install

Install the release of the package:

dotnet add package Stitch.Terminal

Or reference a specific version in your .csproj:

<ItemGroup>
<PackageReference Include="Stitch.Terminal" Version="1.0.0" />
</ItemGroup>

Terminal

The Terminal class allows the library to interface with payment terminal implementations. Each terminal instance handles the protocol required by the connected terminal.

Each Terminal instance manages a single active terminal connection at a time. Create multiple Terminal instances to connect to multiple terminals simultaneously. Only one Terminal can hold an active connection to a given device.

Terminal instances are intended to be long-lived. Create a single Terminal when your application starts, and treat it as the application’s representation of the terminal connected to the current device. Keep that instance available until shutdown, and dispose of it only when the application exits. This gives the terminal time to initialize, connect to the backend, and be ready before a session begins. Avoid creating a new Terminal for each session.

Creating a Terminal

Construct a terminal with a ConnectionConfig, then call ConnectAsync to establish the connection:

var config = ConnectionConfig.Serial(TerminalType.Android, "COM3");
var terminal = new Terminal(config);

TerminalStatus status = await terminal.ConnectAsync();

ConnectAsync returns the terminal's status once connected.

Use ConnectionConfig.Serial for USB or serial connections, and ConnectionConfig.Tcp for terminals reachable over your local network. When using ConnectionConfig.Tcp, you must set the token argument. The token can be fetched on the Terminal.

// Serial connection (Android)
var serialAndroid = ConnectionConfig.Serial(TerminalType.Android, "COM3");

// TCP/IP connection to a Stitch Android terminal (requires token)
var androidTcp = ConnectionConfig.Tcp(
TerminalType.Android,
"192.168.1.101",
token: "tkn_abc123");
Android token

token is required when connecting to a Stitch Android terminal over TCP.

Terminal Status

Get the status of a connected terminal.

TerminalStatus status = await terminal.GetStatusAsync();
Console.WriteLine($"Serial: {status.Serial}");
Console.WriteLine($"Status: {status.Status}");

See TerminalStatusValue for all status values.

Terminal Session

A Terminal Session defines the intent to process a charge, refund, or disbursement in person using a physical payment terminal.

Session lifecycle

A session reaches a terminal state of either Success or Failure. On Success, the session's Outcome contains the resulting charge, refund, or disbursement. On Failure, the cause is available in FailureReason.

If the SDK is unable to observe the session reaching a terminal state, for example because the connection to the terminal is lost mid-session, the Task completes with Status = Pending. Pending is not a terminal state, it is the last state the SDK could confirm. The session may still complete on the terminal. Resolve the outcome using GetSessionAsync or the Stitch HTTP API. Do not treat Pending as a failure or retry with the same intent.

Starting a session

Build a request and call terminal.StartSessionAsync(request). The returned Task<TerminalSession> completes once the session reaches a terminal state (Success or Failure).

// Build the intent (what to charge)
var intent = new ChargeIntent(
Amount: 25.00m,
Currency: "ZAR");

// Build the request
var request = new TerminalSessionCreateRequest
{
Intent = intent,
ExternalReference = "order-456",
Metadata = new Dictionary<string, string> { ["orderId"] = "12345" },
};

// Await the session result
TerminalSession session = await terminal.StartSessionAsync(request);

switch (session.Status)
{
case SessionStatus.Success when session.Outcome is ChargeOutcome { Charge: var charge }:
Console.WriteLine($"Success! Charge ID: {charge.Id}");
break;
case SessionStatus.Failure:
Console.WriteLine($"Failed: {session.FailureReason}");
break;
case SessionStatus.Pending:
// Outcome is unknown
// Resolve via Terminal.GetSessionAsync(session.Id) or the Stitch HTTP API.
Console.WriteLine($"Pending: resolve session {session.Id}");
break;
}

Data Types

TerminalSessionCreateRequest

The request object passed to StartSessionAsync.

var request = new TerminalSessionCreateRequest
{
Intent = intent,
ExternalReference = "order-456",
Metadata = new Dictionary<string, string> { ["orderId"] = "12345" },
};
PropertyRequiredDescription
IntentRequiredDefines the purpose of the session (charge, refund, or disbursement)
ExternalReferenceOptionalA custom identifier to reference this session in your own system. Multiple sessions can share the same external reference
MetadataOptionalKey-value pairs to store additional, structured information relevant to your integration

TerminalSessionIntent

The intent defines what the session should do: take a charge from the customer's card, refund a previous charge back to the same card, or pay out funds to a card as a disbursement.

public abstract record TerminalSessionIntent;

public sealed record ChargeIntent(
decimal Amount,
string Currency,
Money? Cashback = null) : TerminalSessionIntent;

public sealed record RefundIntent(
decimal Amount,
string Currency,
string TerminalSession,
RefundReason Reason) : TerminalSessionIntent;

public sealed record DisbursementIntent(
decimal Amount,
string Currency) : TerminalSessionIntent;
IntentDescription
ChargeIntentTake a payment from the customer's card
RefundIntentRefund a previous charge back to the original card. Linked to a charge
DisbursementIntentPay funds to a card as a stand-alone payout

Charge intent (once-off payment)

var intent = new ChargeIntent(Amount: 30.00m, Currency: "ZAR");

Charge with cashback

var intent = new ChargeIntent(
Amount: 30.00m,
Currency: "ZAR",
Cashback: new Money(5.00m, "ZAR"));

ChargeIntent

PropertyRequiredDescription
AmountRequiredThe charge amount in the currency's major unit (e.g. 30.00m for R30.00)
CurrencyRequiredISO 4217 currency code (only "ZAR" supported)
CashbackOptionalCashback to be dispensed to the customer in addition to the charge amount

Refund intent (linked refund)

A refund returns funds from a previous charge back. The original session ID must be supplied as the TerminalSession.

var intent = new RefundIntent(
Amount: 30.00m,
Currency: "ZAR",
TerminalSession: "ts_abc123",
Reason: RefundReason.RequestedByUser);

RefundIntent

PropertyRequiredDescription
AmountRequiredThe refund amount in the currency's major unit. May be less than or equal to the original charge amount
CurrencyRequiredISO 4217 currency code (only "ZAR" supported). Must match the currency of the source session
TerminalSessionRequiredThe ID of the original terminal session being refunded (e.g. "ts_abc123")
ReasonRequiredThe reason for the refund

RefundReason

ValueDescription
FraudThe original charge was fraudulent
RequestedByUserThe customer requested the refund
DuplicateChargeThe original charge was a duplicate

Disbursement intent (stand-alone payout)

A disbursement pays funds to a card without being linked to a session. The customer presents their card on the terminal to receive the payout.

var intent = new DisbursementIntent(
Amount: 50.00m,
Currency: "ZAR");

DisbursementIntent

PropertyRequiredDescription
AmountRequiredThe disbursement amount in the currency's major unit
CurrencyRequiredISO 4217 currency code (only "ZAR" supported)

Money

public sealed record Money(decimal Amount, string Currency);
PropertyTypeDescription
AmountdecimalAmount in the currency's major unit
CurrencystringISO 4217 currency code

SessionStatus

A session has two terminal states, Success and Failure. Pending is returned only when the SDK could not observe the session reaching a terminal state.

ValueTerminal?Description
SuccessYesSession completed successfully. See Outcome
FailureYesSession failed. See FailureReason
PendingNoOutcome could not be observed. See Session lifecycle

FailureReason

ValueDescription
ExpiredSession timed out before completion
CancelledByApiSession was cancelled via online API
CancelledByTerminalTerminal cancelled transaction, e.g. timeout
BusyTerminalTerminal was busy with another session
DeclinedPayment was declined

SessionOutcome

The outcome when a session completes successfully. The concrete subtype mirrors the original TerminalSessionIntent, ie ChargeIntent produces a ChargeOutcome.

public abstract record SessionOutcome;

public sealed record ChargeOutcome(Charge Charge) : SessionOutcome;

public sealed record RefundOutcome(Refund Refund) : SessionOutcome;

public sealed record DisbursementOutcome(Disbursement Disbursement) : SessionOutcome;
OutcomeDescription
ChargeOutcomeThe result of a ChargeIntent. Contains the resulting Charge
RefundOutcomeThe result of a RefundIntent. Contains the resulting Refund
DisbursementOutcomeThe result of a DisbursementIntent. Contains the resulting Disbursement

Pattern-match on the outcome to read the result:

switch (session.Outcome)
{
case ChargeOutcome { Charge: var charge }:
Console.WriteLine($"Charge {charge.Id}");
break;
case RefundOutcome { Refund: var refund }:
Console.WriteLine($"Refund {refund.Id}");
break;
case DisbursementOutcome { Disbursement: var disbursement }:
Console.WriteLine($"Disbursement {disbursement.Id}");
break;
}

Charge

The charge object from a successful session.

public sealed record Charge(
string Id,
decimal Amount,
string Currency,
Cashback? Cashback,
ChargeStatus Status,
Failure? Failure,
DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt,
ChargeType Type,
Card Card,
string? RetrievalReferenceNumber);
PropertyTypeDescription
IdstringCharge ID (e.g. "ch_abc123")
AmountdecimalThe amount charged in the currency's major unit
CurrencystringThe charge currency in ISO 4217 format (e.g. "ZAR")
CashbackCashback?The cashback dispensed to the customer (null if no cashback)
StatusChargeStatusThe current status of the charge
FailureFailure?Failure details when Status is Failure (null otherwise)
CreatedAtDateTimeOffsetWhen the charge was created
UpdatedAtDateTimeOffsetWhen the charge was last modified
TypeChargeTypeThe type of charge (e.g. InPersonCard)
CardCardCard data (scheme, masked PAN, etc.)
RetrievalReferenceNumberstring?The retrieval reference number (RRN) assigned by the card network for this transaction

Failure

Failure details for a charge, refund, or disbursement. Present when the operation's Status is Failure.

public sealed record Failure(string Reason, ResultCode? ResultCode);
PropertyTypeDescription
ReasonstringThe reason for the failure, available options: authorization_failed
authorization_declined
ResultCodeResultCode?The result code from the card network. Only present when Reason is authorization_declined

ResultCode

The result code from the card network explaining why authorization failed.

public sealed record ResultCode(string Value, string Descriptor, string Detail);
PropertyTypeDescription
ValuestringThe numeric result code value (e.g. "05")
DescriptorstringA machine-readable descriptor for the result code (e.g. "do_not_honour")
DetailstringA human-readable explanation of the result code

Cashback

The cashback dispensed to the customer as part of the charge.

public sealed record Cashback(decimal Amount, string Currency);
PropertyTypeDescription
AmountdecimalThe cashback amount in the currency's major unit
CurrencystringThe cashback currency in ISO 4217 format (e.g. "ZAR")

ChargeStatus

ValueDescription
SuccessThe charge was processed successfully
FailureThe charge did not complete successfully

ChargeType

ValueDescription
InPersonCardAn in-person card charge

Refund

The refund object from a successful refund session. A refund returns funds linked to an original charge.

public sealed record Refund(
string Id,
string TerminalSession,
decimal Amount,
string Currency,
RefundStatus Status,
Failure? Failure,
DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt,
Card? Card,
string? RetrievalReferenceNumber);
PropertyTypeDescription
IdstringRefund ID (e.g. "rf_abc123")
TerminalSessionstringThe terminal session ID of the original charge being refunded (e.g. "ts_abc123")
AmountdecimalThe amount refunded in the currency's major unit
CurrencystringThe refund currency in ISO 4217 format (e.g. "ZAR")
StatusRefundStatusThe current status of the refund
FailureFailure?Failure details when Status is Failure (null otherwise)
CreatedAtDateTimeOffsetWhen the refund was created
UpdatedAtDateTimeOffsetWhen the refund was last modified
CardCard?Card data (scheme, masked PAN, etc.)
RetrievalReferenceNumberstring?The retrieval reference number (RRN) assigned by the card network for this transaction

RefundStatus

ValueDescription
ProcessingThe refund is being processed
SuccessThe refund was processed successfully
FailureThe refund did not complete successfully

Disbursement

The disbursement object from a successful disbursement terminal session. A disbursement pays funds to a card without a linked source charge. The customer presents their card on the terminal to receive the payout.

public sealed record Disbursement(
string Id,
decimal Amount,
string Currency,
DisbursementStatus Status,
Failure? Failure,
DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt,
Card Card,
string? RetrievalReferenceNumber);
PropertyTypeDescription
IdstringDisbursement ID (e.g. "dsb_abc123")
AmountdecimalThe amount disbursed in the currency's major unit
CurrencystringThe disbursement currency in ISO 4217 format (e.g. "ZAR")
StatusDisbursementStatusThe current status of the disbursement
FailureFailure?Failure details when Status is Failure (null otherwise)
CreatedAtDateTimeOffsetWhen the disbursement was created
UpdatedAtDateTimeOffsetWhen the disbursement was last modified
CardCardCard data (scheme, masked PAN, etc.) for the card the funds were paid to
RetrievalReferenceNumberstring?The retrieval reference number (RRN) assigned by the card network for this transaction

DisbursementStatus

ValueDescription
ProcessingThe disbursement is being processed
SuccessThe disbursement was processed successfully
FailureThe disbursement did not complete successfully

Card

public sealed record Card(
string Bin,
string Last4,
CardExpiry Expiry,
CardNetwork? Network,
FundingType? FundingType,
CardIssuer? Issuer);
PropertyTypeDescription
BinstringThe first 8 digits of the card number
Last4stringThe last 4 digits of the card number
ExpiryCardExpiryThe card expiry date
NetworkCardNetwork?The card network (may be null)
FundingTypeFundingType?The funding type of the card (may be null)
IssuerCardIssuer?The card issuer details (may be null)

CardExpiry

public sealed record CardExpiry(string Month, string Year);
PropertyTypeDescription
MonthstringThe expiry month in MM format (01-12)
YearstringThe expiry year in YY format (e.g. "25" for 2025)

CardNetwork

ValueDescription
VisaVisa
MastercardMastercard
AmexAmerican Express
DinersDiners Club

FundingType

ValueDescription
CreditCredit card
DebitDebit card
PrepaidPrepaid card

CardIssuer

public sealed record CardIssuer(string Name, string Country);
PropertyTypeDescription
NamestringThe name of the financial institution that issued the card
CountrystringThe country code (ISO 3166-1 alpha-2) of the card issuer (e.g. "ZA")

ConnectionConfig

public abstract record ConnectionConfig
{
public static SerialConfig Serial(
TerminalType type,
string path);

public static TcpConfig Tcp(
TerminalType type,
string host,
string? token = null);
}

public sealed record SerialConfig(
TerminalType Type,
string Path) : ConnectionConfig;

public sealed record TcpConfig(
TerminalType Type,
string Host,
string? Token = null) : ConnectionConfig;

SerialConfig

PropertyTypeDescription
TypeTerminalTypeThe terminal type (Android)
PathstringDevice path (e.g. "COM3")

TcpConfig

PropertyTypeDescription
TypeTerminalTypeThe terminal type (Android)
HoststringHostname or IP address of the terminal
Tokenstring?Authentication token for the terminal. Required for Stitch Android terminals

TerminalStatus

Returned by terminal.GetStatusAsync() and terminal.ConnectAsync().

public sealed record TerminalStatus(string Serial, TerminalStatusValue Status);
PropertyTypeDescription
SerialstringTerminal serial number
StatusTerminalStatusValueThe terminal's current status. See TerminalStatusValue

TerminalStatusValue

ValueDescription
ReadyTerminal is ready for sessions
BusyTerminal is currently processing a session
OfflineTerminal is offline
LoggedOutTerminal requires login before transacting

Error Handling

SDK methods throw StitchTerminalException for protocol, connection, and argument errors. Session-level failures (e.g. Declined, BusyTerminal) are delivered as a TerminalSession with a Failure status.

StitchTerminalException

public sealed class StitchTerminalException : Exception
{
public ErrorCode ErrorCode { get; }
}
PropertyTypeDescription
ErrorCodeErrorCodeThe error code indicating the type of failure
MessagestringA human-readable error message
try
{
var intent = new ChargeIntent(15.00m, "ZAR");

var request = new TerminalSessionCreateRequest
{
Intent = intent,
};

TerminalSession session = await terminal.StartSessionAsync(request);

if (session.Status == SessionStatus.Success && session.Outcome is ChargeOutcome { Charge: var charge })
{
Console.WriteLine($"Success! Charge ID: {charge.Id}");
}
}
catch (StitchTerminalException ex)
{
var message = ex.ErrorCode switch
{
ErrorCode.TerminalUnavailable => "Terminal is offline or not responding",
ErrorCode.TerminalBusy => "Terminal is busy",
ErrorCode.Authentication => "Check terminal credentials",
ErrorCode.InvalidRequest => "Check the session request",
_ => $"Error: {ex.Message}",
};
Console.WriteLine(message);
}

ErrorCode

ValueDescription
ConfigThe SDK or terminal connection is configured incorrectly
AuthenticationThe terminal token is missing or invalid
TerminalUnavailableThe terminal is offline, disconnected, or not responding
TerminalBusyAnother session is already active on this terminal
TerminalLoggedOutThe terminal must be logged in before it can transact
InvalidRequestThe request is missing required fields or contains invalid values
NetworkThe SDK could not reach Stitch or the required network service
ServerStitch returned a server-side error
UnsupportedThe requested operation is not supported by this terminal or connection type
TimeoutThe SDK operation timed out before it could complete
InternalThe SDK encountered an unexpected internal error. Retry if appropriate, then contact Stitch support with the exception message and logs.

Connection failures

The connection to the terminal is established by ConnectAsync and maintained for the lifetime of the Terminal instance. If the SDK is unable to connect to the terminal (for example, if the terminal is offline or the token is invalid), ConnectAsync throws a StitchTerminalException.

If the connection to the terminal is lost after ConnectAsync has succeeded, the next SDK method call will throw the relevant exception. This will typically occur when creating a new terminal session or when polling GetStatusAsync().

ScenarioError CodeDescription
Terminal offline / not connectedTerminalUnavailableTerminal is not connected or not responding
Terminal busyTerminalBusyAnother session is already active on this terminal
Terminal not logged inTerminalLoggedOutThe terminal must be logged in on the device itself before transacting
Invalid request (missing fields, bad values)InvalidRequestMissing required fields or invalid values (e.g. null amount)
Network errorNetworkCannot reach Stitch servers

See ErrorCode for the full list of values and their descriptions.

Failure during an ongoing session

If the connection to a terminal is lost while StartSessionAsync is ongoing, the SDK can no longer observe the session. The Task completes with a TerminalSession whose Status is Pending. The session may still have completed on the terminal.

Pending sessions have undetermined outcomes

When the connection is lost mid-session, the terminal may already have authorized (or declined) the transaction. The outcome screen shown on the terminal is final and authoritative; what the cardholder saw on the terminal is what actually happened on the card.

Resolving a Pending session

Use Terminal.GetSessionAsync(sessionId) to resolve the outcome of a Pending session. It first queries Stitch directly if available, and then queries any connected terminals to retrieve the outcome.

TerminalSession session = await Terminal.GetSessionAsync("ts_abc123");

For back-office reconciliation without a Terminal instance available, use the Stitch HTTP API directly.

API Reference

Terminal

MethodReturnsDescription
new Terminal(ConnectionConfig config)TerminalConstruct a terminal with the given connection config
terminal.ConnectAsync()Task<TerminalStatus>Establish the connection to the terminal. Returns the terminal status once connected
terminal.StartSessionAsync(TerminalSessionCreateRequest request)Task<TerminalSession>Start a session on this terminal. The returned task completes when the session reaches a terminal state (Success or Failure), or with Pending if the outcome could not be observed
terminal.GetStatusAsync()Task<TerminalStatus>Get the terminal status
Terminal.GetSessionAsync(string sessionId)Task<TerminalSession>Resolve the latest state of a session by ID
terminal.DisposeAsync()ValueTaskAsynchronously disconnect and release native resources
terminal.Dispose()voidSynchronous disposal; calls DisposeAsync().GetAwaiter().GetResult()

TerminalSession

An immutable snapshot of a session, returned by terminal.StartSessionAsync() or Terminal.GetSessionAsync().

public sealed record TerminalSession(
string Id,
TerminalSessionIntent Intent,
SessionStatus Status,
FailureReason? FailureReason,
SessionOutcome? Outcome,
string? ExternalReference,
IReadOnlyDictionary<string, string> Metadata,
DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt);
PropertyTypeDescription
IdstringThe unique session ID (e.g. "ts_abc123")
IntentTerminalSessionIntentThe original intent
StatusSessionStatusSession status: Success, Failure, or Pending
FailureReasonFailureReason?Why the session failed. null unless Status is Failure
OutcomeSessionOutcome?The outcome (ChargeOutcome, RefundOutcome, or DisbursementOutcome). Only present when Status is Success; otherwise null
ExternalReferencestring?The custom identifier. null if not set
MetadataIReadOnlyDictionary<string, string>Key-value pairs for additional information
CreatedAtDateTimeOffsetWhen the session was created
UpdatedAtDateTimeOffsetWhen the session was last updated

Example: end-to-end flow

using Stitch.Terminal;

var config = ConnectionConfig.Tcp(
TerminalType.Android,
"192.168.1.101",
token: "tkn_abc123");

// Created once, kept until application shutdown
var terminal = new Terminal(config);
await terminal.ConnectAsync();

var request = new TerminalSessionCreateRequest
{
Intent = new ChargeIntent(25.00m, "ZAR"),
ExternalReference = "order-456",
};

TerminalSession session = await terminal.StartSessionAsync(request);

switch (session.Status)
{
case SessionStatus.Success when session.Outcome is ChargeOutcome { Charge: var charge }:
Console.WriteLine($"Approved. Charge {charge.Id} for {charge.Amount} {charge.Currency}");
break;
case SessionStatus.Failure:
Console.WriteLine($"Failed: {session.FailureReason}");
break;
case SessionStatus.Pending:
// Outcome undetermined
Console.WriteLine($"Pending: resolve session {session.Id}");
break;
}

// On application shutdown
await terminal.DisposeAsync();