The com.codename1.payment.terminal package takes in-person card payments. In-app purchase sells digital goods inside the app. A card terminal charges a customer standing at a counter or a vending machine. Every kind of terminal extends the same PaymentTerminal class, so a point-of-sale app can switch providers without changing its checkout code:

  • TapToPay uses the phone itself as the reader. The customer holds a card or a wallet to the back of the phone. It works on iOS and Android, through the Stripe Terminal SDK.

  • StripeReaderTerminal drives a Stripe smart reader, such as the WisePOS E, over the Stripe API.

  • SquareTerminal drives a Square Terminal over the Square API.

  • AdyenCloudTerminal drives any Adyen terminal through the Adyen cloud Terminal API, and AdyenLocalTerminal drives one over the shop’s own network, with no internet round trip.

  • ZvtTerminal drives a terminal that speaks ZVT, the till protocol of Germany, Austria and Switzerland, over a serial cable, USB or the network.

  • MdbCashlessTerminal drives the card reader of a vending machine on its MDB bus.

The terminals that speak HTTPS work on every platform, desktop and web included. Neither mobile OS lets an app read a payment card directly, so TapToPay always goes through the payment provider’s certified SDK and gets back only the outcome.

Amounts are in the currency’s minor unit, cents for USD, so no floating point rounding ever reaches a price. A TerminalResult reports one of four statuses: approved, declined, canceled, or failed. Approved means the operation went through: the sale was charged, the refund issued, the reversal done. Treat it as a report and confirm the payment on your server, by its transaction ID, before you fulfill an order.

Operations

Beyond a sale, a terminal can hold an amount and capture it later, reverse a payment, refund one, look a payment up, and close the day. Not every terminal can do everything, so ask supports(TerminalOperation) first; an operation a terminal lacks fails with an UnsupportedOperationException. A request can also ask the customer for a tip or cashback, and TerminalResult.getReceipt() carries what a receipt needs: the card brand, the masked number, the authorization code and, on terminals that send them, the receipt lines.

When the connection drops after a terminal took the card, nobody knows whether the customer was charged. That case is never reported as a decline: the resource fails with a TerminalOutcomeUnknownException. Look the payment up, or ask the customer, before you charge again.

PaymentTerminal terminal = new SquareTerminal("device-id", null);
TerminalPaymentRequest hold = new TerminalPaymentRequest(5000, "USD")
        .setReference("table-7")
        .setPreAuthorization(true);
terminal.collect(hold).ready(auth -> {
    if (!auth.isApproved()) {
        return;
    }
    String id = auth.getTransactionId();
    // later, for the final amount including the tip
    terminal.capture(id, 5750, "USD").ready(done -> Log.p("Captured " + done.getStatus()));
}).except(err -> {
    if (err instanceof TerminalOutcomeUnknownException) {
        // the card may have been charged: look it up before charging again
        terminal.lookup("table-7").ready(found -> Log.p("It was " + found.getStatus()));
    }
});

if (terminal.supports(TerminalOperation.REFUND)) {
    terminal.refund(new TerminalRefundRequest(1250, "USD").setOriginalTransactionId("pi_123"));
}

Tap to Pay on the phone

Your server does three things. It issues Stripe Terminal connection tokens, which the app fetches through a ConnectionTokenProvider. It creates a PaymentIntent for each sale with card_present as the payment method type and hands the client secret to the app. It confirms that the PaymentIntent succeeded.

// Both values come from your server; these are placeholders.
String clientSecretFromServer = "pi_123_secret_456";
ConnectionTokenProvider tokens = () -> {
    AsyncResource<String> token = new AsyncResource<>();
    token.complete("pst_test_connection_token");
    return token;
};
if (TapToPay.isSupported()) {
    TapToPay tap = new TapToPay(tokens, "tml_FDOtHwxAAdIJOh");
    tap.setMerchantDisplayName("Corner Bakery");
    TerminalPaymentRequest req = new TerminalPaymentRequest(450, "USD")
            .setProviderReference(clientSecretFromServer);
    tap.collect(req).ready(result -> {
        if (result.isApproved()) {
            Dialog.show("Paid", result.getTransactionId(), "OK", null);
        }
    });
}

Referencing com.codename1.payment.terminal.tap is what adds the Stripe Terminal SDK to a build. An app that never references it carries none of the SDK, and an app that uses only the network terminals doesn’t either. When the package is referenced, the build:

  • adds the Stripe Terminal SDK, raises the Android minimum SDK to 26 and the iOS deployment target to 16, and declares the NFC and location permissions;

  • adds the com.apple.developer.proximity-reader.payment.acceptance entitlement on iOS, unless you set the ios.entitlements.com.apple.developer.proximity-reader.payment.acceptance build hint yourself.

Apple grants that entitlement on request, and the provisioning profile must carry it: an app that references the package before Apple grants it fails code signing. Tap to Pay on iPhone needs an iPhone XS or newer on iOS 16.4 or later. On Android it needs NFC and Android 8 or later, and the app asks for the location permission before the first payment, because Stripe requires it.

TapToPay.isSupported() answers false on devices that can’t take payments and on platforms with no SDK. In the simulator it answers true and simulates a phone: it asks your token provider for a token and approves the payment. An amount ending in 01, such as 1001, is declined and one ending in 02 fails, so you can try every path. Call setSimulated(true) to use Stripe’s simulated reader on a real device with a test mode PaymentIntent.

Stripe smart readers

StripeReaderTerminal takes the reader ID and an API key: a restricted Stripe key limited to Terminal readers and PaymentIntents, or null when your own server adds the key. It creates a PaymentIntent, hands it to the reader and polls the reader until the payment ends. To create the PaymentIntent on your server instead, pass its ID as the request’s provider reference.

