.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");
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" },
};
| Property | Required | Description |
|---|---|---|
Intent | Required | Defines the purpose of the session (charge, refund, or disbursement) |
ExternalReference | Optional | A custom identifier to reference this session in your own system. Multiple sessions can share the same external reference |
Metadata | Optional | Key-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;
| Intent | Description |
|---|---|
ChargeIntent | Take a payment from the customer's card |
RefundIntent | Refund a previous charge back to the original card. Linked to a charge |
DisbursementIntent | Pay 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
| Property | Required | Description |
|---|---|---|
Amount | Required | The charge amount in the currency's major unit (e.g. 30.00m for R30.00) |
Currency | Required | ISO 4217 currency code (only "ZAR" supported) |
Cashback | Optional | Cashback 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
| Property | Required | Description |
|---|---|---|
Amount | Required | The refund amount in the currency's major unit. May be less than or equal to the original charge amount |
Currency | Required | ISO 4217 currency code (only "ZAR" supported). Must match the currency of the source session |
TerminalSession | Required | The ID of the original terminal session being refunded (e.g. "ts_abc123") |
Reason | Required | The reason for the refund |
RefundReason
| Value | Description |
|---|---|
Fraud | The original charge was fraudulent |
RequestedByUser | The customer requested the refund |
DuplicateCharge | The 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
| Property | Required | Description |
|---|---|---|
Amount | Required | The disbursement amount in the currency's major unit |
Currency | Required | ISO 4217 currency code (only "ZAR" supported) |
Money
public sealed record Money(decimal Amount, string Currency);
| Property | Type | Description |
|---|---|---|
Amount | decimal | Amount in the currency's major unit |
Currency | string | ISO 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.
| Value | Terminal? | Description |
|---|---|---|
Success | Yes | Session completed successfully. See Outcome |
Failure | Yes | Session failed. See FailureReason |
Pending | No | Outcome could not be observed. See Session lifecycle |
FailureReason
| Value | Description |
|---|---|
Expired | Session timed out before completion |
CancelledByApi | Session was cancelled via online API |
CancelledByTerminal | Terminal cancelled transaction, e.g. timeout |
BusyTerminal | Terminal was busy with another session |
Declined | Payment 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;
| Outcome | Description |
|---|---|
ChargeOutcome | The result of a ChargeIntent. Contains the resulting Charge |
RefundOutcome | The result of a RefundIntent. Contains the resulting Refund |
DisbursementOutcome | The 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);
| Property | Type | Description |
|---|---|---|
Id | string | Charge ID (e.g. "ch_abc123") |
Amount | decimal | The amount charged in the currency's major unit |
Currency | string | The charge currency in ISO 4217 format (e.g. "ZAR") |
Cashback | Cashback? | The cashback dispensed to the customer (null if no cashback) |
Status | ChargeStatus | The current status of the charge |
Failure | Failure? | Failure details when Status is Failure (null otherwise) |
CreatedAt | DateTimeOffset | When the charge was created |
UpdatedAt | DateTimeOffset | When the charge was last modified |
Type | ChargeType | The type of charge (e.g. InPersonCard) |
Card | Card | Card data (scheme, masked PAN, etc.) |
RetrievalReferenceNumber | string? | 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);
| Property | Type | Description |
|---|---|---|
Reason | string | The reason for the failure, available options: authorization_failed authorization_declined |
ResultCode | ResultCode? | 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);
| Property | Type | Description |
|---|---|---|
Value | string | The numeric result code value (e.g. "05") |
Descriptor | string | A machine-readable descriptor for the result code (e.g. "do_not_honour") |
Detail | string | A 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);
| Property | Type | Description |
|---|---|---|
Amount | decimal | The cashback amount in the currency's major unit |
Currency | string | The cashback currency in ISO 4217 format (e.g. "ZAR") |
ChargeStatus
| Value | Description |
|---|---|
Success | The charge was processed successfully |
Failure | The charge did not complete successfully |
ChargeType
| Value | Description |
|---|---|
InPersonCard | An 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);
| Property | Type | Description |
|---|---|---|
Id | string | Refund ID (e.g. "rf_abc123") |
TerminalSession | string | The terminal session ID of the original charge being refunded (e.g. "ts_abc123") |
Amount | decimal | The amount refunded in the currency's major unit |
Currency | string | The refund currency in ISO 4217 format (e.g. "ZAR") |
Status | RefundStatus | The current status of the refund |
Failure | Failure? | Failure details when Status is Failure (null otherwise) |
CreatedAt | DateTimeOffset | When the refund was created |
UpdatedAt | DateTimeOffset | When the refund was last modified |
Card | Card? | Card data (scheme, masked PAN, etc.) |
RetrievalReferenceNumber | string? | The retrieval reference number (RRN) assigned by the card network for this transaction |
RefundStatus
| Value | Description |
|---|---|
Processing | The refund is being processed |
Success | The refund was processed successfully |
Failure | The 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);
| Property | Type | Description |
|---|---|---|
Id | string | Disbursement ID (e.g. "dsb_abc123") |
Amount | decimal | The amount disbursed in the currency's major unit |
Currency | string | The disbursement currency in ISO 4217 format (e.g. "ZAR") |
Status | DisbursementStatus | The current status of the disbursement |
Failure | Failure? | Failure details when Status is Failure (null otherwise) |
CreatedAt | DateTimeOffset | When the disbursement was created |
UpdatedAt | DateTimeOffset | When the disbursement was last modified |
Card | Card | Card data (scheme, masked PAN, etc.) for the card the funds were paid to |
RetrievalReferenceNumber | string? | The retrieval reference number (RRN) assigned by the card network for this transaction |
DisbursementStatus
| Value | Description |
|---|---|
Processing | The disbursement is being processed |
Success | The disbursement was processed successfully |
Failure | The disbursement did not complete successfully |
Card
public sealed record Card(
string Bin,
string Last4,
CardExpiry Expiry,
CardNetwork? Network,
FundingType? FundingType,
CardIssuer? Issuer);
| Property | Type | Description |
|---|---|---|
Bin | string | The first 8 digits of the card number |
Last4 | string | The last 4 digits of the card number |
Expiry | CardExpiry | The card expiry date |
Network | CardNetwork? | The card network (may be null) |
FundingType | FundingType? | The funding type of the card (may be null) |
Issuer | CardIssuer? | The card issuer details (may be null) |
CardExpiry
public sealed record CardExpiry(string Month, string Year);
| Property | Type | Description |
|---|---|---|
Month | string | The expiry month in MM format (01-12) |
Year | string | The expiry year in YY format (e.g. "25" for 2025) |
CardNetwork
| Value | Description |
|---|---|
Visa | Visa |
Mastercard | Mastercard |
Amex | American Express |
Diners | Diners Club |
FundingType
| Value | Description |
|---|---|
Credit | Credit card |
Debit | Debit card |
Prepaid | Prepaid card |
CardIssuer
public sealed record CardIssuer(string Name, string Country);
| Property | Type | Description |
|---|---|---|
Name | string | The name of the financial institution that issued the card |
Country | string | The 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
| Property | Type | Description |
|---|---|---|
Type | TerminalType | The terminal type (Android) |
Path | string | Device path (e.g. "COM3") |
TcpConfig
| Property | Type | Description |
|---|---|---|
Type | TerminalType | The terminal type (Android) |
Host | string | Hostname or IP address of the terminal |
Token | string? | 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);
| Property | Type | Description |
|---|---|---|
Serial | string | Terminal serial number |
Status | TerminalStatusValue | The terminal's current status. See TerminalStatusValue |
TerminalStatusValue
| Value | Description |
|---|---|
Ready | Terminal is ready for sessions |
Busy | Terminal is currently processing a session |
Offline | Terminal is offline |
LoggedOut | Terminal 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; }
}
| Property | Type | Description |
|---|---|---|
ErrorCode | ErrorCode | The error code indicating the type of failure |
Message | string | A 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
| Value | Description |
|---|---|
Config | The SDK or terminal connection is configured incorrectly |
Authentication | The terminal token is missing or invalid |
TerminalUnavailable | The terminal is offline, disconnected, or not responding |
TerminalBusy | Another session is already active on this terminal |
TerminalLoggedOut | The terminal must be logged in before it can transact |
InvalidRequest | The request is missing required fields or contains invalid values |
Network | The SDK could not reach Stitch or the required network service |
Server | Stitch returned a server-side error |
Unsupported | The requested operation is not supported by this terminal or connection type |
Timeout | The SDK operation timed out before it could complete |
Internal | The 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().
| Scenario | Error Code | Description |
|---|---|---|
| Terminal offline / not connected | TerminalUnavailable | Terminal is not connected or not responding |
| Terminal busy | TerminalBusy | Another session is already active on this terminal |
| Terminal not logged in | TerminalLoggedOut | The terminal must be logged in on the device itself before transacting |
| Invalid request (missing fields, bad values) | InvalidRequest | Missing required fields or invalid values (e.g. null amount) |
| Network error | Network | Cannot 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.
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
| Method | Returns | Description |
|---|---|---|
new Terminal(ConnectionConfig config) | Terminal | Construct 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() | ValueTask | Asynchronously disconnect and release native resources |
terminal.Dispose() | void | Synchronous 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);
| Property | Type | Description |
|---|---|---|
Id | string | The unique session ID (e.g. "ts_abc123") |
Intent | TerminalSessionIntent | The original intent |
Status | SessionStatus | Session status: Success, Failure, or Pending |
FailureReason | FailureReason? | Why the session failed. null unless Status is Failure |
Outcome | SessionOutcome? | The outcome (ChargeOutcome, RefundOutcome, or DisbursementOutcome). Only present when Status is Success; otherwise null |
ExternalReference | string? | The custom identifier. null if not set |
Metadata | IReadOnlyDictionary<string, string> | Key-value pairs for additional information |
CreatedAt | DateTimeOffset | When the session was created |
UpdatedAt | DateTimeOffset | When 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();