diff --git a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java index 5f0cfffe4f3..236b2b14305 100644 --- a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java +++ b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java @@ -7333,6 +7333,17 @@ public com.codename1.webrtc.spi.WebRtcBridge getWebRtcBridge() { return null; } + /// Returns the platform bridge used by `com.codename1.payment.terminal.tap.TapToPay`: the + /// Stripe Terminal SDK on a device, or the simulator's simulated phone. The default answers + /// `null`, which `TapToPay.isSupported()` reads as unsupported. + /// + /// #### Returns + /// + /// the Tap to Pay bridge, or null when unsupported + public com.codename1.payment.terminal.spi.TapToPayBridge getTapToPayBridge() { + return null; + } + /// Returns the platform bridge used by the `com.codename1.vpn` API to install and control VPN /// configurations. Ports supporting VPN management override this; the default answers `null`. /// diff --git a/CodenameOne/src/com/codename1/io/link/ByteLink.java b/CodenameOne/src/com/codename1/io/link/ByteLink.java new file mode 100644 index 00000000000..3674bc63912 --- /dev/null +++ b/CodenameOne/src/com/codename1/io/link/ByteLink.java @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.io.link; + +import com.codename1.ui.CN; +import java.io.IOException; + +/// A two-way byte connection to one device: a serial port, a TCP socket, a +/// USB endpoint pair, or anything else with bytes in and out. +/// +/// Calls block, so a protocol driver runs them on a thread of its own and +/// hands results to the EDT with `CN.callSerially`. Every blocking call +/// refuses to run on the EDT, where it would freeze the app. +/// +/// ```java +/// ByteLink link = new TcpLink("192.168.1.50", 9100); +/// new Thread(() -> { +/// try { +/// link.open(); +/// link.write("Hello\n".getBytes("UTF-8")); +/// } catch (IOException err) { +/// CN.callSerially(() -> System.out.println("Printer unreachable: " + err)); +/// } finally { +/// link.close(); +/// } +/// }).start(); +/// ``` +public abstract class ByteLink { + /// Connects. Does nothing when already open. + /// + /// #### Throws + /// + /// - `IOException`: when the device cannot be reached + public abstract void open() throws IOException; + + /// Whether [#open()] succeeded and [#close()] has not been called. + /// + /// #### Returns + /// + /// true while open + public abstract boolean isOpen(); + + /// Writes bytes, returning once they are handed to the device. + /// + /// #### Parameters + /// + /// - `data`: the buffer + /// + /// - `offset`: where to start in it + /// + /// - `length`: how many bytes + /// + /// #### Throws + /// + /// - `IOException`: when the link is closed or broken + public abstract void write(byte[] data, int offset, int length) throws IOException; + + /// Reads what has arrived, waiting up to `timeout` milliseconds for the + /// first byte. + /// + /// #### Parameters + /// + /// - `buffer`: where to put the bytes + /// + /// - `offset`: where to start in it + /// + /// - `length`: at most how many bytes + /// + /// - `timeout`: how long to wait, in milliseconds + /// + /// #### Returns + /// + /// the number of bytes read; 0 when nothing arrived in time + /// + /// #### Throws + /// + /// - `IOException`: when the link is closed or broken, including when + /// the other side closed it + public abstract int read(byte[] buffer, int offset, int length, int timeout) throws IOException; + + /// Disconnects. Safe to call more than once, and from any thread; a read + /// blocked in another thread fails soon after. + public abstract void close(); + + /// Writes all of `data`. + /// + /// #### Parameters + /// + /// - `data`: the bytes + /// + /// #### Throws + /// + /// - `IOException`: when the link is closed or broken + public void write(byte[] data) throws IOException { + write(data, 0, data.length); + } + + /// Reads one byte. + /// + /// #### Parameters + /// + /// - `timeout`: how long to wait, in milliseconds + /// + /// #### Returns + /// + /// the byte, 0 to 255; -1 when nothing arrived in time + /// + /// #### Throws + /// + /// - `IOException`: when the link is closed or broken + public int readByte(int timeout) throws IOException { + byte[] one = new byte[1]; + return read(one, 0, 1, timeout) == 1 ? one[0] & 0xff : -1; + } + + /// Reads exactly `length` bytes, each within `timeout` milliseconds of + /// the one before. + /// + /// #### Parameters + /// + /// - `buffer`: where to put them + /// + /// - `offset`: where to start in it + /// + /// - `length`: how many + /// + /// - `timeout`: the longest gap allowed, in milliseconds + /// + /// #### Returns + /// + /// true when all arrived; false on a gap longer than `timeout` + /// + /// #### Throws + /// + /// - `IOException`: when the link is closed or broken + public boolean readFully(byte[] buffer, int offset, int length, int timeout) throws IOException { + int done = 0; + while (done < length) { + int n = read(buffer, offset + done, length - done, timeout); + if (n <= 0) { + return false; + } + done += n; + } + return true; + } + + /// Throws when called on the EDT; for implementations, at the top of + /// every blocking method. + /// + /// #### Throws + /// + /// - `IllegalStateException`: on the EDT + protected static void checkNotEdt() { + if (CN.isEdt()) { + throw new IllegalStateException("Byte links block; use them from a thread of your own, not the EDT"); + } + } + + /// Sleeps briefly between polls; for implementations. + /// + /// #### Parameters + /// + /// - `millis`: how long + protected static void pause(int millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/CodenameOne/src/com/codename1/io/link/MemoryLink.java b/CodenameOne/src/com/codename1/io/link/MemoryLink.java new file mode 100644 index 00000000000..8cf0b8d7a6a --- /dev/null +++ b/CodenameOne/src/com/codename1/io/link/MemoryLink.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.io.link; + +import java.io.IOException; +import java.util.concurrent.atomic.AtomicReference; + +/// Two links joined back to back in memory: what one writes the other reads. +/// For tests and for a simulated device a driver can talk to without +/// hardware. +/// +/// ```java +/// MemoryLink[] pair = MemoryLink.pair(); +/// ByteLink tillSide = pair[0]; +/// ByteLink deviceSide = pair[1]; // answer from a test thread +/// ``` +public final class MemoryLink extends ByteLink { + private final Pipe incoming; + private final Pipe outgoing; + private boolean closed; + + private MemoryLink(Pipe incoming, Pipe outgoing) { + this.incoming = incoming; + this.outgoing = outgoing; + } + + /// Two connected links. + /// + /// #### Returns + /// + /// the two ends; either may be the device's + public static MemoryLink[] pair() { + Pipe a = new Pipe(); + Pipe b = new Pipe(); + return new MemoryLink[] {new MemoryLink(a, b), new MemoryLink(b, a)}; + } + + @Override + public void open() { + // Always connected. + } + + @Override + public boolean isOpen() { + return !closed; + } + + @Override + public void write(byte[] data, int offset, int length) throws IOException { + if (closed || outgoing.isClosed()) { + throw new IOException("The link is closed"); + } + byte[] copy = new byte[length]; + System.arraycopy(data, offset, copy, 0, length); + outgoing.append(copy); + } + + @Override + public int read(byte[] buffer, int offset, int length, int timeout) throws IOException { + long end = System.currentTimeMillis() + timeout; + while (true) { + if (closed) { + throw new IOException("The link is closed"); + } + int n = incoming.take(buffer, offset, length); + if (n > 0) { + return n; + } + if (incoming.isClosed()) { + throw new IOException("The other end closed the link"); + } + if (System.currentTimeMillis() >= end) { + return 0; + } + pause(2); + } + } + + @Override + public void close() { + closed = true; + outgoing.close(); + incoming.close(); + } + + /// One direction: an immutable byte array swapped atomically, so the + /// writer's thread and the reader's need no lock. + private static final class Pipe { + private final AtomicReference data = new AtomicReference(new byte[0]); + private final AtomicReference closed = new AtomicReference(Boolean.FALSE); + + void append(byte[] more) { + while (true) { + byte[] cur = data.get(); + byte[] next = new byte[cur.length + more.length]; + System.arraycopy(cur, 0, next, 0, cur.length); + System.arraycopy(more, 0, next, cur.length, more.length); + if (data.compareAndSet(cur, next)) { + return; + } + } + } + + int take(byte[] buffer, int offset, int length) { + while (true) { + byte[] cur = data.get(); + if (cur.length == 0) { + return 0; + } + int n = Math.min(length, cur.length); + byte[] rest = new byte[cur.length - n]; + System.arraycopy(cur, n, rest, 0, rest.length); + if (data.compareAndSet(cur, rest)) { + System.arraycopy(cur, 0, buffer, offset, n); + return n; + } + } + } + + void close() { + closed.set(Boolean.TRUE); + } + + boolean isClosed() { + return closed.get().booleanValue(); + } + } +} diff --git a/CodenameOne/src/com/codename1/io/link/SerialLink.java b/CodenameOne/src/com/codename1/io/link/SerialLink.java new file mode 100644 index 00000000000..c9a79ca20e8 --- /dev/null +++ b/CodenameOne/src/com/codename1/io/link/SerialLink.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.io.link; + +import com.codename1.hardware.Hardware; +import com.codename1.hardware.HardwareException; +import com.codename1.hardware.SerialPort; +import java.io.IOException; + +/// A serial port: an RS-232 cable, or a USB serial adapter the operating +/// system presents as one (`COM3`, `/dev/ttyUSB0`, `/dev/ttyACM0`). +/// +/// Needs `Hardware.FEATURE_SERIAL`: the Windows and Linux desktop ports and +/// the simulator. On Android, reach a USB serial device through +/// [UsbLink] instead. +public class SerialLink extends ByteLink { + private final String device; + private final int baud; + private final int dataBits; + private final int parity; + private final int stopBits; + private SerialPort port; + + /// 8 data bits, no parity, one stop bit. + /// + /// #### Parameters + /// + /// - `device`: the port's device path or name + /// + /// - `baud`: the speed + public SerialLink(String device, int baud) { + this(device, baud, 8, SerialPort.PARITY_NONE, 1); + } + + /// #### Parameters + /// + /// - `device`: the port's device path or name + /// + /// - `baud`: the speed + /// + /// - `dataBits`: 5 to 8 + /// + /// - `parity`: one of the `SerialPort.PARITY_` constants + /// + /// - `stopBits`: 1 or 2 + public SerialLink(String device, int baud, int dataBits, int parity, int stopBits) { + this.device = device; + this.baud = baud; + this.dataBits = dataBits; + this.parity = parity; + this.stopBits = stopBits; + } + + @Override + public void open() throws IOException { + checkNotEdt(); + if (port != null) { + return; + } + try { + port = Hardware.getInstance().openSerial(device, baud, dataBits, parity, stopBits); + } catch (HardwareException e) { + throw io("Cannot open " + device + ": " + e.getMessage(), e); + } + } + + @Override + public boolean isOpen() { + return port != null; + } + + @Override + public void write(byte[] data, int offset, int length) throws IOException { + checkNotEdt(); + SerialPort p = port; + if (p == null) { + throw new IOException("The link is closed"); + } + try { + p.write(data, offset, length); + } catch (HardwareException e) { + throw io(e.getMessage(), e); + } + } + + @Override + public int read(byte[] buffer, int offset, int length, int timeout) throws IOException { + checkNotEdt(); + SerialPort p = port; + if (p == null) { + throw new IOException("The link is closed"); + } + try { + return Math.max(0, p.read(buffer, offset, length, timeout)); + } catch (HardwareException e) { + throw io(e.getMessage(), e); + } + } + + private static IOException io(String message, Throwable cause) { + IOException out = new IOException(message); + out.initCause(cause); + return out; + } + + @Override + public void close() { + SerialPort p = port; + port = null; + if (p != null) { + p.close(); + } + } +} diff --git a/CodenameOne/src/com/codename1/io/link/StreamLink.java b/CodenameOne/src/com/codename1/io/link/StreamLink.java new file mode 100644 index 00000000000..2cb94218b4b --- /dev/null +++ b/CodenameOne/src/com/codename1/io/link/StreamLink.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.io.link; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.concurrent.atomic.AtomicBoolean; + +/// A link over a pair of streams that are already connected, such as a +/// Bluetooth socket's. Reads wait by polling `available()`, so the input +/// stream must report it; most socket streams do. +public class StreamLink extends ByteLink { + private InputStream in; + private OutputStream out; + // close() runs on another thread than a blocked read, so the flag is an + // atomic. A peer that closes without the stream reporting it (available() + // stays 0) reads as a timeout; callers bound every wait. + private final AtomicBoolean closed = new AtomicBoolean(); + + /// #### Parameters + /// + /// - `in`: the stream from the device + /// + /// - `out`: the stream to the device + public StreamLink(InputStream in, OutputStream out) { + this.in = in; + this.out = out; + } + + /// For subclasses that connect in [#open()] and call + /// [#setStreams(InputStream, OutputStream)]. + protected StreamLink() { + } + + /// Supplies the streams once connected; for subclasses. + /// + /// #### Parameters + /// + /// - `in`: the stream from the device + /// + /// - `out`: the stream to the device + protected void setStreams(InputStream in, OutputStream out) { + this.in = in; + this.out = out; + closed.set(false); + } + + @Override + public void open() throws IOException { + if (in == null || out == null) { + throw new IOException("No streams"); + } + } + + @Override + public boolean isOpen() { + return in != null && !closed.get(); + } + + @Override + public void write(byte[] data, int offset, int length) throws IOException { + checkNotEdt(); + if (!isOpen()) { + throw new IOException("The link is closed"); + } + out.write(data, offset, length); + out.flush(); + } + + @Override + public int read(byte[] buffer, int offset, int length, int timeout) throws IOException { + checkNotEdt(); + long end = System.currentTimeMillis() + timeout; + while (true) { + if (!isOpen()) { + throw new IOException("The link is closed"); + } + int available = in.available(); + if (available > 0) { + int n = in.read(buffer, offset, Math.min(length, available)); + if (n < 0) { + throw new IOException("The device closed the connection"); + } + return n; + } + if (System.currentTimeMillis() >= end) { + return 0; + } + pause(5); + } + } + + @Override + public void close() { + if (closed.getAndSet(true)) { + return; + } + try { + if (in != null) { + in.close(); + } + } catch (IOException e) { + // closing anyway + } + try { + if (out != null) { + out.close(); + } + } catch (IOException e) { + // closing anyway + } + } +} diff --git a/CodenameOne/src/com/codename1/io/link/TcpLink.java b/CodenameOne/src/com/codename1/io/link/TcpLink.java new file mode 100644 index 00000000000..ebbbac3d283 --- /dev/null +++ b/CodenameOne/src/com/codename1/io/link/TcpLink.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.io.link; + +import com.codename1.io.Socket; +import com.codename1.io.SocketConnection; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.concurrent.atomic.AtomicReference; + +/// A TCP connection to a device on the local network: a receipt printer on +/// port 9100, a ZVT or nexo terminal on its configured port. +/// +/// Needs [Socket#isSupported()]: the desktop ports, Android and iOS. A web +/// page cannot open raw sockets. +public class TcpLink extends StreamLink { + private final String host; + private final int port; + private int connectTimeout = 10000; + + /// #### Parameters + /// + /// - `host`: the device's address + /// + /// - `port`: its port + public TcpLink(String host, int port) { + this.host = host; + this.port = port; + } + + /// How long [#open()] waits for the connection. Defaults to ten seconds. + /// + /// #### Parameters + /// + /// - `connectTimeout`: the limit in milliseconds + public void setConnectTimeout(int connectTimeout) { + this.connectTimeout = connectTimeout; + } + + @Override + public void open() throws IOException { + checkNotEdt(); + if (isOpen()) { + return; + } + if (!Socket.isSupported()) { + throw new IOException("This platform has no TCP sockets"); + } + // Answered on the socket's thread. + final AtomicReference result = new AtomicReference(); + SocketConnection sc = new SocketConnection() { + @Override + public void connectionError(int errorCode, String message) { + result.compareAndSet(null, new IOException("Cannot reach " + host + ":" + port + ": " + message)); + } + + @Override + public void connectionEstablished(InputStream is, OutputStream os) { + if (!result.compareAndSet(null, new Object[] {is, os})) { + closeQuietly(is, os); + } + } + }; + sc.setConnectTimeout(connectTimeout); + Socket.connect(host, port, sc); + long end = System.currentTimeMillis() + connectTimeout + 1000L; + while (result.get() == null && System.currentTimeMillis() < end) { + pause(10); + } + Object r = result.getAndSet(new IOException("timed out")); + if (r instanceof Object[]) { + Object[] streams = (Object[]) r; + setStreams((InputStream) streams[0], (OutputStream) streams[1]); + return; + } + // A connection that lands after this is closed by the callback. + throw r instanceof IOException && !"timed out".equals(((IOException) r).getMessage()) + ? (IOException) r : new IOException("Timed out connecting to " + host + ":" + port); + } + + private static void closeQuietly(InputStream is, OutputStream os) { + try { + is.close(); + } catch (IOException e) { + // late connection, discarded + } + try { + os.close(); + } catch (IOException e) { + // late connection, discarded + } + } +} diff --git a/CodenameOne/src/com/codename1/io/link/UsbLink.java b/CodenameOne/src/com/codename1/io/link/UsbLink.java new file mode 100644 index 00000000000..4157f30caa8 --- /dev/null +++ b/CodenameOne/src/com/codename1/io/link/UsbLink.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.io.link; + +import com.codename1.io.usb.Usb; +import com.codename1.io.usb.UsbDevice; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/// A USB device's bulk endpoints: a USB receipt printer, or a USB CDC +/// device -- many payment terminals -- whose serial line settings do not +/// matter. Needs [Usb#isSupported()] (Android) and permission from the user +/// ([Usb#requestPermission(UsbDevice)]) before [#open()]. +/// +/// The link sends no control requests, so a USB serial chip that must be +/// told its baud rate (FTDI, CP210x, CH340) does not work through it; plug +/// those into a desktop, where the operating system drives the chip and +/// [SerialLink] opens it. +/// +/// A read waits in steps of the platform's transfer timeout, five seconds on +/// Android, so a short timeout may wait longer. +public class UsbLink extends ByteLink { + private final UsbDevice device; + private final int inEndpoint; + private final int outEndpoint; + private InputStream in; + private OutputStream out; + + /// #### Parameters + /// + /// - `device`: the device + /// + /// - `inEndpoint`: the address of its bulk IN endpoint (bit 7 set, as + /// `0x81`) + /// + /// - `outEndpoint`: the address of its bulk OUT endpoint + public UsbLink(UsbDevice device, int inEndpoint, int outEndpoint) { + this.device = device; + this.inEndpoint = inEndpoint; + this.outEndpoint = outEndpoint; + } + + @Override + public void open() throws IOException { + checkNotEdt(); + if (out != null) { + return; + } + if (!Usb.isSupported()) { + throw new IOException("This platform has no USB host support"); + } + if (!Usb.hasPermission(device)) { + throw new IOException("No permission for " + device.getDeviceName() + "; call Usb.requestPermission"); + } + out = Usb.openOutputStream(device, outEndpoint); //NOPMD CloseResource - held open until close() + if (inEndpoint >= 0) { + in = Usb.openInputStream(device, inEndpoint); //NOPMD CloseResource - held open until close() + } + } + + @Override + public boolean isOpen() { + return out != null; + } + + @Override + public void write(byte[] data, int offset, int length) throws IOException { + checkNotEdt(); + OutputStream o = out; //NOPMD CloseResource - the link owns the stream + if (o == null) { + throw new IOException("The link is closed"); + } + o.write(data, offset, length); + } + + /// A printer with no IN endpoint (`inEndpoint` of -1) never answers, and + /// a read reports nothing arrived. + @Override + public int read(byte[] buffer, int offset, int length, int timeout) throws IOException { + checkNotEdt(); + if (out == null) { + throw new IOException("The link is closed"); + } + InputStream i = in; //NOPMD CloseResource - the link owns the stream + if (i == null) { + pause(timeout); + return 0; + } + long end = System.currentTimeMillis() + timeout; + do { + // A negative count is the transfer timing out, not the end. + int n = i.read(buffer, offset, length); + if (n > 0) { + return n; + } + } while (System.currentTimeMillis() < end && isOpen()); + return 0; + } + + @Override + public void close() { + InputStream i = in; //NOPMD CloseResource - closed below + OutputStream o = out; //NOPMD CloseResource - closed below + in = null; + out = null; + try { + if (i != null) { + i.close(); + } + } catch (IOException e) { + // closing anyway + } + try { + if (o != null) { + o.close(); + } + } catch (IOException e) { + // closing anyway + } + } +} diff --git a/CodenameOne/src/com/codename1/io/link/package-info.java b/CodenameOne/src/com/codename1/io/link/package-info.java new file mode 100644 index 00000000000..3ae3a7111f4 --- /dev/null +++ b/CodenameOne/src/com/codename1/io/link/package-info.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/// Byte links to devices on a cable or the local network -- a serial port, a +/// TCP socket, a USB bulk endpoint -- behind one blocking interface, for the +/// protocol drivers of payment terminals, receipt printers and other +/// point-of-sale peripherals. +package com.codename1.io.link; diff --git a/CodenameOne/src/com/codename1/payment/terminal/CardReceipt.java b/CodenameOne/src/com/codename1/payment/terminal/CardReceipt.java new file mode 100644 index 00000000000..c487003ad23 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/CardReceipt.java @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal; + +/// What a card receipt has to show, as the terminal reported it. +/// +/// Card schemes require a printed or emailed receipt to carry the +/// application identifier, the application label, the masked card number, +/// how the card was read and the authorization code. Each getter answers +/// null when the terminal did not report that field. +/// +/// Some terminals compose the whole receipt themselves; those lines are in +/// [#getMerchantReceipt()] and [#getCustomerReceipt()], ready to print as +/// they are. Print those when present -- they carry everything the +/// acquirer requires, including fields this class does not model. +public final class CardReceipt { + /// How the card was read. + public enum EntryMode { + /// Tapped: a contactless card, phone or watch. + CONTACTLESS, + /// Inserted: the chip was read. + CHIP, + /// Swiped: the magnetic stripe was read. + MAGSTRIPE, + /// Typed in by hand. + MANUAL, + /// The terminal did not say, or said something else. + UNKNOWN + } + + /// How the cardholder proved they hold the card. + public enum Verification { + /// A PIN, checked online or by the chip. + PIN, + /// A signature, which the merchant must collect on the receipt. + SIGNATURE, + /// The device the customer tapped verified them (a phone's + /// biometrics or passcode). + CONSUMER_DEVICE, + /// No verification: a low-value contactless payment. + NONE, + /// The terminal did not say. + UNKNOWN + } + + private String brand; + private String maskedPan; + private String applicationId; + private String applicationLabel; + private EntryMode entryMode = EntryMode.UNKNOWN; + private Verification verification = Verification.UNKNOWN; + private String authorizationCode; + private String terminalId; + private String merchantId; + private String[] merchantReceipt; + private String[] customerReceipt; + + /// The card brand as the terminal named it, such as `visa`. + public String getBrand() { + return brand; + } + + /// Sets [#getBrand()]. + /// + /// #### Returns + /// + /// this receipt + public CardReceipt setBrand(String brand) { + this.brand = brand; + return this; + } + + /// The card number with all but the last four digits hidden, as the + /// terminal formatted it. + public String getMaskedPan() { + return maskedPan; + } + + /// Sets [#getMaskedPan()]. + /// + /// #### Returns + /// + /// this receipt + public CardReceipt setMaskedPan(String maskedPan) { + this.maskedPan = maskedPan; + return this; + } + + /// The EMV application identifier (AID), such as `A0000000031010`. + public String getApplicationId() { + return applicationId; + } + + /// Sets [#getApplicationId()]. + /// + /// #### Returns + /// + /// this receipt + public CardReceipt setApplicationId(String applicationId) { + this.applicationId = applicationId; + return this; + } + + /// The EMV application label, such as `VISA CREDIT`. + public String getApplicationLabel() { + return applicationLabel; + } + + /// Sets [#getApplicationLabel()]. + /// + /// #### Returns + /// + /// this receipt + public CardReceipt setApplicationLabel(String applicationLabel) { + this.applicationLabel = applicationLabel; + return this; + } + + /// How the card was read; never null. + public EntryMode getEntryMode() { + return entryMode; + } + + /// Sets [#getEntryMode()]. + /// + /// #### Returns + /// + /// this receipt + public CardReceipt setEntryMode(EntryMode entryMode) { + this.entryMode = entryMode == null ? EntryMode.UNKNOWN : entryMode; + return this; + } + + /// How the cardholder was verified; never null. + public Verification getVerification() { + return verification; + } + + /// Sets [#getVerification()]. + /// + /// #### Returns + /// + /// this receipt + public CardReceipt setVerification(Verification verification) { + this.verification = verification == null ? Verification.UNKNOWN : verification; + return this; + } + + /// The issuer's authorization code. + public String getAuthorizationCode() { + return authorizationCode; + } + + /// Sets [#getAuthorizationCode()]. + /// + /// #### Returns + /// + /// this receipt + public CardReceipt setAuthorizationCode(String authorizationCode) { + this.authorizationCode = authorizationCode; + return this; + } + + /// The terminal's ID at the acquirer (the TID). + public String getTerminalId() { + return terminalId; + } + + /// Sets [#getTerminalId()]. + /// + /// #### Returns + /// + /// this receipt + public CardReceipt setTerminalId(String terminalId) { + this.terminalId = terminalId; + return this; + } + + /// The merchant's ID at the acquirer (the MID). + public String getMerchantId() { + return merchantId; + } + + /// Sets [#getMerchantId()]. + /// + /// #### Returns + /// + /// this receipt + public CardReceipt setMerchantId(String merchantId) { + this.merchantId = merchantId; + return this; + } + + /// The merchant's copy of the receipt, line by line, as the terminal + /// composed it; null when it composed none. + public String[] getMerchantReceipt() { + return copy(merchantReceipt); + } + + /// Sets [#getMerchantReceipt()]. + /// + /// #### Returns + /// + /// this receipt + public CardReceipt setMerchantReceipt(String[] lines) { + this.merchantReceipt = copy(lines); + return this; + } + + /// The customer's copy of the receipt, line by line, as the terminal + /// composed it; null when it composed none. + public String[] getCustomerReceipt() { + return copy(customerReceipt); + } + + /// Sets [#getCustomerReceipt()]. + /// + /// #### Returns + /// + /// this receipt + public CardReceipt setCustomerReceipt(String[] lines) { + this.customerReceipt = copy(lines); + return this; + } + + private static String[] copy(String[] lines) { + if (lines == null) { + return null; + } + String[] out = new String[lines.length]; + System.arraycopy(lines, 0, out, 0, lines.length); + return out; + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/HttpTerminalTransport.java b/CodenameOne/src/com/codename1/payment/terminal/HttpTerminalTransport.java new file mode 100644 index 00000000000..573670d7bd6 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/HttpTerminalTransport.java @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal; + +import com.codename1.io.ConnectionRequest; +import com.codename1.io.NetworkManager; +import com.codename1.io.Util; +import com.codename1.ui.CN; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; + +/// The default [TerminalTransport], over [ConnectionRequest]. +/// +/// Error statuses are answered like any other: a provider's error body is +/// what says why a request failed, so it is read and handed on rather than +/// turned into a dialog. +public class HttpTerminalTransport implements TerminalTransport { + private int timeout = 180000; + private boolean insecure; + + /// The read timeout in milliseconds. Defaults to three minutes, because + /// a synchronous terminal request is answered only once the customer has + /// tapped (Adyen's `/sync` waits up to 150 seconds). + /// + /// #### Parameters + /// + /// - `timeout`: the timeout in milliseconds + public void setTimeout(int timeout) { + this.timeout = timeout; + } + + /// Makes sure a request can run while a long one holds a network thread. + /// Adyen's `/sync` payment stays open until the customer taps; with the + /// default single network thread, the abort that cancels it would wait + /// behind it and arrive only after the payment had ended, and every other + /// request of the app would wait too. Raises the thread count to two, + /// only while the queue is idle, because restarting the threads drops + /// whatever they are running. The count stays at two afterwards. + /// + /// #### Returns + /// + /// true when two or more network threads are running + /// Skips the platform's certificate check, for a terminal on the shop's + /// network whose certificate names no host a device can verify. Only for + /// a protocol that authenticates its messages itself, as Adyen's local + /// Terminal API does with its shared key: without that, anyone on the + /// network could answer in the terminal's place. + /// + /// #### Parameters + /// + /// - `insecure`: true to skip the check + public void setInsecure(boolean insecure) { + this.insecure = insecure; + } + + public boolean prepareForLongRequest() { + NetworkManager nm = NetworkManager.getInstance(); + if (nm.getThreadCount() >= 2) { + return true; + } + if (!nm.isQueueIdle()) { + return false; + } + nm.updateThreadCount(2); + return true; + } + + @Override + public void send(String method, String url, Map headers, + String contentType, String body, final Callback callback) { + Request req = new Request(callback); + req.setUrl(url); + req.setPost("POST".equals(method)); + req.setHttpMethod(method); + req.setReadResponseForErrors(true); + req.setFailSilently(true); + req.setDuplicateSupported(true); + req.setTimeout(timeout); + req.setInsecure(insecure); + req.setReadTimeout(timeout); + for (Map.Entry h : headers.entrySet()) { + req.addRequestHeader(h.getKey(), h.getValue()); + } + if (body != null) { + if (contentType != null) { + req.setContentType(contentType); + } + req.setRequestBody(body); + } + NetworkManager.getInstance().addToQueue(req); + } + + /// One terminal request. Equal only to itself: two requests to the same + /// URL are two payments, never a duplicate to merge. + private static final class Request extends ConnectionRequest { + private final Callback callback; + private String responseBody = ""; + private boolean answered; + + Request(Callback callback) { + this.callback = callback; + } + + @Override + protected void readResponse(InputStream input) throws IOException { + responseBody = Util.readToString(input, "UTF-8"); + } + + @Override + protected void handleErrorResponseCode(int code, String message) { + // Answered in postResponse with the body; no dialog. + } + + @Override + protected void handleException(final Exception err) { + if (answered) { + return; + } + answered = true; + CN.callSerially(new Runnable() { + @Override + public void run() { + callback.onError(err); + } + }); + } + + @Override + protected void postResponse() { + if (answered) { + return; + } + answered = true; + callback.onResponse(getResponseCode(), responseBody); + } + + @Override + public boolean equals(Object o) { + return o == this; + } + + @Override + public int hashCode() { + return System.identityHashCode(this); + } + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/PaymentTerminal.java b/CodenameOne/src/com/codename1/payment/terminal/PaymentTerminal.java new file mode 100644 index 00000000000..500e7281c2d --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/PaymentTerminal.java @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal; + +import com.codename1.util.AsyncResource; + +/// A card terminal: takes in-person payments and, where the terminal +/// supports it, everything a point of sale does around them -- refunds, +/// reversals, pre-authorizations and their capture, lookups after a lost +/// connection, and the end-of-day reconciliation. +/// +/// Every operation answers the same way: a resource that completes on the +/// EDT with a [TerminalResult] once the terminal decided -- approved, +/// declined, canceled or failed. It completes with an error only when the +/// terminal could not be asked at all (no connection, a rejected +/// credential, a malformed answer), so a decline is never an exception. +/// One error is special: a [TerminalOutcomeUnknownException] means the +/// card may have been charged, and the app must look the payment up before +/// charging again. +/// +/// Not every terminal can do everything. [#supports(TerminalOperation)] +/// says what this one can; an unsupported operation completes with an +/// [UnsupportedOperationException] without touching the card. +/// +/// For every operation, [TerminalResult.Status#APPROVED] means the +/// operation went through: the sale was charged, the reversal or refund was +/// accepted, the capture took the money. A lookup reports the payment's own +/// status instead. +/// +/// One operation that drives the terminal itself (a sale, or a refund taken +/// on the card) runs at a time per terminal; starting a second completes it +/// with an [IllegalStateException] and leaves the first alone. Operations a +/// provider carries out on its servers without the terminal may run +/// alongside one. +/// +/// The implementations in this tree: +/// +/// - `com.codename1.payment.terminal.tap.TapToPay` -- the phone itself reads +/// the card (Tap to Pay on iPhone and Android, over the Stripe Terminal SDK). +/// - `com.codename1.payment.terminal.stripe.StripeReaderTerminal` -- a Stripe +/// smart reader on the counter, driven over Stripe's API. +/// - `com.codename1.payment.terminal.adyen.AdyenCloudTerminal` and +/// `AdyenLocalTerminal` -- any Adyen terminal, through Adyen's cloud or +/// directly over the shop's network. +/// - `com.codename1.payment.terminal.square.SquareTerminal` -- a Square +/// Terminal, through Square's API. +public abstract class PaymentTerminal { + /// Whether this terminal can perform `operation`. + /// + /// #### Parameters + /// + /// - `operation`: the operation to ask about + /// + /// #### Returns + /// + /// true when [#collect(TerminalPaymentRequest)] or the matching method + /// can carry it out + public abstract boolean supports(TerminalOperation operation); + + /// Takes a payment: a sale, or a pre-authorization when the request + /// says so. + /// + /// #### Parameters + /// + /// - `request`: what to charge + /// + /// #### Returns + /// + /// the outcome, delivered on the EDT + public abstract AsyncResource collect(TerminalPaymentRequest request); + + /// Asks the terminal to abandon the operation in progress. + /// + /// Best effort: a card that was already read may still be approved, so + /// the outcome is whatever the operation delivers, [TerminalResult.Status#CANCELED] + /// when the cancel won. Does nothing when nothing is in progress. + public abstract void cancel(); + + /// Takes money a pre-authorization reserved. Needs + /// [TerminalOperation#CAPTURE]. + /// + /// #### Parameters + /// + /// - `transactionId`: the pre-authorization's [TerminalResult#getTransactionId()] + /// + /// - `amount`: the amount to take, in the minor unit; at most the + /// reserved amount on most acquirers + /// + /// - `currency`: the ISO 4217 code + /// + /// #### Returns + /// + /// the outcome, delivered on the EDT + public AsyncResource capture(String transactionId, long amount, String currency) { + return unsupported(TerminalOperation.CAPTURE); + } + + /// Cancels a payment that has not settled yet, so it never reaches the + /// customer's statement. Once settled, use + /// [#refund(TerminalRefundRequest)]. Needs [TerminalOperation#REVERSAL]. + /// + /// #### Parameters + /// + /// - `transactionId`: the payment's [TerminalResult#getTransactionId()] + /// + /// #### Returns + /// + /// the outcome, delivered on the EDT + public AsyncResource reverse(String transactionId) { + return unsupported(TerminalOperation.REVERSAL); + } + + /// Returns money to a card. Needs [TerminalOperation#REFUND], or + /// [TerminalOperation#UNLINKED_REFUND] when the request names no + /// payment. + /// + /// #### Parameters + /// + /// - `request`: what to return, and to which payment + /// + /// #### Returns + /// + /// the outcome, delivered on the EDT + public AsyncResource refund(TerminalRefundRequest request) { + return unsupported(request != null && request.isUnlinked() + ? TerminalOperation.UNLINKED_REFUND : TerminalOperation.REFUND); + } + + /// Finds out what became of a payment -- the way to settle a + /// [TerminalOutcomeUnknownException]. Needs [TerminalOperation#LOOKUP]. + /// + /// #### Parameters + /// + /// - `reference`: the payment's [TerminalPaymentRequest#getReference()], + /// or its transaction ID where the terminal accepts one + /// + /// #### Returns + /// + /// the payment's result as the terminal or provider recorded it; + /// completes with an error when it has no such payment + public AsyncResource lookup(String reference) { + return unsupported(TerminalOperation.LOOKUP); + } + + /// Closes the day's batch and reports its totals. Needs + /// [TerminalOperation#RECONCILIATION]. + /// + /// #### Returns + /// + /// the report, delivered on the EDT + public AsyncResource reconcile() { + AsyncResource out = new AsyncResource(); + out.error(new UnsupportedOperationException( + "This terminal does not support " + TerminalOperation.RECONCILIATION)); + return out; + } + + /// A resource that has already failed because this terminal cannot + /// perform `operation`; for implementations. + /// + /// #### Parameters + /// + /// - `operation`: the operation refused + /// + /// #### Returns + /// + /// a failed resource + protected static AsyncResource unsupported(TerminalOperation operation) { + AsyncResource out = new AsyncResource(); + out.error(new UnsupportedOperationException("This terminal does not support " + operation)); + return out; + } + + /// A resource that has already failed with `error`; for implementations. + /// + /// #### Parameters + /// + /// - `error`: why + /// + /// #### Returns + /// + /// a failed resource + protected static AsyncResource failed(Throwable error) { + AsyncResource out = new AsyncResource(); + out.error(error); + return out; + } + + /// Rejects a request that asks for an option this terminal lacks; for + /// implementations. + /// + /// #### Parameters + /// + /// - `request`: the request about to be started + /// + /// #### Returns + /// + /// the operation the request needs and this terminal lacks, or null + /// when it can run + protected TerminalOperation missingCapability(TerminalPaymentRequest request) { + if (!supports(TerminalOperation.SALE) && !request.isPreAuthorization()) { + return TerminalOperation.SALE; + } + if (request.isPreAuthorization() && !supports(TerminalOperation.PRE_AUTHORIZATION)) { + return TerminalOperation.PRE_AUTHORIZATION; + } + if (request.isAskForTip() && !supports(TerminalOperation.TIPPING)) { + return TerminalOperation.TIPPING; + } + if (request.getCashbackAmount() > 0 && !supports(TerminalOperation.CASHBACK)) { + return TerminalOperation.CASHBACK; + } + return null; + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/TerminalOperation.java b/CodenameOne/src/com/codename1/payment/terminal/TerminalOperation.java new file mode 100644 index 00000000000..c11962c33cd --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/TerminalOperation.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal; + +/// The operations a [PaymentTerminal] can perform, as reported by +/// [PaymentTerminal#supports(TerminalOperation)]. +/// +/// A terminal asked for an operation it does not support completes the +/// request with an [UnsupportedOperationException] and never touches the +/// card, so checking first is a courtesy to the user rather than a safety +/// requirement. +public enum TerminalOperation { + /// Charge the card now: [PaymentTerminal#collect(TerminalPaymentRequest)]. + SALE, + /// Reserve an amount to capture later, as a hotel or a bar tab does: + /// [TerminalPaymentRequest#setPreAuthorization(boolean)]. + PRE_AUTHORIZATION, + /// Take money reserved by a pre-authorization: + /// [PaymentTerminal#capture(String, long, String)]. + CAPTURE, + /// Cancel a payment that has not settled yet, so it never shows on the + /// statement: [PaymentTerminal#reverse(String)]. + REVERSAL, + /// Return money for an earlier payment, by its transaction ID: + /// [PaymentTerminal#refund(TerminalRefundRequest)]. + REFUND, + /// Return money to a card presented now, with no earlier payment to + /// refer to. + UNLINKED_REFUND, + /// Find out what became of a payment, by the app's own reference: + /// [PaymentTerminal#lookup(String)]. + LOOKUP, + /// Close the day's batch and report its totals: + /// [PaymentTerminal#reconcile()]. + RECONCILIATION, + /// Let the customer add a tip on the terminal: + /// [TerminalPaymentRequest#setAskForTip(boolean)]. + TIPPING, + /// Hand the customer cash on top of the purchase: + /// [TerminalPaymentRequest#setCashbackAmount(long)]. + CASHBACK, + /// Report the data a card receipt must print, through + /// [TerminalResult#getReceipt()]. + RECEIPT_DATA +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/TerminalOutcomeUnknownException.java b/CodenameOne/src/com/codename1/payment/terminal/TerminalOutcomeUnknownException.java new file mode 100644 index 00000000000..28f149ccc23 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/TerminalOutcomeUnknownException.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal; + +import java.io.IOException; + +/// The terminal may or may not have charged the card, and could not say +/// which. +/// +/// This is the one failure a point-of-sale app must never treat as a +/// decline: charging again can take the money twice. Look the payment up +/// -- with [PaymentTerminal#lookup(String)] where the terminal supports it, +/// or on the provider's dashboard by [#getTransactionId()] or the request's +/// reference -- before asking the customer for another card. +public class TerminalOutcomeUnknownException extends IOException { + private final String transactionId; + + /// #### Parameters + /// + /// - `message`: what was known when contact was lost + /// + /// - `transactionId`: the provider's ID for the payment, or null when it + /// never assigned one + public TerminalOutcomeUnknownException(String message, String transactionId) { + super(message); + this.transactionId = transactionId; + } + + /// The provider's ID for the payment in doubt, or null. + public String getTransactionId() { + return transactionId; + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/TerminalPaymentRequest.java b/CodenameOne/src/com/codename1/payment/terminal/TerminalPaymentRequest.java new file mode 100644 index 00000000000..aa7d9994ef8 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/TerminalPaymentRequest.java @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal; + +/// What a [PaymentTerminal] should charge. +/// +/// The amount is in the currency's minor unit -- cents for USD, yen for JPY -- +/// the way every payment provider takes it, so no floating point rounding +/// ever reaches a price. +/// +/// ```java +/// TerminalPaymentRequest req = new TerminalPaymentRequest(1250, "USD") +/// .setReference("order-1042"); +/// ``` +public final class TerminalPaymentRequest { + private final long amount; + private final String currency; + private String reference; + private String providerReference; + private boolean preAuthorization; + private boolean askForTip; + private long tipAmount; + private long cashbackAmount; + + /// #### Parameters + /// + /// - `amount`: the amount in the currency's minor unit; must be positive + /// + /// - `currency`: the ISO 4217 code, such as `USD` + public TerminalPaymentRequest(long amount, String currency) { + if (amount <= 0) { + throw new IllegalArgumentException("amount must be positive: " + amount); + } + if (currency == null || currency.length() != 3) { + throw new IllegalArgumentException("currency must be an ISO 4217 code: " + currency); + } + this.amount = amount; + this.currency = currency; + } + + /// The amount in the currency's minor unit. + public long getAmount() { + return amount; + } + + /// The ISO 4217 currency code, as given. + public String getCurrency() { + return currency; + } + + /// The app's own identifier for the sale, such as an order number. + /// Sent to providers that record one, and what + /// [PaymentTerminal#lookup(String)] finds the payment by; may be null, + /// but a sale without one cannot be looked up after contact is lost. + public String getReference() { + return reference; + } + + /// Sets [#getReference()]. + /// + /// #### Returns + /// + /// this request + public TerminalPaymentRequest setReference(String reference) { + this.reference = reference; + return this; + } + + /// The provider-side payment this request completes, created by the + /// app's server: a Stripe PaymentIntent's client secret for `TapToPay`, + /// or its ID (`pi_...`) for `StripeReaderTerminal`. Most terminals need + /// none. + public String getProviderReference() { + return providerReference; + } + + /// Sets [#getProviderReference()]. + /// + /// #### Returns + /// + /// this request + public TerminalPaymentRequest setProviderReference(String providerReference) { + this.providerReference = providerReference; + return this; + } + + /// True to reserve the amount rather than charge it; the money moves + /// only on [PaymentTerminal#capture(String, long, String)]. Needs + /// [TerminalOperation#PRE_AUTHORIZATION]. + public boolean isPreAuthorization() { + return preAuthorization; + } + + /// Sets [#isPreAuthorization()]. + /// + /// #### Returns + /// + /// this request + public TerminalPaymentRequest setPreAuthorization(boolean preAuthorization) { + this.preAuthorization = preAuthorization; + return this; + } + + /// True to let the customer add a tip on the terminal before the card + /// is read. The tip comes back as [TerminalResult#getTipAmount()]. Needs + /// [TerminalOperation#TIPPING]. + public boolean isAskForTip() { + return askForTip; + } + + /// Sets [#isAskForTip()]. + /// + /// #### Returns + /// + /// this request + public TerminalPaymentRequest setAskForTip(boolean askForTip) { + this.askForTip = askForTip; + return this; + } + + /// A tip the app already knows, in the minor unit, included in + /// [#getAmount()] -- the terminal shows and reports it separately. + /// Zero for none. + public long getTipAmount() { + return tipAmount; + } + + /// Sets [#getTipAmount()]. + /// + /// #### Returns + /// + /// this request + public TerminalPaymentRequest setTipAmount(long tipAmount) { + if (tipAmount < 0 || tipAmount > amount) { + throw new IllegalArgumentException("tip must be between 0 and the amount: " + tipAmount); + } + this.tipAmount = tipAmount; + return this; + } + + /// Cash handed to the customer, in the minor unit, charged on top of + /// [#getAmount()]. Zero for none. Needs [TerminalOperation#CASHBACK], + /// and most acquirers allow it only for debit cards. + public long getCashbackAmount() { + return cashbackAmount; + } + + /// Sets [#getCashbackAmount()]. + /// + /// #### Returns + /// + /// this request + public TerminalPaymentRequest setCashbackAmount(long cashbackAmount) { + if (cashbackAmount < 0) { + throw new IllegalArgumentException("cashback must not be negative: " + cashbackAmount); + } + this.cashbackAmount = cashbackAmount; + return this; + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/TerminalReconciliation.java b/CodenameOne/src/com/codename1/payment/terminal/TerminalReconciliation.java new file mode 100644 index 00000000000..bc951793cae --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/TerminalReconciliation.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal; + +/// The outcome of [PaymentTerminal#reconcile()]: the terminal closed its +/// batch and sent it to the acquirer for settlement. +/// +/// The figures are the terminal's own. A provider that settles on its +/// servers reports what it knows; compare them with the app's records and +/// treat the acquirer's settlement report as authoritative. +public final class TerminalReconciliation { + private final boolean success; + private final int transactionCount; + private final long totalAmount; + private final String currency; + private final String message; + private final String[] receipt; + + /// #### Parameters + /// + /// - `success`: whether the terminal closed the batch + /// + /// - `transactionCount`: the number of payments in it, or -1 when the + /// terminal did not report it + /// + /// - `totalAmount`: their sum in the currency's minor unit, or -1 when + /// not reported + /// + /// - `currency`: the ISO 4217 code of the total, or null + /// + /// - `message`: the terminal's explanation, or null + /// + /// - `receipt`: the report as the terminal printed it, or null + public TerminalReconciliation(boolean success, int transactionCount, long totalAmount, + String currency, String message, String[] receipt) { + this.success = success; + this.transactionCount = transactionCount; + this.totalAmount = totalAmount; + this.currency = currency; + this.message = message; + if (receipt == null) { + this.receipt = null; + } else { + this.receipt = new String[receipt.length]; + System.arraycopy(receipt, 0, this.receipt, 0, receipt.length); + } + } + + /// Whether the terminal closed the batch. + public boolean isSuccess() { + return success; + } + + /// The number of payments in the batch, or -1 when not reported. + public int getTransactionCount() { + return transactionCount; + } + + /// Their sum in the currency's minor unit, or -1 when not reported. + public long getTotalAmount() { + return totalAmount; + } + + /// The ISO 4217 code of the total, or null. + public String getCurrency() { + return currency; + } + + /// The terminal's explanation, or null. + public String getMessage() { + return message; + } + + /// The report as the terminal printed it, line by line, or null. + public String[] getReceipt() { + if (receipt == null) { + return null; + } + String[] out = new String[receipt.length]; + System.arraycopy(receipt, 0, out, 0, receipt.length); + return out; + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/TerminalRefundRequest.java b/CodenameOne/src/com/codename1/payment/terminal/TerminalRefundRequest.java new file mode 100644 index 00000000000..63e60f40e74 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/TerminalRefundRequest.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal; + +/// What a [PaymentTerminal#refund(TerminalRefundRequest)] should return. +/// +/// A linked refund names the payment it returns money for, and goes back to +/// that card without the customer present where the provider allows it. An +/// unlinked refund names none: the customer presents a card on the +/// terminal, and the money goes to that card. Terminals that support only +/// one kind say so through [TerminalOperation#REFUND] and +/// [TerminalOperation#UNLINKED_REFUND]. +/// +/// ```java +/// TerminalRefundRequest linked = new TerminalRefundRequest(500, "USD") +/// .setOriginalTransactionId("pi_3Nk..."); +/// ``` +public final class TerminalRefundRequest { + private final long amount; + private final String currency; + private String originalTransactionId; + private String reference; + + /// #### Parameters + /// + /// - `amount`: the amount to return, in the currency's minor unit; must + /// be positive. A partial refund is an amount below the original's. + /// + /// - `currency`: the ISO 4217 code, such as `USD` + public TerminalRefundRequest(long amount, String currency) { + if (amount <= 0) { + throw new IllegalArgumentException("amount must be positive: " + amount); + } + if (currency == null || currency.length() != 3) { + throw new IllegalArgumentException("currency must be an ISO 4217 code: " + currency); + } + this.amount = amount; + this.currency = currency; + } + + /// The amount to return, in the currency's minor unit. + public long getAmount() { + return amount; + } + + /// The ISO 4217 currency code. + public String getCurrency() { + return currency; + } + + /// The transaction ID of the payment being refunded, as its + /// [TerminalResult#getTransactionId()] reported it; null for an unlinked + /// refund. + public String getOriginalTransactionId() { + return originalTransactionId; + } + + /// Sets [#getOriginalTransactionId()]. + /// + /// #### Returns + /// + /// this request + public TerminalRefundRequest setOriginalTransactionId(String originalTransactionId) { + this.originalTransactionId = originalTransactionId; + return this; + } + + /// True when the refund names no earlier payment. + public boolean isUnlinked() { + return originalTransactionId == null || originalTransactionId.length() == 0; + } + + /// The app's own identifier for the refund; may be null. + public String getReference() { + return reference; + } + + /// Sets [#getReference()]. + /// + /// #### Returns + /// + /// this request + public TerminalRefundRequest setReference(String reference) { + this.reference = reference; + return this; + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/TerminalResult.java b/CodenameOne/src/com/codename1/payment/terminal/TerminalResult.java new file mode 100644 index 00000000000..22156895b85 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/TerminalResult.java @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal; + +/// The outcome of one operation on a [PaymentTerminal]: a sale, a +/// pre-authorization, a capture, a reversal, a refund or a lookup. +/// +/// Only [Status#APPROVED] means money moved (or, for a pre-authorization, +/// was reserved). The transaction ID is the provider's own -- a Stripe +/// PaymentIntent ID, an Adyen PSP reference, a ZVT receipt number -- and is +/// what the app's server should look the payment up by before it fulfills +/// an order: a result on a device is a report, not proof. +/// +/// When a terminal cannot tell whether the card was charged, the request +/// completes with a [TerminalOutcomeUnknownException] instead of a result, +/// so a FAILED result always means no money moved. +public final class TerminalResult { + /// How an operation ended. + public enum Status { + /// The card was charged (or authorized, for a pre-authorization), + /// or the refund, capture or reversal went through. + APPROVED, + /// The card or its issuer refused the payment. + DECLINED, + /// The customer or the app abandoned the operation. + CANCELED, + /// The terminal reported an error that is neither a decline nor a + /// cancel, such as a timeout reading the card. No money moved. + FAILED + } + + private final Status status; + private final String transactionId; + private final String message; + private final long approvedAmount; + private final long tipAmount; + private final String currency; + private final String reference; + private final CardReceipt receipt; + + /// #### Parameters + /// + /// - `status`: how the operation ended; never null + /// + /// - `transactionId`: the provider's ID for the payment, or null + /// + /// - `message`: the provider's explanation, or null + public TerminalResult(Status status, String transactionId, String message) { + this(new Builder(status).transactionId(transactionId).message(message)); + } + + private TerminalResult(Builder b) { + if (b.status == null) { + throw new IllegalArgumentException("status"); + } + this.status = b.status; + this.transactionId = b.transactionId; + this.message = b.message; + this.approvedAmount = b.approvedAmount; + this.tipAmount = b.tipAmount; + this.currency = b.currency; + this.reference = b.reference; + this.receipt = b.receipt; + } + + /// How the operation ended. + public Status getStatus() { + return status; + } + + /// True for [Status#APPROVED]. + public boolean isApproved() { + return status == Status.APPROVED; + } + + /// The provider's identifier for the payment, or null when the provider + /// gave none. Pass it to capture, reverse or refund the payment later. + public String getTransactionId() { + return transactionId; + } + + /// The provider's explanation (a decline code, an error message), or + /// null. + public String getMessage() { + return message; + } + + /// The amount the terminal reported approved, in the minor unit, tip + /// and cashback included; -1 when it did not report one. Can be less + /// than requested when the issuer approved part of it. + public long getApprovedAmount() { + return approvedAmount; + } + + /// The tip included in [#getApprovedAmount()], in the minor unit; 0 for + /// none. + public long getTipAmount() { + return tipAmount; + } + + /// The ISO 4217 code of the amounts, or null when not reported. + public String getCurrency() { + return currency; + } + + /// The app's reference for the operation, as the request carried it or + /// a lookup found it; may be null. + public String getReference() { + return reference; + } + + /// The data a card receipt must show, or null when the terminal + /// reported none. + public CardReceipt getReceipt() { + return receipt; + } + + @Override + public String toString() { + return "TerminalResult[" + status + ", " + transactionId + ", " + message + "]"; + } + + /// Assembles a [TerminalResult]; what each terminal implementation uses. + public static final class Builder { + private final Status status; + private String transactionId; + private String message; + private long approvedAmount = -1; + private long tipAmount; + private String currency; + private String reference; + private CardReceipt receipt; + + /// #### Parameters + /// + /// - `status`: how the operation ended; never null + public Builder(Status status) { + if (status == null) { + throw new IllegalArgumentException("status"); + } + this.status = status; + } + + /// Sets [TerminalResult#getTransactionId()]. + /// + /// #### Returns + /// + /// this builder + public Builder transactionId(String transactionId) { + this.transactionId = transactionId; + return this; + } + + /// Sets [TerminalResult#getMessage()]. + /// + /// #### Returns + /// + /// this builder + public Builder message(String message) { + this.message = message; + return this; + } + + /// Sets [TerminalResult#getApprovedAmount()] and + /// [TerminalResult#getCurrency()]. + /// + /// #### Returns + /// + /// this builder + public Builder amount(long approvedAmount, String currency) { + this.approvedAmount = approvedAmount; + this.currency = currency; + return this; + } + + /// Sets [TerminalResult#getTipAmount()]. + /// + /// #### Returns + /// + /// this builder + public Builder tip(long tipAmount) { + this.tipAmount = tipAmount; + return this; + } + + /// Sets [TerminalResult#getReference()]. + /// + /// #### Returns + /// + /// this builder + public Builder reference(String reference) { + this.reference = reference; + return this; + } + + /// Sets [TerminalResult#getReceipt()]. + /// + /// #### Returns + /// + /// this builder + public Builder receipt(CardReceipt receipt) { + this.receipt = receipt; + return this; + } + + /// The result. + public TerminalResult build() { + return new TerminalResult(this); + } + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/TerminalTransport.java b/CodenameOne/src/com/codename1/payment/terminal/TerminalTransport.java new file mode 100644 index 00000000000..fe6729b9f53 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/TerminalTransport.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal; + +import java.util.Map; + +/// How a network terminal reaches its provider: one HTTP exchange. +/// +/// [HttpTerminalTransport] is the default and goes through Codename One's +/// network stack. Supply another to route requests through your own server +/// (so the credential never ships in the app), to add tracing, or to script +/// a test. +public interface TerminalTransport { + /// Receives the outcome of one [#send]. + /// A callback that ignores the answer: for a request whose outcome some + /// other request reports, such as a cancel. + Callback IGNORE = new Callback() { + @Override + public void onResponse(int status, String body) { + } + + @Override + public void onError(Throwable error) { + } + }; + + interface Callback { + /// The server answered, with any status. + /// + /// #### Parameters + /// + /// - `status`: the HTTP status code + /// + /// - `body`: the response body as UTF-8, empty when there was none + void onResponse(int status, String body); + + /// No answer: the connection failed or timed out. + /// + /// #### Parameters + /// + /// - `error`: what went wrong + void onError(Throwable error); + } + + /// Performs one request. Exactly one of the callback's methods must be + /// called, on the EDT. + /// + /// #### Parameters + /// + /// - `method`: `GET` or `POST` + /// + /// - `url`: the absolute URL + /// + /// - `headers`: request headers; may be empty, never null + /// + /// - `contentType`: the body's content type, or null for a bodiless request + /// + /// - `body`: the request body, or null + /// + /// - `callback`: receives the outcome + void send(String method, String url, Map headers, + String contentType, String body, Callback callback); +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/adyen/AdyenCloudTerminal.java b/CodenameOne/src/com/codename1/payment/terminal/adyen/AdyenCloudTerminal.java new file mode 100644 index 00000000000..70dd8efc01b --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/adyen/AdyenCloudTerminal.java @@ -0,0 +1,822 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal.adyen; + +import com.codename1.io.JSONParser; +import com.codename1.io.Log; +import com.codename1.payment.terminal.CardReceipt; +import com.codename1.payment.terminal.HttpTerminalTransport; +import com.codename1.payment.terminal.PaymentTerminal; +import com.codename1.payment.terminal.TerminalOperation; +import com.codename1.payment.terminal.TerminalOutcomeUnknownException; +import com.codename1.payment.terminal.TerminalPaymentRequest; +import com.codename1.payment.terminal.TerminalRefundRequest; +import com.codename1.payment.terminal.TerminalResult; +import com.codename1.payment.terminal.TerminalTransport; +import com.codename1.ui.CN; +import com.codename1.util.AsyncResource; +import java.io.IOException; +import java.util.Calendar; +import java.util.Date; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; + +/// Any Adyen payment terminal, through Adyen's cloud Terminal API. +/// +/// Each payment is one synchronous `PaymentRequest` to Adyen's `/sync` +/// endpoint, answered once the customer has tapped (or after about 150 +/// seconds). It is plain HTTPS and JSON, so it works on every platform -- +/// the desktop ports, mobile and the web -- with no native SDK. +/// +/// #### Credentials +/// +/// The cloud Terminal API takes an API key, which must not ship in an app a +/// customer can install. On a till you control, use a key whose only role is +/// the Terminal API. Otherwise point [#setEndpoint(String)] at your own +/// server, which adds the key and forwards the body to Adyen. +/// +/// ```java +/// String apiKey = null; // null: your endpoint adds the key +/// AdyenCloudTerminal terminal = new AdyenCloudTerminal(apiKey, "POS-1", "V400m-346403161"); +/// terminal.collect(new TerminalPaymentRequest(1099, "EUR").setReference("order-7")) +/// .ready(result -> System.out.println(result)); +/// ``` +/// +/// Starts against Adyen's test environment; call [#setLive(boolean)] for +/// production. +/// +/// #### What else it does +/// +/// - Pre-authorizations (`authorisationType=PreAuth`); capture them from +/// your server with Adyen's Checkout API, which needs the secret key this +/// class must not hold. +/// - [#reverse(String)] reverses a payment by its PSP reference. +/// - [#refund(TerminalRefundRequest)] refunds a payment by its PSP +/// reference, or, without one, pays the amount to whichever card is +/// presented (an unlinked refund, which the merchant account must allow). +/// - Tipping on the terminal and cashback. +/// - [#lookup(String)] asks the terminal what became of a payment this +/// object started, by its reference. +/// - Receipt lines and card fields from the terminal's `PaymentReceipt`. +public class AdyenCloudTerminal extends PaymentTerminal { + private static final String TEST_BASE = "https://terminal-api-test.adyen.com"; + /// How often a lost answer is followed up with a status request: past + /// the 150 seconds a terminal waits for a card. + private static final int STATUS_ATTEMPTS = 32; + private static final int STATUS_RETRY_DELAY = 5000; + private static final String LIVE_BASE = "https://terminal-api-live.adyen.com"; + + private final String apiKey; + private final String saleId; + private final String poiId; + private String base = TEST_BASE; + private TerminalTransport transport = new HttpTerminalTransport(); + private static int serviceCounter; + + private AsyncResource pending; + private String pendingServiceId; + private String pendingCategory; + private boolean cancelRequested; + /// ServiceIDs of the payments started here, by reference, for lookup. + private final Map serviceIds = new HashMap(); + + /// #### Parameters + /// + /// - `apiKey`: the Terminal API key, sent as `X-API-Key`; may be null when + /// the transport or your own server authenticates instead + /// + /// - `saleId`: your identifier for this point of sale, such as a till + /// number + /// + /// - `poiId`: the terminal's ID, `[model]-[serial number]` + public AdyenCloudTerminal(String apiKey, String saleId, String poiId) { + if (saleId == null || saleId.length() == 0) { + throw new IllegalArgumentException("saleId"); + } + if (poiId == null || poiId.length() == 0) { + throw new IllegalArgumentException("poiId"); + } + this.apiKey = apiKey; + this.saleId = saleId; + this.poiId = poiId; + } + + /// Switches between Adyen's test (the default) and live endpoints. + /// + /// #### Parameters + /// + /// - `live`: true for production + public void setLive(boolean live) { + base = live ? LIVE_BASE : TEST_BASE; + } + + /// Sends requests to another base URL, such as a server of yours that + /// adds the API key. The paths `/sync` and `/async` are appended. + /// + /// #### Parameters + /// + /// - `endpoint`: the base URL, with no trailing slash + public void setEndpoint(String endpoint) { + base = endpoint; + } + + /// Replaces the HTTP transport. + /// + /// #### Parameters + /// + /// - `transport`: the transport + public void setTransport(TerminalTransport transport) { + this.transport = transport; + } + + @Override + public boolean supports(TerminalOperation operation) { + switch (operation) { + case SALE: + case PRE_AUTHORIZATION: + case REVERSAL: + case REFUND: + case UNLINKED_REFUND: + case LOOKUP: + case TIPPING: + case CASHBACK: + case RECEIPT_DATA: + return true; + default: + return false; + } + } + + @Override + public AsyncResource collect(TerminalPaymentRequest request) { + TerminalOperation missing = missingCapability(request); + if (missing != null) { + return unsupported(missing); + } + String serviceId = nextServiceId(); + String reference = request.getReference() != null ? request.getReference() : serviceId; + StringBuilder acquirer = new StringBuilder(); + if (request.isPreAuthorization()) { + acquirer.append("authorisationType=PreAuth"); + } + if (request.isAskForTip()) { + acquirer.append(acquirer.length() > 0 ? "&" : "").append("tenderOption=AskGratuity"); + } + StringBuilder amounts = new StringBuilder(); + amounts.append("{\"Currency\":").append(quote(request.getCurrency())) + .append(",\"RequestedAmount\":").append(majorUnits(request.getAmount(), request.getCurrency())); + if (request.getTipAmount() > 0) { + amounts.append(",\"TipAmount\":").append(majorUnits(request.getTipAmount(), request.getCurrency())); + } + if (request.getCashbackAmount() > 0) { + amounts.append(",\"CashBackAmount\":") + .append(majorUnits(request.getCashbackAmount(), request.getCurrency())); + } + amounts.append('}'); + String body = "\"PaymentRequest\":{" + saleData(reference, acquirer.toString()) + "," + + "\"PaymentTransaction\":{\"AmountsReq\":" + amounts + "}}"; + return run("Payment", serviceId, reference, body); + } + + @Override + public AsyncResource refund(TerminalRefundRequest request) { + String serviceId = nextServiceId(); + String reference = request.getReference() != null ? request.getReference() : serviceId; + if (!request.isUnlinked()) { + // A referenced refund is a reversal with an amount; it needs no card. + String body = "\"ReversalRequest\":{" + original(request.getOriginalTransactionId()) + "," + + "\"ReversalReason\":\"MerchantCancel\",\"ReversedAmount\":" + + majorUnits(request.getAmount(), request.getCurrency()) + "}"; + return run("Reversal", serviceId, null, body); + } + String body = "\"PaymentRequest\":{" + saleData(reference, "") + "," + + "\"PaymentTransaction\":{\"AmountsReq\":{\"Currency\":" + quote(request.getCurrency()) + + ",\"RequestedAmount\":" + majorUnits(request.getAmount(), request.getCurrency()) + "}}," + + "\"PaymentData\":{\"PaymentType\":\"Refund\"}}"; + return run("Payment", serviceId, reference, body); + } + + @Override + public AsyncResource reverse(String transactionId) { + if (transactionId == null || transactionId.length() == 0) { + return failed(new IllegalArgumentException("transactionId")); + } + String serviceId = nextServiceId(); + String body = "\"ReversalRequest\":{" + original(transactionId) + "," + + "\"ReversalReason\":\"MerchantCancel\"}"; + return run("Reversal", serviceId, null, body); + } + + /// Asks the terminal what became of a payment started by this object, + /// by the reference it was started with. The terminal keeps its recent + /// transactions only, and a payment started by another process cannot + /// be found this way; look those up in Adyen's Customer Area or through + /// your server's webhooks. + @Override + public AsyncResource lookup(String reference) { + final AsyncResource out = new AsyncResource(); + String serviceId = reference == null ? null : serviceIds.get(reference); + if (serviceId == null) { + out.error(new IOException("No payment with reference " + reference + " was started here")); + return out; + } + transport.send("POST", base + "/sync", headers(), "application/json", + statusRequest("Payment", serviceId), new LookupCallback(out)); + return out; + } + + /// The payment being reversed or refunded. Adyen identifies it by the + /// `tenderReference.pspReference` the payment answered with, which is + /// what [TerminalResult#getTransactionId()] carries. + private String original(String transactionId) { + return "\"OriginalPOITransaction\":{\"SaleID\":" + quote(saleId) + ",\"POIID\":" + quote(poiId) + + ",\"POITransactionID\":{\"TransactionID\":" + quote(transactionId) + + ",\"TimeStamp\":" + quote(timestamp()) + "}}"; + } + + private String saleData(String reference, String acquirerData) { + return "\"SaleData\":{\"SaleTransactionID\":{\"TransactionID\":" + quote(reference) + + ",\"TimeStamp\":" + quote(timestamp()) + "}" + + (acquirerData.length() > 0 ? ",\"SaleToAcquirerData\":" + quote(acquirerData) : "") + + "}"; + } + + /// Sends one request of `category` (Payment or Reversal) and follows a + /// lost answer up with status requests. + private AsyncResource run(final String category, final String serviceId, String reference, + String requestBody) { + final AsyncResource out = new AsyncResource(); + if (pending != null) { + out.error(new IllegalStateException("An operation is already in progress on " + poiId)); + return out; + } + pending = out; + pendingServiceId = serviceId; + pendingCategory = category; + cancelRequested = false; + if (reference != null) { + serviceIds.put(reference, serviceId); + } + String body = "{\"SaleToPOIRequest\":{" + header(category, serviceId) + "," + requestBody + "}}"; + if (transport instanceof HttpTerminalTransport + && !((HttpTerminalTransport) transport).prepareForLongRequest()) { + Log.p("AdyenCloudTerminal: one network thread is busy; cancel() will reach the terminal" + + " only after the request ends", Log.WARNING); + } + transport.send("POST", base + "/sync", headers(), "application/json", body, + new TerminalTransport.Callback() { + @Override + public void onResponse(int status, String responseBody) { + if (pending != out) { //NOPMD CompareObjectsWithEquals - identity: is this still the operation in flight + return; + } + if (status == 429 || status >= 500 + || responseBody == null || responseBody.trim().length() == 0) { + // The terminal may still be taking the payment. + checkStatus(out, serviceId, 0); + return; + } + if (status < 200 || status >= 300) { + // Rejected before it reached the terminal. + fail(new IOException("Adyen answered HTTP " + status + ": " + responseBody)); + return; + } + try { + finish(parseResponse(responseBody, cancelRequested)); + } catch (IOException e) { + checkStatus(out, serviceId, 0); + } + } + + @Override + public void onError(Throwable error) { + if (pending == out) { //NOPMD CompareObjectsWithEquals - identity: is this still the operation in flight + // A dropped connection says nothing about the + // payment, which may have been charged: ask. + checkStatus(out, serviceId, 0); + } + } + }); + return out; + } + + @Override + public void cancel() { + if (pending == null || cancelRequested) { + return; + } + cancelRequested = true; + // The synchronous payment request answers with the outcome. + sendAbort(pendingServiceId, pendingCategory); + } + + private void sendAbort(String serviceId, String category) { + String body = "{\"SaleToPOIRequest\":{" + + header("Abort", nextServiceId()) + "," + + "\"AbortRequest\":{\"AbortReason\":\"MerchantAbort\",\"MessageReference\":{" + + "\"MessageCategory\":" + quote(category) + ",\"SaleID\":" + quote(saleId) + + ",\"ServiceID\":" + quote(serviceId) + "}}}}"; + transport.send("POST", base + "/async", headers(), "application/json", body, + TerminalTransport.IGNORE); + } + + /// Asks the terminal what became of the payment `serviceId` after its + /// answer was lost, so a charged card is never reported as an error that + /// invites a second charge. Repeats while the terminal says the payment + /// is still in progress, up to [#STATUS_ATTEMPTS] times. + private void checkStatus(final AsyncResource out, final String serviceId, + final int attempt) { + if (pending != out) { //NOPMD CompareObjectsWithEquals - identity: is this still the payment in flight + return; + } + if (attempt >= STATUS_ATTEMPTS) { + // Stop the terminal from finishing a payment nobody is waiting + // for any more; it may still have been charged already. + sendAbort(serviceId, pendingCategory); + fail(new TerminalOutcomeUnknownException("The answer from Adyen was lost and the outcome is unknown;" + + " look up sale " + saleId + " service " + serviceId + " before charging again", serviceId)); + return; + } + transport.send("POST", base + "/sync", headers(), "application/json", + statusRequest(pendingCategory, serviceId), + new TerminalTransport.Callback() { + @Override + public void onResponse(int status, String responseBody) { + if (pending != out) { //NOPMD CompareObjectsWithEquals - identity: is this still the payment in flight + return; + } + TerminalResult r = null; + if (status >= 200 && status < 300) { + try { + r = parseStatusResponse(responseBody, cancelRequested); + } catch (IOException e) { + r = null; + } + } + if (r != null) { + finish(r); + } else { + retryStatus(out, serviceId, attempt); + } + } + + @Override + public void onError(Throwable error) { + retryStatus(out, serviceId, attempt); + } + }); + } + + private String statusRequest(String category, String serviceId) { + return "{\"SaleToPOIRequest\":{" + + header("TransactionStatus", nextServiceId()) + "," + + "\"TransactionStatusRequest\":{\"ReceiptReprintFlag\":true," + + "\"DocumentQualifier\":[\"CashierReceipt\",\"CustomerReceipt\"]," + + "\"MessageReference\":{\"MessageCategory\":" + quote(category) + ",\"SaleID\":" + quote(saleId) + + ",\"ServiceID\":" + quote(serviceId) + "}}}}"; + } + + private void retryStatus(final AsyncResource out, final String serviceId, + final int attempt) { + schedule(STATUS_RETRY_DELAY, new Runnable() { + @Override + public void run() { + checkStatus(out, serviceId, attempt + 1); + } + }); + } + + /// Runs `task` on the EDT after `delay` milliseconds. Overridable so a + /// subclass can drive the retries from its own clock. + /// + /// #### Parameters + /// + /// - `delay`: the delay in milliseconds + /// + /// - `task`: what to run + protected void schedule(int delay, Runnable task) { + CN.setTimeout(delay, task); + } + + /// Maps a `TransactionStatus` answer to the payment's result, or null + /// while the outcome is not known yet (in progress, or no answer the + /// terminal could find). Package-private for the tests. + static TerminalResult parseStatusResponse(String body, boolean cancelRequested) throws IOException { + if (body == null || body.trim().length() == 0) { + return null; + } + Map root = JSONParser.parseJSON(body); + Map resp = map(root.get("SaleToPOIResponse")); + Map status = resp == null ? null : map(resp.get("TransactionStatusResponse")); + Map response = status == null ? null : map(status.get("Response")); + if (response == null || !"Success".equals(string(response.get("Result")))) { + return null; + } + Map repeated = map(status.get("RepeatedMessageResponse")); + Map body2 = repeated == null ? null + : map(repeated.get("RepeatedResponseMessageBody")); + Map payment = body2 == null ? null : map(body2.get("PaymentResponse")); + if (payment == null && body2 != null) { + payment = map(body2.get("ReversalResponse")); + } + return payment == null ? null : parsePayment(payment, cancelRequested); + } + + /// Maps a `/sync` answer to a result. Package-private for the tests. + static TerminalResult parseResponse(String body, boolean cancelRequested) throws IOException { + if (body == null || body.trim().length() == 0) { + throw new IOException("Adyen answered an empty body"); + } + Map root = JSONParser.parseJSON(body); + Map resp = map(root.get("SaleToPOIResponse")); + Map payment = resp == null ? null : map(resp.get("PaymentResponse")); + if (payment == null && resp != null) { + payment = map(resp.get("ReversalResponse")); + } + if (payment == null) { + // An EventNotification (the terminal rejected the request + // outright) arrives inside a SaleToPOIRequest. + Map req = map(root.get("SaleToPOIRequest")); + Map event = req == null ? null : map(req.get("EventNotification")); + String detail = event == null ? null : string(event.get("EventDetails")); + if (detail == null && event != null) { + detail = string(event.get("EventToNotify")); + } + return new TerminalResult(TerminalResult.Status.FAILED, null, + detail != null ? detail : "Adyen answered no PaymentResponse"); + } + return parsePayment(payment, cancelRequested); + } + + private static TerminalResult parsePayment(Map payment, boolean cancelRequested) { + Map response = map(payment.get("Response")); + String result = response == null ? null : string(response.get("Result")); + String condition = response == null ? null : string(response.get("ErrorCondition")); + String additional = response == null ? null : string(response.get("AdditionalResponse")); + // tenderReference.pspReference: the identifier a referenced refund + // or reversal needs. The bare pspReference only when it is missing. + Map poiData = map(payment.get("POIData")); + Map poiTx = poiData == null ? null : map(poiData.get("POITransactionID")); + String pspReference = poiTx == null ? null : string(poiTx.get("TransactionID")); + if (pspReference == null) { + pspReference = formValue(additional, "pspReference"); + } + if ("Success".equals(result) || "Partial".equals(result)) { + TerminalResult.Builder b = new TerminalResult.Builder(TerminalResult.Status.APPROVED) + .transactionId(pspReference).receipt(receipt(payment, additional)); + Map pr = map(payment.get("PaymentResult")); + Map amounts = pr == null ? null : map(pr.get("AmountsResp")); + if (amounts != null) { + String currency = string(amounts.get("Currency")); + long authorized = minorUnits(amounts.get("AuthorizedAmount"), currency); + if (authorized >= 0 && currency != null) { + b.amount(authorized, currency); + } + long tip = minorUnits(amounts.get("TipAmount"), currency); + if (tip > 0) { + b.tip(tip); + } + } + Map sale = map(payment.get("SaleData")); + Map saleTx = sale == null ? null : map(sale.get("SaleTransactionID")); + if (saleTx != null) { + b.reference(string(saleTx.get("TransactionID"))); + } + return b.build(); + } + String message = formValue(additional, "refusalReason"); + if (message == null) { + message = formValue(additional, "message"); + } + if (message == null) { + message = condition; + } + TerminalResult.Status s; + // The terminal's own condition wins: a refusal that lands after the + // cashier pressed cancel is still a refusal. + if ("Refusal".equals(condition)) { + s = TerminalResult.Status.DECLINED; + } else if ("Aborted".equals(condition) || "Cancel".equals(condition) || cancelRequested) { + s = TerminalResult.Status.CANCELED; + } else { + s = TerminalResult.Status.FAILED; + } + return new TerminalResult(s, pspReference, message); + } + + /// The card fields and printable lines of a payment answer. + private static CardReceipt receipt(Map payment, String additional) { + CardReceipt r = new CardReceipt(); + boolean any = false; + String brand = formValue(additional, "paymentMethod"); + if (brand != null) { + r.setBrand(brand); + any = true; + } + String last4 = formValue(additional, "cardSummary"); + if (last4 != null) { + r.setMaskedPan("**** **** **** " + last4); + any = true; + } + String auth = formValue(additional, "authCode"); + if (auth != null) { + r.setAuthorizationCode(auth); + any = true; + } + String aid = formValue(additional, "AID"); + if (aid != null) { + r.setApplicationId(aid); + any = true; + } + String label = formValue(additional, "applicationPreferredName"); + if (label != null) { + r.setApplicationLabel(label); + } + String posEntry = formValue(additional, "posEntryMode"); + if (posEntry != null) { + if (posEntry.indexOf("CLESS") >= 0 || posEntry.indexOf("CONTACTLESS") >= 0) { + r.setEntryMode(CardReceipt.EntryMode.CONTACTLESS); + } else if (posEntry.indexOf("ICC") >= 0 || posEntry.indexOf("CHIP") >= 0) { + r.setEntryMode(CardReceipt.EntryMode.CHIP); + } else if (posEntry.indexOf("MAGSTRIPE") >= 0 || posEntry.indexOf("SWIPE") >= 0) { + r.setEntryMode(CardReceipt.EntryMode.MAGSTRIPE); + } + } + Object receipts = payment.get("PaymentReceipt"); + if (receipts instanceof List) { + for (Object o : (List) receipts) { + Map pr = map(o); + if (pr == null) { + continue; + } + String[] lines = receiptLines(map(pr.get("OutputContent"))); + if ("CustomerReceipt".equals(string(pr.get("DocumentQualifier")))) { + r.setCustomerReceipt(lines); + } else { + r.setMerchantReceipt(lines); + } + any = true; + } + } + return any ? r : null; + } + + /// The printable lines of an `OutputContent`: each `OutputText` is a + /// URL-encoded `name=...&value=...` pair. + private static String[] receiptLines(Map content) { + List out = new ArrayList(); + Object texts = content == null ? null : content.get("OutputText"); + if (texts instanceof List) { + for (Object o : (List) texts) { + Map t = map(o); + String text = t == null ? null : string(t.get("Text")); + if (text == null) { + continue; + } + String name = formValue(text, "name"); + String value = formValue(text, "value"); + if (name == null && value == null) { + out.add(text); + } else if (name == null || name.length() == 0) { + out.add(value); + } else if (value == null || value.length() == 0) { + out.add(name); + } else { + out.add(name + ": " + value); + } + } + } + return out.toArray(new String[out.size()]); + } + + /// Reads a decimal amount as minor units; -1 when absent. + static long minorUnits(Object amount, String currency) { + if (!(amount instanceof Number) || currency == null) { + return -1; + } + int exponent = exponent(currency); + double scale = exponent == 0 ? 1 : exponent == 3 ? 1000 : 100; + double v = ((Number) amount).doubleValue() * scale; + return (long) Math.floor(v + 0.5); + } + + /// Formats a minor-unit amount as the decimal Adyen expects, by the + /// currency's ISO 4217 exponent. Package-private for the tests. + static String majorUnits(long minor, String currency) { + int exponent = exponent(currency); + if (exponent == 0) { + return Long.toString(minor); + } + long div = exponent == 3 ? 1000L : 100L; + String frac = Long.toString(minor % div); + while (frac.length() < exponent) { + frac = "0" + frac; + } + return (minor / div) + "." + frac; + } + + private static int exponent(String currency) { + // Folded by hand: toUpperCase() is locale sensitive, and a Turkish + // device would turn the i of an ISO code into a dotted capital. + StringBuilder u = new StringBuilder(currency.length()); + for (int i = 0; i < currency.length(); i++) { + char ch = currency.charAt(i); + u.append(ch >= 'a' && ch <= 'z' ? (char) (ch - ('a' - 'A')) : ch); + } + String c = u.toString(); + String zero = ",BIF,CLP,DJF,GNF,ISK,JPY,KMF,KRW,PYG,RWF,UGX,UYI,VND,VUV,XAF,XOF,XPF,"; + String three = ",BHD,IQD,JOD,KWD,LYD,OMR,TND,"; + if (zero.indexOf("," + c + ",") >= 0) { + return 0; + } + if (three.indexOf("," + c + ",") >= 0) { + return 3; + } + return 2; + } + + private String header(String category, String serviceId) { + return "\"MessageHeader\":{\"ProtocolVersion\":\"3.0\",\"MessageClass\":\"Service\"," + + "\"MessageCategory\":" + quote(category) + ",\"MessageType\":\"Request\"," + + "\"SaleID\":" + quote(saleId) + ",\"ServiceID\":" + quote(serviceId) + + ",\"POIID\":" + quote(poiId) + "}"; + } + + private Map headers() { + Map h = new HashMap(); + if (apiKey != null) { + h.put("X-API-Key", apiKey); + } + return h; + } + + private void finish(TerminalResult r) { + AsyncResource out = pending; + pending = null; + out.complete(r); + } + + private void fail(Throwable t) { + AsyncResource out = pending; + pending = null; + out.error(t); + } + + /// A ServiceID: at most ten characters and unique per sale within a + /// day. The low digits of the clock plus a counter satisfy both. + private static String nextServiceId() { + serviceCounter = (serviceCounter + 1) % 100; + long t = (System.currentTimeMillis() / 10) % 100000000L; + String c = Integer.toString(serviceCounter); + return t + (c.length() < 2 ? "0" + c : c); + } + + /// ISO 8601 in UTC, which the Terminal API requires for TimeStamp. + private static String timestamp() { + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + cal.setTime(new Date()); + return cal.get(Calendar.YEAR) + "-" + pad(cal.get(Calendar.MONTH) + 1, 2) + + "-" + pad(cal.get(Calendar.DAY_OF_MONTH), 2) + + "T" + pad(cal.get(Calendar.HOUR_OF_DAY), 2) + + ":" + pad(cal.get(Calendar.MINUTE), 2) + + ":" + pad(cal.get(Calendar.SECOND), 2) + + "." + pad(cal.get(Calendar.MILLISECOND), 3) + "Z"; + } + + private static String pad(int v, int width) { + String s = Integer.toString(v); + while (s.length() < width) { + s = "0" + s; + } + return s; + } + + /// A JSON string literal. + static String quote(String s) { + StringBuilder b = new StringBuilder(s.length() + 2); + b.append('"'); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '"' || c == '\\') { + b.append('\\').append(c); + } else if (c < 0x20) { + String hex = Integer.toHexString(c); + b.append("\\u"); + for (int k = hex.length(); k < 4; k++) { + b.append('0'); + } + b.append(hex); + } else { + b.append(c); + } + } + return b.append('"').toString(); + } + + /// Reads one key out of Adyen's `AdditionalResponse`, a URL-encoded + /// `k=v&k=v` string. + private static String formValue(String form, String key) { + if (form == null) { + return null; + } + String prefix = key + "="; + int start = 0; + while (start <= form.length()) { + int end = form.indexOf('&', start); + if (end < 0) { + end = form.length(); + } + if (form.startsWith(prefix, start)) { + return decode(form.substring(start + prefix.length(), end)); + } + start = end + 1; + } + return null; + } + + private static String decode(String s) { + StringBuilder b = new StringBuilder(s.length()); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '+') { + b.append(' '); + } else if (c == '%' && i + 2 < s.length() && isHex(s.charAt(i + 1)) && isHex(s.charAt(i + 2))) { + // Byte-wise: the keys read here (pspReference, refusalReason, + // message) are ASCII. + b.append((char) Integer.parseInt(s.substring(i + 1, i + 3), 16)); + i += 2; + } else { + b.append(c); + } + } + return b.toString(); + } + + private static boolean isHex(char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + } + + @SuppressWarnings("unchecked") + private static Map map(Object o) { + return o instanceof Map ? (Map) o : null; + } + + private static String string(Object o) { + return o instanceof String ? (String) o : null; + } + + /// Delivers a lookup's status answer. + private static final class LookupCallback implements TerminalTransport.Callback { + private final AsyncResource out; + + LookupCallback(AsyncResource out) { + this.out = out; + } + + @Override + public void onResponse(int status, String responseBody) { + TerminalResult r = null; + if (status >= 200 && status < 300) { + try { + r = parseStatusResponse(responseBody, false); + } catch (IOException e) { + r = null; + } + } + if (r != null) { + out.complete(r); + } else { + out.error(new TerminalOutcomeUnknownException("The terminal could not report the" + + " payment yet; ask again shortly", null)); + } + } + + @Override + public void onError(Throwable error) { + out.error(error); + } + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/adyen/AdyenLocalTerminal.java b/CodenameOne/src/com/codename1/payment/terminal/adyen/AdyenLocalTerminal.java new file mode 100644 index 00000000000..9e2c47d0817 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/adyen/AdyenLocalTerminal.java @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal.adyen; + +import com.codename1.io.JSONParser; +import com.codename1.payment.terminal.HttpTerminalTransport; +import com.codename1.payment.terminal.TerminalTransport; +import com.codename1.security.Aes; +import com.codename1.security.Hash; +import com.codename1.security.Hmac; +import com.codename1.security.Pbkdf2; +import com.codename1.security.SecureRandom; +import com.codename1.util.Base64; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.Map; + +/// Any Adyen payment terminal, reached directly over the shop's network +/// with Adyen's local Terminal API -- no internet round trip, so a sale +/// keeps working when the till's connection to Adyen is slow. +/// +/// It speaks the same messages as [AdyenCloudTerminal] and does everything +/// it does. The difference is the transport: each message is encrypted +/// and authenticated with a key shared with the terminal, configured in +/// the Customer Area under the terminal's *Integrations* settings (key +/// identifier, passphrase and version). +/// +/// ```java +/// String passphrase = null; // load from secure storage, never ship it in code +/// AdyenLocalTerminal terminal = new AdyenLocalTerminal("192.168.1.40", "POS-1", "V400m-346403161", +/// "mykey", passphrase, 1); +/// terminal.collect(new TerminalPaymentRequest(1099, "EUR").setReference("order-7")) +/// .ready(result -> System.out.println(result)); +/// ``` +/// +/// #### Trust +/// +/// The terminal answers HTTPS on port 8443 with a certificate issued by +/// Adyen's own authority to a name no device can resolve, so the platform's +/// certificate check is skipped. What proves that an answer came from the +/// terminal is the message itself: every answer must carry an HMAC made +/// with the shared key, and one that does not is rejected. Keep the +/// passphrase out of the app's code and storage a customer can read. +public class AdyenLocalTerminal extends AdyenCloudTerminal { + private static final byte[] SALT = ascii("AdyenNexoV1Salt"); + private static final int ITERATIONS = 4000; + + private final String keyIdentifier; + private final int keyVersion; + private final byte[] hmacKey; + private final byte[] cipherKey; + private final byte[] ivBase; + + /// #### Parameters + /// + /// - `host`: the terminal's IP address or host name on the shop network + /// + /// - `saleId`: your identifier for this point of sale, such as a till + /// number + /// + /// - `poiId`: the terminal's ID, `[model]-[serial number]` + /// + /// - `keyIdentifier`: the shared key's identifier + /// + /// - `passphrase`: the shared key's passphrase + /// + /// - `keyVersion`: the shared key's version + public AdyenLocalTerminal(String host, String saleId, String poiId, String keyIdentifier, String passphrase, + int keyVersion) { + super(null, saleId, poiId); + if (host == null || host.length() == 0) { + throw new IllegalArgumentException("host"); + } + if (keyIdentifier == null || passphrase == null) { + throw new IllegalArgumentException("keyIdentifier and passphrase are required"); + } + this.keyIdentifier = keyIdentifier; + this.keyVersion = keyVersion; + // PBKDF2-HMAC-SHA1, 80 bytes: HMAC key, AES-256 key, IV base. + byte[] dk = Pbkdf2.derive(Hash.SHA1, utf8(passphrase), SALT, ITERATIONS, 80); + hmacKey = slice(dk, 0, 32); + cipherKey = slice(dk, 32, 32); + ivBase = slice(dk, 64, 16); + HttpTerminalTransport http = new HttpTerminalTransport(); + http.setInsecure(true); + super.setTransport(new Encrypting(http)); + super.setEndpoint("https://" + host + ":8443"); + } + + /// Replaces the transport underneath the encryption; every message + /// still goes through it encrypted. + /// + /// #### Parameters + /// + /// - `transport`: the transport + @Override + public void setTransport(TerminalTransport transport) { + super.setTransport(new Encrypting(transport)); + } + + /// Encrypts one message as `{"SaleToPOIRequest": {"MessageHeader", + /// "NexoBlob", "SecurityTrailer"}}`. Package-private for the tests. + String encrypt(String message) throws IOException { + byte[] plain = utf8(message); + byte[] nonce = SecureRandom.bytes(16); + byte[] cipher = Aes.cbcEncrypt(cipherKey, iv(nonce), pad(plain)); + byte[] mac = Hmac.sha256(hmacKey, plain); + Map root = JSONParser.parseJSON(message); + String category = root.containsKey("SaleToPOIResponse") ? "SaleToPOIResponse" : "SaleToPOIRequest"; + return "{" + quote(category) + ":{\"MessageHeader\":" + headerOf(message) + + ",\"NexoBlob\":" + quote(Base64.encodeNoNewline(cipher)) + + ",\"SecurityTrailer\":{\"AdyenCryptoVersion\":1,\"KeyIdentifier\":" + quote(keyIdentifier) + + ",\"KeyVersion\":" + keyVersion + + ",\"Nonce\":" + quote(Base64.encodeNoNewline(nonce)) + + ",\"Hmac\":" + quote(Base64.encodeNoNewline(mac)) + "}}}"; + } + + /// Decrypts and authenticates one message; throws when the HMAC does not + /// match. Package-private for the tests. + String decrypt(String envelope) throws IOException { + Map root = JSONParser.parseJSON(envelope); + Object inner = root.get("SaleToPOIResponse"); + if (!(inner instanceof Map)) { + inner = root.get("SaleToPOIRequest"); + } + if (!(inner instanceof Map)) { + throw new IOException("The terminal answered no Terminal API message"); + } + Map msg = (Map) inner; + Object blob = msg.get("NexoBlob"); + Object trailer = msg.get("SecurityTrailer"); + if (!(blob instanceof String) || !(trailer instanceof Map)) { + throw new IOException("The terminal answered an unencrypted message"); + } + Object nonceText = ((Map) trailer).get("Nonce"); + Object macText = ((Map) trailer).get("Hmac"); + if (!(nonceText instanceof String) || !(macText instanceof String)) { + throw new IOException("The terminal's message has no nonce or HMAC"); + } + byte[] nonce = Base64.decode(ascii((String) nonceText)); + byte[] cipher = Base64.decode(ascii((String) blob)); + if (nonce == null || nonce.length != 16 || cipher == null || cipher.length == 0 || cipher.length % 16 != 0) { + throw new IOException("The terminal's message is malformed"); + } + byte[] plain = unpad(Aes.cbcDecrypt(cipherKey, iv(nonce), cipher)); + byte[] mac = Base64.decode(ascii((String) macText)); + if (mac == null || !Hmac.constantTimeEquals(mac, Hmac.sha256(hmacKey, plain))) { + throw new IOException("The terminal's message failed authentication; check the shared key"); + } + return new String(plain, "UTF-8"); + } + + private byte[] iv(byte[] nonce) { + byte[] iv = new byte[16]; + for (int i = 0; i < 16; i++) { + iv[i] = (byte) (ivBase[i] ^ nonce[i]); + } + return iv; + } + + /// The MessageHeader object of a message this class built: it holds no + /// nested object, so it ends at the first closing brace. + private static String headerOf(String message) throws IOException { + String key = "\"MessageHeader\":"; + int start = message.indexOf(key); + int end = start < 0 ? -1 : message.indexOf('}', start); + if (end < 0) { + throw new IOException("The message has no MessageHeader"); + } + return message.substring(start + key.length(), end + 1); + } + + private static byte[] pad(byte[] data) { + int n = 16 - data.length % 16; + byte[] out = new byte[data.length + n]; + System.arraycopy(data, 0, out, 0, data.length); + for (int i = data.length; i < out.length; i++) { + out[i] = (byte) n; + } + return out; + } + + private static byte[] unpad(byte[] data) throws IOException { + int n = data[data.length - 1] & 0xff; + if (n < 1 || n > 16 || n > data.length) { + throw new IOException("The terminal's message failed authentication; check the shared key"); + } + return slice(data, 0, data.length - n); + } + + private static byte[] slice(byte[] a, int from, int len) { + byte[] out = new byte[len]; + System.arraycopy(a, from, out, 0, len); + return out; + } + + private static byte[] utf8(String s) { + try { + return s.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException("UTF-8"); //NOPMD PreserveStackTrace - UTF-8 always exists + } + } + + private static byte[] ascii(String s) { + byte[] b = new byte[s.length()]; + for (int i = 0; i < b.length; i++) { + b[i] = (byte) s.charAt(i); + } + return b; + } + + /// Encrypts every request body, sends it to `/nexo`, and hands the + /// callback the decrypted, authenticated answer. An answer that fails + /// authentication reaches the callback as a lost answer, so a payment in + /// flight is looked up rather than trusted. + private final class Encrypting implements TerminalTransport { + private final TerminalTransport inner; + + Encrypting(TerminalTransport inner) { + this.inner = inner; + } + + @Override + public void send(String method, String url, Map headers, String contentType, String body, + final Callback callback) { + String target = url; + int slash = url.lastIndexOf('/'); + if (slash > url.indexOf("//") + 1) { + target = url.substring(0, slash) + "/nexo"; + } + String wire; + try { + wire = body == null ? null : encrypt(body); + } catch (IOException e) { + callback.onError(e); + return; + } + inner.send(method, target, headers, contentType, wire, new Callback() { + @Override + public void onResponse(int status, String responseBody) { + if (responseBody == null || responseBody.trim().length() == 0 + || status < 200 || status >= 300) { + callback.onResponse(status, responseBody); + return; + } + String plain; + try { + plain = decrypt(responseBody); + } catch (IOException e) { + callback.onError(e); + return; + } + callback.onResponse(status, plain); + } + + @Override + public void onError(Throwable error) { + callback.onError(error); + } + }); + } + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/adyen/package-info.java b/CodenameOne/src/com/codename1/payment/terminal/adyen/package-info.java new file mode 100644 index 00000000000..d928bba0fbb --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/adyen/package-info.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/// Adyen payment terminals through Adyen's cloud Terminal API: +/// [AdyenCloudTerminal]. Plain HTTPS and JSON, so it works on every +/// platform. +package com.codename1.payment.terminal.adyen; diff --git a/CodenameOne/src/com/codename1/payment/terminal/mdb/MdbBus.java b/CodenameOne/src/com/codename1/payment/terminal/mdb/MdbBus.java new file mode 100644 index 00000000000..23ba521e225 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/mdb/MdbBus.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal.mdb; + +import java.io.IOException; + +/// The MDB bus as an adapter presents it. MDB runs 9-bit serial at 9600 +/// baud, which an ordinary serial port cannot send, so a vending +/// controller reaches it through an adapter board (USB or UART to MDB). +/// Implement this over your adapter's command set. +/// +/// The adapter owns the wire: it sets the mode bit on the address byte, +/// appends and checks the checksum, sends ACK, and retransmits on NAK. +public interface MdbBus { + /// Sends one command block and returns the peripheral's answer. + /// + /// #### Parameters + /// + /// - `block`: the address byte (with the command in its low three + /// bits) and the data, without the checksum + /// + /// - `timeout`: how long to wait, in milliseconds + /// + /// #### Returns + /// + /// the answer's data bytes without the checksum; an empty array for a + /// bare ACK; null when the peripheral did not answer + /// + /// #### Throws + /// + /// - `IOException`: when the adapter fails + byte[] transact(byte[] block, int timeout) throws IOException; +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/mdb/MdbCashlessTerminal.java b/CodenameOne/src/com/codename1/payment/terminal/mdb/MdbCashlessTerminal.java new file mode 100644 index 00000000000..22b121e67bb --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/mdb/MdbCashlessTerminal.java @@ -0,0 +1,405 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal.mdb; + +import com.codename1.payment.terminal.PaymentTerminal; +import com.codename1.payment.terminal.TerminalOperation; +import com.codename1.payment.terminal.TerminalOutcomeUnknownException; +import com.codename1.payment.terminal.TerminalPaymentRequest; +import com.codename1.payment.terminal.TerminalResult; +import com.codename1.ui.CN; +import com.codename1.util.AsyncResource; +import java.io.IOException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +/// A cashless reader on an MDB bus, driven by the app as the vending +/// machine controller (VMC), following MDB/ICP level 1 cashless device +/// commands. +/// +/// ```java +/// MdbBus myAdapter = (block, timeout) -> new byte[0]; // your adapter board +/// MdbCashlessTerminal reader = new MdbCashlessTerminal(myAdapter); +/// reader.setItemNumber(12); +/// reader.collect(new TerminalPaymentRequest(250, "EUR")).ready(result -> { +/// if (result.isApproved()) { +/// boolean ok = true; // whether the machine dispensed item 12 +/// reader.completeVend(ok); +/// } +/// }); +/// ``` +/// +/// A sale enables the reader and waits for the customer to present a card, +/// then asks to vend the price. An approval is delivered before anything is +/// dispensed; call [#completeVend(boolean)] once the product is out, or not, +/// so the reader settles or refunds. With [#setAutoComplete(boolean)] the +/// vend is reported successful at once, for a machine that cannot fail. +/// The approval is an authorization: a vend never completed within five +/// session timeouts is reported failed, and the reader refunds it. The +/// resource [#completeVend(boolean)] returns says whether the money was kept. +/// +/// Amounts convert through the reader's scale factor and decimal places +/// from its setup answer. +public class MdbCashlessTerminal extends PaymentTerminal { + private static final int ADDR = 0x10; + private static final int RESET = ADDR; + private static final int SETUP = ADDR | 1; + private static final int POLL = ADDR | 2; + private static final int VEND = ADDR | 3; + private static final int READER = ADDR | 4; + + private final MdbBus bus; + private int itemNumber = 0xffff; + private boolean autoComplete; + private int sessionTimeout = 60000; + private int scale = 1; + private int decimals = 2; + private boolean setUp; + private final AtomicBoolean busy = new AtomicBoolean(); + private final AtomicBoolean cancelRequested = new AtomicBoolean(); + /// 0 none, 1 dispensed, 2 failed. + private final AtomicInteger vendOutcome = new AtomicInteger(); + private final AtomicReference> settlement = + new AtomicReference>(new AsyncResource()); + + /// #### Parameters + /// + /// - `bus`: the adapter to the MDB bus + public MdbCashlessTerminal(MdbBus bus) { + this.bus = bus; + } + + /// The item number reported with each vend; 0xFFFF (the default) means + /// unspecified. + /// + /// #### Parameters + /// + /// - `itemNumber`: the product's number + public void setItemNumber(int itemNumber) { + this.itemNumber = itemNumber; + } + + /// Reports every approved vend as dispensed at once. + /// + /// #### Parameters + /// + /// - `autoComplete`: true to skip [#completeVend(boolean)] + public void setAutoComplete(boolean autoComplete) { + this.autoComplete = autoComplete; + } + + /// How long a sale waits for a card and for the reader's answer. + /// Defaults to a minute. + /// + /// #### Parameters + /// + /// - `sessionTimeout`: the limit in milliseconds + public void setSessionTimeout(int sessionTimeout) { + this.sessionTimeout = sessionTimeout; + } + + @Override + public boolean supports(TerminalOperation operation) { + return operation == TerminalOperation.SALE; + } + + @Override + public AsyncResource collect(TerminalPaymentRequest request) { + TerminalOperation missing = missingCapability(request); + if (missing != null) { + return unsupported(missing); + } + AsyncResource out = new AsyncResource(); + if (!busy.compareAndSet(false, true)) { + out.error(new IllegalStateException("The reader is busy")); + return out; + } + cancelRequested.set(false); + vendOutcome.set(0); + settlement.set(new AsyncResource()); + start(new Sale(request, out)); + return out; + } + + /// Tells the reader whether the approved product was dispensed. A + /// failed vend is refunded by the reader. + /// + /// #### Parameters + /// + /// - `dispensed`: true when the customer got the product + /// + /// #### Returns + /// + /// true once the reader has kept the payment, false when it refunded it + /// or the vend could not be reported to it (check the reader's journal) + public AsyncResource completeVend(boolean dispensed) { + AsyncResource s = settlement.get(); + vendOutcome.set(dispensed ? 1 : 2); + return s; + } + + /// Cancels a sale still waiting for a card or an approval. + @Override + public void cancel() { + cancelRequested.set(true); + } + + /// Runs `task` on a thread of its own; tests override it. + /// + /// #### Parameters + /// + /// - `task`: the blocking work + protected void start(Runnable task) { + new Thread(task, "MDB").start(); + } + + /// Hands a result to the app on the EDT; tests override it. + /// + /// #### Parameters + /// + /// - `task`: the delivery + protected void deliver(Runnable task) { + CN.callSerially(task); + } + + /// Waits between polls; tests override it. + /// + /// #### Parameters + /// + /// - `millis`: how long + protected void pause(int millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private byte[] cmd(int... bytes) throws IOException { + byte[] b = new byte[bytes.length]; + for (int i = 0; i < b.length; i++) { + b[i] = (byte) bytes[i]; + } + byte[] r = null; + for (int attempt = 0; attempt < 3 && r == null; attempt++) { + r = bus.transact(b, 200); + } + if (r == null) { + throw new IOException("The cashless reader does not answer"); + } + return r; + } + + private void setUpReader() throws IOException { + if (setUp) { + return; + } + cmd(RESET); + long end = System.currentTimeMillis() + 5000; + boolean config = false; + while (!config) { + byte[] r = cmd(SETUP, 0x00, 0x01, 0x00, 0x00, 0x00); + if (r.length >= 8 && r[0] == 0x01) { + scale = Math.max(1, r[4] & 0xff); + decimals = r[5] & 0xff; + config = true; + } else if (System.currentTimeMillis() > end) { + throw new IOException("The cashless reader sent no configuration"); + } else { + cmd(POLL); + pause(50); + } + } + cmd(SETUP, 0x01, 0xff, 0xff, 0x00, 0x00); + setUp = true; + } + + /// The amount in the reader's units: minor units of a two-decimal + /// currency, rescaled to the reader's decimals and divided by its scale. + private int toMdb(long amount) { + long v = amount; + for (int d = decimals; d < 2; d++) { + if (v % 10 != 0) { + throw new IllegalArgumentException("The reader cannot charge " + amount + + " with " + decimals + " decimals"); + } + v /= 10; + } + for (int d = 2; d < decimals; d++) { + v *= 10; + } + // The vend request carries 16 bits; a price the reader cannot + // express exactly must fail here, never be charged truncated. + if (v % scale != 0 || v / scale > 0xfffe || v < 0) { + throw new IllegalArgumentException("The reader cannot charge " + amount + + " (scale " + scale + ", " + decimals + " decimals)"); + } + return (int) (v / scale); + } + + private long fromMdb(int value) { + long v = (long) value * scale; + for (int d = decimals; d < 2; d++) { + v *= 10; + } + for (int d = 2; d < decimals; d++) { + v /= 10; + } + return v; + } + + /// Polls until the reader reports one of `wanted`, or a session end. + private byte[] pollFor(long deadline, int... wanted) throws IOException { + while (true) { + byte[] r = cmd(POLL); + if (r.length > 0) { + int code = r[0] & 0xff; + for (int w : wanted) { + if (code == w) { + return r; + } + } + if (code == 0x00) { + setUp = false; + throw new IOException("The cashless reader reset"); + } + } + if (System.currentTimeMillis() > deadline) { + return null; + } + pause(100); + } + } + + private final class Sale implements Runnable { + private final TerminalPaymentRequest request; + private final AsyncResource out; + + Sale(TerminalPaymentRequest request, AsyncResource out) { + this.request = request; + this.out = out; + } + + @Override + public void run() { + TerminalResult result = null; + Throwable error = null; + boolean approved = false; + boolean vendSent = false; + try { + setUpReader(); + // the reader's scale is known only after setup + int price = toMdb(request.getAmount()); + cmd(READER, 0x01); + long deadline = System.currentTimeMillis() + sessionTimeout; + byte[] begin = null; + while (begin == null && !cancelRequested.get() && System.currentTimeMillis() < deadline) { + begin = pollFor(System.currentTimeMillis() + 500, 0x03); + } + if (begin == null) { + cmd(READER, 0x00); + result = new TerminalResult.Builder(TerminalResult.Status.CANCELED) + .message(cancelRequested.get() ? "Canceled" : "No card presented") + .reference(request.getReference()).build(); + } else { + vendSent = true; + cmd(VEND, 0x00, price >> 8, price & 0xff, itemNumber >> 8, itemNumber & 0xff); + byte[] answer = pollFor(System.currentTimeMillis() + sessionTimeout, 0x05, 0x06, 0x04); + if (answer == null) { + throw new TerminalOutcomeUnknownException("The reader did not answer the vend", null); + } + if ((answer[0] & 0xff) == 0x05) { + approved = true; + int amt = answer.length >= 3 ? ((answer[1] & 0xff) << 8) | (answer[2] & 0xff) : price; + result = new TerminalResult.Builder(TerminalResult.Status.APPROVED) + .amount(fromMdb(amt), request.getCurrency()) + .reference(request.getReference()).build(); + } else { + result = new TerminalResult.Builder(TerminalResult.Status.DECLINED) + .message((answer[0] & 0xff) == 0x06 ? "Vend denied" : "The reader cancelled the session") + .reference(request.getReference()).build(); + } + } + } catch (TerminalOutcomeUnknownException e) { + error = e; + } catch (IOException e) { + error = vendSent ? unknown(e) : e; + } catch (RuntimeException e) { + error = e; + } + final TerminalResult r = result; + final Throwable e = error; + deliver(new Runnable() { + @Override + public void run() { + if (e != null) { + out.error(e); + } else { + out.complete(r); + } + } + }); + finish(approved && error == null); + } + + private TerminalOutcomeUnknownException unknown(Throwable cause) { + // The vend request went out: the reader may have approved it and + // may still settle, so this is never a plain failure. + TerminalOutcomeUnknownException u = new TerminalOutcomeUnknownException( + "Lost the reader after the vend request: " + cause.getMessage(), null); + u.initCause(cause); + return u; + } + + private void finish(boolean approved) { + AsyncResource settled = settlement.get(); + boolean kept = false; + try { + if (approved) { + if (autoComplete) { + vendOutcome.set(1); + } + long deadline = System.currentTimeMillis() + 5L * sessionTimeout; + while (vendOutcome.get() == 0 && System.currentTimeMillis() < deadline) { + pause(50); + } + if (vendOutcome.get() == 1) { + cmd(VEND, 0x02, itemNumber >> 8, itemNumber & 0xff); + kept = true; + } else { + cmd(VEND, 0x03); + } + } + cmd(VEND, 0x04); + pollFor(System.currentTimeMillis() + 5000, 0x07); + cmd(READER, 0x00); + } catch (IOException e) { + setUp = false; + } finally { + busy.set(false); + settled.complete(Boolean.valueOf(kept)); + } + } + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/mdb/package-info.java b/CodenameOne/src/com/codename1/payment/terminal/mdb/package-info.java new file mode 100644 index 00000000000..284f50b959e --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/mdb/package-info.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/// MDB cashless payment for vending machines: the app is the vending machine +/// controller and drives a card reader on the MDB bus through an adapter. +package com.codename1.payment.terminal.mdb; diff --git a/CodenameOne/src/com/codename1/payment/terminal/package-info.java b/CodenameOne/src/com/codename1/payment/terminal/package-info.java new file mode 100644 index 00000000000..f011c6fa581 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/package-info.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/// In-person card payments: card terminals behind one interface. +/// +/// A [PaymentTerminal] takes a [TerminalPaymentRequest] and answers with a +/// [TerminalResult]. Three kinds ship with Codename One: +/// +/// - `com.codename1.payment.terminal.tap` -- the phone itself is the reader +/// (Tap to Pay on iPhone and Android), over the Stripe Terminal SDK. +/// - `com.codename1.payment.terminal.stripe` -- a Stripe smart reader on the +/// counter, driven over Stripe's API. +/// - `com.codename1.payment.terminal.adyen` -- an Adyen terminal, through +/// Adyen's cloud Terminal API. +/// +/// The two network terminals are plain HTTPS, so they work on every +/// platform, desktop included, and add nothing to a build. Only the `tap` +/// package brings a native SDK, and only into apps that reference it. +/// +/// In-app purchases and Apple Pay / Google Pay checkout are a different +/// thing, in `com.codename1.payment`. +package com.codename1.payment.terminal; diff --git a/CodenameOne/src/com/codename1/payment/terminal/spi/TapToPayBridge.java b/CodenameOne/src/com/codename1/payment/terminal/spi/TapToPayBridge.java new file mode 100644 index 00000000000..6c0bf62479a --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/spi/TapToPayBridge.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal.spi; + +/// What a port implements to read a card with the phone itself. Not for +/// applications, which use `com.codename1.payment.terminal.tap.TapToPay`. +/// +/// Ports answer every request through +/// `com.codename1.payment.terminal.tap.TapToPayCallbacks`, from any thread; +/// the callbacks move to the EDT themselves. +public interface TapToPayBridge { + /// True when this device can read a card at all (the right hardware and + /// OS version, NFC present). Answers quickly, with no network. + /// + /// #### Returns + /// + /// whether Tap to Pay can run here + boolean isDeviceSupported(); + + /// Takes one payment: set up the SDK if needed, connect the phone as a + /// reader at `locationId`, retrieve the PaymentIntent and collect and + /// confirm it. Answered by `TapToPayCallbacks.deliverResult`. + /// + /// #### Parameters + /// + /// - `requestId`: echoed back with the outcome + /// + /// - `clientSecret`: the PaymentIntent's client secret + /// + /// - `amount`: the amount in minor units, as the app asked; the + /// PaymentIntent is authoritative, this is for simulators and logs + /// + /// - `currency`: the ISO 4217 code, as the app asked + /// + /// - `locationId`: the Stripe location the phone acts as a reader for + /// + /// - `merchantDisplayName`: the name on the payment sheet, or null + /// + /// - `simulated`: connect Stripe's simulated reader instead of the phone + void collect(int requestId, String clientSecret, long amount, String currency, + String locationId, String merchantDisplayName, boolean simulated); + + /// Cancels the collection `requestId` if it is still waiting for a card. + /// + /// #### Parameters + /// + /// - `requestId`: the request to cancel + void cancel(int requestId); + + /// Answers a `TapToPayCallbacks.fetchConnectionToken` request. + /// + /// #### Parameters + /// + /// - `tokenRequestId`: the ID the port asked with + /// + /// - `token`: the token, or null when `error` is set + /// + /// - `error`: why no token could be had, or null + void connectionTokenReady(int tokenRequestId, String token, String error); +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/spi/package-info.java b/CodenameOne/src/com/codename1/payment/terminal/spi/package-info.java new file mode 100644 index 00000000000..521a5ef6310 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/spi/package-info.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/// The port side of Tap to Pay: the interface each platform implements over +/// its payment SDK. Applications use `com.codename1.payment.terminal.tap`. +package com.codename1.payment.terminal.spi; diff --git a/CodenameOne/src/com/codename1/payment/terminal/square/SquareTerminal.java b/CodenameOne/src/com/codename1/payment/terminal/square/SquareTerminal.java new file mode 100644 index 00000000000..7e2b5280bb4 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/square/SquareTerminal.java @@ -0,0 +1,761 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal.square; + +import com.codename1.io.JSONParser; +import com.codename1.io.Util; +import com.codename1.payment.terminal.CardReceipt; +import com.codename1.payment.terminal.HttpTerminalTransport; +import com.codename1.payment.terminal.PaymentTerminal; +import com.codename1.payment.terminal.TerminalOperation; +import com.codename1.payment.terminal.TerminalOutcomeUnknownException; +import com.codename1.payment.terminal.TerminalPaymentRequest; +import com.codename1.payment.terminal.TerminalRefundRequest; +import com.codename1.payment.terminal.TerminalResult; +import com.codename1.payment.terminal.TerminalTransport; +import com.codename1.ui.CN; +import com.codename1.util.AsyncResource; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/// A Square Terminal, driven through Square's Terminal API. +/// +/// Each sale creates a terminal checkout for the paired device and polls it +/// until the customer has paid or it is canceled. It is plain HTTPS and +/// JSON, so it works on every platform with no native SDK. +/// +/// #### Credentials +/// +/// Square's API takes an access token, which must not ship in an app a +/// customer can install. On a till you control, use a token limited to the +/// `PAYMENTS_WRITE` and `PAYMENTS_READ` permissions. Otherwise point +/// [#setApiBase(String)] at your own server, which adds the token and +/// forwards the same paths to Square. +/// +/// ```java +/// String accessToken = null; // null: your server adds the token +/// SquareTerminal terminal = new SquareTerminal("121CS145A5000029", accessToken); +/// terminal.collect(new TerminalPaymentRequest(1250, "USD").setReference("order-7")) +/// .ready(result -> System.out.println(result)); +/// ``` +/// +/// #### What it does +/// +/// - Sales, with tipping on the device when the request asks for it. +/// - Pre-authorizations (the checkout does not complete the payment), then +/// [#capture(String, long, String)] completes it -- at the authorized +/// amount, which Square cannot lower on completion. +/// - [#reverse(String)] cancels a payment that is not completed yet. +/// - [#refund(TerminalRefundRequest)] refunds a payment by its ID; Square +/// needs no card for it, and refunds no card that is not linked to one. +/// - [#lookup(String)] reads a payment by its ID. +/// +/// Every request that moves money carries an idempotency key and is +/// repeated with the same key when its answer is lost, so a retry can +/// never charge twice. Starts against Square's sandbox; call +/// [#setLive(boolean)] for production. +public class SquareTerminal extends PaymentTerminal { + private static final String SANDBOX = "https://connect.squareupsandbox.com"; + private static final String LIVE = "https://connect.squareup.com"; + private static final String VERSION = "2024-07-17"; + /// Retries of a request whose answer was lost, with the same key. + private static final int RETRIES = 3; + private static int keyCounter; + + private final String deviceId; + private final String accessToken; + private String apiBase = SANDBOX; + private TerminalTransport transport = new HttpTerminalTransport(); + private int pollInterval = 1000; + private long maxWait = 5 * 60 * 1000L; + private Checkout current; + + /// #### Parameters + /// + /// - `deviceId`: the paired Square Terminal's device ID + /// + /// - `accessToken`: sent as a bearer token; may be null when your own + /// server adds it + public SquareTerminal(String deviceId, String accessToken) { + if (deviceId == null || deviceId.length() == 0) { + throw new IllegalArgumentException("deviceId"); + } + this.deviceId = deviceId; + this.accessToken = accessToken; + } + + /// Switches between Square's sandbox (the default) and production. + /// + /// #### Parameters + /// + /// - `live`: true for production + public void setLive(boolean live) { + apiBase = live ? LIVE : SANDBOX; + } + + /// Sends requests to another base URL, such as a server of yours that + /// adds the access token. + /// + /// #### Parameters + /// + /// - `apiBase`: the base URL, with no trailing slash + public void setApiBase(String apiBase) { + this.apiBase = apiBase; + } + + /// Replaces the HTTP transport. + /// + /// #### Parameters + /// + /// - `transport`: the transport + public void setTransport(TerminalTransport transport) { + this.transport = transport; + } + + /// How often the checkout is polled, in milliseconds. Defaults to one + /// second. + /// + /// #### Parameters + /// + /// - `pollInterval`: the interval in milliseconds + public void setPollInterval(int pollInterval) { + this.pollInterval = pollInterval; + } + + /// How long the device waits for the customer before the checkout times + /// out. Defaults to five minutes; Square accepts one to five. + /// + /// #### Parameters + /// + /// - `maxWait`: the limit in milliseconds + public void setMaxWait(long maxWait) { + this.maxWait = maxWait; + } + + @Override + public boolean supports(TerminalOperation operation) { + switch (operation) { + case SALE: + case PRE_AUTHORIZATION: + case CAPTURE: + case REVERSAL: + case REFUND: + case LOOKUP: + case TIPPING: + case RECEIPT_DATA: + return true; + default: + return false; + } + } + + @Override + public AsyncResource collect(TerminalPaymentRequest request) { + TerminalOperation missing = missingCapability(request); + if (missing != null) { + return unsupported(missing); + } + AsyncResource out = new AsyncResource(); + if (current != null) { + out.error(new IllegalStateException("A payment is already in progress on " + deviceId)); + return out; + } + final Checkout c = new Checkout(out, request.getReference()); + // The device ends the checkout at its deadline; past that plus a + // margin, an unreachable server leaves the outcome unknown. + c.giveUpAt = System.currentTimeMillis() + Math.max(60000L, Math.min(300000L, maxWait)) + 120000L; + current = c; + long seconds = Math.max(60, Math.min(300, maxWait / 1000)); + StringBuilder body = new StringBuilder(); + body.append("{\"idempotency_key\":").append(quote(nextKey())) + .append(",\"checkout\":{\"amount_money\":").append(money(request.getAmount(), request.getCurrency())) + .append(",\"deadline_duration\":\"PT").append(seconds).append("S\"") + .append(",\"device_options\":{\"device_id\":").append(quote(deviceId)) + .append(",\"skip_receipt_screen\":true") + .append(",\"tip_settings\":{\"allow_tipping\":").append(request.isAskForTip()).append("}}"); + if (request.getReference() != null) { + body.append(",\"reference_id\":").append(quote(request.getReference())); + } + if (request.isPreAuthorization()) { + body.append(",\"payment_options\":{\"autocomplete\":false}"); + } + body.append("}}"); + send("POST", "/v2/terminals/checkouts", body.toString(), 0, new Answer() { + @Override + void ok(Map json) { + Map co = map(json.get("checkout")); + String id = co == null ? null : string(co.get("id")); + if (id == null) { + fail(c, new IOException("Square answered no checkout ID")); + return; + } + c.checkoutId = id; + if (c.cancelRequested) { + sendCancel(c); + } + schedulePoll(c); + } + + @Override + void error(int status, String message) { + fail(c, new IOException(message)); + } + + @Override + void lost(Throwable why) { + // The checkout may be on the device: the customer can pay it. + fail(c, new TerminalOutcomeUnknownException("Square's answer was lost; the checkout may be on" + + " the device. Check it in the Square Dashboard before charging again", null)); + } + }); + return out; + } + + @Override + public void cancel() { + Checkout c = current; + if (c == null || c.cancelRequested) { + return; + } + c.cancelRequested = true; + if (c.checkoutId != null) { + sendCancel(c); + } + } + + private void sendCancel(Checkout c) { + // The next poll reads the outcome. + transport.send("POST", apiBase + "/v2/terminals/checkouts/" + Util.encodeUrl(c.checkoutId) + "/cancel", + headers(), "application/json", "{}", TerminalTransport.IGNORE); + } + + private void schedulePoll(final Checkout c) { + schedule(pollInterval, new Runnable() { + @Override + public void run() { + poll(c); + } + }); + } + + private void poll(final Checkout c) { + if (c.done) { + return; + } + if (System.currentTimeMillis() > c.giveUpAt) { + fail(c, new TerminalOutcomeUnknownException("Square stopped answering about checkout " + + c.checkoutId + "; check it before charging again", c.checkoutId)); + return; + } + transport.send("GET", apiBase + "/v2/terminals/checkouts/" + Util.encodeUrl(c.checkoutId), headers(), + null, null, new TerminalTransport.Callback() { + @Override + public void onResponse(int status, String body) { + if (c.done) { + return; + } + Map co = null; + if (status >= 200 && status < 300) { + try { + co = map(JSONParser.parseJSON(body == null ? "{}" : body).get("checkout")); + } catch (IOException e) { + co = null; + } + } + if (co == null || !evaluate(c, co)) { + // Keep polling through errors: the device decides, + // and the checkout's own deadline ends it. + schedulePoll(c); + } + } + + @Override + public void onError(Throwable error) { + if (!c.done) { + schedulePoll(c); + } + } + }); + } + + /// Reads a checkout; true when it reached an outcome. Package-private + /// for the tests. + boolean evaluate(Checkout c, Map checkout) { + String status = string(checkout.get("status")); + if ("COMPLETED".equals(status)) { + Object ids = checkout.get("payment_ids"); + String paymentId = ids instanceof List && !((List) ids).isEmpty() + ? string(((List) ids).get(0)) : null; + if (paymentId == null) { + finish(c, new TerminalResult.Builder(TerminalResult.Status.APPROVED) + .reference(c.reference).build()); + } else { + completed(c, paymentId); + } + return true; + } + if ("CANCELED".equals(status)) { + String reason = string(checkout.get("cancel_reason")); + TerminalResult.Status s = "TIMED_OUT".equals(reason) && !c.cancelRequested + ? TerminalResult.Status.FAILED : TerminalResult.Status.CANCELED; + finish(c, new TerminalResult.Builder(s).transactionId(c.checkoutId).message(reason) + .reference(c.reference).build()); + return true; + } + return false; + } + + /// The checkout completed: reads the payment for its amounts and card. + /// The money has moved, so a failure to read it still reports approval. + private void completed(final Checkout c, final String paymentId) { + transport.send("GET", apiBase + "/v2/payments/" + Util.encodeUrl(paymentId), headers(), null, null, + new TerminalTransport.Callback() { + @Override + public void onResponse(int status, String body) { + TerminalResult r = null; + if (status >= 200 && status < 300) { + try { + r = paymentResult(map(JSONParser.parseJSON(body == null ? "{}" : body) + .get("payment"))); + } catch (IOException e) { + r = null; + } + } + finish(c, r != null ? r : new TerminalResult.Builder(TerminalResult.Status.APPROVED) + .transactionId(paymentId).reference(c.reference).build()); + } + + @Override + public void onError(Throwable error) { + finish(c, new TerminalResult.Builder(TerminalResult.Status.APPROVED) + .transactionId(paymentId).reference(c.reference).build()); + } + }); + } + + @Override + public AsyncResource capture(String transactionId, long amount, String currency) { + if (transactionId == null || transactionId.length() == 0) { + return failed(new IllegalArgumentException("transactionId")); + } + return paymentCall("/v2/payments/" + Util.encodeUrl(transactionId) + "/complete", "{}", transactionId, + false); + } + + @Override + public AsyncResource reverse(String transactionId) { + if (transactionId == null || transactionId.length() == 0) { + return failed(new IllegalArgumentException("transactionId")); + } + return paymentCall("/v2/payments/" + Util.encodeUrl(transactionId) + "/cancel", "{}", transactionId, + true); + } + + @Override + public AsyncResource refund(TerminalRefundRequest request) { + if (request.isUnlinked()) { + return unsupported(TerminalOperation.UNLINKED_REFUND); + } + final AsyncResource out = new AsyncResource(); + final String paymentId = request.getOriginalTransactionId(); + StringBuilder body = new StringBuilder(); + body.append("{\"idempotency_key\":").append(quote(nextKey())) + .append(",\"payment_id\":").append(quote(paymentId)) + .append(",\"amount_money\":").append(money(request.getAmount(), request.getCurrency())); + if (request.getReference() != null) { + body.append(",\"reason\":").append(quote(request.getReference())); + } + body.append('}'); + send("POST", "/v2/refunds", body.toString(), 0, new Answer() { + @Override + void ok(Map json) { + out.complete(refundResult(map(json.get("refund")), paymentId)); + } + + @Override + void error(int status, String message) { + out.complete(new TerminalResult.Builder(TerminalResult.Status.FAILED).transactionId(paymentId) + .message(message).build()); + } + + @Override + void lost(Throwable why) { + out.error(new TerminalOutcomeUnknownException("Square's answer to the refund was lost; check " + + paymentId + " before retrying", paymentId)); + } + }); + return out; + } + + @Override + public AsyncResource lookup(String reference) { + final AsyncResource out = new AsyncResource(); + if (reference == null || reference.length() == 0) { + out.error(new IllegalArgumentException("reference")); + return out; + } + send("GET", "/v2/payments/" + Util.encodeUrl(reference), null, 0, new Answer() { + @Override + void ok(Map json) { + TerminalResult r = paymentResult(map(json.get("payment"))); + if (r == null) { + out.error(new IOException("Square answered no payment")); + } else { + out.complete(r); + } + } + + @Override + void error(int status, String message) { + out.error(new IOException(message)); + } + + @Override + void lost(Throwable why) { + out.error(why); + } + }); + return out; + } + + /// Completes or cancels a payment; a lost answer is an unknown outcome. + private AsyncResource paymentCall(String path, String body, final String paymentId, + final boolean isReversal) { + final AsyncResource out = new AsyncResource(); + send("POST", path, body, 0, new Answer() { + @Override + void ok(Map json) { + TerminalResult r = paymentResult(map(json.get("payment"))); + if (r == null) { + r = new TerminalResult.Builder(TerminalResult.Status.APPROVED).transactionId(paymentId).build(); + } else if (isReversal && r.getStatus() == TerminalResult.Status.CANCELED) { + // A canceled payment is a reversal that went through. + r = new TerminalResult.Builder(TerminalResult.Status.APPROVED).transactionId(paymentId) + .amount(r.getApprovedAmount(), r.getCurrency()).reference(r.getReference()).build(); + } + out.complete(r); + } + + @Override + void error(int status, String message) { + out.complete(new TerminalResult.Builder(TerminalResult.Status.FAILED).transactionId(paymentId) + .message(message).build()); + } + + @Override + void lost(Throwable why) { + out.error(new TerminalOutcomeUnknownException("Square's answer was lost; check " + paymentId + + " before retrying", paymentId)); + } + }); + return out; + } + + /// Sends one request, repeating it (with the same body, hence the same + /// idempotency key) while its answer is lost or Square is unavailable. + private void send(final String method, final String path, final String body, final int attempt, + final Answer answer) { + transport.send(method, apiBase + path, headers(), body == null ? null : "application/json", body, + new TerminalTransport.Callback() { + @Override + public void onResponse(int status, String text) { + if ((status == 429 || status >= 500) && attempt < RETRIES) { + retry(method, path, body, attempt, answer); + return; + } + Map json; + try { + json = JSONParser.parseJSON(text == null ? "{}" : text); + } catch (IOException e) { + if (attempt < RETRIES) { + retry(method, path, body, attempt, answer); + } else { + answer.lost(e); + } + return; + } + if (status == 429 || status >= 500) { + answer.lost(new IOException("Square answered HTTP " + status)); + } else if (status < 200 || status >= 300) { + answer.error(status, errorMessage(json, status)); + } else { + answer.ok(json); + } + } + + @Override + public void onError(Throwable error) { + if (attempt < RETRIES) { + retry(method, path, body, attempt, answer); + } else { + answer.lost(error); + } + } + }); + } + + private void retry(final String method, final String path, final String body, final int attempt, + final Answer answer) { + schedule(pollInterval, new Runnable() { + @Override + public void run() { + send(method, path, body, attempt + 1, answer); + } + }); + } + + /// Runs `task` on the EDT after `delay` milliseconds. Overridable so a + /// subclass can drive the polling from its own clock. + /// + /// #### Parameters + /// + /// - `delay`: the delay in milliseconds + /// + /// - `task`: what to run + protected void schedule(int delay, Runnable task) { + CN.setTimeout(delay, task); + } + + /// Maps a Square payment; null when there is none. Package-private for + /// the tests. + static TerminalResult paymentResult(Map payment) { + if (payment == null) { + return null; + } + String status = string(payment.get("status")); + TerminalResult.Status s; + if ("COMPLETED".equals(status) || "APPROVED".equals(status)) { + s = TerminalResult.Status.APPROVED; + } else if ("CANCELED".equals(status)) { + s = TerminalResult.Status.CANCELED; + } else if ("FAILED".equals(status)) { + s = TerminalResult.Status.DECLINED; + } else { + // PENDING: Square has not decided. + return null; + } + TerminalResult.Builder b = new TerminalResult.Builder(s).transactionId(string(payment.get("id"))) + .reference(string(payment.get("reference_id"))); + Map total = map(payment.get("total_money")); + if (total == null) { + total = map(payment.get("amount_money")); + } + if (total != null && total.get("amount") instanceof Number) { + b.amount(((Number) total.get("amount")).longValue(), string(total.get("currency"))); + } + Map tip = map(payment.get("tip_money")); + if (tip != null && tip.get("amount") instanceof Number) { + b.tip(((Number) tip.get("amount")).longValue()); + } + Map details = map(payment.get("card_details")); + if (details != null) { + b.receipt(receipt(details)); + if (s == TerminalResult.Status.DECLINED) { + b.message(string(details.get("status"))); + } + } + return b.build(); + } + + private static CardReceipt receipt(Map details) { + CardReceipt r = new CardReceipt(); + Map card = map(details.get("card")); + if (card != null) { + r.setBrand(string(card.get("card_brand"))); + String last4 = string(card.get("last_4")); + if (last4 != null) { + r.setMaskedPan("**** **** **** " + last4); + } + } + String entry = string(details.get("entry_method")); + if ("CONTACTLESS".equals(entry)) { + r.setEntryMode(CardReceipt.EntryMode.CONTACTLESS); + } else if ("EMV".equals(entry)) { + r.setEntryMode(CardReceipt.EntryMode.CHIP); + } else if ("SWIPED".equals(entry)) { + r.setEntryMode(CardReceipt.EntryMode.MAGSTRIPE); + } else if ("KEYED".equals(entry)) { + r.setEntryMode(CardReceipt.EntryMode.MANUAL); + } + r.setAuthorizationCode(string(details.get("auth_result_code"))); + r.setApplicationId(string(details.get("application_identifier"))); + r.setApplicationLabel(string(details.get("application_name"))); + String cvm = string(details.get("verification_method")); + if (cvm != null) { + if (cvm.indexOf("PIN") >= 0) { + r.setVerification(CardReceipt.Verification.PIN); + } else if (cvm.indexOf("SIGNATURE") >= 0) { + r.setVerification(CardReceipt.Verification.SIGNATURE); + } else if ("NONE".equals(cvm)) { + r.setVerification(CardReceipt.Verification.NONE); + } + } + return r; + } + + /// Maps a Square refund. Package-private for the tests. + static TerminalResult refundResult(Map refund, String paymentId) { + if (refund == null) { + return new TerminalResult.Builder(TerminalResult.Status.APPROVED).transactionId(paymentId).build(); + } + String status = string(refund.get("status")); + TerminalResult.Status s; + if ("COMPLETED".equals(status) || "PENDING".equals(status)) { + s = TerminalResult.Status.APPROVED; + } else if ("REJECTED".equals(status)) { + s = TerminalResult.Status.DECLINED; + } else { + s = TerminalResult.Status.FAILED; + } + TerminalResult.Builder b = new TerminalResult.Builder(s).transactionId(string(refund.get("id"))) + .message(status); + Map m = map(refund.get("amount_money")); + if (m != null && m.get("amount") instanceof Number) { + b.amount(((Number) m.get("amount")).longValue(), string(m.get("currency"))); + } + return b.build(); + } + + private void finish(Checkout c, TerminalResult r) { + if (c.done) { + return; + } + c.done = true; + if (current == c) { //NOPMD CompareObjectsWithEquals - identity: is this still the checkout in flight + current = null; + } + c.out.complete(r); + } + + private void fail(Checkout c, Throwable t) { + if (c.done) { + return; + } + c.done = true; + if (current == c) { //NOPMD CompareObjectsWithEquals - identity: is this still the checkout in flight + current = null; + } + c.out.error(t); + } + + private Map headers() { + Map h = new HashMap(); + if (accessToken != null) { + h.put("Authorization", "Bearer " + accessToken); + } + h.put("Square-Version", VERSION); + return h; + } + + private static String money(long amount, String currency) { + return "{\"amount\":" + amount + ",\"currency\":" + quote(upper(currency)) + "}"; + } + + /// A key unique to this request: the clock, a counter and a random + /// part, so two tills started in the same millisecond differ. + private static String nextKey() { + keyCounter++; + return Long.toString(System.currentTimeMillis(), 36) + "-" + keyCounter + "-" + + Long.toString((long) (Math.random() * Long.MAX_VALUE), 36); + } + + private static String errorMessage(Map json, int status) { + Object errors = json.get("errors"); + if (errors instanceof List && !((List) errors).isEmpty()) { + Map e = map(((List) errors).get(0)); + if (e != null) { + String detail = string(e.get("detail")); + return detail != null ? detail : string(e.get("code")); + } + } + return "Square answered HTTP " + status; + } + + /// A JSON string literal. + static String quote(String s) { + StringBuilder b = new StringBuilder(s.length() + 2); + b.append('"'); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '"' || c == '\\') { + b.append('\\').append(c); + } else if (c < 0x20) { + String hex = Integer.toHexString(c); + b.append("\\u"); + for (int k = hex.length(); k < 4; k++) { + b.append('0'); + } + b.append(hex); + } else { + b.append(c); + } + } + return b.append('"').toString(); + } + + /// Upper-cases an ASCII token without consulting the locale. + private static String upper(String s) { + StringBuilder b = new StringBuilder(s.length()); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + b.append(c >= 'a' && c <= 'z' ? (char) (c - ('a' - 'A')) : c); + } + return b.toString(); + } + + @SuppressWarnings("unchecked") + private static Map map(Object o) { + return o instanceof Map ? (Map) o : null; + } + + private static String string(Object o) { + return o instanceof String ? (String) o : null; + } + + /// One checkout's state. Package-private for the tests. + static final class Checkout { + final AsyncResource out; + final String reference; + String checkoutId; + long giveUpAt; + boolean cancelRequested; + boolean done; + + Checkout(AsyncResource out, String reference) { + this.out = out; + this.reference = reference; + } + } + + /// What a request's final answer is: a 2xx JSON body, a 4xx refusal, or + /// nothing usable after the retries. + private abstract static class Answer { + abstract void ok(Map json); + + abstract void error(int status, String message); + + abstract void lost(Throwable why); + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/square/package-info.java b/CodenameOne/src/com/codename1/payment/terminal/square/package-info.java new file mode 100644 index 00000000000..b450cffab7f --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/square/package-info.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/// A Square Terminal on the counter, driven through Square's Terminal API. +package com.codename1.payment.terminal.square; diff --git a/CodenameOne/src/com/codename1/payment/terminal/stripe/StripeReaderTerminal.java b/CodenameOne/src/com/codename1/payment/terminal/stripe/StripeReaderTerminal.java new file mode 100644 index 00000000000..16bfd970dd6 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/stripe/StripeReaderTerminal.java @@ -0,0 +1,907 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal.stripe; + +import com.codename1.io.JSONParser; +import com.codename1.io.Util; +import com.codename1.payment.terminal.CardReceipt; +import com.codename1.payment.terminal.HttpTerminalTransport; +import com.codename1.payment.terminal.PaymentTerminal; +import com.codename1.payment.terminal.TerminalOperation; +import com.codename1.payment.terminal.TerminalOutcomeUnknownException; +import com.codename1.payment.terminal.TerminalPaymentRequest; +import com.codename1.payment.terminal.TerminalRefundRequest; +import com.codename1.payment.terminal.TerminalResult; +import com.codename1.payment.terminal.TerminalTransport; +import com.codename1.ui.CN; +import com.codename1.util.AsyncResource; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/// A Stripe smart reader (WisePOS E, S700, S710) on the counter, driven +/// through Stripe's server-driven integration. +/// +/// The reader is on the store's network and registered to a Stripe +/// location; nothing here talks to it directly. Each payment is a request +/// to Stripe's API that hands a PaymentIntent to the reader, followed by +/// polling the reader's action until the customer has tapped. That is plain +/// HTTPS, so this works on every platform -- the desktop ports, mobile and +/// the web -- with no native SDK. +/// +/// #### Credentials +/// +/// Stripe's API takes a secret key, which must not ship in an app a +/// customer can install. For a point-of-sale app on a till you control, use +/// a **restricted** key limited to Terminal readers and PaymentIntents. +/// Otherwise point [#setApiBase(String)] at your own server, which adds the +/// key and forwards the same paths to `https://api.stripe.com` -- the API key +/// passed here can then be your own session token, or null. +/// +/// ```java +/// String restrictedKey = null; // null: your server adds the key +/// StripeReaderTerminal reader = new StripeReaderTerminal("tmr_FDOt2wlRZEdpd7", restrictedKey); +/// reader.collect(new TerminalPaymentRequest(1250, "USD")).ready(result -> { +/// if (result.isApproved()) { +/// // Confirm result.getTransactionId() on your server, then fulfill. +/// } +/// }); +/// ``` +/// +/// A request with a [TerminalPaymentRequest#getProviderReference()] uses +/// that PaymentIntent (`pi_...`), created by your server, as it is: its +/// amount, capture method and metadata are the server's. Without one, a +/// card-present PaymentIntent is created first, with manual capture for a +/// pre-authorization and the request's reference in its metadata, where +/// [#lookup(String)] finds it. +/// +/// #### What else it does +/// +/// - [#capture(String, long, String)] captures a pre-authorization. +/// - [#reverse(String)] cancels a PaymentIntent that is not captured yet. +/// - [#refund(TerminalRefundRequest)] refunds a payment by its PaymentIntent +/// ID. Stripe refunds a card-present payment to the card without the +/// reader, so unlinked refunds are not supported. +/// - [#lookup(String)] reads a PaymentIntent by ID (`pi_...`), or finds one +/// by the reference a sale was started with. The ID is the reliable key: +/// Stripe's search trails its writes by up to a minute, and a +/// PaymentIntent your server created carries no reference unless it set +/// `metadata[reference]`. +/// - Tipping on the reader needs a tipping configuration on the reader's +/// Stripe location. +/// +/// Settlement happens on Stripe's side, so there is no reconciliation, and +/// cashback is not offered. +public class StripeReaderTerminal extends PaymentTerminal { + private final String readerId; + private final String apiKey; + private String apiBase = "https://api.stripe.com"; + private TerminalTransport transport = new HttpTerminalTransport(); + /// Polls made after the deadline, to read what the cancel did, before + /// the payment is reported as failed with an unknown outcome. + private static final int POLLS_AFTER_TIMEOUT = 30; + private int pollInterval = 1000; + private long maxWait = 5 * 60 * 1000L; + + private Payment current; + + /// #### Parameters + /// + /// - `readerId`: the reader's ID, `tmr_...` + /// + /// - `apiKey`: sent as a bearer token; a restricted Stripe key, or + /// whatever your own server expects when [#setApiBase(String)] points + /// there. May be null when the transport authenticates by itself. + public StripeReaderTerminal(String readerId, String apiKey) { + if (readerId == null || readerId.length() == 0) { + throw new IllegalArgumentException("readerId"); + } + this.readerId = readerId; + this.apiKey = apiKey; + } + + /// The reader this terminal drives. + public String getReaderId() { + return readerId; + } + + /// Sends requests to another base URL than `https://api.stripe.com`, + /// such as a server of yours that adds the secret key. + /// + /// #### Parameters + /// + /// - `apiBase`: the base URL, with no trailing slash + public void setApiBase(String apiBase) { + this.apiBase = apiBase; + } + + /// Replaces the HTTP transport. + /// + /// #### Parameters + /// + /// - `transport`: the transport + public void setTransport(TerminalTransport transport) { + this.transport = transport; + } + + /// How often the reader is polled while a payment is in progress, in + /// milliseconds. Defaults to one second. + /// + /// #### Parameters + /// + /// - `pollInterval`: the interval in milliseconds + public void setPollInterval(int pollInterval) { + this.pollInterval = pollInterval; + } + + /// How long a payment may wait for the customer before it is canceled and + /// reported as [TerminalResult.Status#FAILED]. Defaults to five minutes. + /// + /// #### Parameters + /// + /// - `maxWait`: the limit in milliseconds + public void setMaxWait(long maxWait) { + this.maxWait = maxWait; + } + + @Override + public boolean supports(TerminalOperation operation) { + switch (operation) { + case SALE: + case PRE_AUTHORIZATION: + case CAPTURE: + case REVERSAL: + case REFUND: + case LOOKUP: + case TIPPING: + case RECEIPT_DATA: + return true; + default: + return false; + } + } + + @Override + public AsyncResource collect(TerminalPaymentRequest request) { + TerminalOperation missing = missingCapability(request); + if (missing != null) { + return unsupported(missing); + } + AsyncResource out = new AsyncResource(); + if (current != null) { + out.error(new IllegalStateException("A payment is already in progress on " + readerId)); + return out; + } + final Payment p = new Payment(out, System.currentTimeMillis() + maxWait); + p.reference = request.getReference(); + p.askForTip = request.isAskForTip(); + p.tipEligibleAmount = request.getAmount() - request.getTipAmount(); + current = p; + String pi = request.getProviderReference(); + if (pi != null && pi.length() > 0) { + process(p, pi); + return out; + } + StringBuilder body = new StringBuilder(); + body.append("amount=").append(request.getAmount()) + .append("¤cy=").append(Util.encodeUrl(asciiLower(request.getCurrency()))) + .append("&payment_method_types%5B%5D=card_present") + .append("&capture_method=").append(request.isPreAuthorization() ? "manual" : "automatic"); + if (request.getTipAmount() > 0) { + body.append("&amount_details%5Btip%5D%5Bamount%5D=").append(request.getTipAmount()); + } + if (request.getReference() != null) { + body.append("&metadata%5Breference%5D=").append(Util.encodeUrl(request.getReference())); + } + post("/v1/payment_intents", body.toString(), new Step(p) { + @Override + void ok(Map json) { + Object id = json.get("id"); + if (!(id instanceof String)) { + fail(p, new IOException("Stripe answered no PaymentIntent ID")); + return; + } + process(p, (String) id); + } + }); + return out; + } + + @Override + public void cancel() { + Payment p = current; + if (p == null || p.cancelRequested) { + return; + } + p.cancelRequested = true; + if (p.paymentIntentId != null) { + // Before process_payment_intent the reader may be busy with + // another till's sale; process() sees the flag instead. + sendCancelAction(); + } + } + + private void process(final Payment p, String paymentIntentId) { + p.paymentIntentId = paymentIntentId; + if (p.cancelRequested) { + finish(p, new TerminalResult(TerminalResult.Status.CANCELED, paymentIntentId, null)); + return; + } + String path = "/v1/terminal/readers/" + Util.encodeUrl(readerId) + "/process_payment_intent"; + StringBuilder body = new StringBuilder("payment_intent=").append(Util.encodeUrl(paymentIntentId)); + if (p.askForTip) { + body.append("&process_config%5Btipping%5D%5Bamount_eligible%5D=").append(p.tipEligibleAmount); + } else { + body.append("&process_config%5Bskip_tipping%5D=true"); + } + post(path, body.toString(), new Step(p, true) { + @Override + void ok(Map json) { + if (!evaluate(p, json)) { + schedulePoll(p); + } + } + }); + } + + private void schedulePoll(final Payment p) { + schedule(pollInterval, new Runnable() { + @Override + public void run() { + poll(p); + } + }); + } + + private void poll(final Payment p) { + if (p.done) { + return; + } + if (System.currentTimeMillis() > p.deadline) { + if (!p.timedOut) { + // Cancel, then keep reading: a card tapped in the last + // interval may still have been charged, and reporting FAILED + // over a success is how a sale gets charged twice. + p.timedOut = true; + sendCancelAction(); + } else if (p.pollsAfterTimeout >= POLLS_AFTER_TIMEOUT) { + // Not FAILED: the action may still complete (a customer in + // the middle of PIN entry cannot be canceled), and FAILED + // invites a second charge. + fail(p, new TerminalOutcomeUnknownException("The reader did not report an outcome; check PaymentIntent " + + p.paymentIntentId + " before charging again", p.paymentIntentId)); + return; + } else { + p.pollsAfterTimeout++; + } + } + Map headers = headers(); + transport.send("GET", apiBase + "/v1/terminal/readers/" + Util.encodeUrl(readerId), headers, null, null, + new Step(p, true) { + @Override + void ok(Map json) { + if (!evaluate(p, json)) { + schedulePoll(p); + } + } + }); + } + + /// Reads a reader object; true when the payment reached an outcome. + /// Package-private for the tests. + boolean evaluate(Payment p, Map reader) { + Object a = reader.get("action"); + if (!(a instanceof Map)) { + // The action is cleared when it is canceled. + if (p.cancelRequested) { + finish(p, new TerminalResult(TerminalResult.Status.CANCELED, p.paymentIntentId, null)); + return true; + } + if (p.timedOut) { + finish(p, new TerminalResult(TerminalResult.Status.FAILED, p.paymentIntentId, + "The customer did not present a card in time")); + return true; + } + return false; + } + @SuppressWarnings("unchecked") + Map action = (Map) a; + if (!isOurs(p, action)) { + // Another action is on the reader (a previous sale's, another + // till's): its outcome is not this payment's. + return false; + } + Object status = action.get("status"); + if ("succeeded".equals(status)) { + approved(p); + return true; + } + if ("failed".equals(status)) { + String code = string(action.get("failure_code")); + String message = string(action.get("failure_message")); + TerminalResult.Status s; + // The reader's own code wins: a decline that lands after the + // cashier pressed cancel is still a decline. + if ("card_declined".equals(code) || "expired_card".equals(code) + || "incorrect_pin".equals(code) || "insufficient_funds".equals(code)) { + s = TerminalResult.Status.DECLINED; + } else if (p.timedOut && !p.cancelRequested + && ("canceled".equals(code) || "action_canceled".equals(code))) { + // Canceled by the timeout, not by anyone. + s = TerminalResult.Status.FAILED; + message = "The customer did not present a card in time"; + } else if (p.cancelRequested || "customer_canceled".equals(code) + || "canceled".equals(code) || "action_canceled".equals(code)) { + s = TerminalResult.Status.CANCELED; + } else { + s = TerminalResult.Status.FAILED; + } + finish(p, new TerminalResult(s, p.paymentIntentId, message != null ? message : code)); + return true; + } + return false; + } + + private static boolean isOurs(Payment p, Map action) { + Object ppi = action.get("process_payment_intent"); + if (!(ppi instanceof Map)) { + // Stripe always sends it for this action type; an answer without + // it is treated as ours, as the tests' minimal readers are. + return action.get("type") == null || "process_payment_intent".equals(action.get("type")); + } + Object pi = ((Map) ppi).get("payment_intent"); + if (pi instanceof Map) { + pi = ((Map) pi).get("id"); + } + return pi == null || pi.equals(p.paymentIntentId); + } + + /// The reader approved: reads the PaymentIntent for the amounts and the + /// receipt fields. The money has moved, so a failure to read them still + /// reports the approval, without the details. + private void approved(final Payment p) { + transport.send("GET", apiBase + "/v1/payment_intents/" + Util.encodeUrl(p.paymentIntentId) + + "?expand%5B%5D=latest_charge", headers(), null, null, new TerminalTransport.Callback() { + @Override + public void onResponse(int status, String body) { + TerminalResult r = null; + if (status >= 200 && status < 300) { + try { + r = paymentIntentResult(JSONParser.parseJSON(body == null ? "{}" : body)); + } catch (IOException e) { + r = null; + } + } + finish(p, r != null && r.isApproved() ? r + : new TerminalResult.Builder(TerminalResult.Status.APPROVED) + .transactionId(p.paymentIntentId).reference(p.reference).build()); + } + + @Override + public void onError(Throwable error) { + finish(p, new TerminalResult.Builder(TerminalResult.Status.APPROVED) + .transactionId(p.paymentIntentId).reference(p.reference).build()); + } + }); + } + + @Override + public AsyncResource capture(String transactionId, long amount, String currency) { + if (transactionId == null || transactionId.length() == 0) { + return failed(new IllegalArgumentException("transactionId")); + } + return moneyCall("/v1/payment_intents/" + Util.encodeUrl(transactionId) + "/capture", + "amount_to_capture=" + amount, transactionId, false, false); + } + + @Override + public AsyncResource reverse(String transactionId) { + if (transactionId == null || transactionId.length() == 0) { + return failed(new IllegalArgumentException("transactionId")); + } + return moneyCall("/v1/payment_intents/" + Util.encodeUrl(transactionId) + "/cancel", + "", transactionId, true, false); + } + + @Override + public AsyncResource refund(TerminalRefundRequest request) { + if (request.isUnlinked()) { + return unsupported(TerminalOperation.UNLINKED_REFUND); + } + StringBuilder body = new StringBuilder("payment_intent=") + .append(Util.encodeUrl(request.getOriginalTransactionId())) + .append("&amount=").append(request.getAmount()); + if (request.getReference() != null) { + body.append("&metadata%5Breference%5D=").append(Util.encodeUrl(request.getReference())); + } + return moneyCall("/v1/refunds", body.toString(), request.getOriginalTransactionId(), false, true); + } + + @Override + public AsyncResource lookup(String reference) { + final AsyncResource out = new AsyncResource(); + if (reference == null || reference.length() == 0) { + out.error(new IllegalArgumentException("reference")); + return out; + } + final boolean byId = reference.startsWith("pi_"); + String url = byId + ? apiBase + "/v1/payment_intents/" + Util.encodeUrl(reference) + "?expand%5B%5D=latest_charge" + : apiBase + "/v1/payment_intents/search?query=" + + Util.encodeUrl("metadata['reference']:'" + reference.replace("'", "\\'") + "'") + + "&expand%5B%5D=data.latest_charge"; + final String ref = reference; + transport.send("GET", url, headers(), null, null, new JsonCallback(out) { + @Override + void ok(Map json) { + Map pi = json; + if (!byId) { + Object data = json.get("data"); + if (!(data instanceof List) || ((List) data).isEmpty() + || !(((List) data).get(0) instanceof Map)) { + // Stripe's search index trails its writes by up to a + // minute, so "not found" right after a lost answer + // is not proof that nothing was charged. + out.error(new TerminalOutcomeUnknownException("Stripe's search finds no PaymentIntent" + + " with reference " + ref + " yet; search lags by up to a minute, so ask again" + + " or look up the pi_ ID", null)); + return; + } + @SuppressWarnings("unchecked") + Map first = (Map) ((List) data).get(0); + pi = first; + } + TerminalResult r = paymentIntentResult(pi); + if (r == null) { + out.error(new TerminalOutcomeUnknownException("PaymentIntent " + pi.get("id") + + " is still processing", string(pi.get("id")))); + return; + } + out.complete(r); + } + }); + return out; + } + + /// A capture, cancel or refund: one POST that moves money. A lost + /// answer is an unknown outcome, not a failure. + private AsyncResource moneyCall(String path, String body, final String paymentIntentId, + final boolean isReversal, final boolean isRefund) { + final AsyncResource out = new AsyncResource(); + post(path, body, new MoneyCallback(out, paymentIntentId, isReversal, isRefund)); + return out; + } + + /// Delivers the answer to a capture, cancel or refund. + private static final class MoneyCallback implements TerminalTransport.Callback { + private final AsyncResource out; + private final String paymentIntentId; + private final boolean isReversal; + private final boolean isRefund; + + MoneyCallback(AsyncResource out, String paymentIntentId, boolean isReversal, + boolean isRefund) { + this.out = out; + this.paymentIntentId = paymentIntentId; + this.isReversal = isReversal; + this.isRefund = isRefund; + } + + @Override + public void onResponse(int status, String text) { + if (status == 429 || status >= 500) { + out.error(new TerminalOutcomeUnknownException("Stripe answered HTTP " + status + + "; check " + paymentIntentId + " before retrying", paymentIntentId)); + return; + } + Map json; + try { + json = JSONParser.parseJSON(text == null ? "{}" : text); + } catch (IOException e) { + out.error(new TerminalOutcomeUnknownException("Stripe's answer could not be read; check " + + paymentIntentId + " before retrying", paymentIntentId)); + return; + } + if (status < 200 || status >= 300) { + out.complete(new TerminalResult.Builder(TerminalResult.Status.FAILED) + .transactionId(paymentIntentId).message(errorMessage(json, status)).build()); + return; + } + if (isRefund) { + out.complete(refundResult(json, paymentIntentId)); + return; + } + TerminalResult r = paymentIntentResult(json); + if (isReversal && r != null && r.getStatus() == TerminalResult.Status.CANCELED) { + // A canceled PaymentIntent is a reversal that went through. + r = new TerminalResult.Builder(TerminalResult.Status.APPROVED) + .transactionId(r.getTransactionId()).message(r.getMessage()) + .amount(r.getApprovedAmount(), r.getCurrency()).reference(r.getReference()).build(); + } + out.complete(r != null ? r : new TerminalResult.Builder(TerminalResult.Status.APPROVED) + .transactionId(paymentIntentId).build()); + } + + @Override + public void onError(Throwable error) { + out.error(new TerminalOutcomeUnknownException("No answer from Stripe (" + error.getMessage() + + "); check " + paymentIntentId + " before retrying", paymentIntentId)); + } + } + + /// Maps a refund object. Package-private for the tests. + static TerminalResult refundResult(Map refund, String paymentIntentId) { + String status = string(refund.get("status")); + TerminalResult.Status s; + if ("succeeded".equals(status) || "pending".equals(status)) { + s = TerminalResult.Status.APPROVED; + } else if ("canceled".equals(status)) { + s = TerminalResult.Status.CANCELED; + } else { + s = TerminalResult.Status.FAILED; + } + TerminalResult.Builder b = new TerminalResult.Builder(s) + .transactionId(string(refund.get("id")) != null ? string(refund.get("id")) : paymentIntentId) + .message(string(refund.get("failure_reason")) != null ? string(refund.get("failure_reason")) : status); + long amount = number(refund.get("amount")); + if (amount >= 0) { + b.amount(amount, upper(string(refund.get("currency")))); + } + Object metadata = refund.get("metadata"); + if (metadata instanceof Map) { + b.reference(string(((Map) metadata).get("reference"))); + } + return b.build(); + } + + /// Maps a PaymentIntent, ideally with `latest_charge` expanded; null + /// while it is still processing. Package-private for the tests. + static TerminalResult paymentIntentResult(Map pi) { + String status = string(pi.get("status")); + String id = string(pi.get("id")); + TerminalResult.Status s; + String message = null; + if ("succeeded".equals(status) || "requires_capture".equals(status)) { + s = TerminalResult.Status.APPROVED; + } else if ("canceled".equals(status)) { + s = TerminalResult.Status.CANCELED; + message = string(pi.get("cancellation_reason")); + } else if ("processing".equals(status)) { + return null; + } else { + // requires_payment_method / requires_confirmation / + // requires_action: no money moved. A decline leaves its reason + // in last_payment_error. + Object err = pi.get("last_payment_error"); + if (err instanceof Map) { + String code = string(((Map) err).get("code")); + message = string(((Map) err).get("message")); + s = "card_declined".equals(code) || "expired_card".equals(code) + || "incorrect_pin".equals(code) || "insufficient_funds".equals(code) + ? TerminalResult.Status.DECLINED : TerminalResult.Status.FAILED; + } else { + s = TerminalResult.Status.FAILED; + message = status; + } + } + TerminalResult.Builder b = new TerminalResult.Builder(s).transactionId(id).message(message); + long amount = number(pi.get("amount_received")); + if (amount <= 0) { + amount = number(pi.get("amount_capturable")); + } + if (amount <= 0) { + amount = number(pi.get("amount")); + } + b.amount(amount, upper(string(pi.get("currency")))); + Object details = pi.get("amount_details"); + if (details instanceof Map) { + Object tip = ((Map) details).get("tip"); + if (tip instanceof Map) { + long t = number(((Map) tip).get("amount")); + if (t > 0) { + b.tip(t); + } + } + } + Object metadata = pi.get("metadata"); + if (metadata instanceof Map) { + b.reference(string(((Map) metadata).get("reference"))); + } + Object charge = pi.get("latest_charge"); + if (charge instanceof Map) { + b.receipt(receipt((Map) charge)); + } + return b.build(); + } + + private static CardReceipt receipt(Map charge) { + Object pmd = charge.get("payment_method_details"); + if (!(pmd instanceof Map)) { + return null; + } + Object cp = ((Map) pmd).get("card_present"); + if (!(cp instanceof Map)) { + cp = ((Map) pmd).get("interac_present"); + } + if (!(cp instanceof Map)) { + return null; + } + Map card = (Map) cp; + CardReceipt r = new CardReceipt().setBrand(string(card.get("brand"))); + String last4 = string(card.get("last4")); + if (last4 != null) { + r.setMaskedPan("**** **** **** " + last4); + } + String read = string(card.get("read_method")); + if (read != null) { + if (read.startsWith("contactless")) { + r.setEntryMode(CardReceipt.EntryMode.CONTACTLESS); + } else if ("contact_emv".equals(read)) { + r.setEntryMode(CardReceipt.EntryMode.CHIP); + } else if (read.startsWith("magnetic_stripe")) { + r.setEntryMode(CardReceipt.EntryMode.MAGSTRIPE); + } + } + Object rc = card.get("receipt"); + if (rc instanceof Map) { + Map m = (Map) rc; + r.setApplicationLabel(string(m.get("application_preferred_name"))); + r.setApplicationId(string(m.get("dedicated_file_name"))); + r.setAuthorizationCode(string(m.get("authorization_code"))); + String cvm = string(m.get("cardholder_verification_method")); + if (cvm != null) { + if (cvm.indexOf("pin") >= 0) { + r.setVerification(CardReceipt.Verification.PIN); + } else if (cvm.indexOf("signature") >= 0) { + r.setVerification(CardReceipt.Verification.SIGNATURE); + } else if ("none".equals(cvm)) { + r.setVerification(CardReceipt.Verification.NONE); + } + } + } + return r; + } + + private static String errorMessage(Map json, int status) { + Object err = json.get("error"); + if (err instanceof Map) { + Object m = ((Map) err).get("message"); + if (m instanceof String) { + return (String) m; + } + } + return "Stripe answered HTTP " + status; + } + + private static long number(Object o) { + return o instanceof Number ? ((Number) o).longValue() : -1; + } + + /// Upper-cases an ASCII token without consulting the locale. + private static String upper(String s) { + if (s == null) { + return null; + } + StringBuilder b = new StringBuilder(s.length()); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + b.append(c >= 'a' && c <= 'z' ? (char) (c - ('a' - 'A')) : c); + } + return b.toString(); + } + + /// Parses a 2xx JSON answer into `ok`; anything else fails `out`. + private abstract static class JsonCallback implements TerminalTransport.Callback { + private final AsyncResource out; + + JsonCallback(AsyncResource out) { + this.out = out; + } + + abstract void ok(Map json); + + @Override + public void onResponse(int status, String body) { + Map json; + try { + json = JSONParser.parseJSON(body == null ? "{}" : body); + } catch (IOException e) { + out.error(e); + return; + } + if (status < 200 || status >= 300) { + out.error(new IOException(errorMessage(json, status))); + return; + } + ok(json); + } + + @Override + public void onError(Throwable error) { + out.error(error); + } + } + + private void sendCancelAction() { + // The next poll reads the outcome. + post("/v1/terminal/readers/" + Util.encodeUrl(readerId) + "/cancel_action", "", TerminalTransport.IGNORE); + } + + /// Runs `task` on the EDT after `delay` milliseconds. Overridable so a + /// subclass can drive the polling from its own clock. + /// + /// #### Parameters + /// + /// - `delay`: the delay in milliseconds + /// + /// - `task`: what to run + protected void schedule(int delay, Runnable task) { + CN.setTimeout(delay, task); + } + + private void post(String path, String body, TerminalTransport.Callback cb) { + transport.send("POST", apiBase + path, headers(), + "application/x-www-form-urlencoded", body, cb); + } + + private Map headers() { + Map h = new HashMap(); + if (apiKey != null) { + h.put("Authorization", "Bearer " + apiKey); + } + return h; + } + + private void finish(Payment p, TerminalResult result) { + TerminalResult r = result.getReference() == null && p.reference != null + ? withReference(result, p.reference) : result; + if (p.done) { + return; + } + p.done = true; + if (current == p) { //NOPMD CompareObjectsWithEquals - identity: is this still the payment in flight + current = null; + } + p.out.complete(r); + } + + private void fail(Payment p, Throwable t) { + if (p.done) { + return; + } + p.done = true; + if (current == p) { //NOPMD CompareObjectsWithEquals - identity: is this still the payment in flight + current = null; + } + p.out.error(t); + } + + private static TerminalResult withReference(TerminalResult r, String reference) { + return new TerminalResult.Builder(r.getStatus()).transactionId(r.getTransactionId()) + .message(r.getMessage()).amount(r.getApprovedAmount(), r.getCurrency()) + .tip(r.getTipAmount()).receipt(r.getReceipt()).reference(reference).build(); + } + + private static String string(Object o) { + return o instanceof String ? (String) o : null; + } + + /// Lower-cases an ASCII token without consulting the locale. + private static String asciiLower(String s) { + StringBuilder b = new StringBuilder(s.length()); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + b.append(c >= 'A' && c <= 'Z' ? (char) (c + ('a' - 'A')) : c); + } + return b.toString(); + } + + /// One payment's state. Package-private for the tests. + static final class Payment { + final AsyncResource out; + final long deadline; + String paymentIntentId; + String reference; + boolean askForTip; + long tipEligibleAmount; + boolean cancelRequested; + boolean timedOut; + int pollsAfterTimeout; + boolean done; + + Payment(AsyncResource out, long deadline) { + this.out = out; + this.deadline = deadline; + } + } + + /// Parses a 2xx JSON answer; anything else fails the payment with + /// Stripe's own error message. A step that runs once the reader may + /// already hold the payment (handing it over, polling) keeps polling + /// through a network error, a 429 or a 5xx instead: failing there would + /// report an error for a card that is being charged. + private abstract class Step implements TerminalTransport.Callback { + private final Payment p; + private final boolean readerHasIt; + + Step(Payment p) { + this(p, false); + } + + Step(Payment p, boolean readerHasIt) { + this.p = p; + this.readerHasIt = readerHasIt; + } + + private boolean retry() { + if (!readerHasIt) { + return false; + } + schedulePoll(p); + return true; + } + + abstract void ok(Map json); + + @Override + public void onResponse(int status, String body) { + if (p.done) { + return; + } + Map json; + try { + json = JSONParser.parseJSON(body == null ? "{}" : body); + } catch (IOException e) { + if (!retry()) { + fail(p, e); + } + return; + } + if ((status == 429 || status >= 500) && retry()) { + return; + } + if (status < 200 || status >= 300) { + String message = "Stripe answered HTTP " + status; + Object err = json.get("error"); + if (err instanceof Map) { + Object m = ((Map) err).get("message"); + if (m instanceof String) { + message = (String) m; + } + } + fail(p, new IOException(message)); + return; + } + ok(json); + } + + @Override + public void onError(Throwable error) { + if (p.done || retry()) { + return; + } + fail(p, error); + } + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/stripe/package-info.java b/CodenameOne/src/com/codename1/payment/terminal/stripe/package-info.java new file mode 100644 index 00000000000..d4c554bc964 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/stripe/package-info.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/// Stripe smart readers (WisePOS E, S700) on the counter, driven through +/// Stripe's server-driven Terminal integration: [StripeReaderTerminal]. +/// Plain HTTPS, so it works on every platform. +package com.codename1.payment.terminal.stripe; diff --git a/CodenameOne/src/com/codename1/payment/terminal/tap/ConnectionTokenProvider.java b/CodenameOne/src/com/codename1/payment/terminal/tap/ConnectionTokenProvider.java new file mode 100644 index 00000000000..ceb66d40bf0 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/tap/ConnectionTokenProvider.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal.tap; + +import com.codename1.util.AsyncResource; + +/// Supplies Stripe Terminal connection tokens, which the Tap to Pay SDK asks +/// for whenever it needs to talk to Stripe. +/// +/// A connection token is created by **your server** with its secret key +/// (`POST /v1/terminal/connection_tokens`) and handed to the app; the secret +/// key itself never reaches the device. Fetch a fresh token on every call -- +/// the SDK caches what it needs and asks again when that expires. +/// +/// ```java +/// ConnectionTokenProvider tokens = () -> { +/// AsyncResource out = new AsyncResource<>(); +/// Rest.post("https://example.com/terminal/token").fetchAsJsonMap(r -> { +/// if (r.getResponseCode() == 200) { +/// out.complete((String) r.getResponseData().get("secret")); +/// } else { +/// out.error(new IOException("token: HTTP " + r.getResponseCode())); +/// } +/// }); +/// return out; +/// }; +/// ``` +public interface ConnectionTokenProvider { + /// Fetches one connection token. Called on the EDT. + /// + /// #### Returns + /// + /// a resource completed with the token's `secret`, or with an error + AsyncResource fetchConnectionToken(); +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/tap/TapToPay.java b/CodenameOne/src/com/codename1/payment/terminal/tap/TapToPay.java new file mode 100644 index 00000000000..9eb8cf2bf19 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/tap/TapToPay.java @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal.tap; + +import com.codename1.payment.terminal.PaymentTerminal; +import com.codename1.payment.terminal.TerminalOperation; +import com.codename1.payment.terminal.TerminalPaymentRequest; +import com.codename1.payment.terminal.TerminalResult; +import com.codename1.payment.terminal.spi.TapToPayBridge; +import com.codename1.ui.Display; +import com.codename1.util.AsyncResource; + +/// Takes contactless card payments with the phone itself: Tap to Pay on +/// iPhone and Tap to Pay on Android, over the Stripe Terminal SDK. +/// +/// The customer holds their card or wallet to the back of the phone; there +/// is no reader hardware. Neither OS lets an app read a payment card +/// directly, so this always goes through Stripe, whose SDK carries the +/// certified card-reading component and returns only the outcome. +/// +/// #### What your server does +/// +/// 1. Issues connection tokens (`POST /v1/terminal/connection_tokens`), +/// which the app fetches through a [ConnectionTokenProvider]. +/// 2. Creates a PaymentIntent for each sale with +/// `payment_method_types[]=card_present` and hands its client secret to +/// the app as the request's [TerminalPaymentRequest#getProviderReference()]. +/// 3. Confirms the PaymentIntent succeeded before fulfilling the order. +/// +/// ```java +/// // From your server; placeholders here. +/// String clientSecretFromServer = "pi_123_secret_456"; +/// ConnectionTokenProvider tokens = () -> { +/// AsyncResource 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()) { +/// // tell the server to verify result.getTransactionId() +/// } +/// }); +/// } +/// ``` +/// +/// #### Platform requirements +/// +/// - **iOS**: iPhone XS or newer on iOS 16.4 or later, and the Tap to Pay on +/// iPhone entitlement, which Apple grants on request to apps of supported +/// payment providers. The build adds the entitlement to the app; the +/// provisioning profile must carry it too. +/// - **Android**: Android 8 (API 26) or later with NFC, not rooted, with +/// Google Play services. Builds that use this package get a minimum SDK +/// of 26. +/// - **Simulator**: a simulated phone that asks your token provider for a +/// token, then approves. An amount ending in `01` (such as 1001) is +/// declined, and one ending in `02` fails, so both paths can be tried. +/// +/// Referencing this package is what adds the Stripe Terminal SDK to an +/// Android or iOS build; an app that does not use it carries none of it. +public final class TapToPay extends PaymentTerminal { + private final ConnectionTokenProvider tokens; + private final String locationId; + private String merchantDisplayName; + private boolean simulated; + private int currentRequest = -1; + + /// #### Parameters + /// + /// - `tokens`: fetches connection tokens from your server + /// + /// - `locationId`: the Stripe location (`tml_...`) the phone takes + /// payments for + public TapToPay(ConnectionTokenProvider tokens, String locationId) { + if (tokens == null) { + throw new IllegalArgumentException("tokens"); + } + if (locationId == null || locationId.length() == 0) { + throw new IllegalArgumentException("locationId"); + } + this.tokens = tokens; + this.locationId = locationId; + } + + /// True when this device can take Tap to Pay payments: the build + /// includes the SDK and the hardware and OS are supported. False in an + /// app whose build was not given the SDK, and on platforms with none + /// (desktop, web). + /// + /// #### Returns + /// + /// whether [#collect(TerminalPaymentRequest)] can run here + public static boolean isSupported() { + TapToPayBridge bridge = Display.getInstance().getTapToPayBridge(); + return bridge != null && bridge.isDeviceSupported(); + } + + /// The name shown on the payment sheet. Defaults to the name on the + /// Stripe account. + /// + /// #### Parameters + /// + /// - `merchantDisplayName`: the name, or null for the default + public void setMerchantDisplayName(String merchantDisplayName) { + this.merchantDisplayName = merchantDisplayName; + } + + /// Uses Stripe's simulated reader instead of the phone's NFC, so a test + /// mode integration can run end to end on any device. Requires a test + /// mode PaymentIntent. + /// + /// #### Parameters + /// + /// - `simulated`: true for the simulated reader + public void setSimulated(boolean simulated) { + this.simulated = simulated; + } + + /// Takes a payment. The request needs the PaymentIntent's client secret + /// as its [TerminalPaymentRequest#getProviderReference()]. + /// + /// The first payment also connects the phone as a reader, which can + /// download its configuration and take a while; on iOS the merchant is + /// asked to accept Apple's terms the first time. + /// + /// #### Parameters + /// + /// - `request`: what to charge + /// + /// #### Returns + /// + /// the outcome, delivered on the EDT + /// Sales only. A pre-authorization, + /// capture, refund or reversal is decided by the PaymentIntent your + /// server creates (`capture_method=manual`) and carried out with its + /// secret key, so the app never asks for one here. + @Override + public boolean supports(TerminalOperation operation) { + return operation == TerminalOperation.SALE; + } + + @Override + public AsyncResource collect(TerminalPaymentRequest request) { + TerminalOperation missing = missingCapability(request); + if (missing != null) { + return unsupported(missing); + } + AsyncResource out = new AsyncResource(); + TapToPayBridge bridge = Display.getInstance().getTapToPayBridge(); + if (bridge == null || !bridge.isDeviceSupported()) { + out.error(new IllegalStateException("Tap to Pay is not supported on this device")); + return out; + } + String secret = request.getProviderReference(); + if (secret == null || secret.length() == 0) { + out.error(new IllegalArgumentException( + "Tap to Pay needs the PaymentIntent client secret as the provider reference")); + return out; + } + if (currentRequest >= 0 || TapToPayCallbacks.hasPending()) { + out.error(new IllegalStateException("A Tap to Pay payment is already in progress")); + return out; + } + int id = TapToPayCallbacks.register(this, out, request.getReference()); + currentRequest = id; + bridge.collect(id, secret, request.getAmount(), request.getCurrency(), + locationId, merchantDisplayName, simulated); + return out; + } + + @Override + public void cancel() { + if (currentRequest < 0) { + return; + } + TapToPayBridge bridge = Display.getInstance().getTapToPayBridge(); + if (bridge != null) { + bridge.cancel(currentRequest); + } + } + + ConnectionTokenProvider getTokens() { + return tokens; + } + + void requestFinished(int id) { + if (currentRequest == id) { + currentRequest = -1; + } + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/tap/TapToPayCallbacks.java b/CodenameOne/src/com/codename1/payment/terminal/tap/TapToPayCallbacks.java new file mode 100644 index 00000000000..42d6206c85c --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/tap/TapToPayCallbacks.java @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal.tap; + +import com.codename1.io.Log; +import com.codename1.payment.terminal.TerminalOutcomeUnknownException; +import com.codename1.payment.terminal.TerminalResult; +import com.codename1.payment.terminal.spi.TapToPayBridge; +import com.codename1.ui.CN; +import com.codename1.ui.Display; +import com.codename1.util.AsyncResource; +import com.codename1.util.SuccessCallback; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/// The entry points a port's [TapToPayBridge] calls back into. Not for +/// applications. +/// +/// Every method may be called from any thread; each moves to the EDT before +/// touching state. On iOS these are reached from native code by their C +/// names, which is also what keeps them in a translated build. +public final class TapToPayCallbacks { + /// The card was charged. + public static final int STATUS_APPROVED = 0; + /// The card was declined. + public static final int STATUS_DECLINED = 1; + /// The payment was canceled. + public static final int STATUS_CANCELED = 2; + /// The reader reported an error that is not a decline. + public static final int STATUS_FAILED = 3; + /// The payment could not be attempted (SDK setup, connection, the + /// PaymentIntent could not be retrieved); completes the request with an + /// error rather than a result. + public static final int STATUS_ERROR = 4; + /// The card may have been charged and the SDK could not say: completes + /// the request with a [TerminalOutcomeUnknownException] carrying the + /// transaction ID. + public static final int STATUS_UNKNOWN = 5; + + private static final Map PENDING = new HashMap(); + private static TapToPay tokenOwner; + private static int nextId = 1; + + private TapToPayCallbacks() { + } + + static int register(TapToPay owner, AsyncResource out, String reference) { + int id = nextId++; + PENDING.put(Integer.valueOf(id), new Pending(owner, out, reference)); + tokenOwner = owner; + return id; + } + + static boolean hasPending() { + return !PENDING.isEmpty(); + } + + /// The SDK needs a connection token. Asks the [ConnectionTokenProvider] + /// of the most recent payment and answers with + /// [TapToPayBridge#connectionTokenReady(int, String, String)]. + /// + /// #### Parameters + /// + /// - `tokenRequestId`: the port's ID for this request, echoed back + public static void fetchConnectionToken(final int tokenRequestId) { + CN.callSerially(new Runnable() { + @Override + public void run() { + final TapToPayBridge bridge = Display.getInstance().getTapToPayBridge(); + if (bridge == null) { + return; + } + TapToPay owner = tokenOwner; + if (owner == null) { + bridge.connectionTokenReady(tokenRequestId, null, + "No TapToPay instance has started a payment"); + return; + } + AsyncResource token; + try { + token = owner.getTokens().fetchConnectionToken(); + } catch (RuntimeException e) { + Log.e(e); + bridge.connectionTokenReady(tokenRequestId, null, String.valueOf(e.getMessage())); + return; + } + if (token == null) { + bridge.connectionTokenReady(tokenRequestId, null, + "The ConnectionTokenProvider returned null"); + return; + } + token.ready(new SuccessCallback() { + @Override + public void onSucess(String value) { + if (value == null || value.length() == 0) { + bridge.connectionTokenReady(tokenRequestId, null, + "The ConnectionTokenProvider supplied an empty token"); + } else { + bridge.connectionTokenReady(tokenRequestId, value, null); + } + } + }).except(new SuccessCallback() { + @Override + public void onSucess(Throwable value) { + bridge.connectionTokenReady(tokenRequestId, null, + value == null ? "Connection token failed" : String.valueOf(value.getMessage())); + } + }); + } + }); + } + + /// The outcome of [TapToPayBridge#collect]. + /// + /// #### Parameters + /// + /// - `requestId`: the request's ID + /// + /// - `status`: one of the `STATUS_` constants + /// + /// - `transactionId`: the PaymentIntent ID, or null + /// + /// - `message`: the SDK's explanation, or null + public static void deliverResult(final int requestId, final int status, + final String transactionId, final String message) { + CN.callSerially(new Runnable() { + @Override + public void run() { + Pending p = PENDING.remove(Integer.valueOf(requestId)); + if (p == null) { + return; + } + p.owner.requestFinished(requestId); + TerminalResult.Status s; + switch (status) { + case STATUS_APPROVED: + s = TerminalResult.Status.APPROVED; + break; + case STATUS_DECLINED: + s = TerminalResult.Status.DECLINED; + break; + case STATUS_CANCELED: + s = TerminalResult.Status.CANCELED; + break; + case STATUS_FAILED: + s = TerminalResult.Status.FAILED; + break; + case STATUS_UNKNOWN: + p.out.error(new TerminalOutcomeUnknownException( + message == null ? "The payment's outcome is unknown" : message, transactionId)); + return; + default: + p.out.error(new IOException(message == null ? "Tap to Pay failed" : message)); + return; + } + p.out.complete(new TerminalResult.Builder(s).transactionId(transactionId).message(message) + .reference(p.reference).build()); + } + }); + } + + private static final class Pending { + final TapToPay owner; + final AsyncResource out; + final String reference; + + Pending(TapToPay owner, AsyncResource out, String reference) { + this.owner = owner; + this.out = out; + this.reference = reference; + } + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/tap/package-info.java b/CodenameOne/src/com/codename1/payment/terminal/tap/package-info.java new file mode 100644 index 00000000000..93f2877f6e1 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/tap/package-info.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/// Tap to Pay: the phone itself reads a contactless card, on iPhone and +/// Android, over the Stripe Terminal SDK. Start with [TapToPay]. +/// +/// Referencing this package is what adds the Stripe Terminal SDK, its +/// permissions and, on iOS, the Tap to Pay entitlement to a build. An app +/// that does not use it carries none of that. +package com.codename1.payment.terminal.tap; diff --git a/CodenameOne/src/com/codename1/payment/terminal/zvt/ZvtCodec.java b/CodenameOne/src/com/codename1/payment/terminal/zvt/ZvtCodec.java new file mode 100644 index 00000000000..145b5e4440d --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/zvt/ZvtCodec.java @@ -0,0 +1,425 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal.zvt; + +import com.codename1.io.link.ByteLink; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +/// APDUs, the serial frame around them, BCD and the bitmap fields, as the +/// ZVT specification (PA00P015, with the transport in PA00P016) defines them. +final class ZvtCodec { + static final int DLE = 0x10; + static final int STX = 0x02; + static final int ETX = 0x03; + static final int ACK = 0x06; + static final int NAK = 0x15; + + private ZvtCodec() { + } + + /// One APDU: two control bytes and the data. + static final class Apdu { + final int cls; + final int instr; + final byte[] data; + + Apdu(int cls, int instr, byte[] data) { + this.cls = cls; + this.instr = instr; + this.data = data == null ? new byte[0] : data; + } + + boolean is(int c, int i) { + return cls == c && instr == i; + } + + @Override + public String toString() { + return hex(cls) + " " + hex(instr) + " (" + data.length + " bytes)"; + } + } + + /// The bytes of an APDU; a data block over 254 bytes takes the FF form + /// with a two-byte little-endian length. + static byte[] encode(Apdu a) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.write(a.cls); + out.write(a.instr); + int len = a.data.length; + if (len < 0xff) { + out.write(len); + } else { + out.write(0xff); + out.write(len & 0xff); + out.write((len >> 8) & 0xff); + } + out.write(a.data, 0, len); + return out.toByteArray(); + } + + /// CRC-CCITT as ZVT's transport uses it: reflected polynomial 0x8408, + /// start 0, over the APDU and the closing ETX; sent low byte first. + static int crc(byte[] apdu) { + int crc = 0; + for (int i = 0; i <= apdu.length; i++) { + int b = i < apdu.length ? apdu[i] & 0xff : ETX; + crc ^= b; + for (int k = 0; k < 8; k++) { + crc = (crc & 1) != 0 ? (crc >>> 1) ^ 0x8408 : crc >>> 1; + } + } + return crc & 0xffff; + } + + /// DLE STX, the APDU with every DLE doubled, DLE ETX, CRC low, CRC high. + static byte[] frame(byte[] apdu) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.write(DLE); + out.write(STX); + for (byte raw : apdu) { + int b = raw & 0xff; + out.write(b); + if (b == DLE) { + out.write(DLE); + } + } + out.write(DLE); + out.write(ETX); + int c = crc(apdu); + out.write(c & 0xff); + out.write((c >> 8) & 0xff); + return out.toByteArray(); + } + + /// Reads one APDU sent without a frame (TCP). + /// How long the bytes of a message that has started may take to arrive. + static final int BYTE_TIMEOUT = 5000; + + static Apdu readApdu(ByteLink link, int timeout) throws IOException { + // Only the wait for a message honours the caller's timeout; once one + // starts, the rest arrives within BYTE_TIMEOUT or the link is broken. + int first = link.readByte(timeout); + if (first < 0) { + return null; + } + byte[] head = new byte[3]; + head[0] = (byte) first; + if (!link.readFully(head, 1, 2, BYTE_TIMEOUT)) { + throw new IOException("Truncated APDU header"); + } + int len = head[2] & 0xff; + if (len == 0xff) { + byte[] ext = new byte[2]; + if (!link.readFully(ext, 0, 2, BYTE_TIMEOUT)) { + throw new IOException("Truncated APDU length"); + } + len = (ext[0] & 0xff) | ((ext[1] & 0xff) << 8); + } + byte[] data = new byte[len]; + if (!link.readFully(data, 0, len, BYTE_TIMEOUT)) { + throw new IOException("Truncated APDU"); + } + return new Apdu(head[0] & 0xff, head[1] & 0xff, data); + } + + /// Reads one serial frame and returns its APDU bytes, or null when no + /// frame started in time. Throws [BadFrame] on a CRC or framing error, + /// which the caller answers with NAK. + static byte[] readFrame(ByteLink link, int timeout) throws IOException { + int b; + do { + b = link.readByte(timeout); + if (b < 0) { + return null; + } + while (b == DLE) { + b = link.readByte(BYTE_TIMEOUT); + if (b == STX) { + return readFrameBody(link, BYTE_TIMEOUT); + } + } + } while (true); + } + + private static byte[] readFrameBody(ByteLink link, int timeout) throws IOException { + ByteArrayOutputStream body = new ByteArrayOutputStream(); + while (true) { + int b = next(link, timeout); + if (b == DLE) { + int n = next(link, timeout); + if (n == ETX) { + break; + } + if (n != DLE) { + throw new BadFrame(); + } + } + body.write(b); + } + int lo = next(link, timeout); + int hi = next(link, timeout); + byte[] apdu = body.toByteArray(); + if (crc(apdu) != (lo | (hi << 8))) { + throw new BadFrame(); + } + return apdu; + } + + private static int next(ByteLink link, int timeout) throws IOException { + int b = link.readByte(timeout); + if (b < 0) { + throw new BadFrame(); + } + return b; + } + + /// Parses APDU bytes read from a frame. + static Apdu parse(byte[] bytes) throws IOException { + if (bytes.length < 3) { + throw new IOException("Short APDU"); + } + int len = bytes[2] & 0xff; + int start = 3; + if (len == 0xff) { + if (bytes.length < 5) { + throw new IOException("Short APDU"); + } + len = (bytes[3] & 0xff) | ((bytes[4] & 0xff) << 8); + start = 5; + } + if (start + len > bytes.length) { + throw new IOException("Truncated APDU"); + } + byte[] data = new byte[len]; + System.arraycopy(bytes, start, data, 0, len); + return new Apdu(bytes[0] & 0xff, bytes[1] & 0xff, data); + } + + /// A CRC or framing error. + static final class BadFrame extends IOException { + BadFrame() { + super("Bad ZVT frame"); + } + } + + /// Packs digits two to a byte, left padded with zeros to `bytes` bytes. + static byte[] bcd(long value, int bytes) { + byte[] out = new byte[bytes]; + long v = value; + for (int i = bytes - 1; i >= 0; i--) { + int lo = (int) (v % 10); + v /= 10; + int hi = (int) (v % 10); + v /= 10; + out[i] = (byte) ((hi << 4) | lo); + } + return out; + } + + /// The digits of packed BCD; a nibble above 9 (padding F, masking E) + /// ends or replaces the digit as written. + static String digits(byte[] data, int offset, int length) { + StringBuilder sb = new StringBuilder(); + for (int i = offset; i < offset + length; i++) { + nibble(sb, (data[i] >> 4) & 0xf); + nibble(sb, data[i] & 0xf); + } + return sb.toString(); + } + + private static void nibble(StringBuilder sb, int n) { + if (n <= 9) { + sb.append((char) ('0' + n)); + } else if (n == 0xe) { + sb.append('*'); + } else if (n == 0xd) { + sb.append('='); + } + } + + static long number(byte[] data, int offset, int length) { + long v = 0; + for (int i = offset; i < offset + length; i++) { + v = v * 100L + ((data[i] >> 4) & 0xf) * 10L + (data[i] & 0xf); + } + return v; + } + + static String hex(int b) { + String s = Integer.toHexString(b & 0xff); + return s.length() == 1 ? "0" + s : s; + } + + static String hex(byte[] data) { + StringBuilder sb = new StringBuilder(); + for (byte b : data) { + sb.append(hex(b)); + } + return sb.toString(); + } + + static byte[] unhex(String s) { + byte[] out = new byte[s.length() / 2]; + for (int i = 0; i < out.length; i++) { + out[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16); + } + return out; + } + + /// The size of a fixed-length bitmap, or -2 for LLVAR, -3 for LLLVAR, + /// -6 for the TLV container, -1 when unknown. + static int bmpLength(int bmp) { + switch (bmp) { + case 0x01: case 0x02: case 0x03: case 0x05: case 0x19: case 0x27: + case 0x8A: case 0x8C: case 0xA0: case 0xD0: case 0xD2: case 0xD3: + case 0xE0: case 0xE9: case 0xEA: case 0xF0: case 0xF9: case 0xFA: + case 0xFB: case 0xFC: case 0x72: case 0x73: case 0x74: case 0x75: + return 1; + case 0x0D: case 0x0E: case 0x17: case 0x3A: case 0x49: case 0x87: + return 2; + case 0x0B: case 0x0C: case 0x37: case 0x3D: case 0x88: case 0xAA: + return 3; + case 0x29: case 0x70: case 0x71: + return 4; + case 0xBA: + return 5; + case 0x04: + return 6; + case 0x3B: case 0xEB: + return 8; + case 0x2A: + return 15; + case 0x22: case 0x23: case 0x2D: case 0x8B: case 0xA7: case 0xD1: + return -2; + case 0x24: case 0x2E: case 0x3C: case 0x60: case 0x9A: case 0xAF: + return -3; + case 0x06: + return -6; + default: + if ((bmp >= 0xE1 && bmp <= 0xE8) || (bmp >= 0xF1 && bmp <= 0xF8)) { + return -2; + } + return -1; + } + } + + /// The bitmaps of a data block, by number; a TLV container is kept + /// whole under 0x06. Parsing stops at a bitmap it does not know, since + /// its length cannot be told. + static byte[][] bitmaps(byte[] data, int from) { + byte[][] out = new byte[256][]; + int i = from; + while (i < data.length) { + int bmp = data[i++] & 0xff; + int len = bmpLength(bmp); + if (len == -2 || len == -3) { + int digits = -len; + if (i + digits > data.length) { + break; + } + int n = 0; + for (int k = 0; k < digits; k++) { + n = n * 10 + (data[i + k] & 0x0f); + } + i += digits; + len = n; + } else if (len == -6) { + int[] tl = tlvLength(data, i); + if (tl == null) { + break; + } + i = tl[0]; + len = tl[1]; + } else if (len < 0) { + break; + } + if (i + len > data.length) { + break; + } + byte[] v = new byte[len]; + System.arraycopy(data, i, v, 0, len); + out[bmp] = v; + i += len; + } + return out; + } + + /// The BER length at `i`: {index after it, length}, or null. + static int[] tlvLength(byte[] data, int i) { + if (i >= data.length) { + return null; + } + int b = data[i] & 0xff; + if (b < 0x80) { + return new int[] {i + 1, b}; + } + if (b == 0x81 && i + 1 < data.length) { + return new int[] {i + 2, data[i + 1] & 0xff}; + } + if (b == 0x82 && i + 2 < data.length) { + return new int[] {i + 3, ((data[i + 1] & 0xff) << 8) | (data[i + 2] & 0xff)}; + } + return null; + } + + /// A BER length, as written before a TLV value. + static void writeTlvLength(ByteArrayOutputStream out, int len) { + if (len < 0x80) { + out.write(len); + } else if (len <= 0xff) { + out.write(0x81); + out.write(len); + } else { + out.write(0x82); + out.write(len >> 8); + out.write(len & 0xff); + } + } + + /// The ISO 4217 number of a currency ZVT terminals handle, or -1. + static int currencyNumber(String code) { + if (code == null) { + return -1; + } + String[] table = {"EUR", "978", "CHF", "756", "GBP", "826", "USD", "840", "DKK", "208", + "SEK", "752", "NOK", "578", "PLN", "985", "CZK", "203", "HUF", "348"}; + for (int i = 0; i < table.length; i += 2) { + if (table[i].equalsIgnoreCase(code)) { + return Integer.parseInt(table[i + 1]); + } + } + return -1; + } + + static String currencyCode(int number) { + String[] table = {"EUR", "978", "CHF", "756", "GBP", "826", "USD", "840", "DKK", "208", + "SEK", "752", "NOK", "578", "PLN", "985", "CZK", "203", "HUF", "348"}; + for (int i = 0; i < table.length; i += 2) { + if (Integer.parseInt(table[i + 1]) == number) { + return table[i]; + } + } + return null; + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/zvt/ZvtTerminal.java b/CodenameOne/src/com/codename1/payment/terminal/zvt/ZvtTerminal.java new file mode 100644 index 00000000000..ad0027050d0 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/zvt/ZvtTerminal.java @@ -0,0 +1,819 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.payment.terminal.zvt; + +import com.codename1.io.link.ByteLink; +import com.codename1.io.link.TcpLink; +import com.codename1.payment.terminal.CardReceipt; +import com.codename1.payment.terminal.PaymentTerminal; +import com.codename1.payment.terminal.TerminalOperation; +import com.codename1.payment.terminal.TerminalOutcomeUnknownException; +import com.codename1.payment.terminal.TerminalPaymentRequest; +import com.codename1.payment.terminal.TerminalReconciliation; +import com.codename1.payment.terminal.TerminalRefundRequest; +import com.codename1.payment.terminal.TerminalResult; +import com.codename1.payment.terminal.zvt.ZvtCodec.Apdu; +import com.codename1.ui.CN; +import com.codename1.util.AsyncResource; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +/// A card terminal that speaks ZVT, the till protocol of the German-speaking +/// markets, over a serial cable, USB or the local network. +/// +/// ```java +/// ZvtTerminal terminal = new ZvtTerminal(new TcpLink("192.168.1.80", 20007), 0); +/// terminal.collect(new TerminalPaymentRequest(1250, "EUR")).ready(result -> { +/// if (result.isApproved()) { +/// System.out.println("Keep " + result.getTransactionId() + " to reverse it"); +/// } +/// }); +/// ``` +/// +/// The terminal handles the card and the bank; the app sends an amount and +/// gets the outcome. Over TCP the APDUs go as they are (20007 is the usual +/// port); over a serial line or USB they are framed with DLE/STX and a CRC, +/// and each frame is acknowledged. [#setSerialFraming(boolean)] chooses, +/// and defaults to framing on every link but a [TcpLink]. +/// +/// Supported: sale, pre-authorisation and its booking (capture), reversal, +/// unlinked refund and the end-of-day. ZVT has no refund of a given payment; +/// reverse it the same day, or refund an amount. With +/// [#setReceiptsToApp(boolean)] the terminal sends its receipts to the app +/// instead of printing them, and the app must then print them. +/// +/// The transaction ID is the terminal's receipt number, with what booking a +/// pre-authorisation needs; keep it as an opaque string. +public class ZvtTerminal extends PaymentTerminal { + private static final int RESULT_ABORTED = 0x6c; + private static final int[] OK = {0x80, 0x00, 0x00}; + + private final ByteLink link; + private final int password; + private boolean serialFraming; + private boolean receiptsToApp; + private int cardTimeout = 180000; + private boolean registered; + private final AtomicBoolean busy = new AtomicBoolean(); + private final AtomicBoolean abortRequested = new AtomicBoolean(); + + /// #### Parameters + /// + /// - `link`: the connection to the terminal; it is opened when needed + /// + /// - `password`: the terminal's six digit till password, often 0 or + /// 123456 + public ZvtTerminal(ByteLink link, int password) { + this.link = link; + this.password = password; + this.serialFraming = !(link instanceof TcpLink); + } + + /// Whether APDUs go in DLE/STX frames with a CRC and acknowledgement, as + /// on a serial line, or as they are, as over TCP. + /// + /// #### Parameters + /// + /// - `serialFraming`: true to frame + public void setSerialFraming(boolean serialFraming) { + this.serialFraming = serialFraming; + } + + /// Asks the terminal to send its receipts to the app, in + /// [TerminalResult#getReceipt()], rather than print them. The app is + /// then responsible for printing; a cardholder is entitled to one. + /// + /// #### Parameters + /// + /// - `receiptsToApp`: true to receive the receipts + public void setReceiptsToApp(boolean receiptsToApp) { + if (this.receiptsToApp != receiptsToApp) { + this.receiptsToApp = receiptsToApp; + registered = false; + } + } + + /// The longest the terminal may stay silent during an operation before + /// the outcome is reported unknown. Defaults to three minutes; a + /// terminal sends intermediate status while it waits for the card. + /// + /// #### Parameters + /// + /// - `cardTimeout`: the limit in milliseconds + public void setCardTimeout(int cardTimeout) { + this.cardTimeout = cardTimeout; + } + + @Override + public boolean supports(TerminalOperation operation) { + switch (operation) { + case SALE: + case PRE_AUTHORIZATION: + case CAPTURE: + case REVERSAL: + case UNLINKED_REFUND: + case RECONCILIATION: + return true; + case RECEIPT_DATA: + return receiptsToApp; + default: + return false; + } + } + + @Override + public AsyncResource collect(TerminalPaymentRequest request) { + TerminalOperation missing = missingCapability(request); + if (missing != null) { + return unsupported(missing); + } + int cc = ZvtCodec.currencyNumber(request.getCurrency()); + if (cc < 0) { + return failed(new IllegalArgumentException("Unsupported currency " + request.getCurrency())); + } + ByteArrayOutputStream data = new ByteArrayOutputStream(); + put(data, 0x04, ZvtCodec.bcd(request.getAmount(), 6)); + put(data, 0x49, ZvtCodec.bcd(cc, 2)); + boolean pre = request.isPreAuthorization(); + return money(new Apdu(0x06, pre ? 0x22 : 0x01, data.toByteArray()), pre, request.getReference()); + } + + /// Books a pre-authorisation (Book Total, 06 24) for `amount`. + @Override + public AsyncResource capture(String transactionId, long amount, String currency) { + TxId id = TxId.parse(transactionId); + int cc = ZvtCodec.currencyNumber(currency); + if (id == null || cc < 0) { + return failed(new IllegalArgumentException("Not a ZVT pre-authorisation, or unsupported currency")); + } + ByteArrayOutputStream data = new ByteArrayOutputStream(); + put(data, 0x87, ZvtCodec.bcd(id.receipt, 2)); + put(data, 0x04, ZvtCodec.bcd(amount, 6)); + put(data, 0x49, ZvtCodec.bcd(cc, 2)); + if (id.trace >= 0) { + put(data, 0x0B, ZvtCodec.bcd(id.trace, 3)); + } + if (id.aid != null) { + put(data, 0x3B, id.aid); + } + return money(new Apdu(0x06, 0x24, data.toByteArray()), false, null); + } + + /// Reverses a payment of the current batch (06 30), or releases a + /// pre-authorisation (06 25). + @Override + public AsyncResource reverse(String transactionId) { + TxId id = TxId.parse(transactionId); + if (id == null) { + return failed(new IllegalArgumentException("Not a ZVT transaction ID: " + transactionId)); + } + ByteArrayOutputStream data = new ByteArrayOutputStream(); + if (!id.preAuthorization) { + data.write(ZvtCodec.bcd(password, 3), 0, 3); + } + put(data, 0x87, ZvtCodec.bcd(id.receipt, 2)); + return money(new Apdu(0x06, id.preAuthorization ? 0x25 : 0x30, data.toByteArray()), false, null); + } + + /// Refunds an amount (06 31). ZVT cannot refund a given payment, so a + /// request naming one is refused; reverse it instead. + @Override + public AsyncResource refund(TerminalRefundRequest request) { + if (!request.isUnlinked()) { + return unsupported(TerminalOperation.REFUND); + } + int cc = ZvtCodec.currencyNumber(request.getCurrency()); + if (cc < 0) { + return failed(new IllegalArgumentException("Unsupported currency " + request.getCurrency())); + } + ByteArrayOutputStream data = new ByteArrayOutputStream(); + data.write(ZvtCodec.bcd(password, 3), 0, 3); + put(data, 0x04, ZvtCodec.bcd(request.getAmount(), 6)); + put(data, 0x49, ZvtCodec.bcd(cc, 2)); + return money(new Apdu(0x06, 0x31, data.toByteArray()), false, request.getReference()); + } + + /// Runs the end-of-day (06 50), which closes the batch and sends it to + /// the acquirer. + @Override + public AsyncResource reconcile() { + final AsyncResource out = new AsyncResource(); + if (!busy.compareAndSet(false, true)) { + out.error(new IllegalStateException("The terminal is busy")); + return out; + } + final Apdu cmd = new Apdu(0x06, 0x50, ZvtCodec.bcd(password, 3)); + abortRequested.set(false); + start(new EndOfDay(cmd, out)); + return out; + } + + /// Asks the terminal to abort (06 B0). Terminals honour it while waiting + /// for the card; once the card is read the operation usually completes. + @Override + public void cancel() { + if (!busy.get()) { + return; + } + // Only the operation's own thread touches the link: an abort written + // from here could interleave with its ACKs and replies. It sends 06 B0 + // at its next wait, or skips the command when it has not sent it yet. + abortRequested.set(true); + } + + /// Runs `task` on a thread of its own; tests override it. + /// + /// #### Parameters + /// + /// - `task`: the blocking work + protected void start(Runnable task) { + new Thread(task, "ZVT").start(); + } + + /// Hands a result to the app on the EDT; tests override it. + /// + /// #### Parameters + /// + /// - `task`: the delivery + protected void deliver(Runnable task) { + CN.callSerially(task); + } + + private AsyncResource money(Apdu cmd, boolean preAuthorization, String reference) { + AsyncResource out = new AsyncResource(); + if (!busy.compareAndSet(false, true)) { + out.error(new IllegalStateException("The terminal is busy")); + return out; + } + abortRequested.set(false); + start(new Money(cmd, preAuthorization, reference, out)); + return out; + } + + private static void put(ByteArrayOutputStream out, int bmp, byte[] value) { + out.write(bmp); + out.write(value, 0, value.length); + } + + private void complete(final AsyncResource out, final TerminalResult result, final Throwable error) { + busy.set(false); + deliver(new Deliver(out, result, error)); + } + + private static final class Deliver implements Runnable { + private final AsyncResource out; + private final TerminalResult result; + private final Throwable error; + + Deliver(AsyncResource out, TerminalResult result, Throwable error) { + this.out = out; + this.result = result; + this.error = error; + } + + @Override + public void run() { + if (error != null) { + out.error(error); + } else { + out.complete(result); + } + } + } + + /// What the terminal said during one command. + private static final class Exchange { + boolean accepted; + int refusal = -1; + boolean completed; + int abortCode = -1; + byte[][] status; + final List merchant = new ArrayList(); + final List customer = new ArrayList(); + final List pending = new ArrayList(); + int receiptsClosed; + } + + /// Opens and registers as needed, sends `cmd` and follows the terminal + /// until it completes or aborts. + private Exchange execute(Apdu cmd) throws IOException { + link.open(); + if (abortRequested.getAndSet(false)) { + return canceledBeforeSending(); + } + if (!registered) { + int config = 0x08; + if (receiptsToApp) { + config |= 0x02 | 0x04 | 0x80; + } + ByteArrayOutputStream reg = new ByteArrayOutputStream(); + reg.write(ZvtCodec.bcd(password, 3), 0, 3); + reg.write(config); + reg.write(ZvtCodec.bcd(978, 2), 0, 2); + Exchange r = dialog(new Apdu(0x06, 0x00, reg.toByteArray()), false); + if (!r.completed) { + throw new IOException("The terminal refused registration" + + (r.abortCode >= 0 ? " (" + describe(r.abortCode) + ")" : "")); + } + registered = true; + } + if (abortRequested.getAndSet(false)) { + return canceledBeforeSending(); + } + return dialog(cmd, true); + } + + private static Exchange canceledBeforeSending() { + Exchange ex = new Exchange(); + ex.accepted = true; + ex.abortCode = RESULT_ABORTED; + return ex; + } + + /// Once a money command may have reached the terminal, a missing or odd + /// answer is an unknown outcome, never a plain error: the terminal can be + /// charging the card while its 80 00 is late or lost. + private TerminalOutcomeUnknownException unknown(String message, Throwable cause) { + TerminalOutcomeUnknownException e = new TerminalOutcomeUnknownException(message, null); + if (cause != null) { + e.initCause(cause); + } + return e; + } + + private Exchange dialog(Apdu cmd, boolean money) throws IOException { + Exchange ex = new Exchange(); + Apdu first; + try { + send(cmd, true); + first = receive(10000); + } catch (IOException e) { + if (money) { + throw unknown("The terminal may have taken the command: " + e.getMessage(), e); + } + throw e; + } + if (first == null) { + if (money) { + throw unknown("The terminal did not confirm the command", null); + } + throw new IOException("The terminal did not answer"); + } + if (first.cls == 0x84) { + ex.refusal = first.instr; + return ex; + } + if (first.cls != 0x80) { + if (money) { + throw unknown("Unexpected answer " + first, null); + } + throw new IOException("Unexpected answer " + first); + } + ex.accepted = true; + try { + return follow(ex); + } catch (TerminalOutcomeUnknownException e) { + throw e; + } catch (IOException e) { + // Accepted and then lost: the terminal may have charged the card. + throw unknown("Lost the terminal mid-operation: " + e.getMessage(), e); + } + } + + private Exchange follow(Exchange ex) throws IOException { + long deadline = System.currentTimeMillis() + cardTimeout; + while (true) { + if (abortRequested.getAndSet(false)) { + send(new Apdu(0x06, 0xB0, null), true); + } + Apdu m = receive(500); + if (m == null) { + if (System.currentTimeMillis() > deadline) { + throw new TerminalOutcomeUnknownException("The terminal went silent mid-operation", null); + } + continue; + } + deadline = System.currentTimeMillis() + cardTimeout; + if (m.cls == 0x80 || m.cls == 0x84) { + // our abort's acknowledgement + continue; + } + if (m.is(0x04, 0xFF)) { + reply(OK); + } else if (m.is(0x04, 0x0F)) { + ex.status = ZvtCodec.bitmaps(m.data, 0); + reply(OK); + } else if (m.is(0x06, 0xD1)) { + printLine(ex, m.data); + reply(OK); + } else if (m.is(0x06, 0xD3)) { + printBlock(ex, m.data); + reply(OK); + } else if (m.is(0x06, 0x0F)) { + reply(OK); + ex.completed = true; + return ex; + } else if (m.is(0x06, 0x1E)) { + reply(OK); + ex.abortCode = m.data.length > 0 ? m.data[0] & 0xff : 0xff; + return ex; + } else { + reply(new int[] {0x84, 0x83, 0x00}); + } + } + } + + private void reply(int[] bytes) throws IOException { + byte[] b = new byte[bytes.length]; + for (int i = 0; i < b.length; i++) { + b[i] = (byte) bytes[i]; + } + writeApdu(b, true); + } + + private void send(Apdu a, boolean waitForAck) throws IOException { + writeApdu(ZvtCodec.encode(a), waitForAck); + } + + private void writeApdu(byte[] apdu, boolean waitForAck) throws IOException { + if (!serialFraming) { + link.write(apdu); + return; + } + byte[] frame = ZvtCodec.frame(apdu); + for (int attempt = 0; attempt < 3; attempt++) { + link.write(frame); + if (!waitForAck) { + return; + } + int b = link.readByte(5000); + if (b == ZvtCodec.ACK) { + return; + } + } + throw new IOException("The terminal did not acknowledge"); + } + + private Apdu receive(int timeout) throws IOException { + if (!serialFraming) { + return ZvtCodec.readApdu(link, timeout); + } + for (int attempt = 0; attempt < 3; attempt++) { + try { + byte[] apdu = ZvtCodec.readFrame(link, timeout); + if (apdu == null) { + return null; + } + link.write(new byte[] {ZvtCodec.ACK}); + return ZvtCodec.parse(apdu); + } catch (ZvtCodec.BadFrame e) { + link.write(new byte[] {ZvtCodec.NAK}); + } + } + throw new IOException("Repeated bad frames from the terminal"); + } + + private static void printLine(Exchange ex, byte[] data) { + if (data.length == 0) { + return; + } + int attr = data[0] & 0xff; + if (attr == 0xff) { + ex.pending.add(""); + return; + } + ex.pending.add(text(data, 1, data.length - 1)); + if ((attr & 0x80) != 0 && attr != 0x80) { + closeReceipt(ex, 0); + } + } + + private static void printBlock(Exchange ex, byte[] data) { + int type = 0; + boolean last = false; + int i = data.length > 0 && (data[0] & 0xff) == 0x06 ? 1 : 0; + int[] tl = ZvtCodec.tlvLength(data, i); + int end = tl == null ? data.length : Math.min(data.length, tl[0] + tl[1]); + i = tl == null ? i : tl[0]; + List lines = new ArrayList(); + while (i < end) { + int tag = data[i++] & 0xff; + if ((tag & 0x1f) == 0x1f && i < end) { + tag = (tag << 8) | (data[i++] & 0xff); + } + tl = ZvtCodec.tlvLength(data, i); + if (tl == null) { + break; + } + int vs = tl[0]; + int vl = Math.min(tl[1], end - vs); + if (tag == 0x25) { + // print texts: walk inside it + end = vs + vl; + i = vs; + continue; + } + if (tag == 0x07) { + lines.add(text(data, vs, vl)); + } else if (tag == 0x09 && vl > 0) { + int a = data[vs] & 0xff; + last = (a & 0x80) != 0 && a != 0x80; + } else if (tag == 0x1F07 && vl > 0) { + type = data[vs] & 0xff; + } + i = vs + vl; + } + ex.pending.addAll(lines); + if (last || type != 0) { + closeReceipt(ex, type); + } + } + + /// Files the collected lines: by the terminal's receipt type when it + /// gives one, else the first receipt is the merchant's and the next the + /// cardholder's, the order German terminals print them. + private static void closeReceipt(Exchange ex, int type) { + if (ex.pending.isEmpty()) { + return; + } + boolean merchant = type == 1 || (type == 0 && ex.receiptsClosed == 0); + (merchant ? ex.merchant : ex.customer).addAll(ex.pending); + ex.pending.clear(); + ex.receiptsClosed++; + } + + private static String text(byte[] data, int offset, int length) { + StringBuilder sb = new StringBuilder(); + for (int i = offset; i < offset + length; i++) { + int c = data[i] & 0xff; + if (c == 0) { + break; + } + sb.append((char) c); + } + return sb.toString(); + } + + static String describe(int code) { + switch (code) { + case 0x64: return "card not readable"; + case 0x65: return "card data not present"; + case 0x6a: return "card rejected"; + case RESULT_ABORTED: return "aborted by timeout or the abort key"; + case 0x9a: return "ZVT protocol error"; + case 0xc5: return "payment method not supported"; + case 0xc6: return "currency not applicable"; + case 0xcd: return "cashback not possible"; + default: return "ZVT error 0x" + ZvtCodec.hex(code); + } + } + + private TerminalResult result(Exchange ex, boolean preAuthorization, String reference) { + byte[][] s = ex.status; + // 06 1E's code wins over an earlier status; a completion (06 0F) + // without a status, from a terminal that sends none, is a success. + int code; + if (ex.abortCode >= 0) { + code = ex.abortCode == 0 ? 0xff : ex.abortCode; + } else if (s != null && s[0x27] != null && s[0x27].length > 0) { + code = s[0x27][0] & 0xff; + } else { + code = ex.completed ? 0 : -1; + } + if (!ex.accepted) { + return new TerminalResult.Builder(TerminalResult.Status.DECLINED) + .message("The terminal refused the command (84 " + ZvtCodec.hex(ex.refusal) + ")") + .reference(reference).build(); + } + TerminalResult.Status st; + if (code == 0 && ex.completed) { + st = TerminalResult.Status.APPROVED; + } else if (code == RESULT_ABORTED) { + st = TerminalResult.Status.CANCELED; + } else { + st = TerminalResult.Status.DECLINED; + } + closeReceipt(ex, 0); + TerminalResult.Builder b = new TerminalResult.Builder(st) + .message(st == TerminalResult.Status.APPROVED ? null : describe(code < 0 ? 0xff : code)) + .reference(reference); + if (s != null) { + String cur = s[0x49] == null ? null : ZvtCodec.currencyCode((int) ZvtCodec.number(s[0x49], 0, 2)); + if (s[0x04] != null) { + b.amount(ZvtCodec.number(s[0x04], 0, 6), cur); + } + if (s[0x87] != null) { + TxId id = new TxId(); + id.receipt = (int) ZvtCodec.number(s[0x87], 0, 2); + id.trace = s[0x0B] == null ? -1 : (int) ZvtCodec.number(s[0x0B], 0, 3); + id.aid = s[0x3B]; + id.preAuthorization = preAuthorization; + b.transactionId(id.toString()); + } + CardReceipt r = new CardReceipt(); + if (s[0x8B] != null) { + r.setBrand(text(s[0x8B], 0, s[0x8B].length)); + } + if (s[0x22] != null) { + r.setMaskedPan(ZvtCodec.digits(s[0x22], 0, s[0x22].length)); + } + if (s[0x3B] != null) { + r.setAuthorizationCode(text(s[0x3B], 0, s[0x3B].length).trim()); + } + if (s[0x29] != null) { + r.setTerminalId(ZvtCodec.digits(s[0x29], 0, 4)); + } + if (s[0x2A] != null) { + r.setMerchantId(text(s[0x2A], 0, s[0x2A].length).trim()); + } + if (!ex.merchant.isEmpty()) { + r.setMerchantReceipt(ex.merchant.toArray(new String[ex.merchant.size()])); + } + if (!ex.customer.isEmpty()) { + r.setCustomerReceipt(ex.customer.toArray(new String[ex.customer.size()])); + } + b.receipt(r); + } + return b.build(); + } + + /// The end-of-day receipt lines, or null; copied by hand so no cast sits + /// under the caller's catch (ParparVM does not check casts). + private static String[] report(Exchange ex) { + int n = ex.merchant.size() + ex.customer.size(); + if (n == 0) { + return null; + } + String[] out = new String[n]; + int i = 0; + for (String s : ex.merchant) { + out[i++] = s; + } + for (String s : ex.customer) { + out[i++] = s; + } + return out; + } + + private void dropLink() { + registered = false; + link.close(); + } + + /// The pieces of a ZVT payment the follow-up commands need, as one + /// string: `receipt:trace:aid[:P]`. + static final class TxId { + int receipt; + int trace = -1; + byte[] aid; + boolean preAuthorization; + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(receipt).append(':'); + if (trace >= 0) { + sb.append(trace); + } + sb.append(':'); + if (aid != null) { + sb.append(ZvtCodec.hex(aid)); + } + if (preAuthorization) { + sb.append(":P"); + } + return sb.toString(); + } + + static TxId parse(String s) { + if (s == null) { + return null; + } + String[] parts = split(s); + try { + TxId id = new TxId(); + id.receipt = Integer.parseInt(parts[0]); + if (parts.length > 1 && parts[1].length() > 0) { + id.trace = Integer.parseInt(parts[1]); + } + if (parts.length > 2 && parts[2].length() > 0) { + id.aid = ZvtCodec.unhex(parts[2]); + } + id.preAuthorization = parts.length > 3 && "P".equals(parts[3]); + return id; + } catch (NumberFormatException e) { + return null; + } + } + + private static String[] split(String s) { + List out = new ArrayList(); + int start = 0; + int i = s.indexOf(':'); + while (i >= 0) { + out.add(s.substring(start, i)); + start = i + 1; + i = s.indexOf(':', start); + } + out.add(s.substring(start)); + return out.toArray(new String[out.size()]); + } + } + + private final class Money implements Runnable { + private final Apdu cmd; + private final boolean preAuthorization; + private final String reference; + private final AsyncResource out; + + Money(Apdu cmd, boolean preAuthorization, String reference, AsyncResource out) { + this.cmd = cmd; + this.preAuthorization = preAuthorization; + this.reference = reference; + this.out = out; + } + + @Override + public void run() { + try { + Exchange ex = execute(cmd); + complete(out, result(ex, preAuthorization, reference), null); + } catch (IOException e) { + dropLink(); + complete(out, null, e); + } catch (RuntimeException e) { + dropLink(); + complete(out, null, e); + } + } + } + + private final class EndOfDay implements Runnable { + private final Apdu cmd; + private final AsyncResource out; + + EndOfDay(Apdu cmd, AsyncResource out) { + this.cmd = cmd; + this.out = out; + } + + @Override + public void run() { + TerminalReconciliation rec = null; + Throwable err = null; + try { + Exchange ex = execute(cmd); + byte[][] s = ex.status; + long total = s != null && s[0x04] != null ? ZvtCodec.number(s[0x04], 0, 6) : -1; + String cur = s != null && s[0x49] != null + ? ZvtCodec.currencyCode((int) ZvtCodec.number(s[0x49], 0, 2)) : null; + closeReceipt(ex, 0); + rec = new TerminalReconciliation(ex.completed, -1, total, cur, + ex.completed ? null : describe(ex.abortCode < 0 ? 0xff : ex.abortCode), + report(ex)); + } catch (IOException e) { + dropLink(); + err = e; + } catch (RuntimeException e) { + dropLink(); + err = e; + } + busy.set(false); + final TerminalReconciliation r = rec; + final Throwable e = err; + deliver(new Runnable() { + @Override + public void run() { + if (e != null) { + out.error(e); + } else { + out.complete(r); + } + } + }); + } + } +} diff --git a/CodenameOne/src/com/codename1/payment/terminal/zvt/package-info.java b/CodenameOne/src/com/codename1/payment/terminal/zvt/package-info.java new file mode 100644 index 00000000000..afda72b10e7 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/zvt/package-info.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/// ZVT, the German protocol between a till and a card terminal, over a +/// serial cable or TCP. Most terminals sold in Germany, Austria and +/// Switzerland speak it -- Ingenico, Verifone, PAX, CCV and Worldline models +/// among them. +package com.codename1.payment.terminal.zvt; diff --git a/CodenameOne/src/com/codename1/pos/CustomerDisplay.java b/CodenameOne/src/com/codename1/pos/CustomerDisplay.java new file mode 100644 index 00000000000..248d35a8266 --- /dev/null +++ b/CodenameOne/src/com/codename1/pos/CustomerDisplay.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.pos; + +import com.codename1.io.link.ByteLink; +import java.io.IOException; + +/// A customer-facing pole display with the Epson DM-D (ESC/POS) command set, +/// two lines of 20 characters by default, as most VFD and LCD pole displays +/// accept. +/// +/// Its calls block; run them off the EDT. +public class CustomerDisplay { + private final ByteLink link; + private int width = 20; + + /// #### Parameters + /// + /// - `link`: the connection, usually serial or USB + public CustomerDisplay(ByteLink link) { + this.link = link; + } + + /// Characters per line. Defaults to 20. + /// + /// #### Parameters + /// + /// - `width`: the display's line width + public void setWidth(int width) { + this.width = width; + } + + /// Clears the display. + /// + /// #### Throws + /// + /// - `IOException`: when the display cannot be reached + public void clear() throws IOException { + link.open(); + link.write(new byte[] {0x1b, 0x40, 0x0c}); + } + + /// Shows two lines, each cut or padded to the width. + /// + /// #### Parameters + /// + /// - `top`: the first line + /// + /// - `bottom`: the second line + /// + /// #### Throws + /// + /// - `IOException`: when the display cannot be reached + public void show(String top, String bottom) throws IOException { + link.open(); + byte[] out = new byte[3 + width * 2]; + out[0] = 0x1b; + out[1] = 0x40; + out[2] = 0x0c; + fill(out, 3, top); + fill(out, 3 + width, bottom); + link.write(out); + } + + /// Shows a label on the left of the top line and an amount on the right + /// of the bottom line, the usual "item / total" layout. + /// + /// #### Parameters + /// + /// - `label`: the item or "TOTAL" + /// + /// - `amount`: the formatted amount + /// + /// #### Throws + /// + /// - `IOException`: when the display cannot be reached + public void showAmount(String label, String amount) throws IOException { + StringBuilder sb = new StringBuilder(); + for (int i = amount.length(); i < width; i++) { + sb.append(' '); + } + sb.append(amount); + show(label, sb.toString()); + } + + private void fill(byte[] out, int at, String s) { + String t = s == null ? "" : s; + for (int i = 0; i < width; i++) { + char c = i < t.length() ? t.charAt(i) : ' '; + out[at + i] = (byte) (c < 256 ? c : '?'); + } + } +} diff --git a/CodenameOne/src/com/codename1/pos/EscPosPrinter.java b/CodenameOne/src/com/codename1/pos/EscPosPrinter.java new file mode 100644 index 00000000000..ee2b9712769 --- /dev/null +++ b/CodenameOne/src/com/codename1/pos/EscPosPrinter.java @@ -0,0 +1,358 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.pos; + +import com.codename1.io.link.ByteLink; +import com.codename1.ui.CN; +import com.codename1.ui.Image; +import com.codename1.util.AsyncResource; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +/// A receipt printer that speaks ESC/POS -- Epson, Star in ESC/POS mode, +/// Bixolon, Xprinter and most thermal printers -- over the network (port +/// 9100), a serial line or USB. +/// +/// Calls build a job in memory; [#print()] sends it. +/// +/// ```java +/// EscPosPrinter p = new EscPosPrinter(new TcpLink("192.168.1.60", 9100)); +/// p.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(); +/// p.print().except(err -> Dialog.show("Printer", err.getMessage(), "OK", null)); +/// ``` +/// +/// Text goes out one byte per character in the printer's current code page +/// (code page 0, PC437, after [#reset()]); characters above 255 print as +/// `?`. +public class EscPosPrinter { + /// Left alignment, for [#align(int)]. + public static final int LEFT = 0; + /// Centered, for [#align(int)]. + public static final int CENTER = 1; + /// Right alignment, for [#align(int)]. + public static final int RIGHT = 2; + + private final ByteLink link; + private ByteArrayOutputStream job = new ByteArrayOutputStream(); + + /// #### Parameters + /// + /// - `link`: the connection to the printer; opened when printing + public EscPosPrinter(ByteLink link) { + this.link = link; + reset(); + } + + private EscPosPrinter raw(int... bytes) { + for (int b : bytes) { + job.write(b); + } + return this; + } + + /// Restores the printer's defaults (ESC @). + /// + /// #### Returns + /// + /// this printer + public final EscPosPrinter reset() { + return raw(0x1b, 0x40); + } + + /// Appends text without a line break. + /// + /// #### Parameters + /// + /// - `text`: the text + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter text(String text) { + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + job.write(c < 256 ? c : '?'); + } + return this; + } + + /// Appends a line of text. + /// + /// #### Parameters + /// + /// - `text`: the text + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter line(String text) { + return text(text).raw(0x0a); + } + + /// Bold on or off (ESC E). + /// + /// #### Parameters + /// + /// - `on`: true for bold + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter bold(boolean on) { + return raw(0x1b, 0x45, on ? 1 : 0); + } + + /// Underline on or off (ESC -). + /// + /// #### Parameters + /// + /// - `on`: true to underline + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter underline(boolean on) { + return raw(0x1b, 0x2d, on ? 1 : 0); + } + + /// Alignment of the following lines (ESC a). + /// + /// #### Parameters + /// + /// - `alignment`: [#LEFT], [#CENTER] or [#RIGHT] + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter align(int alignment) { + return raw(0x1b, 0x61, alignment); + } + + /// Character size as multiples of normal (GS !). + /// + /// #### Parameters + /// + /// - `width`: 1 to 8 + /// + /// - `height`: 1 to 8 + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter size(int width, int height) { + int w = Math.max(1, Math.min(8, width)) - 1; + int h = Math.max(1, Math.min(8, height)) - 1; + return raw(0x1d, 0x21, (w << 4) | h); + } + + /// Feeds blank lines (ESC d). + /// + /// #### Parameters + /// + /// - `lines`: how many + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter feed(int lines) { + return raw(0x1b, 0x64, Math.max(0, Math.min(255, lines))); + } + + /// Cuts the paper, partially where the printer supports it (GS V 1). + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter cut() { + return raw(0x1d, 0x56, 0x01); + } + + /// Kicks the cash drawer on the printer's drawer port (ESC p), pin 2. + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter openDrawer() { + return openDrawer(0); + } + + /// Kicks a cash drawer (ESC p). + /// + /// #### Parameters + /// + /// - `pin`: 0 for connector pin 2, 1 for pin 5 (a second drawer) + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter openDrawer(int pin) { + return raw(0x1b, 0x70, pin, 25, 250); + } + + /// A QR code (GS ( k, model 2, error correction M). + /// + /// #### Parameters + /// + /// - `data`: what it encodes, ASCII + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter qr(String data) { + return qr(data, 6); + } + + /// A QR code with a chosen module size. + /// + /// #### Parameters + /// + /// - `data`: what it encodes, ASCII + /// + /// - `moduleSize`: dots per module, 1 to 16 + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter qr(String data, int moduleSize) { + raw(0x1d, 0x28, 0x6b, 4, 0, 0x31, 0x41, 0x32, 0x00); + raw(0x1d, 0x28, 0x6b, 3, 0, 0x31, 0x43, Math.max(1, Math.min(16, moduleSize))); + raw(0x1d, 0x28, 0x6b, 3, 0, 0x31, 0x45, 0x31); + int len = data.length() + 3; + raw(0x1d, 0x28, 0x6b, len & 0xff, (len >> 8) & 0xff, 0x31, 0x50, 0x30); + text(data); + return raw(0x1d, 0x28, 0x6b, 3, 0, 0x31, 0x51, 0x30); + } + + /// A raster image (GS v 0), thresholded to black and white. Scale it to + /// the paper's width in dots first -- 384 for 58mm paper, 576 for 80mm. + /// + /// #### Parameters + /// + /// - `image`: the image + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter image(Image image) { + int w = image.getWidth(); + int h = image.getHeight(); + int[] rgb = image.getRGB(); + int bytesPerRow = (w + 7) / 8; + raw(0x1d, 0x76, 0x30, 0, bytesPerRow & 0xff, bytesPerRow >> 8, h & 0xff, h >> 8); + for (int y = 0; y < h; y++) { + for (int bx = 0; bx < bytesPerRow; bx++) { + int b = 0; + for (int bit = 0; bit < 8; bit++) { + int x = bx * 8 + bit; + if (x < w && dark(rgb[y * w + x])) { + b |= 0x80 >> bit; + } + } + job.write(b); + } + } + return this; + } + + private static boolean dark(int argb) { + int a = (argb >>> 24) & 0xff; + int lum = (((argb >> 16) & 0xff) * 299 + ((argb >> 8) & 0xff) * 587 + (argb & 0xff) * 114) / 1000; + return a > 127 && lum < 128; + } + + /// Appends raw bytes, for commands this class does not cover. + /// + /// #### Parameters + /// + /// - `bytes`: the bytes + /// + /// #### Returns + /// + /// this printer + public EscPosPrinter bytes(byte[] bytes) { + job.write(bytes, 0, bytes.length); + return this; + } + + /// The job built so far. + /// + /// #### Returns + /// + /// the bytes [#print()] would send + public byte[] getJob() { + return job.toByteArray(); + } + + /// Sends the job on the calling thread, which must not be the EDT, and + /// starts a new one. + /// + /// #### Throws + /// + /// - `IOException`: when the printer cannot be reached + public void send() throws IOException { + byte[] data = job.toByteArray(); + job = new ByteArrayOutputStream(); + link.open(); + link.write(data); + } + + /// Sends the job on a thread of its own and starts a new one. + /// + /// #### Returns + /// + /// completes on the EDT once the bytes are handed to the printer + public AsyncResource print() { + final AsyncResource out = new AsyncResource(); + final byte[] data = job.toByteArray(); + job = new ByteArrayOutputStream(); + new Thread(new Runnable() { + @Override + public void run() { + Throwable err = null; + try { + link.open(); + link.write(data); + } catch (IOException e) { + link.close(); + err = e; + } + final Throwable e = err; + CN.callSerially(new Runnable() { + @Override + public void run() { + if (e != null) { + out.error(e); + } else { + out.complete(Boolean.TRUE); + } + } + }); + } + }, "Printer").start(); + return out; + } +} diff --git a/CodenameOne/src/com/codename1/pos/LinkScanner.java b/CodenameOne/src/com/codename1/pos/LinkScanner.java new file mode 100644 index 00000000000..ee32691410e --- /dev/null +++ b/CodenameOne/src/com/codename1/pos/LinkScanner.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.pos; + +import com.codename1.io.link.ByteLink; +import com.codename1.ui.CN; +import com.codename1.util.SuccessCallback; +import java.io.IOException; +import java.util.concurrent.atomic.AtomicBoolean; + +/// A barcode scanner that sends each code as a line over a serial port, +/// USB serial or TCP. (A scanner in keyboard mode needs no class: it types +/// into the focused text field.) +/// +/// ```java +/// LinkScanner scanner = new LinkScanner(new SerialLink("/dev/ttyACM0", 9600)); +/// scanner.start(code -> System.out.println("Scanned " + code)); +/// ``` +public class LinkScanner { + private final ByteLink link; + private final AtomicBoolean running = new AtomicBoolean(); + + /// #### Parameters + /// + /// - `link`: the scanner's connection + public LinkScanner(ByteLink link) { + this.link = link; + } + + /// Starts reading on a thread of its own. Each code, without its line + /// ending, goes to `onScan` on the EDT. + /// + /// #### Parameters + /// + /// - `onScan`: receives each code + public void start(final SuccessCallback onScan) { + if (!running.compareAndSet(false, true)) { + return; + } + new Thread(new Runnable() { + @Override + public void run() { + StringBuilder code = new StringBuilder(); + byte[] buf = new byte[64]; + try { + link.open(); + while (running.get()) { + int n = link.read(buf, 0, buf.length, 500); + for (int i = 0; i < n; i++) { + int c = buf[i] & 0xff; + if (c == '\r' || c == '\n') { + if (code.length() > 0) { + deliver(onScan, code.toString()); + code.setLength(0); + } + } else { + code.append((char) c); + } + } + } + } catch (IOException e) { + // the link failed or was closed by stop() + } finally { + running.set(false); + link.close(); + } + } + }, "Scanner").start(); + } + + /// Stops reading and closes the link. + public void stop() { + running.set(false); + link.close(); + } + + private static void deliver(final SuccessCallback onScan, final String code) { + CN.callSerially(new Runnable() { + @Override + public void run() { + onScan.onSucess(code); + } + }); + } +} diff --git a/CodenameOne/src/com/codename1/pos/package-info.java b/CodenameOne/src/com/codename1/pos/package-info.java new file mode 100644 index 00000000000..f1a108ef1ea --- /dev/null +++ b/CodenameOne/src/com/codename1/pos/package-info.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/// Point-of-sale peripherals: ESC/POS receipt printers and the cash drawer +/// they drive, customer pole displays and serial barcode scanners, over the +/// byte links of `com.codename1.io.link`. +package com.codename1.pos; diff --git a/CodenameOne/src/com/codename1/ui/Display.java b/CodenameOne/src/com/codename1/ui/Display.java index 37c140b6690..eff1c0913a1 100644 --- a/CodenameOne/src/com/codename1/ui/Display.java +++ b/CodenameOne/src/com/codename1/ui/Display.java @@ -6841,6 +6841,17 @@ public com.codename1.webrtc.spi.WebRtcBridge getWebRtcBridge() { return impl.getWebRtcBridge(); } + /// Returns the platform bridge used by `com.codename1.payment.terminal.tap.TapToPay` to read + /// a card with the device, or null when unsupported. Internal -- application code uses + /// `TapToPay` rather than this bridge directly. + /// + /// #### Returns + /// + /// the Tap to Pay bridge, or null + public com.codename1.payment.terminal.spi.TapToPayBridge getTapToPayBridge() { + return impl.getTapToPayBridge(); + } + /// Returns the platform bridge used by the `com.codename1.vpn` API to manage VPN /// configurations, or null when unsupported on this port. Internal -- application code uses /// the `com.codename1.vpn` packages rather than this bridge directly. diff --git a/Ports/Android/build.xml b/Ports/Android/build.xml index 3c30dfbdc9f..15e411f4615 100644 --- a/Ports/Android/build.xml +++ b/Ports/Android/build.xml @@ -130,7 +130,7 @@ a package to one file is not adding it. --> + excludes="com/codename1/impl/android/ar/**,com/codename1/impl/android/ai/**,com/codename1/impl/android/cipher/**,com/codename1/impl/android/nearby/**,com/codename1/impl/android/webrtc/**,com/codename1/impl/android/taptopay/**,com/codename1/impl/android/unifiedpush/**,com/codename1/impl/android/referrer/**,com/codename1/impl/android/appupdate/**,com/codename1/impl/android/cast/**,com/codename1/impl/android/wallet/**,com/codename1/impl/android/biometrics/**,com/codename1/impl/android/BillingSupport.java,com/codename1/impl/android/AmazonBillingSupport.java"> diff --git a/Ports/Android/nbproject/project.properties b/Ports/Android/nbproject/project.properties index 14868dc4710..51f60ee1ca3 100644 --- a/Ports/Android/nbproject/project.properties +++ b/Ports/Android/nbproject/project.properties @@ -36,7 +36,7 @@ endorsed.classpath= # excludes= attribute in build.xml. The list lives in three files; the Maven # build is green with only one of them updated, so adding a package here alone # is not adding it. -excludes=com/codename1/impl/android/ar/**,com/codename1/impl/android/ai/**,com/codename1/impl/android/cipher/**,com/codename1/impl/android/nearby/**,com/codename1/impl/android/webrtc/**,com/codename1/impl/android/unifiedpush/**,com/codename1/impl/android/referrer/**,com/codename1/impl/android/appupdate/**,com/codename1/impl/android/cast/**,com/codename1/impl/android/wallet/**,com/codename1/impl/android/biometrics/**,com/codename1/impl/android/BillingSupport.java,com/codename1/impl/android/AmazonBillingSupport.java +excludes=com/codename1/impl/android/ar/**,com/codename1/impl/android/ai/**,com/codename1/impl/android/cipher/**,com/codename1/impl/android/nearby/**,com/codename1/impl/android/webrtc/**,com/codename1/impl/android/taptopay/**,com/codename1/impl/android/unifiedpush/**,com/codename1/impl/android/referrer/**,com/codename1/impl/android/appupdate/**,com/codename1/impl/android/cast/**,com/codename1/impl/android/wallet/**,com/codename1/impl/android/biometrics/**,com/codename1/impl/android/BillingSupport.java,com/codename1/impl/android/AmazonBillingSupport.java file.reference.android-support-v7-appcompat.jar=../../../cn1-binaries/android/android-support-v7-appcompat.jar file.reference.android-support-v7-cardview.jar=../../../cn1-binaries/android/android-support-v7-cardview.jar file.reference.android-support-v7-gridlayout.jar=../../../cn1-binaries/android/android-support-v7-gridlayout.jar diff --git a/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java b/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java index 1b47299a996..752cab6296d 100644 --- a/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java +++ b/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java @@ -16749,6 +16749,36 @@ public synchronized com.codename1.webrtc.spi.WebRtcBridge getWebRtcBridge() { return webRtcBridge; } + private com.codename1.payment.terminal.spi.TapToPayBridge tapToPayBridge; + private boolean tapToPayLoaded; + + /// The Tap to Pay bridge, loaded by name from the optional + /// `com.codename1.impl.android.taptopay` package -- the same way the + /// WebRTC backend is reached. The builder deletes that package, and + /// leaves the Stripe Terminal SDK out, for an app that never referenced + /// `com.codename1.payment.terminal.tap`; this then answers null, which + /// `TapToPay.isSupported()` reports as unsupported. + @Override + public synchronized com.codename1.payment.terminal.spi.TapToPayBridge getTapToPayBridge() { + if (!tapToPayLoaded) { + tapToPayLoaded = true; + Object instance = null; + try { + Class clazz = Class.forName( + "com.codename1.impl.android.taptopay.AndroidTapToPay"); + instance = clazz.getConstructor(android.content.Context.class) + .newInstance(getContext()); + } catch (Throwable t) { + // Expected: the package was not bundled. + instance = null; + } + // Tested rather than cast, so a mismatched class stays inert. + tapToPayBridge = instance instanceof com.codename1.payment.terminal.spi.TapToPayBridge + ? (com.codename1.payment.terminal.spi.TapToPayBridge) instance : null; + } + return tapToPayBridge; + } + private com.codename1.impl.android.call.AndroidCallBridge callBridge; private com.codename1.impl.android.vpn.AndroidVpnBridge vpnBridge; diff --git a/Ports/Android/src/com/codename1/impl/android/taptopay/AndroidTapToPay.java b/Ports/Android/src/com/codename1/impl/android/taptopay/AndroidTapToPay.java new file mode 100644 index 00000000000..229b30eddd1 --- /dev/null +++ b/Ports/Android/src/com/codename1/impl/android/taptopay/AndroidTapToPay.java @@ -0,0 +1,428 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.impl.android.taptopay; + +import android.app.Application; +import android.content.Context; +import android.content.pm.PackageManager; +import android.nfc.NfcAdapter; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import com.codename1.impl.android.AndroidImplementation; +import com.codename1.payment.terminal.tap.TapToPayCallbacks; +import com.codename1.payment.terminal.spi.TapToPayBridge; +import com.stripe.stripeterminal.Terminal; +import com.stripe.stripeterminal.TerminalApplicationDelegate; +import com.stripe.stripeterminal.external.callable.Callback; +import com.stripe.stripeterminal.external.callable.Cancelable; +import com.stripe.stripeterminal.external.callable.ConnectionTokenCallback; +import com.stripe.stripeterminal.external.callable.ConnectionTokenProvider; +import com.stripe.stripeterminal.external.callable.DiscoveryListener; +import com.stripe.stripeterminal.external.callable.PaymentIntentCallback; +import com.stripe.stripeterminal.external.callable.ReaderCallback; +import com.stripe.stripeterminal.external.callable.TerminalListener; +import com.stripe.stripeterminal.external.models.ConnectionConfiguration; +import com.stripe.stripeterminal.external.models.DiscoveryConfiguration; +import com.stripe.stripeterminal.external.models.LocaleConfig; +import com.stripe.stripeterminal.external.models.PaymentIntent; +import com.stripe.stripeterminal.external.models.PaymentIntentStatus; +import com.stripe.stripeterminal.external.models.Reader; +import com.stripe.stripeterminal.external.models.TapUseCase; +import com.stripe.stripeterminal.external.models.TerminalErrorCode; +import com.stripe.stripeterminal.external.models.TerminalException; +import com.stripe.stripeterminal.log.LogLevel; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/// Tap to Pay on Android, over the Stripe Terminal SDK +/// (`com.stripe:stripeterminal-taptopay`). +/// +/// Loaded by name from `AndroidImplementation.getTapToPayBridge()`. The +/// builder deletes this package, and leaves the SDK out of the Gradle +/// project, for an app that never referenced +/// `com.codename1.payment.terminal.tap`; the loader then answers null. +/// +/// Every SDK call and every field is confined to the main thread, through +/// [#main]: the SDK answers on threads of its own, and one thread owning the +/// state is what lets it go without locks. Answers to Java go through +/// [TapToPayCallbacks], which moves to the EDT itself. +/// +/// The SDK runs the card read in a separate process (`:stripetaptopay`, +/// declared by its own manifest). That process starts the app's +/// `Application` class, which for a Codename One app is the platform's own +/// and does nothing, so no `TapToPay.isInTapToPayProcess()` guard is needed. +public class AndroidTapToPay implements TapToPayBridge { + private final Context context; + private final Handler main = new Handler(Looper.getMainLooper()); + + private final Map tokenCallbacks = + new HashMap(); + private int nextTokenId = 1; + + private int activeRequest = -1; + private Cancelable collecting; + private Cancelable discovering; + private boolean cancelRequested; + private boolean connecting; + + public AndroidTapToPay(Context context) { + this.context = context.getApplicationContext(); + } + + @Override + public boolean isDeviceSupported() { + if (Build.VERSION.SDK_INT < 26) { + return false; + } + if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)) { + return false; + } + return NfcAdapter.getDefaultAdapter(context) != null; + } + + @Override + public void collect(final int requestId, final String clientSecret, long amount, + String currency, final String locationId, final String merchantDisplayName, + final boolean simulated) { + // Asked on the calling thread (the EDT): checkForPermission prompts + // through the port's usual flow and blocks until the user answers. + // Stripe refuses to connect a Tap to Pay reader without location. + if (!AndroidImplementation.checkForPermission("android.permission.ACCESS_FINE_LOCATION", + "Location is required to accept card payments")) { + TapToPayCallbacks.deliverResult(requestId, TapToPayCallbacks.STATUS_ERROR, null, + "Location permission denied"); + return; + } + main.post(new Runnable() { + @Override + public void run() { + if (activeRequest >= 0) { + TapToPayCallbacks.deliverResult(requestId, TapToPayCallbacks.STATUS_ERROR, null, + "A Tap to Pay payment is already in progress"); + return; + } + activeRequest = requestId; + cancelRequested = false; + try { + ensureInitialized(); + } catch (Throwable t) { + finishError(requestId, "Stripe Terminal could not start: " + t.getMessage()); + return; + } + Reader connected = Terminal.getInstance().getConnectedReader(); + if (connected != null) { + retrieve(requestId, clientSecret); + } else { + discoverAndConnect(requestId, clientSecret, locationId, merchantDisplayName, simulated); + } + } + }); + } + + private void ensureInitialized() throws TerminalException { + if (Terminal.isInitialized()) { + return; + } + if (context instanceof Application) { + TerminalApplicationDelegate.onCreate((Application) context); + } + Terminal.init(context, LogLevel.WARNING, new ConnectionTokenProvider() { + @Override + public void fetchConnectionToken(final ConnectionTokenCallback callback) { + main.post(new Runnable() { + @Override + public void run() { + int id = nextTokenId++; + tokenCallbacks.put(Integer.valueOf(id), callback); + TapToPayCallbacks.fetchConnectionToken(id); + } + }); + } + }, new TerminalListener() { + }, null, LocaleConfig.CardLanguagePreferenceIfAvailable.INSTANCE); + } + + @Override + public void connectionTokenReady(final int tokenRequestId, final String token, final String error) { + main.post(new Runnable() { + @Override + public void run() { + ConnectionTokenCallback cb = tokenCallbacks.remove(Integer.valueOf(tokenRequestId)); + if (cb == null) { + return; + } + if (token != null) { + cb.onSuccess(token); + } else { + cb.onFailure(new com.stripe.stripeterminal.external.models.ConnectionTokenException( + error == null ? "No connection token" : error)); + } + } + }); + } + + private void discoverAndConnect(final int requestId, final String clientSecret, + final String locationId, final String merchantDisplayName, boolean simulated) { + connecting = false; + discovering = Terminal.getInstance().discoverReaders( + new DiscoveryConfiguration.TapToPayDiscoveryConfiguration(simulated), + new DiscoveryListener() { + @Override + public void onUpdateDiscoveredReaders(final List readers) { + main.post(new Runnable() { + @Override + public void run() { + if (connecting || readers == null || readers.isEmpty() + || activeRequest != requestId) { + return; + } + connecting = true; + connect(requestId, readers.get(0), clientSecret, locationId, + merchantDisplayName); + } + }); + } + }, + new Callback() { + @Override + public void onSuccess() { + // Discovery ends once a reader is connected. + } + + @Override + public void onFailure(final TerminalException e) { + main.post(new Runnable() { + @Override + public void run() { + if (!connecting && activeRequest == requestId) { + finishError(requestId, describe(e)); + } + } + }); + } + }); + } + + private void connect(final int requestId, Reader reader, final String clientSecret, + String locationId, String merchantDisplayName) { + ConnectionConfiguration.TapToPayConnectionConfiguration config = + new ConnectionConfiguration.TapToPayConnectionConfiguration( + new TapUseCase.Pay(locationId), true, null, merchantDisplayName); + Terminal.getInstance().connectReader(reader, config, new ReaderCallback() { + @Override + public void onSuccess(Reader connected) { + main.post(new Runnable() { + @Override + public void run() { + retrieve(requestId, clientSecret); + } + }); + } + + @Override + public void onFailure(final TerminalException e) { + main.post(new Runnable() { + @Override + public void run() { + connecting = false; + finishError(requestId, describe(e)); + } + }); + } + }); + } + + private void retrieve(final int requestId, String clientSecret) { + if (cancelRequested) { + finish(requestId, TapToPayCallbacks.STATUS_CANCELED, null, null); + return; + } + Terminal.getInstance().retrievePaymentIntent(clientSecret, new IntentStep(requestId, false) { + @Override + void next(PaymentIntent intent) { + collectMethod(requestId, intent); + } + }); + } + + private void collectMethod(final int requestId, PaymentIntent intent) { + if (cancelRequested) { + finish(requestId, TapToPayCallbacks.STATUS_CANCELED, intent.getId(), null); + return; + } + collecting = Terminal.getInstance().collectPaymentMethod(intent, new IntentStep(requestId, true) { + @Override + void next(PaymentIntent collected) { + collecting = null; + confirm(requestId, collected); + } + }); + } + + private void confirm(final int requestId, PaymentIntent intent) { + Terminal.getInstance().confirmPaymentIntent(intent, new IntentStep(requestId, true, true) { + @Override + void next(PaymentIntent confirmed) { + PaymentIntentStatus s = confirmed.getStatus(); + if (s == PaymentIntentStatus.SUCCEEDED || s == PaymentIntentStatus.REQUIRES_CAPTURE) { + finish(requestId, TapToPayCallbacks.STATUS_APPROVED, confirmed.getId(), null); + } else { + finish(requestId, TapToPayCallbacks.STATUS_FAILED, confirmed.getId(), + "PaymentIntent status " + s); + } + } + }); + } + + @Override + public void cancel(final int requestId) { + main.post(new Runnable() { + @Override + public void run() { + if (activeRequest != requestId) { + return; + } + cancelRequested = true; + if (!connecting && discovering != null && !discovering.isCompleted()) { + // No reader yet: nothing is charged, end it now. The + // discovery is stopped by finish(). + finish(requestId, TapToPayCallbacks.STATUS_CANCELED, null, null); + return; + } + if (collecting != null && !collecting.isCompleted()) { + collecting.cancel(new Callback() { + @Override + public void onSuccess() { + // collectPaymentMethod answers CANCELED. + } + + @Override + public void onFailure(TerminalException e) { + // Too late: the card was read; the payment goes on. + } + }); + } + } + }); + } + + private void finish(int requestId, int status, String transactionId, String message) { + if (activeRequest != requestId) { + return; + } + activeRequest = -1; + collecting = null; + if (discovering != null && !discovering.isCompleted()) { + // A discovery left running makes the next one fail. + discovering.cancel(new Callback() { + @Override + public void onSuccess() { + } + + @Override + public void onFailure(TerminalException e) { + } + }); + } + discovering = null; + TapToPayCallbacks.deliverResult(requestId, status, transactionId, message); + } + + private void finishError(int requestId, String message) { + finish(requestId, TapToPayCallbacks.STATUS_ERROR, null, message); + } + + private static String describe(TerminalException e) { + if (e == null) { + return "Stripe Terminal failed"; + } + return e.getErrorCode() + ": " + e.getErrorMessage(); + } + + /// A PaymentIntent step: success continues, failure ends the payment + /// with the status the error code means. Before a card was asked for + /// (`afterCollect` false), a failure is an error, not a declined card. + private abstract class IntentStep implements PaymentIntentCallback { + private final int requestId; + private final boolean afterCollect; + private final boolean confirming; + + IntentStep(int requestId, boolean afterCollect) { + this(requestId, afterCollect, false); + } + + IntentStep(int requestId, boolean afterCollect, boolean confirming) { + this.requestId = requestId; + this.afterCollect = afterCollect; + this.confirming = confirming; + } + + abstract void next(PaymentIntent intent); + + @Override + public void onSuccess(final PaymentIntent intent) { + main.post(new Runnable() { + @Override + public void run() { + if (activeRequest == requestId) { + next(intent); + } + } + }); + } + + @Override + public void onFailure(final TerminalException e) { + main.post(new Runnable() { + @Override + public void run() { + TerminalErrorCode code = e == null ? null : e.getErrorCode(); + PaymentIntent pi = e == null ? null : e.getPaymentIntent(); + String id = pi == null ? null : pi.getId(); + int status; + if (code == TerminalErrorCode.CANCELED || code == TerminalErrorCode.CANCELED_BY_READER) { + status = TapToPayCallbacks.STATUS_CANCELED; + } else if (code == TerminalErrorCode.DECLINED_BY_STRIPE_API + || code == TerminalErrorCode.DECLINED_BY_READER) { + status = TapToPayCallbacks.STATUS_DECLINED; + } else if (confirming) { + // Stripe: a confirm that fails for any other reason + // (network, timeout) may still have charged the + // card. Not FAILED, which invites a second charge. + finish(requestId, TapToPayCallbacks.STATUS_UNKNOWN, id, + "The payment's outcome is unknown; check PaymentIntent " + + id + " before charging again (" + describe(e) + ")"); + return; + } else if (afterCollect) { + status = TapToPayCallbacks.STATUS_FAILED; + } else { + status = TapToPayCallbacks.STATUS_ERROR; + } + finish(requestId, status, id, describe(e)); + } + }); + } + } +} diff --git a/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java b/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java index d53fa531014..d2ad643ccf3 100644 --- a/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java +++ b/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java @@ -20525,6 +20525,23 @@ public com.codename1.webrtc.spi.WebRtcBridge getWebRtcBridge() { return webRtc; } + private com.codename1.impl.javase.taptopay.SimulatedTapToPay tapToPay; + + /// The simulator's simulated phone: see + /// [com.codename1.impl.javase.taptopay.SimulatedTapToPay]. A desktop + /// build has no NFC reader to pay with, so it answers null; a desktop + /// point of sale uses a network terminal instead. + @Override + public com.codename1.payment.terminal.spi.TapToPayBridge getTapToPayBridge() { + if (!isSimulator()) { + return null; + } + if (tapToPay == null) { + tapToPay = new com.codename1.impl.javase.taptopay.SimulatedTapToPay(); + } + return tapToPay; + } + /// The VPN bridge for the simulator and desktop builds: a simulated /// configuration store that tunnels nothing. /// diff --git a/Ports/JavaSE/src/com/codename1/impl/javase/taptopay/SimulatedTapToPay.java b/Ports/JavaSE/src/com/codename1/impl/javase/taptopay/SimulatedTapToPay.java new file mode 100644 index 00000000000..4883c0b91eb --- /dev/null +++ b/Ports/JavaSE/src/com/codename1/impl/javase/taptopay/SimulatedTapToPay.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.impl.javase.taptopay; + +import com.codename1.payment.terminal.tap.TapToPayCallbacks; +import com.codename1.payment.terminal.spi.TapToPayBridge; +import com.codename1.ui.CN; +import java.util.HashMap; +import java.util.Map; + +/// The simulator's Tap to Pay phone. +/// +/// It goes through the same steps a device does where the app can see them: +/// it asks the app's connection token provider for a token first (so a +/// broken token endpoint fails here, not on a phone), then waits as a +/// customer would and answers. The amount picks the outcome -- one ending +/// in `01` is declined, one ending in `02` fails, anything else is approved -- +/// so every path of an app can be exercised without a card. +public class SimulatedTapToPay implements TapToPayBridge { + /// How long the simulated customer takes to tap, in milliseconds. + private static final int TAP_DELAY = 1500; + + private final Map tokenToRequest = new HashMap(); + private final Map amounts = new HashMap(); + private int nextToken = 1; + + @Override + public boolean isDeviceSupported() { + return true; + } + + @Override + public void collect(int requestId, String clientSecret, long amount, String currency, + String locationId, String merchantDisplayName, boolean simulated) { + int token = nextToken++; + tokenToRequest.put(Integer.valueOf(token), Integer.valueOf(requestId)); + amounts.put(Integer.valueOf(requestId), Long.valueOf(amount)); + TapToPayCallbacks.fetchConnectionToken(token); + } + + @Override + public void connectionTokenReady(int tokenRequestId, String token, String error) { + Integer requestId = tokenToRequest.remove(Integer.valueOf(tokenRequestId)); + if (requestId == null) { + return; + } + final int id = requestId.intValue(); + if (error != null) { + amounts.remove(requestId); + TapToPayCallbacks.deliverResult(id, TapToPayCallbacks.STATUS_ERROR, null, + "Connection token: " + error); + return; + } + CN.setTimeout(TAP_DELAY, new Runnable() { + @Override + public void run() { + Long amount = amounts.remove(Integer.valueOf(id)); + if (amount == null) { + // Canceled while waiting. + return; + } + long cents = amount.longValue() % 100; + String pi = "pi_simulated_" + id; + if (cents == 1) { + TapToPayCallbacks.deliverResult(id, TapToPayCallbacks.STATUS_DECLINED, pi, + "card_declined (simulated)"); + } else if (cents == 2) { + TapToPayCallbacks.deliverResult(id, TapToPayCallbacks.STATUS_FAILED, pi, + "The card was removed too soon (simulated)"); + } else { + TapToPayCallbacks.deliverResult(id, TapToPayCallbacks.STATUS_APPROVED, pi, null); + } + } + }); + } + + @Override + public void cancel(int requestId) { + if (amounts.remove(Integer.valueOf(requestId)) != null) { + TapToPayCallbacks.deliverResult(requestId, TapToPayCallbacks.STATUS_CANCELED, null, null); + } + } +} diff --git a/Ports/iOSPort/nativeSources/CN1TapToPay.m b/Ports/iOSPort/nativeSources/CN1TapToPay.m new file mode 100644 index 00000000000..95d717ead4f --- /dev/null +++ b/Ports/iOSPort/nativeSources/CN1TapToPay.m @@ -0,0 +1,446 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +// Tap to Pay on iPhone over StripeTerminal: the natives behind +// com.codename1.impl.ios.IOSTapToPay. +// +// Compiled for real only when IPhoneBuilder uncommented +// CN1_INCLUDE_TAP_TO_PAY (the app references +// com.codename1.payment.terminal.tap) and the StripeTerminal framework the +// catalog adds is on the header path. Otherwise every native is a stub and +// isTapToPayCompiled answers false, so IOSImplementation never hands out the +// bridge -- the stubs are never asked a request, and in such a build the +// TapToPayCallbacks class was not translated, so its header does not exist. +// +// Memory: the port builds without ARC. Every piece of state lives in a +// static, is touched only on the main queue, and is retained explicitly; +// completion blocks capture ints, never store into __block variables. + +#import "CodenameOne_GLViewController.h" + +#if defined(CN1_INCLUDE_TAP_TO_PAY) && !TARGET_OS_TV && !TARGET_OS_WATCH && !TARGET_OS_OSX && __has_include() +#define CN1_TAP_TO_PAY_HAS_SDK 1 +#endif + +#ifdef CN1_TAP_TO_PAY_HAS_SDK + +// The SDK's headers declare object properties with no ownership attribute, +// which clang warns about in a non-ARC file such as this one. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wobjc-property-no-attribute" +#import +#pragma clang diagnostic pop +#include "com_codename1_payment_terminal_tap_TapToPayCallbacks.h" +#import "java_lang_String.h" + +extern JAVA_OBJECT fromNSString(CODENAME_ONE_THREAD_STATE, NSString *str); +extern NSString *toNSString(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT str); + +// Mirrors TapToPayCallbacks.STATUS_*. +#define CN1T_APPROVED 0 +#define CN1T_DECLINED 1 +#define CN1T_CANCELED 2 +#define CN1T_FAILED 3 +#define CN1T_ERROR 4 +#define CN1T_UNKNOWN 5 + +static JAVA_OBJECT cn1tJString(NSString *s) { + return s == nil ? JAVA_NULL : fromNSString(getThreadLocalData(), s); +} + +static NSString *cn1tNSString(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT s) { + return s == JAVA_NULL ? nil : toNSString(threadStateData, s); +} + +static void cn1tOnMain(dispatch_block_t block) { + if ([NSThread isMainThread]) { + block(); + } else { + dispatch_async(dispatch_get_main_queue(), block); + } +} + +static void cn1tDeliver(int requestId, int status, NSString *transactionId, NSString *message) { + com_codename1_payment_terminal_tap_TapToPayCallbacks_deliverResult___int_int_java_lang_String_java_lang_String( + getThreadLocalData(), requestId, status, cn1tJString(transactionId), cn1tJString(message)); +} + +// ---- State, owned by the main queue ---- + +static int cn1tActiveRequest = -1; +static BOOL cn1tCancelRequested = NO; +static BOOL cn1tConnecting = NO; +static SCPCancelable *cn1tCollecting = nil; +static SCPCancelable *cn1tDiscovery = nil; +static NSMutableDictionary *cn1tTokenCompletions = nil; +static int cn1tNextTokenId = 1; + +static void cn1tSetCollecting(SCPCancelable *c) { + [c retain]; + [cn1tCollecting release]; + cn1tCollecting = c; +} + +static void cn1tSetDiscovery(SCPCancelable *c) { + [c retain]; + [cn1tDiscovery release]; + cn1tDiscovery = c; +} + +static void cn1tFinish(int requestId, int status, NSString *transactionId, NSString *message) { + if (cn1tActiveRequest != requestId) { + return; + } + cn1tActiveRequest = -1; + cn1tSetCollecting(nil); + cn1tDeliver(requestId, status, transactionId, message); +} + +static int cn1tStatusForError(NSError *error, BOOL afterCollect) { + if ([error.domain isEqualToString:SCPErrorDomain]) { + if (error.code == SCPErrorCanceled) { + return CN1T_CANCELED; + } + if (error.code == SCPErrorDeclinedByStripeAPI || error.code == SCPErrorDeclinedByReader) { + return CN1T_DECLINED; + } + } + return afterCollect ? CN1T_FAILED : CN1T_ERROR; +} + +// ---- The SDK's delegates: one object, alive for the process ---- + +@interface CN1TapToPayDelegate : NSObject +@property (nonatomic, assign) int discoveryRequest; +@property (nonatomic, copy) NSString *clientSecret; +@property (nonatomic, copy) NSString *locationId; +@property (nonatomic, copy) NSString *merchantDisplayName; +@end + +static CN1TapToPayDelegate *cn1tDelegate = nil; + +static void cn1tRetrieve(int requestId, NSString *clientSecret); + +static void cn1tEnsureInitialized(void) { + if (cn1tDelegate == nil) { + cn1tDelegate = [[CN1TapToPayDelegate alloc] init]; + cn1tTokenCompletions = [[NSMutableDictionary alloc] init]; + } + if (![SCPTerminal isInitialized]) { + [SCPTerminal initWithTokenProvider:cn1tDelegate]; + } +} + +@implementation CN1TapToPayDelegate + +- (void)fetchConnectionToken:(SCPConnectionTokenCompletionBlock)completion { + SCPConnectionTokenCompletionBlock copied = [completion copy]; + cn1tOnMain(^{ + int tokenId = cn1tNextTokenId++; + [cn1tTokenCompletions setObject:copied forKey:[NSNumber numberWithInt:tokenId]]; + [copied release]; + com_codename1_payment_terminal_tap_TapToPayCallbacks_fetchConnectionToken___int( + getThreadLocalData(), tokenId); + }); +} + +- (void)terminal:(SCPTerminal *)terminal didUpdateDiscoveredReaders:(NSArray *)readers { + int requestId = self.discoveryRequest; + SCPReader *reader = readers.count > 0 ? [readers objectAtIndex:0] : nil; + if (reader == nil || cn1tConnecting || cn1tActiveRequest != requestId) { + return; + } + cn1tConnecting = YES; + NSError *configError = nil; + SCPTapToPayConnectionConfigurationBuilder *builder = + [[[SCPTapToPayConnectionConfigurationBuilder alloc] initWithDelegate:self + locationId:self.locationId] autorelease]; + [builder setAutoReconnectOnUnexpectedDisconnect:YES]; + if (self.merchantDisplayName != nil) { + [builder setMerchantDisplayName:self.merchantDisplayName]; + } + SCPTapToPayConnectionConfiguration *config = [builder build:&configError]; + if (config == nil) { + cn1tFinish(requestId, CN1T_ERROR, nil, configError.localizedDescription); + return; + } + NSString *secret = self.clientSecret; + [[SCPTerminal shared] connectReader:reader connectionConfig:config + completion:^(SCPReader *connected, NSError *error) { + cn1tOnMain(^{ + if (error != nil) { + cn1tFinish(requestId, CN1T_ERROR, nil, error.localizedDescription); + } else { + cn1tRetrieve(requestId, secret); + } + }); + }]; +} + +// SCPReaderInteractionDelegate's required methods. Stripe drives the payment +// sheet itself for Tap to Pay, so there is nothing to show from here. +- (void)reader:(SCPReader *)reader didStartInstallingUpdate:(SCPReaderSoftwareUpdate *)update + cancelable:(SCPCancelable *)cancelable { +} + +- (void)reader:(SCPReader *)reader didReportReaderSoftwareUpdateProgress:(float)progress { +} + +- (void)reader:(SCPReader *)reader didFinishInstallingUpdate:(SCPReaderSoftwareUpdate *)update + error:(NSError *)error { +} + +- (void)reader:(SCPReader *)reader didRequestReaderInput:(SCPReaderInputOptions)inputOptions { +} + +- (void)reader:(SCPReader *)reader didRequestReaderDisplayMessage:(SCPReaderDisplayMessage)displayMessage { +} + +@end + +// ---- The payment ---- + +static void cn1tConfirm(int requestId, SCPPaymentIntent *intent) { + [[SCPTerminal shared] confirmPaymentIntent:intent + completion:^(SCPPaymentIntent *confirmed, SCPConfirmPaymentIntentError *error) { + NSString *transactionId = confirmed != nil ? confirmed.stripeId + : (error.paymentIntent != nil ? error.paymentIntent.stripeId : nil); + if (error != nil) { + int status = cn1tStatusForError(error, YES); + NSString *message = error.declineCode != nil ? error.declineCode : error.localizedDescription; + if (status == CN1T_FAILED) { + // Stripe: a confirm that fails for any other reason than a + // decline (network, timeout) may still have charged the card, + // so it is not reported as FAILED, which invites a retry. + status = CN1T_UNKNOWN; + message = [NSString stringWithFormat:@"The payment's outcome is unknown; check PaymentIntent %@ before charging again (%@)", + transactionId, error.localizedDescription]; + } + cn1tOnMain(^{ cn1tFinish(requestId, status, transactionId, message); }); + return; + } + BOOL ok = confirmed.status == SCPPaymentIntentStatusSucceeded + || confirmed.status == SCPPaymentIntentStatusRequiresCapture; + cn1tOnMain(^{ + cn1tFinish(requestId, ok ? CN1T_APPROVED : CN1T_FAILED, transactionId, + ok ? nil : @"PaymentIntent did not succeed"); + }); + }]; +} + +static void cn1tCollect(int requestId, SCPPaymentIntent *intent) { + if (cn1tCancelRequested) { + cn1tFinish(requestId, CN1T_CANCELED, intent.stripeId, nil); + return; + } + SCPCancelable *c = [[SCPTerminal shared] collectPaymentMethod:intent + completion:^(SCPPaymentIntent *collected, NSError *error) { + cn1tOnMain(^{ + if (cn1tActiveRequest != requestId) { + return; + } + cn1tSetCollecting(nil); + if (error != nil) { + cn1tFinish(requestId, cn1tStatusForError(error, YES), intent.stripeId, + error.localizedDescription); + } else { + cn1tConfirm(requestId, collected); + } + }); + }]; + cn1tSetCollecting(c); +} + +static void cn1tRetrieve(int requestId, NSString *clientSecret) { + if (cn1tCancelRequested) { + cn1tFinish(requestId, CN1T_CANCELED, nil, nil); + return; + } + [[SCPTerminal shared] retrievePaymentIntent:clientSecret + completion:^(SCPPaymentIntent *intent, NSError *error) { + cn1tOnMain(^{ + if (cn1tActiveRequest != requestId) { + return; + } + if (error != nil) { + cn1tFinish(requestId, cn1tStatusForError(error, NO), nil, error.localizedDescription); + } else { + cn1tCollect(requestId, intent); + } + }); + }]; +} + +// ---- Natives ---- + +JAVA_BOOLEAN com_codename1_impl_ios_IOSTapToPay_isTapToPayCompiled___R_boolean( + CODENAME_ONE_THREAD_STATE, JAVA_OBJECT __cn1ThisObject) { + return JAVA_TRUE; +} + +JAVA_BOOLEAN com_codename1_impl_ios_IOSTapToPay_isTapToPayDeviceSupported___R_boolean( + CODENAME_ONE_THREAD_STATE, JAVA_OBJECT __cn1ThisObject) { + // supportsReadersOfType is an instance method, so the SDK is initialized + // first; that needs only the token provider, and fetches nothing. + __block BOOL supported = NO; + dispatch_block_t check = ^{ + cn1tEnsureInitialized(); + NSError *error = nil; + supported = [[SCPTerminal shared] supportsReadersOfType:SCPDeviceTypeTapToPay + discoveryMethod:SCPDiscoveryMethodTapToPay + simulated:NO + error:&error]; + }; + // A BOOL in a __block variable is a value, not an object: nothing to retain. + if ([NSThread isMainThread]) { + check(); + } else { + dispatch_sync(dispatch_get_main_queue(), check); + } + return supported ? JAVA_TRUE : JAVA_FALSE; +} + +JAVA_VOID com_codename1_impl_ios_IOSTapToPay_tapToPayCollect___int_java_lang_String_long_java_lang_String_java_lang_String_java_lang_String_boolean( + CODENAME_ONE_THREAD_STATE, JAVA_OBJECT __cn1ThisObject, JAVA_INT requestId, JAVA_OBJECT clientSecret, + JAVA_LONG amount, JAVA_OBJECT currency, JAVA_OBJECT locationId, JAVA_OBJECT merchantDisplayName, + JAVA_BOOLEAN simulated) { + // Converted on the calling thread, where the Java strings are alive; the + // block retains the NSStrings it captures. + NSString *secret = cn1tNSString(threadStateData, clientSecret); + NSString *location = cn1tNSString(threadStateData, locationId); + NSString *merchant = cn1tNSString(threadStateData, merchantDisplayName); + int rid = requestId; + BOOL sim = simulated ? YES : NO; + cn1tOnMain(^{ + if (cn1tActiveRequest >= 0) { + cn1tDeliver(rid, CN1T_ERROR, nil, @"A Tap to Pay payment is already in progress"); + return; + } + cn1tActiveRequest = rid; + cn1tCancelRequested = NO; + cn1tEnsureInitialized(); + if ([SCPTerminal shared].connectedReader != nil) { + cn1tRetrieve(rid, secret); + return; + } + NSError *configError = nil; + SCPTapToPayDiscoveryConfigurationBuilder *builder = + [[[SCPTapToPayDiscoveryConfigurationBuilder alloc] init] autorelease]; + [builder setSimulated:sim]; + SCPTapToPayDiscoveryConfiguration *config = [builder build:&configError]; + if (config == nil) { + cn1tFinish(rid, CN1T_ERROR, nil, configError.localizedDescription); + return; + } + cn1tConnecting = NO; + cn1tDelegate.discoveryRequest = rid; + cn1tDelegate.clientSecret = secret; + cn1tDelegate.locationId = location; + cn1tDelegate.merchantDisplayName = merchant; + SCPCancelable *d = [[SCPTerminal shared] discoverReaders:config delegate:cn1tDelegate + completion:^(NSError *error) { + cn1tOnMain(^{ + cn1tSetDiscovery(nil); + if (error != nil && !cn1tConnecting && cn1tActiveRequest == rid) { + cn1tFinish(rid, cn1tStatusForError(error, NO), nil, error.localizedDescription); + } + }); + }]; + cn1tSetDiscovery(d); + }); +} + +JAVA_VOID com_codename1_impl_ios_IOSTapToPay_tapToPayCancel___int( + CODENAME_ONE_THREAD_STATE, JAVA_OBJECT __cn1ThisObject, JAVA_INT requestId) { + int rid = requestId; + cn1tOnMain(^{ + if (cn1tActiveRequest != rid) { + return; + } + cn1tCancelRequested = YES; + if (cn1tCollecting != nil && !cn1tCollecting.completed) { + // collectPaymentMethod then answers SCPErrorCanceled. + [cn1tCollecting cancel:^(NSError *error) { + }]; + } else if (cn1tDiscovery != nil && !cn1tConnecting && !cn1tDiscovery.completed) { + [cn1tDiscovery cancel:^(NSError *error) { + }]; + cn1tFinish(rid, CN1T_CANCELED, nil, nil); + } + }); +} + +JAVA_VOID com_codename1_impl_ios_IOSTapToPay_tapToPayTokenReady___int_java_lang_String_java_lang_String( + CODENAME_ONE_THREAD_STATE, JAVA_OBJECT __cn1ThisObject, JAVA_INT tokenRequestId, JAVA_OBJECT token, + JAVA_OBJECT error) { + NSString *t = cn1tNSString(threadStateData, token); + NSString *e = cn1tNSString(threadStateData, error); + int tid = tokenRequestId; + cn1tOnMain(^{ + NSNumber *key = [NSNumber numberWithInt:tid]; + SCPConnectionTokenCompletionBlock completion = [cn1tTokenCompletions objectForKey:key]; + if (completion == nil) { + return; + } + // Retained across the removal: the dictionary held the only reference. + [completion retain]; + [cn1tTokenCompletions removeObjectForKey:key]; + if (t != nil) { + completion(t, nil); + } else { + NSDictionary *info = [NSDictionary dictionaryWithObject:(e != nil ? e : @"No connection token") + forKey:NSLocalizedDescriptionKey]; + completion(nil, [NSError errorWithDomain:@"CN1TapToPay" code:1 userInfo:info]); + } + [completion release]; + }); +} + +#else // no SDK: the stubs + +JAVA_BOOLEAN com_codename1_impl_ios_IOSTapToPay_isTapToPayCompiled___R_boolean( + CODENAME_ONE_THREAD_STATE, JAVA_OBJECT __cn1ThisObject) { + return JAVA_FALSE; +} + +JAVA_BOOLEAN com_codename1_impl_ios_IOSTapToPay_isTapToPayDeviceSupported___R_boolean( + CODENAME_ONE_THREAD_STATE, JAVA_OBJECT __cn1ThisObject) { + return JAVA_FALSE; +} + +JAVA_VOID com_codename1_impl_ios_IOSTapToPay_tapToPayCollect___int_java_lang_String_long_java_lang_String_java_lang_String_java_lang_String_boolean( + CODENAME_ONE_THREAD_STATE, JAVA_OBJECT __cn1ThisObject, JAVA_INT requestId, JAVA_OBJECT clientSecret, + JAVA_LONG amount, JAVA_OBJECT currency, JAVA_OBJECT locationId, JAVA_OBJECT merchantDisplayName, + JAVA_BOOLEAN simulated) { +} + +JAVA_VOID com_codename1_impl_ios_IOSTapToPay_tapToPayCancel___int( + CODENAME_ONE_THREAD_STATE, JAVA_OBJECT __cn1ThisObject, JAVA_INT requestId) { +} + +JAVA_VOID com_codename1_impl_ios_IOSTapToPay_tapToPayTokenReady___int_java_lang_String_java_lang_String( + CODENAME_ONE_THREAD_STATE, JAVA_OBJECT __cn1ThisObject, JAVA_INT tokenRequestId, JAVA_OBJECT token, + JAVA_OBJECT error) { +} + +#endif diff --git a/Ports/iOSPort/nativeSources/CodenameOne_GLViewController.h b/Ports/iOSPort/nativeSources/CodenameOne_GLViewController.h index 0d2abf5e83c..2849dea1cb6 100644 --- a/Ports/iOSPort/nativeSources/CodenameOne_GLViewController.h +++ b/Ports/iOSPort/nativeSources/CodenameOne_GLViewController.h @@ -454,6 +454,18 @@ BOOL cn1_watch_apply_mirrored_surface(NSString *kind, NSData *json, #undef CN1_INCLUDE_WEBRTC #endif +// CN1_INCLUDE_TAP_TO_PAY gates the com.codename1.payment.terminal.tap native +// bridge (CN1TapToPay.m over StripeTerminal). IPhoneBuilder uncomments it +// only when the classpath scanner saw com.codename1.payment.terminal.tap.*; +// the network terminals beside that package need no native code. Off, the +// natives still exist and report the feature absent. +//#define CN1_INCLUDE_TAP_TO_PAY + +// StripeTerminal ships iOS device and simulator slices only. +#if TARGET_OS_TV || TARGET_OS_WATCH || TARGET_OS_OSX || TARGET_OS_MACCATALYST +#undef CN1_INCLUDE_TAP_TO_PAY +#endif + // CN1_INCLUDE_VPN gates the com.codename1.vpn native bridge (CN1Vpn.{h,m}: // NEVPNManager and the IKEv2/IPsec protocol configuration). Note this is a // different thing from the VPN DETECTION in IOSNative.m, which is always diff --git a/Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java b/Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java index f8afd2f8ad6..a01e314fc7d 100644 --- a/Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java +++ b/Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java @@ -487,6 +487,23 @@ public com.codename1.home.spi.HomeBridge getHomeBridge() { private IOSWebRtc webRtc; + @Override + public com.codename1.payment.terminal.spi.TapToPayBridge getTapToPayBridge() { + // Null when CN1_INCLUDE_TAP_TO_PAY was off: the builder enables it + // only for an app that references com.codename1.payment.terminal.tap, + // and only then is StripeTerminal linked. + if (tapToPay == null) { + IOSTapToPay candidate = new IOSTapToPay(); + if (!candidate.isTapToPayCompiled()) { + return null; + } + tapToPay = candidate; + } + return tapToPay; + } + + private IOSTapToPay tapToPay; + /// The WebRTC bridge, on the WebRTC framework. /// /// Unlike [#getCallBridge()] this answers null when the build did not diff --git a/Ports/iOSPort/src/com/codename1/impl/ios/IOSTapToPay.java b/Ports/iOSPort/src/com/codename1/impl/ios/IOSTapToPay.java new file mode 100644 index 00000000000..c5bd70d9223 --- /dev/null +++ b/Ports/iOSPort/src/com/codename1/impl/ios/IOSTapToPay.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.impl.ios; + +import com.codename1.payment.terminal.spi.TapToPayBridge; + +/// The iOS [TapToPayBridge], over StripeTerminal; the natives are in +/// `CN1TapToPay.m`. They are declared here rather than on [IOSNative], which +/// is past the size SpotBugs analyses (see `IOSFeatureNative`). +/// +/// Answers come back through the static +/// `com.codename1.payment.terminal.tap.TapToPayCallbacks` methods, which +/// move to the EDT themselves. +class IOSTapToPay implements TapToPayBridge { + /// True when this build compiled the natives in (`CN1_INCLUDE_TAP_TO_PAY`). + native boolean isTapToPayCompiled(); + + native boolean isTapToPayDeviceSupported(); + + native void tapToPayCollect(int requestId, String clientSecret, long amount, String currency, + String locationId, String merchantDisplayName, boolean simulated); + + native void tapToPayCancel(int requestId); + + native void tapToPayTokenReady(int tokenRequestId, String token, String error); + + @Override + public boolean isDeviceSupported() { + return isTapToPayDeviceSupported(); + } + + @Override + public void collect(int requestId, String clientSecret, long amount, String currency, + String locationId, String merchantDisplayName, boolean simulated) { + tapToPayCollect(requestId, clientSecret, amount, currency, locationId, + merchantDisplayName, simulated); + } + + @Override + public void cancel(int requestId) { + tapToPayCancel(requestId); + } + + @Override + public void connectionTokenReady(int tokenRequestId, String token, String error) { + tapToPayTokenReady(tokenRequestId, token, error); + } +} diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava001Snippet.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava001Snippet.java new file mode 100644 index 00000000000..ec958995ecc --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava001Snippet.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.snippets.generated; + +import com.codename1.io.Log; +import com.codename1.payment.terminal.*; +import com.codename1.payment.terminal.adyen.*; +import com.codename1.payment.terminal.stripe.*; +import com.codename1.payment.terminal.tap.*; +import com.codename1.ui.*; +import com.codename1.util.*; + +class CardTerminalsJava001Snippet { + String clientSecretFromServer = "pi_123_secret_456"; + String stripeKey = "sk_test_123"; + String adyenKey = "test-key"; + + AsyncResource fetchTokenFromMyServer() { + return new AsyncResource(); + } + + void sample() { + // tag::card-terminals-java-001[] + // Both values come from your server; these are placeholders. + String clientSecretFromServer = "pi_123_secret_456"; + ConnectionTokenProvider tokens = () -> { + AsyncResource 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); + } + }); + } + // end::card-terminals-java-001[] + } +} diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava002Snippet.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava002Snippet.java new file mode 100644 index 00000000000..5e5f313771c --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava002Snippet.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.snippets.generated; + +import com.codename1.io.Log; +import com.codename1.payment.terminal.*; +import com.codename1.payment.terminal.adyen.*; +import com.codename1.payment.terminal.stripe.*; +import com.codename1.payment.terminal.tap.*; +import com.codename1.ui.*; +import com.codename1.util.*; + +class CardTerminalsJava002Snippet { + String clientSecretFromServer = "pi_123_secret_456"; + String stripeKey = "sk_test_123"; + String adyenKey = "test-key"; + + AsyncResource fetchTokenFromMyServer() { + return new AsyncResource(); + } + + void sample() { + // tag::card-terminals-java-002[] + 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()); + }); + // end::card-terminals-java-002[] + } +} diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava003Snippet.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava003Snippet.java new file mode 100644 index 00000000000..be90271db8e --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava003Snippet.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.snippets.generated; + +import com.codename1.io.Log; +import com.codename1.payment.terminal.*; +import com.codename1.payment.terminal.adyen.*; +import com.codename1.payment.terminal.stripe.*; +import com.codename1.payment.terminal.tap.*; +import com.codename1.ui.*; +import com.codename1.util.*; + +class CardTerminalsJava003Snippet { + String clientSecretFromServer = "pi_123_secret_456"; + String stripeKey = "sk_test_123"; + String adyenKey = "test-key"; + + AsyncResource fetchTokenFromMyServer() { + return new AsyncResource(); + } + + void sample() { + // tag::card-terminals-java-003[] + 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())); + // end::card-terminals-java-003[] + } +} diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava004Snippet.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava004Snippet.java new file mode 100644 index 00000000000..c42c92bfa46 --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava004Snippet.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.snippets.generated; + +import com.codename1.io.Log; +import com.codename1.payment.terminal.*; +import com.codename1.payment.terminal.square.*; + +class CardTerminalsJava004Snippet { + void sample() { + // tag::card-terminals-java-004[] + 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")); + } + // end::card-terminals-java-004[] + } +} diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava005Snippet.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava005Snippet.java new file mode 100644 index 00000000000..e08ca692c90 --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava005Snippet.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.snippets.generated; + +import com.codename1.io.Log; +import com.codename1.payment.terminal.*; +import com.codename1.payment.terminal.adyen.*; +import com.codename1.payment.terminal.square.*; + +class CardTerminalsJava005Snippet { + void sample() { + // tag::card-terminals-java-005[] + 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())); + // end::card-terminals-java-005[] + } +} diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava006Snippet.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava006Snippet.java new file mode 100644 index 00000000000..8aba4d20ac6 --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava006Snippet.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.snippets.generated; + +import com.codename1.io.Log; +import com.codename1.hardware.SerialPort; +import com.codename1.io.link.*; +import com.codename1.payment.terminal.*; +import com.codename1.payment.terminal.zvt.*; + +class CardTerminalsJava006Snippet { + void sample() { + // tag::card-terminals-java-006[] + 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())); + // end::card-terminals-java-006[] + } +} diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava007Snippet.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava007Snippet.java new file mode 100644 index 00000000000..86187c1c81d --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava007Snippet.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.snippets.generated; + +import com.codename1.payment.terminal.*; +import com.codename1.payment.terminal.mdb.*; + +class CardTerminalsJava007Snippet { + void sample() { + // tag::card-terminals-java-007[] + 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); + } + }); + // end::card-terminals-java-007[] + } +} diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava008Snippet.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava008Snippet.java new file mode 100644 index 00000000000..b3fb57662d1 --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava008Snippet.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codenameone.developerguide.snippets.generated; + +import com.codename1.io.Log; +import com.codename1.io.link.*; +import com.codename1.pos.*; + +class CardTerminalsJava008Snippet { + void sample() { + // tag::card-terminals-java-008[] + 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)); + // end::card-terminals-java-008[] + } +} diff --git a/docs/developer-guide/Card-Terminals.asciidoc b/docs/developer-guide/Card-Terminals.asciidoc new file mode 100644 index 00000000000..b218da6b9ff --- /dev/null +++ b/docs/developer-guide/Card-Terminals.asciidoc @@ -0,0 +1,106 @@ +[[card-terminals]] +== Card Terminals + +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. + +[source,java] +---- +include::../demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava004Snippet.java[tag=card-terminals-java-004,indent=0] +---- + +=== 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. + +[source,java] +---- +include::../demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava001Snippet.java[tag=card-terminals-java-001,indent=0] +---- + +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. + +[source,java] +---- +include::../demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava002Snippet.java[tag=card-terminals-java-002,indent=0] +---- + +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. + +[source,java] +---- +include::../demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava003Snippet.java[tag=card-terminals-java-003,indent=0] +---- + +`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. + +[source,java] +---- +include::../demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava005Snippet.java[tag=card-terminals-java-005,indent=0] +---- + +=== 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. + +[source,java] +---- +include::../demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava006Snippet.java[tag=card-terminals-java-006,indent=0] +---- + +=== 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. + +[source,java] +---- +include::../demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava007Snippet.java[tag=card-terminals-java-007,indent=0] +---- + +=== Links and peripherals + +`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. + +[source,java] +---- +include::../demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava008Snippet.java[tag=card-terminals-java-008,indent=0] +---- diff --git a/docs/developer-guide/developer-guide.asciidoc b/docs/developer-guide/developer-guide.asciidoc index 2ed7c0e5f66..b421a6d4158 100644 --- a/docs/developer-guide/developer-guide.asciidoc +++ b/docs/developer-guide/developer-guide.asciidoc @@ -312,6 +312,8 @@ include::Commerce.asciidoc[] include::Monetization.asciidoc[] +include::Card-Terminals.asciidoc[] + include::Advertising.asciidoc[] include::Analytics.asciidoc[] diff --git a/maven/android/pom.xml b/maven/android/pom.xml index 84c8208891c..59fa1273778 100644 --- a/maven/android/pom.xml +++ b/maven/android/pom.xml @@ -142,6 +142,11 @@ app that referenced com.codename1.webrtc; the builder deletes the package for everyone else. --> com/codename1/impl/android/webrtc/** + + com/codename1/impl/android/taptopay/**