String stripeKey = null; // null: your server adds the key
PaymentTerminal reader = new StripeReaderTerminal("tmr_FDOt2wlRZEdpd7", stripeKey);
reader.collect(new TerminalPaymentRequest(1250, "USD")).ready(result -> {
    Log.p("Reader answered " + result.getStatus());
});

The API key is a secret. Ship it only in an app that runs on hardware you control, such as a desktop register in a shop. Otherwise, point setApiBase at your own server and have it forward the calls.

Adyen terminals

AdyenCloudTerminal takes a Terminal API key, an ID for the register and the terminal’s POI ID. It sends a payment request and waits for the terminal’s answer. It targets the test environment until you call setLive(true). The payment request stays open until the customer taps, so the terminal makes Codename One use two network threads, letting cancel() and the rest of the app’s requests through meanwhile. It can only switch while no other request is running; otherwise a cancel waits until the payment request ends. The API key can start payments on every terminal of the merchant account, so the same rule applies as for Stripe: ship it only on hardware you control, and otherwise pass null and point setEndpoint at your own server.

String adyenKey = null; // null: your endpoint adds the key
AdyenCloudTerminal terminal = new AdyenCloudTerminal(adyenKey, "POS-1", "V400m-324688179");
terminal.collect(new TerminalPaymentRequest(1250, "EUR").setReference("order-1042"))
        .ready(result -> Log.p("Terminal answered " + result.getStatus()));

cancel() stops a payment that’s waiting for a card on any terminal. Once the card is read, the payment can’t be stopped from the app.

Square Terminal and Adyen on the local network

SquareTerminal takes the device ID that pairing the terminal gave you and an access token, or null when your own server adds the token. It targets the Square sandbox until you call setLive(true). A checkout waits for the customer, then the terminal reads the payment it produced.

AdyenLocalTerminal talks to the terminal’s own address on the shop network. It encrypts every message with the key you configured for the terminal in the Adyen Customer Area, and the terminal proves itself by answering under the same key, so the app needs no certificate for it.

SquareTerminal square = new SquareTerminal("device-id-from-pairing", null);
square.setLive(true);

AdyenLocalTerminal adyen = new AdyenLocalTerminal("192.168.1.42", "POS-1", "V400m-324688179",
        "key-identifier", "key-passphrase", 1);
adyen.collect(new TerminalPaymentRequest(1250, "EUR"))
        .ready(result -> Log.p("Adyen answered " + result.getStatus()));

ZVT terminals

ZvtTerminal takes a byte link and the terminal’s till password. Over the network the usual port is 20007. Over a serial cable or a USB serial connection, ZVT frames each message and checks it, which ZvtTerminal does on any link other than TCP. By default the terminal prints its own receipts; setReceiptsToApp(true) hands them to the app instead, which must then print them. ZVT has no refund of a given payment: reverse it while it’s in the current batch, or refund an amount.

ZvtTerminal overLan = new ZvtTerminal(new TcpLink("192.168.1.80", 20007), 0);
ZvtTerminal overCable = new ZvtTerminal(new SerialLink("COM3", 9600, 8, SerialPort.PARITY_NONE, 2), 123456);
overCable.setReceiptsToApp(true);
overLan.collect(new TerminalPaymentRequest(1250, "EUR")).ready(result -> {
    if (result.getReceipt() != null) {
        Log.p("Card " + result.getReceipt().getBrand());
    }
});
overLan.reconcile().ready(day -> Log.p("Batch total " + day.getTotalAmount()));

Vending machines

An MDB card reader is a peripheral on the vending machine’s bus, and the app plays the machine’s controller. MDB runs a 9-bit serial line that ordinary serial ports can’t produce, so the app reaches it through an adapter board; implement the one-method MdbBus interface over that adapter’s commands. An approval arrives before anything is dispensed. Call completeVend with whether the product came out, and the reader settles the payment or returns the money.

MdbBus adapter = (block, timeout) -> new byte[0]; // your adapter board
MdbCashlessTerminal reader = new MdbCashlessTerminal(adapter);
reader.setItemNumber(12);
reader.collect(new TerminalPaymentRequest(250, "EUR")).ready(result -> {
    if (result.isApproved()) {
        boolean dispensed = true; // what the machine reported for item 12
        reader.completeVend(dispensed);
    }
});

com.codename1.io.link gives the protocol drivers one blocking interface over a serial port (SerialLink, on the desktop ports), a TCP socket (TcpLink), a USB device’s bulk endpoints (UsbLink, on Android) and an existing pair of streams (StreamLink). MemoryLink.pair() joins two links back to back for tests and simulated devices. Links block, so use them from a thread of your own; they refuse to run on the EDT. UsbLink sends no control requests, so a USB serial chip that must be told its baud rate, such as FTDI, works only on a desktop, where the operating system drives it.

com.codename1.pos builds on the links. EscPosPrinter prints to almost any thermal receipt printer and kicks the cash drawer connected to it. CustomerDisplay drives a pole display, and LinkScanner reads a barcode scanner that sends each code as a line. A scanner in keyboard mode needs nothing: it types into the focused text field.

EscPosPrinter printer = new EscPosPrinter(new TcpLink("192.168.1.60", 9100));
printer.align(EscPosPrinter.CENTER).bold(true).size(2, 2).line("CAFE")
        .size(1, 1).bold(false).align(EscPosPrinter.LEFT)
        .line("Latte              3.50")
        .qr("https://example.com/r/1042")
        .feed(3).cut().openDrawer();
printer.print().except(err -> Log.p("Printer: " + err.getMessage()));

LinkScanner scanner = new LinkScanner(new SerialLink("/dev/ttyACM0", 9600));
scanner.start(code -> Log.p("Scanned " + code));