From e704930d84223b0b274e938fa9395b9bf64280ab Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:06:32 +0200 Subject: [PATCH 01/15] Card terminal API: Tap to Pay (Stripe Terminal), Stripe smart readers, Adyen cloud terminals Co-Authored-By: Claude Opus 5.5 --- .../impl/CodenameOneImplementation.java | 11 + .../terminal/HttpTerminalTransport.java | 153 +++++ .../payment/terminal/PaymentTerminal.java | 67 +++ .../terminal/TerminalPaymentRequest.java | 100 ++++ .../payment/terminal/TerminalResult.java | 92 +++ .../payment/terminal/TerminalTransport.java | 83 +++ .../terminal/adyen/AdyenCloudTerminal.java | 526 ++++++++++++++++++ .../payment/terminal/adyen/package-info.java | 26 + .../payment/terminal/package-info.java | 41 ++ .../payment/terminal/spi/TapToPayBridge.java | 80 +++ .../payment/terminal/spi/package-info.java | 25 + .../terminal/stripe/StripeReaderTerminal.java | 464 +++++++++++++++ .../payment/terminal/stripe/package-info.java | 26 + .../terminal/tap/ConnectionTokenProvider.java | 55 ++ .../payment/terminal/tap/TapToPay.java | 195 +++++++ .../terminal/tap/TapToPayCallbacks.java | 182 ++++++ .../payment/terminal/tap/package-info.java | 29 + CodenameOne/src/com/codename1/ui/Display.java | 11 + Ports/Android/build.xml | 2 +- Ports/Android/nbproject/project.properties | 2 +- .../impl/android/AndroidImplementation.java | 30 + .../android/taptopay/AndroidTapToPay.java | 427 ++++++++++++++ .../com/codename1/impl/javase/JavaSEPort.java | 17 + .../javase/taptopay/SimulatedTapToPay.java | 103 ++++ Ports/iOSPort/nativeSources/CN1TapToPay.m | 445 +++++++++++++++ .../CodenameOne_GLViewController.h | 12 + .../codename1/impl/ios/IOSImplementation.java | 17 + .../com/codename1/impl/ios/IOSTapToPay.java | 68 +++ .../CardTerminalsJava001Snippet.java | 57 ++ .../CardTerminalsJava002Snippet.java | 50 ++ .../CardTerminalsJava003Snippet.java | 49 ++ docs/developer-guide/Card-Terminals.asciidoc | 52 ++ docs/developer-guide/developer-guide.asciidoc | 2 + maven/android/pom.xml | 5 + .../builders/AndroidGradleBuilder.java | 35 ++ .../com/codename1/builders/IPhoneBuilder.java | 30 + .../AndroidSixteenKbPageFloorTest.java | 5 + .../payment/terminal/ScriptedTransport.java | 77 +++ .../adyen/AdyenCloudTerminalTest.java | 196 +++++++ .../stripe/StripeReaderTerminalTest.java | 251 +++++++++ .../payment/terminal/tap/TapToPayTest.java | 198 +++++++ .../TestCodenameOneImplementation.java | 12 + .../build/shared/PlatformFeatureCatalog.java | 44 ++ .../shared/PlatformFeatureCatalogTest.java | 24 + 44 files changed, 4374 insertions(+), 2 deletions(-) create mode 100644 CodenameOne/src/com/codename1/payment/terminal/HttpTerminalTransport.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/PaymentTerminal.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/TerminalPaymentRequest.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/TerminalResult.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/TerminalTransport.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/adyen/AdyenCloudTerminal.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/adyen/package-info.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/package-info.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/spi/TapToPayBridge.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/spi/package-info.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/stripe/StripeReaderTerminal.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/stripe/package-info.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/tap/ConnectionTokenProvider.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/tap/TapToPay.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/tap/TapToPayCallbacks.java create mode 100644 CodenameOne/src/com/codename1/payment/terminal/tap/package-info.java create mode 100644 Ports/Android/src/com/codename1/impl/android/taptopay/AndroidTapToPay.java create mode 100644 Ports/JavaSE/src/com/codename1/impl/javase/taptopay/SimulatedTapToPay.java create mode 100644 Ports/iOSPort/nativeSources/CN1TapToPay.m create mode 100644 Ports/iOSPort/src/com/codename1/impl/ios/IOSTapToPay.java create mode 100644 docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava001Snippet.java create mode 100644 docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava002Snippet.java create mode 100644 docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava003Snippet.java create mode 100644 docs/developer-guide/Card-Terminals.asciidoc create mode 100644 maven/core-unittests/src/test/java/com/codename1/payment/terminal/ScriptedTransport.java create mode 100644 maven/core-unittests/src/test/java/com/codename1/payment/terminal/adyen/AdyenCloudTerminalTest.java create mode 100644 maven/core-unittests/src/test/java/com/codename1/payment/terminal/stripe/StripeReaderTerminalTest.java create mode 100644 maven/core-unittests/src/test/java/com/codename1/payment/terminal/tap/TapToPayTest.java 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/payment/terminal/HttpTerminalTransport.java b/CodenameOne/src/com/codename1/payment/terminal/HttpTerminalTransport.java new file mode 100644 index 00000000000..78c796e6824 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/HttpTerminalTransport.java @@ -0,0 +1,153 @@ +/* + * 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; + + /// 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 + 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.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..26c428c02d5 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/PaymentTerminal.java @@ -0,0 +1,67 @@ +/* + * 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 that takes one in-person payment at a time. +/// +/// Every implementation answers the same way: [#collect(TerminalPaymentRequest)] +/// returns a resource that completes with a [TerminalResult] once the card +/// was approved, declined or the payment canceled. It completes with an +/// error only when the terminal could not be asked at all -- no network, a +/// rejected credential, a malformed answer -- so a decline is never an +/// exception. +/// +/// 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. Works from every +/// platform, the desktop ones included. +/// - `com.codename1.payment.terminal.adyen.AdyenCloudTerminal` -- any Adyen +/// terminal, through Adyen's cloud Terminal API. Every platform as well. +public interface PaymentTerminal { + /// Starts a payment. + /// + /// Only one payment can be in progress per terminal; a second call while + /// one is running completes with an error and leaves the first alone. + /// + /// #### Parameters + /// + /// - `request`: what to charge + /// + /// #### Returns + /// + /// the outcome, delivered on the EDT + AsyncResource collect(TerminalPaymentRequest request); + + /// Asks the terminal to abandon the payment in progress. + /// + /// Best effort: a card that was already read may still be approved, so + /// the payment's outcome is whatever [#collect(TerminalPaymentRequest)] + /// delivers, [TerminalResult.Status#CANCELED] when the cancel won. Does + /// nothing when no payment is in progress. + void cancel(); +} 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..4335077ae71 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/TerminalPaymentRequest.java @@ -0,0 +1,100 @@ +/* + * 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; + + /// #### 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 (Adyen's sale transaction ID); may + /// be null. + 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`. Adyen needs none. + public String getProviderReference() { + return providerReference; + } + + /// Sets [#getProviderReference()]. + /// + /// #### Returns + /// + /// this request + public TerminalPaymentRequest setProviderReference(String providerReference) { + this.providerReference = providerReference; + 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..48c115ef71c --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/TerminalResult.java @@ -0,0 +1,92 @@ +/* + * 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 [PaymentTerminal#collect(TerminalPaymentRequest)]. +/// +/// Only [Status#APPROVED] means money moved. The transaction ID is the +/// provider's own -- a Stripe PaymentIntent ID, an Adyen PSP reference -- 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. +public final class TerminalResult { + /// How a payment ended. + public enum Status { + /// The card was charged (or authorized, for a manual-capture + /// payment). + APPROVED, + /// The card or its issuer refused the payment. + DECLINED, + /// The customer or the app abandoned the payment. + CANCELED, + /// The terminal reported an error that is neither a decline nor a + /// cancel, such as a timeout reading the card. + FAILED + } + + private final Status status; + private final String transactionId; + private final String message; + + /// #### Parameters + /// + /// - `status`: how the payment 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) { + if (status == null) { + throw new IllegalArgumentException("status"); + } + this.status = status; + this.transactionId = transactionId; + this.message = message; + } + + /// How the payment 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. + public String getTransactionId() { + return transactionId; + } + + /// The provider's explanation (a decline code, an error message), or + /// null. + public String getMessage() { + return message; + } + + @Override + public String toString() { + return "TerminalResult[" + status + ", " + transactionId + ", " + message + "]"; + } +} 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..4652893cd3b --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/adyen/AdyenCloudTerminal.java @@ -0,0 +1,526 @@ +/* + * 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.HttpTerminalTransport; +import com.codename1.payment.terminal.PaymentTerminal; +import com.codename1.payment.terminal.TerminalPaymentRequest; +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.HashMap; +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 +/// 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. +public class AdyenCloudTerminal implements 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 boolean cancelRequested; + + /// #### 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 AsyncResource collect(TerminalPaymentRequest request) { + final AsyncResource out = new AsyncResource(); + if (pending != null) { + out.error(new IllegalStateException("A payment is already in progress on " + poiId)); + return out; + } + final String serviceId = nextServiceId(); + pending = out; + pendingServiceId = serviceId; + cancelRequested = false; + String reference = request.getReference() != null ? request.getReference() : serviceId; + String body = "{\"SaleToPOIRequest\":{" + + header("Payment", serviceId) + "," + + "\"PaymentRequest\":{" + + "\"SaleData\":{\"SaleTransactionID\":{\"TransactionID\":" + quote(reference) + + ",\"TimeStamp\":" + quote(timestamp()) + "}}," + + "\"PaymentTransaction\":{\"AmountsReq\":{\"Currency\":" + quote(request.getCurrency()) + + ",\"RequestedAmount\":" + majorUnits(request.getAmount(), request.getCurrency()) + + "}}}}}"; + if (transport instanceof HttpTerminalTransport + && !((HttpTerminalTransport) transport).prepareForLongRequest()) { + Log.p("AdyenCloudTerminal: one network thread is busy; cancel() will reach the terminal" + + " only after the payment 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 payment 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) { + fail(new IOException("Adyen answered HTTP " + status + ": " + responseBody)); + return; + } + try { + finish(parseResponse(responseBody, cancelRequested)); + } catch (IOException e) { + fail(e); + } + } + + @Override + public void onError(Throwable error) { + if (pending == out) { //NOPMD CompareObjectsWithEquals - identity: is this still the payment 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); + } + + private void sendAbort(String serviceId) { + String body = "{\"SaleToPOIRequest\":{" + + header("Abort", nextServiceId()) + "," + + "\"AbortRequest\":{\"AbortReason\":\"MerchantAbort\",\"MessageReference\":{" + + "\"MessageCategory\":\"Payment\",\"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); + fail(new IOException("The answer from Adyen was lost and the payment's outcome is unknown;" + + " look up sale " + saleId + " service " + serviceId + " before charging again")); + return; + } + String body = "{\"SaleToPOIRequest\":{" + + header("TransactionStatus", nextServiceId()) + "," + + "\"TransactionStatusRequest\":{\"ReceiptReprintFlag\":false," + + "\"MessageReference\":{\"MessageCategory\":\"Payment\",\"SaleID\":" + quote(saleId) + + ",\"ServiceID\":" + quote(serviceId) + "}}}}"; + 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 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 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")); + 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) { + // 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")); + String pspReference = formValue(additional, "pspReference"); + if (pspReference == null) { + Map poiData = map(payment.get("POIData")); + Map poiTx = poiData == null ? null : map(poiData.get("POITransactionID")); + pspReference = poiTx == null ? null : string(poiTx.get("TransactionID")); + } + if ("Success".equals(result)) { + return new TerminalResult(TerminalResult.Status.APPROVED, pspReference, null); + } + 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); + } + + /// 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.setTimeInMillis(System.currentTimeMillis()); + 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; + } +} 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/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/stripe/StripeReaderTerminal.java b/CodenameOne/src/com/codename1/payment/terminal/stripe/StripeReaderTerminal.java new file mode 100644 index 00000000000..20c6010aaf6 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/stripe/StripeReaderTerminal.java @@ -0,0 +1,464 @@ +/* + * 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.HttpTerminalTransport; +import com.codename1.payment.terminal.PaymentTerminal; +import com.codename1.payment.terminal.TerminalPaymentRequest; +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.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 +/// 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. Without one, a +/// card-present PaymentIntent with automatic capture is created first. +public class StripeReaderTerminal implements 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 AsyncResource collect(TerminalPaymentRequest request) { + 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); + current = p; + String pi = request.getProviderReference(); + if (pi != null && pi.length() > 0) { + process(p, pi); + return out; + } + String body = "amount=" + request.getAmount() + + "¤cy=" + Util.encodeUrl(asciiLower(request.getCurrency())) + + "&payment_method_types%5B%5D=card_present" + + "&capture_method=automatic"; + post("/v1/payment_intents", body, 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"; + post(path, "payment_intent=" + Util.encodeUrl(paymentIntentId), 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 IOException("The reader did not report an outcome; check PaymentIntent " + + p.paymentIntentId + " on the server before charging again")); + return; + } + } + 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)) { + finish(p, new TerminalResult(TerminalResult.Status.APPROVED, p.paymentIntentId, null)); + 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); + } + + 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 r) { + 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 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; + 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..b8e8be0c05d --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/tap/TapToPay.java @@ -0,0 +1,195 @@ +/* + * 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.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 +/// 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 implements 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 + @Override + public AsyncResource collect(TerminalPaymentRequest request) { + 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); + 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..172a849daa6 --- /dev/null +++ b/CodenameOne/src/com/codename1/payment/terminal/tap/TapToPayCallbacks.java @@ -0,0 +1,182 @@ +/* + * 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.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; + + 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) { + int id = nextId++; + PENDING.put(Integer.valueOf(id), new Pending(owner, out)); + 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; + default: + p.out.error(new IOException(message == null ? "Tap to Pay failed" : message)); + return; + } + p.out.complete(new TerminalResult(s, transactionId, message)); + } + }); + } + + private static final class Pending { + final TapToPay owner; + final AsyncResource out; + + Pending(TapToPay owner, AsyncResource out) { + this.owner = owner; + this.out = out; + } + } +} 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/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..1a6f1dfc49c --- /dev/null +++ b/Ports/Android/src/com/codename1/impl/android/taptopay/AndroidTapToPay.java @@ -0,0 +1,427 @@ +/* + * 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. + finishError(requestId, "The payment's outcome is unknown; check PaymentIntent " + + id + " on the server 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..90ae2a99e2c --- /dev/null +++ b/Ports/iOSPort/nativeSources/CN1TapToPay.m @@ -0,0 +1,445 @@ +/* + * 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 + +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_ERROR; + message = [NSString stringWithFormat:@"The payment's outcome is unknown; check PaymentIntent %@ on the server 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..021ac15c377 --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava001Snippet.java @@ -0,0 +1,57 @@ +/* + * 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[] + if (TapToPay.isSupported()) { + TapToPay tap = new TapToPay(() -> fetchTokenFromMyServer(), "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..cd953c16017 --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava002Snippet.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 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[] + 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..9fb96ec1b41 --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/CardTerminalsJava003Snippet.java @@ -0,0 +1,49 @@ +/* + * 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[] + 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/developer-guide/Card-Terminals.asciidoc b/docs/developer-guide/Card-Terminals.asciidoc new file mode 100644 index 00000000000..507aa69e172 --- /dev/null +++ b/docs/developer-guide/Card-Terminals.asciidoc @@ -0,0 +1,52 @@ +[[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. Every kind of terminal implements the same `PaymentTerminal` interface, 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. +* `AdyenCloudTerminal` drives any Adyen terminal through the Adyen cloud Terminal API. + +The two network terminals speak plain HTTPS, so they work on every platform, desktop and web included. Neither 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. Treat it as a report and confirm the payment on your server, by its transaction ID, before you fulfill an order. + +=== 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. 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/**