AmwalPay.Ecr drives an Amwal POS terminal from a .NET till: sale, void, refund, inquiry, e-receipt, and close receipt. Wi-Fi and USB use the terminal’s ECR port. Web Service uses HTTPS to the Amwal Hub. Card data stays on the terminal.
Package AmwalPay.Ecr 1.0.3. Open one session, call the operation, then read the result.
Install #
- .NET Framework 4.6.2 or later, or .NET 8 or later. C# 9 or later. On an SDK-style .NET Framework project set
<LangVersion>9.0</LangVersion> - Web Service is HTTPS. On .NET Framework 4.6.2 the process must allow TLS 1.2.
dotnet add package AmwalPay.Ecr --version 1.0.3
Pin the version. A patch release can add API.
Open a session #
Open one session for the terminal and keep it, every sale, void, refund, inquiry, e-receipt, and close receipt can use it.
Wi-Fi implementation #
Each terminal have IP and port will be display on idle screen use that IP and port to establish connection from till to send operations for each terminal, and the till and terminal should be on same wifi.
using AmwalPay.Ecr;
EcrSessionPlan plan = EcrSessions.Plan(
link: new EcrLink.Lan(Host: "192.168.1.50"), // port defaults to 9100
config: new EcrConfig { SecureHashKey = wifiKey });
if (!plan.IsReady)
{
Show(string.Join("; ", plan.Issues));
return;
}
EcrOpenedSession session = EcrSessions.Open("P653200085189", plan);
Web Service implementation #
EcrSessionPlan plan = EcrSessions.Plan(
link: new EcrLink.WebService(MerchantId: "13593", TerminalId: "101311"),
config: new EcrConfig
{
SecureHashKey = webServiceKey,
Environment = EcrEnvironment.UAT, // SIT is the default; PROD for live
});
EcrOpenedSession session = EcrSessions.Open("P653200008251", plan);
Hub addresses stay inside the SDK. EcrEnvironment.FromName reads SIT, UAT, and PROD, ignoring case. Any other name reads as SIT.
USB cable implementation #
There is no IP address. The terminal profile is USB cable, and the signing key is the Wi-Fi key. Windows shows the cable as a COM port, “MediaTek USB VCOM (Android)”. The bytes are the same framed messages as Wi-Fi.
The COM number can change the next time the cable is plugged in. Store SerialPortChoice.Selection (the USB serial when the device has one) and open SerialPortBinding.Port for the sale. SerialPorts.List returns only the devices plugged in on that call. A COM port remembered from an earlier plug is not in the list.
You need driver to install on system for usb compatibility and work well, amwalpay will provide that driver.
ConnectedPorts listed = SerialPorts.ListFor(saved: storedCable, terminalSerial: "");
// listed.Ports is what is plugged in now. listed.Selected is what to store.
SerialPortBinding open = SerialPorts.PortFor(listed.Selected);
if (open.Port.Length == 0)
{
Show("Plug the terminal in. Windows assigns the COM port from the USB serial.");
return;
}
EcrSessionPlan plan = EcrSessions.Plan(
link: new EcrLink.UsbCable(ComPort: open.Port),
config: new EcrConfig { SecureHashKey = wifiKey });
if (!plan.IsReady)
{
Show(string.Join("; ", plan.Issues));
return;
}
EcrOpenedSession session = EcrSessions.Open(
"P653200085189",
plan,
usbChannel: () => new SerialEcrChannel(open.Port));
Open requires usbChannel for a cable plan. SerialEcrChannel opens that COM port for the sale and leaves it closed between calls. A cable session uses the same sale, void, refund, inquiry, e-receipt, and close receipt calls as Wi-Fi.
Operations #
Amounts are decimal in major units (1.234 with the m suffix). merchantReference names this attempt. Save it before the call. Leave it blank and the SDK generates one and returns it on the result.
Sale #
The cardholder presents the card on the terminal.
string reference = "ORDER-1001-1"; Save(reference); EcrResult result = await session.SaleAsync(1.234m, reference);
Read result with the switch in Read the result.
Void #
Cancels an earlier transaction for its full amount. No card. receiptNumber is the receipt number (STAN). originalTerminalId names another terminal when the original was not taken on this one. Web Service ignores it and uses the terminal in the plan. The void has its own merchant reference.
EcrResult result = await session.VoidAsync(
receiptNumber: stan,
originalTerminalId: "",
merchantReference: "ORDER-1001-V1");
Refund #
Returns some or all of an earlier transaction. The cardholder presents the card. transactionDate is the original day, yyyyMMdd.
EcrResult result = await session.RefundAsync(
amount: 1.000m,
receiptNumber: stan,
transactionDate: "20261019",
originalTerminalId: "",
merchantReference: "ORDER-1001-R1");
Inquiry by receipt number #
Reads a transaction. No card, no money. Safe to repeat.
EcrInquiry inquiry = await session.InquireAsync(
receiptNumber: stan,
transactionDate: "20261019");
Inquiry by merchant reference #
Reads the attempt you named originalReference. Use this when the sale, void, or refund never answered: you still have the reference you sent, and you do not yet have a receipt number. transactionDate is optional. On Wi-Fi and USB, originalTerminalId names another terminal.
EcrInquiry inquiry = await session.InquireByReferenceAsync("ORDER-1001-1");
E-receipt #
Wi-Fi and USB. Returns a URL for a QR code. Safe to repeat. Ready carries Url. Unavailable means there is no receipt to show. Failed means the exchange failed; repeat the call.
EcrReceipt receipt = await session.ReceiptAsync(
receiptNumber: stan,
transactionDate: "20261019");
if (receipt is EcrReceipt.Ready ready)
ShowQr(ready.Url);
On Web Service the same call returns EcrReceipt.Unavailable. session.SupportsReceipt is false there.
Close receipt #
Asks the terminal to leave the receipt screen and return to idle. Call it from the till’s Close receipt action when the cashier is finished. Sale, void, refund, and dismissing a dialog do not send it. Safe to repeat: Idle means the terminal is idle, whether a receipt was up or not.
EcrReceiptClosed closed = await session.CloseReceiptAsync(
merchantReference: "",
originalMerchantReference: "ORDER-1001-1");
originalMerchantReference is the sale, void, or refund you are dismissing. Web Service requires it. Wi-Fi and USB ignore it. Both session arguments are strings, so pass them by name.
| Call | Sale’s reference |
|---|---|
EcrOpenedSession.CloseReceiptAsync(merchantReference, originalMerchantReference) | Second argument |
EcrWebServiceTerminal.CloseReceiptAsync(originalMerchantReference, merchantReference) | First argument |
EcrTerminal.CloseReceiptAsync(merchantReference) | None. Wi-Fi and USB only. |
switch (closed)
{
case EcrReceiptClosed.Idle:
break;
case EcrReceiptClosed.Refused refused:
Show(refused.Reason); // firmware has no CLOSE_RECEIPT; leave the receipt up
break;
case EcrReceiptClosed.Failed failed:
Show(failed.Failure.Message); // nothing changed; the call can be repeated
break;
}
Settlement #
Closes the current batch and prints the settlement receipt. Wi-Fi, USB cable, and Web Service use the same session call. It uses the full response timeout, because a close can wait on pending reversals. Safe to repeat when the answer is lost: a batch that closed answers NothingToSettle the next time, and one that did not settles on the retry. SupportsSettlementis true for Wi-Fi, USB cable, and Web Service.
EcrSettlement settlement = await session.SettlementAsync();
switch (settlement)
{
case EcrSettlement.Settled settled:
Show(settled.BatchId, settled.NetAmount, settled.Totals);
break;
case EcrSettlement.NothingToSettle nothing:
Show(nothing.Message);
break;
case EcrSettlement.NotSettled open:
Show(open.Reason);
break;
case EcrSettlement.Failed failed:
Show(failed.Failure.Message); // the batch may or may not have closed
break;
}
Amounts in Settled are major units. Totals always has SALE, REFUND, VOID, PRE_AUTH, and CAPTURE, with a zero row where the terminal omitted one. CloseReceiptAsync puts the terminal’s settlement summary away; it is the same call as after a sale.
Reachability #
Wi-Fi and USB, before a sale. Proves the port or cable answers. It does not prove the terminal is idle.
EcrReachability? probe = await session.ProbeReachabilityAsync();
if (probe is { Reachable: false })
Show(probe.Error);
ProbeTimeout is 3 seconds. A Web Service sale does not run this probe.
On Web Service, check reachability is its own action. It asks whether the terminal is reachable or not.
EcrReachability? check = await session.CheckReachabilityAsync();
Read the result #
SaleAsync, VoidAsync, and RefundAsync return EcrResult.
switch (result)
{
case EcrResult.Approved approved:
Record(approved.MerchantReference, approved.Amount, approved.Rrn, approved.AuthCode);
if (approved.PartialApproval)
CollectBalance(approved.RequestedAmount, approved.Amount);
break;
case EcrResult.Declined declined:
Show(declined.Reason);
break;
case EcrResult.Failed failed when failed.Settled && failed.Recovered is EcrInquiry.Found found:
Apply(found.Transaction);
break;
case EcrResult.Failed failed when failed.Failure.OutcomeUnknown:
MarkUnresolved(failed.MerchantReference);
break;
case EcrResult.Failed failed:
Show(failed.Failure.Message);
break;
}
| Result | Meaning |
|---|---|
Approved | Money moved. Amount is what was taken or returned. ResponseCode is 00 on a plain approval. MaskedPan is masked. |
Approved with PartialApproval | The issuer authorised less than you asked. RequestedAmount is what you asked. Collect the difference before you hand over the goods. |
Declined | The terminal answered and refused. Reason is the text to show. NextStep is None. |
Failed and Failure.Unreachable | Nothing was sent. Wi-Fi and USB only. |
Failed and Failure.OutcomeUnknown | The request went out and the answer did not settle it: timeout, connection lost, malformed answer, or a signature that does not match. The payment may have completed. |
Failed.Settled | Wi-Fi or USB already inquired. Recovered is EcrInquiry.Found. Record that transaction. |
ArgumentException | The call was rejected before anything was sent. A merchant reference longer than 32 characters, or one that contains a space, &, or =, throws here. |
OperationCanceledException | Your token cancelled the wait. The terminal may still complete a request that already left. |
An answer whose nextStep is INQUIRE_BY_MERCHANT_REFERENCE arrives as Failed (Timeout or ConnectionLost). That includes a Web Service timeout, a lost HTTP call, an empty or unreadable body, and an HTTP 5xx with nothing readable. Failure.OutcomeUnknown is false only for Unreachable.
Inquiry #
| Result | Meaning |
|---|---|
Found | Transaction is the record. Status is the outcome (Approved, Declined, Voided, or other text from the backend). Compare it ignoring case. |
NotFound | This lookup returned no record. Reason is the backend’s text when it sent any. |
Failed | The lookup itself failed. Repeat the inquiry. An inquiry does not move money. |
On Found, Transaction.Stan is the receipt number. CanVoid and CanRefund say whether the terminal would accept that operation now. When PartialApproval is set, Amount is what was asked and AuthorizedAmount is what was charged.
Errors and response codes #
Three kinds of problem reach a till, and the SDK reports each one its own way:
- Transaction response codes — the terminal (or the bank behind it) answered. They arrive on the result:
Approved.ResponseCode,Declined.ResponseCode. - Web Service errors — the Amwal Hub, or the HTTPS call to it, failed. The SDK turns them into a
Declinedor aFailed; it never throws for them. - SDK (DLL) errors — the SDK refused the call, or could not complete the exchange. A call it refuses throws before anything is sent; an exchange that fails comes back as
Failedwith aFailureand a message.
Transaction response codes #
| Code | Meaning | Returned as | Money moved | What the till does |
|---|---|---|---|---|
00 | Approved | Approved | Yes | Record it. Check PartialApproval |
51 | Declined by the bank — or, with the message “Card read timeout”, no card was presented within 15 seconds | Declined | No | Show Reason. A new attempt needs a new reference |
12 | The terminal cannot perform this operation: the TMS profile does not allow it, or the terminal software is too old for it | Declined | No | Do not retry; ask Amwal to enable it |
13 | The amount is not valid | Declined | No | Correct the amount |
17 | Cancelled at the terminal | Declined | No | Start again if the cashier wants to |
25 | The original transaction was not found (void, refund, inquiry by receipt number) | Declined | No | Check the receipt number and its day |
58 | No merchant is signed in on the terminal | Declined | No | Sign the merchant in on the terminal, then retry |
63 | Unsigned, signed with the wrong key, or the till’s clock is too far from the terminal’s | Declined | No | Check the key (Wi-Fi key, not the Web Service key) and the till’s clock |
96 | A transaction is already running on the terminal | Declined | No | Wait for it to finish, then retry. Inquiries are answered even while busy |
91 | The transaction did not complete, or the terminal could not tell how it ended | Failed (outcome unknown) | Unknown | Resolve an unknown outcome |
94 | This exact request was answered before (duplicate) | Failed (outcome unknown) | Probably | Inquire by reference — the transaction probably exists |
| Any other code | The bank’s own code, passed through unchanged (for example 05, 909) | Declined | No | Show Reason |
91 and 94 come with nextStep INQUIRE_BY_MERCHANT_REFERENCE, which is why the SDK returns them as Failed, not Declined: the payment may exist. Every code the terminal produces itself (12, 13, 17, 25, 58, 63, 96) means nothing was attempted.
Web Service errors #
What the SDK returns when the Hub, or the HTTPS call to it, does not give a normal answer:
| What happened | Returned as | Failure / ResponseCode | Message |
|---|---|---|---|
| The HTTPS call timed out | Failed | Timeout | “Timed out after 2m 20s” (the call’s deadline) |
| No connection, TLS failure, or the connection dropped | Failed | Timeout | The network error’s own text |
| The Hub answered with an empty body | Failed | ConnectionLost | “Empty response from Web Service (…)” |
| The Hub answered with something that is not JSON | Failed | ConnectionLost | “Response was not valid JSON: …” |
| HTTP 5xx with nothing readable | Failed | ConnectionLost | The HTTP reason, e.g. “Internal Server Error” |
| HTTP 4xx with nothing readable | Declined | ResponseCode = the HTTP status (400, 401, …) | The HTTP reason, e.g. “Unauthorized” |
| Any HTTP status with a readable Hub envelope | As the envelope says | The Hub’s responseCode | The Hub’s errorList, or its message |
The Hub’s envelope carries nextStep INQUIRE_BY_MERCHANT_REFERENCE (e.g. NO_RESPONSE, the terminal did not answer the Hub in time) | Failed | Timeout (or ConnectionLost) | The Hub’s message |
The Hub’s envelope says success: false with no nextStep | Declined | The Hub’s responseCode | The Hub’s errorList, or its message |
MerchantId / TerminalId missing from the config (only when you build EcrWebServiceTerminal yourself) | Failed | Malformed | “merchantId and terminalId must be set on EcrConfig for Web Service ECR” |
Every Failed above is an unknown outcome: inquire by reference, never resend. Recovered is always null on Web Service, so the inquiry is the till’s. A Declined from the Hub (an HTTP 4xx, or success: false without nextStep) means the request was refused before it reached the terminal — most often a wrong Web Service key or wrong merchant or terminal IDs.
SDK (DLL) errors #
Thrown before anything is sent. Fix the call; there is nothing to reconcile.
| Exception | Message | Cause |
|---|---|---|
ArgumentException | “secureHashKey must be an even-length hex string of at least 16 characters, or empty to send unsigned messages” | An invalid key assigned to EcrConfig.SecureHashKey. Pass operator input as rawSecureHashKey to Plan to get it in Issues instead |
ArgumentException | “A merchant reference is at most 32 characters, was N” | Merchant reference too long |
ArgumentException | “A merchant reference takes printable ASCII without spaces, ‘&’ or ‘=’: was …” | Merchant reference with a forbidden character |
ArgumentException | “Cannot open a session with unresolved issues: …” | EcrSessions.Open with a plan whose IsReady is false |
ArgumentException | “An inquiry by reference needs the original’s reference” | InquireByReferenceAsync with an empty reference |
ArgumentException | “Void needs the original’s receipt number” (or Refund) | Void or refund without receiptNumber |
ArgumentException | “Close receipt needs the original merchant reference” | EcrWebServiceTerminal.CloseReceiptAsync without it (the session returns Failed instead — see below) |
ArgumentException | “Web Service secureHashValue could not be computed — check the secure hash key” | The Web Service key could not be used to sign |
ArgumentException | — | EcrTerminal.RunAsync with an operation that does not move money (inquiry, receipt, close receipt, settlement) |
InvalidOperationException | “USB cable sessions require a channel factory” | Open on a cable plan without usbChannel |
OperationCanceledException | — | Your CancellationToken was cancelled. A request that already left may still complete |
Listed in plan.Issues by EcrSessions.Plan — show them to the operator:
| Issue | Fix |
|---|---|
| “Wi-Fi/CABLE secure hash key is not configured” / “Web Service secure hash key is not configured” | Enter the key the plan names in SigningKeyLabel |
| “Secure hash key must be an even-length hex string of at least 16 characters” | Re-enter the key |
| “IP address is required for Wi-Fi ECR” | Enter the IP address from the terminal’s idle screen |
| “Port must be between 1 and 65535 (default 9100)” | Correct the port |
| “Merchant ID is required for Web Service” / “Terminal ID is required for Web Service” | Enter them from the terminal’s Settings → About |
| “Merchant ID must be numeric” / “Terminal ID must be numeric” | Remove anything that is not a digit |
| “Invalid ECR configuration” | The configuration as a whole could not be used; check every field |
Returned as Failed when an exchange with the terminal (Wi-Fi or USB cable) does not complete:
Failure | Message | Cause | Outcome |
|---|---|---|---|
Unreachable | The socket error, then the address — e.g. “Connection refused (192.168.1.50:9100)”, “Connection timed out after 10000 ms (…)” | Wrong IP or port, terminal off or not in Wi-Fi ECR mode, another network | Nothing sent |
Unreachable | “Windows has not assigned a COM port to this terminal. Plug it in. The COM number follows the device serial and can change.” | Cable unplugged, driver missing, or a stale COM port | Nothing sent |
Timeout | “The terminal did not answer within 2m. The transaction may still have completed — inquire before retrying.” | No answer within ResponseTimeout | Unknown |
ConnectionLost | “Terminal closed the connection: …” | The connection dropped after the request left | Unknown |
Malformed | “Terminal returned an empty message” / “Terminal returned a message that is not valid JSON: …” | An unreadable answer | Unknown |
Unauthenticated | “The answer was not signed with this terminal’s key.” | The answer’s signature does not match the key on the till | Unknown |
Unauthenticated | “The answer belongs to a different request. The transaction may still have completed — inquire before retrying.” | The answer is for another request | Unknown |
And on a Web Service session, CloseReceiptAsync without originalMerchantReference returns EcrReceiptClosed.Failed with Malformed: “Web Service close receipt needs the original merchant reference”. Nothing was sent.
Resolve an unknown outcome #
A Failed result whose Failure.OutcomeUnknown is true — and the codes 91 and 94 — mean the customer may have been charged. Never send the sale again.
- Save the merchant reference before every sale, void or refund.
- On Wi-Fi and the USB cable, read
Failed.Recoveredfirst: the SDK has already inquired once.EcrInquiry.Foundsettles the attempt. - Otherwise call
InquireByReferenceAsyncwith the saved reference. On Web Service this inquiry is always the till’s. - Read
Found.Transaction.Status, ignoring case:Approved— the attempt completed.Declined— it did not. A new attempt needs a new reference.- Anything else — leave the order unresolved and check with Amwal.
NotFoundmeans this lookup returned no record; confirm on the terminal, or with Amwal, before taking payment again.EcrInquiry.Failedmeans the lookup itself failed: inquire again.- On start-up, inquire every attempt still marked unresolved.
Failure.Unreachable is the one failure with nothing to look up: the connection was never made, so nothing was sent.
Important notes #
Resolve an unknown outcome #
Failure.OutcomeUnknown means the payment may have completed. Inquire by the merchant reference of that attempt. Charge the order again only after Transaction.Status is Declined, or after the terminal confirms the attempt did not complete.
- Save the reference before
SaleAsync,VoidAsync, orRefundAsync. - On Wi-Fi and USB, read
Failed.Recoveredfirst. WithAutoInquireOnFailureleft on (the default), the SDK has already calledInquireByReferenceAsynconce.EcrInquiry.Foundsettles the attempt.NotFound,Failed, or null leaves it unknown. Web Service setsRecoveredto null. - Call
InquireByReferenceAsyncwith the saved reference. - Read
Found.Transaction.Status, ignoring case.Approved— the attempt completed. On a void or refund, the void or refund completed.Declined— it did not. A new attempt needs a new reference.- Any other value, including
VoidedandReversed— leave the order unresolved.
NotFoundafter a lost answer means this lookup returned no record. The same answer follows a terminal reset, or a record that has aged out. Confirm on the terminal, or with Amwal, before you take payment again.EcrInquiry.Failedmeans the lookup failed. Inquire again.- On startup, inquire every attempt still marked unresolved.
Failure.Unreachable means the connection was never made. There is no attempt to look up.
Merchant reference #
32 characters maximum, with space, &, and = excluded. The SDK trims the value. Use one reference per attempt; an order number plus an attempt suffix fits. A void and a refund each get a new reference.
Receipt number #
Approved does not carry it. Read Transaction.Stan from an inquiry by merchant reference, or read the printed receipt. The SDK sends the number padded to 6 digits. Pass that receipt’s day as yyyyMMdd to refund, inquiry by receipt number, and e-receipt. A receipt number is unique on one terminal for one day.
Amounts and currency #
CurrencyCode defaults to "512" and MinorUnitDigits to 3 (OMR). Another currency needs both. MinorUnitDigitsaccepts 0 to 4. The SDK rounds half away from zero to that many places, then sends minor units.
Timeouts #
| Transport | Wait |
|---|---|
| Wi-Fi | ConnectTimeout 10 s, then ResponseTimeout 120 s. A lost answer can add one more response wait for the automatic inquiry. |
| USB | The till waits 120 seconds for the answer, the same as Wi-Fi. |
Web Service through Plan | A ResponseTimeout of 120 s becomes EcrConfig.WebServiceResponseTimeout (130 s). Any other value is kept. The HTTP deadline is ConnectTimeout + ResponseTimeout: 130 s with the defaults. |
new EcrWebServiceTerminal(...) skips the 130 s raise. Set ResponseTimeout = EcrConfig.WebServiceResponseTimeout on that config.
The default wait covers card present and PIN. Cancelling CancellationToken ends the wait in your process. A request that already reached the terminal can still complete.
Keys #
Even-length hex, at least 16 characters. Assigning an invalid key on EcrConfig throws ArgumentException. Pass operator-typed text as rawSecureHashKey to Plan and the same problem is listed in Issues.
Open requires a key. new EcrTerminal(...) and new EcrWebServiceTerminal(...) with an empty key send unsigned requests and skip the answer check.
Wi-Fi and USB sign the field secureHash. Web Service signs secureHashValue. The two secrets are issued separately. plan.SigningKeyLabel names the one this plan expects.
Logging #
IEcrLogger logger = EcrLogger.From(line => Trace.WriteLine(line)); EcrOpenedSession session = EcrSessions.Open(serial, plan, logger: logger);
Logging is off until you pass a logger. EcrLogger.None discards every line. Each line is the request or the response: masked PAN, amount, and reference. An exception thrown by the sink escapes the call.
When you build the message yourself #
EcrTransactionType is Sale, Void, Refund, Inquiry, Receipt, CloseReceipt, Settlement. EcrTransactionTypes.MenuOptions is the operator menu: sale, void, refund, inquiry. RequiresAmount, RequiresOriginalStan, RequiresOriginalDate, MovesMoney, and AllowsOtherTerminal say which fields that operation needs. EcrTerminal.RunAsync accepts only the three that move money.
EcrWebServiceSaleRequest, EcrWebServiceVoidRequest, EcrWebServiceRefundRequest, EcrWebServiceTransactionStatusRequest, EcrWebServiceCloseReceiptRequest, EcrWebServiceSettleRequest, and EcrWebServiceCheckReachabilityRequest are for a caller that builds the message. EcrWebServiceRequestJson writes each one and signs it when you pass the key. The session methods do this themselves.
