From b704a9cae91feccb5876510503d6d05b3d9b1249 Mon Sep 17 00:00:00 2001 From: BreX900 Date: Sun, 19 Nov 2023 15:17:16 +0100 Subject: [PATCH] chore: formatted kotlin files --- .../workflows/stripe_terminal_integration.yml | 17 +- stripe_terminal/README.md | 3 + stripe_terminal/android/build.gradle | 17 +- .../kotlin/mek/stripeterminal/Extensions.kt | 2 +- .../mek/stripeterminal/TerminalPlugin.kt | 605 ++++++++++-------- .../main/kotlin/mek/stripeterminal/Utils.kt | 7 +- .../mek/stripeterminal/api/TerminalApi.kt | 585 +++++++++++------ .../mek/stripeterminal/api/ToApiExtensions.kt | 244 ++++--- .../stripeterminal/api/ToHostExtensions.kt | 100 +-- .../stripeterminal/mappings/ChargeMappings.kt | 13 +- .../plugin/DiscoverReadersSubject.kt | 64 +- .../plugin/ReaderDelegatePlugin.kt | 45 +- ...kt => ReaderReconnectionListenerPlugin.kt} | 22 +- .../plugin/TerminalDelegatePlugin.kt | 47 +- .../plugin/TerminalErrorHandler.kt | 5 +- .../StripeTerminalPluginTest.kt | 18 +- 16 files changed, 1119 insertions(+), 675 deletions(-) rename stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/{ReaderReconnectionDelegatePlugin.kt => ReaderReconnectionListenerPlugin.kt} (62%) diff --git a/.github/workflows/stripe_terminal_integration.yml b/.github/workflows/stripe_terminal_integration.yml index 06952ed..a96f5c0 100644 --- a/.github/workflows/stripe_terminal_integration.yml +++ b/.github/workflows/stripe_terminal_integration.yml @@ -34,6 +34,14 @@ jobs: - name: Analyze code run: flutter analyze --no-fatal-infos + + # Android + - uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'zulu' + - run: ./gradlew spotlessCheck + working-directory: stripe_terminal/android integration-example: runs-on: macos-latest @@ -45,10 +53,6 @@ jobs: steps: - uses: actions/checkout@v3 - - name: setup-cocoapods - uses: maxim-lobanov/setup-cocoapods@v1 - with: - podfile-path: stripe_terminal/example/ios/Podfile.lock - uses: subosito/flutter-action@v2 with: flutter-version: '3.16.x' @@ -65,4 +69,9 @@ jobs: - name: Analyze code run: flutter analyze --no-fatal-infos + # IOS + - uses: maxim-lobanov/setup-cocoapods@v1 + with: + podfile-path: stripe_terminal/example/ios/Podfile.lock + - run: pod install --deployment --project-directory=ios diff --git a/stripe_terminal/README.md b/stripe_terminal/README.md index 17a1d78..fbe3243 100644 --- a/stripe_terminal/README.md +++ b/stripe_terminal/README.md @@ -169,3 +169,6 @@ Much code in this plugin is auto generated: - [one_for_all](https://pub.dev/packages/one_for_all) is used to generate the code for communication between platforms. Run this [script](tool/generate_api.dart) - [index_generator](https://pub.dev/packages/index_generator) is used to generate library exports + +### Android +Format code with `./gradlew spotlessApply` diff --git a/stripe_terminal/android/build.gradle b/stripe_terminal/android/build.gradle index 7dd6466..4330536 100644 --- a/stripe_terminal/android/build.gradle +++ b/stripe_terminal/android/build.gradle @@ -1,6 +1,3 @@ -group 'packages.mek' -version '1.0-SNAPSHOT' - buildscript { ext.kotlin_version = '1.7.10' repositories { @@ -14,6 +11,13 @@ buildscript { } } +plugins { + id "com.diffplug.spotless" version "6.22.0" +} + +group 'packages.mek' +version '1.0-SNAPSHOT' + allprojects { repositories { google() @@ -68,4 +72,11 @@ dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" api "com.stripe:stripeterminal-localmobile:3.2.0" api "com.stripe:stripeterminal-core:3.2.0" +} + +spotless { + kotlin { + target("**/*.kt") + ktlint("1.0.1") + } } \ No newline at end of file diff --git a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/Extensions.kt b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/Extensions.kt index 3bc551d..0fa1bbc 100644 --- a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/Extensions.kt +++ b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/Extensions.kt @@ -2,4 +2,4 @@ package mek.stripeterminal fun Map.toHashMap(): HashMap { return hashMapOf(*map { (k, v) -> k to v }.toTypedArray()) -} \ No newline at end of file +} diff --git a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/TerminalPlugin.kt b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/TerminalPlugin.kt index b3b73c4..d582dd4 100644 --- a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/TerminalPlugin.kt +++ b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/TerminalPlugin.kt @@ -28,117 +28,118 @@ import com.stripe.stripeterminal.external.models.SetupIntent import com.stripe.stripeterminal.external.models.SetupIntentCancellationParameters import com.stripe.stripeterminal.external.models.SetupIntentConfiguration import com.stripe.stripeterminal.external.models.SetupIntentParameters -import com.stripe.stripeterminal.external.models.SimulatedCard -import com.stripe.stripeterminal.external.models.SimulatedCardType -import com.stripe.stripeterminal.external.models.SimulatorConfiguration import com.stripe.stripeterminal.external.models.TerminalException import com.stripe.stripeterminal.log.LogLevel +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.embedding.engine.plugins.activity.ActivityAware +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding +import io.flutter.plugin.common.BinaryMessenger import mek.stripeterminal.api.CartApi import mek.stripeterminal.api.ConnectionStatusApi import mek.stripeterminal.api.DeviceTypeApi import mek.stripeterminal.api.DiscoverReadersControllerApi +import mek.stripeterminal.api.DiscoveryConfigurationApi import mek.stripeterminal.api.LocationApi import mek.stripeterminal.api.PaymentIntentApi -import mek.stripeterminal.api.ReaderApi -import mek.stripeterminal.api.Result -import mek.stripeterminal.api.TerminalHandlersApi -import mek.stripeterminal.api.TerminalPlatformApi -import mek.stripeterminal.api.toApi -import mek.stripeterminal.api.toHost -import mek.stripeterminal.plugin.ReaderDelegatePlugin -import mek.stripeterminal.plugin.ReaderReconnectionListenerPlugin -import mek.stripeterminal.plugin.TerminalErrorHandler -import io.flutter.embedding.engine.plugins.FlutterPlugin -import io.flutter.embedding.engine.plugins.activity.ActivityAware -import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding -import io.flutter.plugin.common.BinaryMessenger -import mek.stripeterminal.api.DiscoveryConfigurationApi import mek.stripeterminal.api.PaymentIntentParametersApi import mek.stripeterminal.api.PaymentStatusApi +import mek.stripeterminal.api.ReaderApi import mek.stripeterminal.api.RefundApi +import mek.stripeterminal.api.Result import mek.stripeterminal.api.SetupIntentApi import mek.stripeterminal.api.SetupIntentUsageApi import mek.stripeterminal.api.TerminalExceptionCodeApi +import mek.stripeterminal.api.TerminalHandlersApi +import mek.stripeterminal.api.TerminalPlatformApi import mek.stripeterminal.api.TippingConfigurationApi +import mek.stripeterminal.api.toApi +import mek.stripeterminal.api.toHost import mek.stripeterminal.api.toPlatformError import mek.stripeterminal.plugin.DiscoverReadersSubject +import mek.stripeterminal.plugin.ReaderDelegatePlugin +import mek.stripeterminal.plugin.ReaderReconnectionListenerPlugin import mek.stripeterminal.plugin.TerminalDelegatePlugin +import mek.stripeterminal.plugin.TerminalErrorHandler class TerminalPlugin : FlutterPlugin, ActivityAware, TerminalPlatformApi { - private lateinit var _handlers: TerminalHandlersApi - - private var _activity: Activity? = null - private val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - arrayOf( - Manifest.permission.BLUETOOTH_SCAN, - Manifest.permission.BLUETOOTH_ADMIN, - ) - } else { - arrayOf( - Manifest.permission.BLUETOOTH_ADMIN, - ) - } + private lateinit var handlers: TerminalHandlersApi + + private var activity: Activity? = null + private val permissions = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + arrayOf( + Manifest.permission.BLUETOOTH_SCAN, + Manifest.permission.BLUETOOTH_ADMIN, + ) + } else { + arrayOf( + Manifest.permission.BLUETOOTH_ADMIN, + ) + } - private val _terminal: Terminal get() = Terminal.getInstance() + private val terminal: Terminal get() = Terminal.getInstance() override fun onInit(shouldPrintLogs: Boolean) { - val permissionStatus = permissions.map { - ContextCompat.checkSelfPermission(_activity!!, it) - } + val permissionStatus = permissions.map { ContextCompat.checkSelfPermission(activity!!, it) } if (permissionStatus.contains(PackageManager.PERMISSION_DENIED)) { throw createApiError( TerminalExceptionCodeApi.UNKNOWN, "You have declined the necessary permission, please allow from settings to continue.", - ).toPlatformError() + ) + .toPlatformError() } - // If a hot restart is performed in flutter the terminal is already initialized but we need to clean it up + // If a hot restart is performed in flutter the terminal is already initialized but we need to + // clean it up if (Terminal.isInitialized()) { clean() return } - TerminalApplicationDelegate.onCreate(_activity!!.application) - val delegate = TerminalDelegatePlugin(_handlers) + TerminalApplicationDelegate.onCreate(activity!!.application) + val delegate = TerminalDelegatePlugin(handlers) Terminal.initTerminal( - _activity!!.applicationContext, + activity!!.applicationContext, if (shouldPrintLogs) LogLevel.VERBOSE else LogLevel.NONE, delegate, delegate, ) } - override fun onClearCachedCredentials() = _terminal.clearCachedCredentials() + override fun onClearCachedCredentials() = terminal.clearCachedCredentials() - //region Reader discovery, connection and updates - private lateinit var _discoverReadersController: DiscoverReadersControllerApi - private var _discoverReadersSubject = DiscoverReadersSubject() - private val _discoveredReaders: List get() = _discoverReadersSubject.readers - private lateinit var _readerDelegate: ReaderDelegatePlugin - private lateinit var _readerReconnectionDelegate: ReaderReconnectionListenerPlugin + // region Reader discovery, connection and updates + private lateinit var discoverReadersController: DiscoverReadersControllerApi + private var discoverReadersSubject = DiscoverReadersSubject() + private val discoveredReaders: List + get() = discoverReadersSubject.readers - override fun onGetConnectionStatus(): ConnectionStatusApi = _terminal.connectionStatus.toApi() + private lateinit var readerDelegate: ReaderDelegatePlugin + private lateinit var readerReconnectionDelegate: ReaderReconnectionListenerPlugin + + override fun onGetConnectionStatus(): ConnectionStatusApi = terminal.connectionStatus.toApi() override fun onSupportsReadersOfType( deviceType: DeviceTypeApi?, discoveryConfiguration: DiscoveryConfigurationApi, ): Boolean { - val hostDeviceType = (if (deviceType != null) deviceType.toHost() else DeviceType.UNKNOWN) - ?: return false + val hostDeviceType = + (if (deviceType != null) deviceType.toHost() else DeviceType.UNKNOWN) ?: return false val hostDiscoveryConfiguration = discoveryConfiguration.toHost() ?: return false - val result = _terminal.supportsReadersOfType( - deviceType = hostDeviceType, - discoveryConfiguration = hostDiscoveryConfiguration, - ) + val result = + terminal.supportsReadersOfType( + deviceType = hostDeviceType, + discoveryConfiguration = hostDiscoveryConfiguration, + ) return result.isSupported } private fun setupDiscoverReadersController(binaryMessenger: BinaryMessenger) { - _discoverReadersController = DiscoverReadersControllerApi(binaryMessenger) - _discoverReadersController.setHandler( - _discoverReadersSubject::onListen, - _discoverReadersSubject::onCancel + discoverReadersController = DiscoverReadersControllerApi(binaryMessenger) + discoverReadersController.setHandler( + discoverReadersSubject::onListen, + discoverReadersSubject::onCancel, ) } @@ -150,16 +151,17 @@ class TerminalPlugin : FlutterPlugin, ActivityAware, TerminalPlatformApi { ) { val reader = findActiveReader(serialNumber) - _terminal.connectBluetoothReader(reader, + terminal.connectBluetoothReader( + reader, ConnectionConfiguration.BluetoothConnectionConfiguration( locationId = locationId, autoReconnectOnUnexpectedDisconnect = autoReconnectOnUnexpectedDisconnect, - bluetoothReaderReconnectionListener = _readerReconnectionDelegate, + bluetoothReaderReconnectionListener = readerReconnectionDelegate, ), - _readerDelegate, + readerDelegate, object : TerminalErrorHandler(result::error), ReaderCallback { override fun onSuccess(reader: Reader) = result.success(reader.toApi()) - } + }, ) } @@ -169,29 +171,32 @@ class TerminalPlugin : FlutterPlugin, ActivityAware, TerminalPlatformApi { ) { val reader = findActiveReader(serialNumber) - _terminal.connectHandoffReader(reader, + terminal.connectHandoffReader( + reader, ConnectionConfiguration.HandoffConnectionConfiguration(), - _readerDelegate, + readerDelegate, object : TerminalErrorHandler(result::error), ReaderCallback { override fun onSuccess(reader: Reader) = result.success(reader.toApi()) - } + }, ) } override fun onConnectInternetReader( result: Result, serialNumber: String, - failIfInUse: Boolean + failIfInUse: Boolean, ) { val reader = findActiveReader(serialNumber) - _terminal.connectInternetReader(reader, + terminal.connectInternetReader( + reader, ConnectionConfiguration.InternetConnectionConfiguration( failIfInUse = failIfInUse, ), object : TerminalErrorHandler(result::error), ReaderCallback { override fun onSuccess(reader: Reader) = result.success(reader.toApi()) - }) + }, + ) } override fun onConnectMobileReader( @@ -201,13 +206,17 @@ class TerminalPlugin : FlutterPlugin, ActivityAware, TerminalPlatformApi { ) { val reader = findActiveReader(serialNumber) - val config = ConnectionConfiguration.LocalMobileConnectionConfiguration( - locationId = locationId, - ) - _terminal.connectLocalMobileReader(reader, config, + val config = + ConnectionConfiguration.LocalMobileConnectionConfiguration( + locationId = locationId, + ) + terminal.connectLocalMobileReader( + reader, + config, object : TerminalErrorHandler(result::error), ReaderCallback { override fun onSuccess(reader: Reader) = result.success(reader.toApi()) - }) + }, + ) } override fun onConnectUsbReader( @@ -218,29 +227,31 @@ class TerminalPlugin : FlutterPlugin, ActivityAware, TerminalPlatformApi { ) { val reader = findActiveReader(serialNumber) - _terminal.connectUsbReader(reader, + terminal.connectUsbReader( + reader, ConnectionConfiguration.UsbConnectionConfiguration( locationId = locationId, autoReconnectOnUnexpectedDisconnect = autoReconnectOnUnexpectedDisconnect, - usbReaderReconnectionListener = _readerReconnectionDelegate, + usbReaderReconnectionListener = readerReconnectionDelegate, ), - _readerDelegate, + readerDelegate, object : TerminalErrorHandler(result::error), ReaderCallback { override fun onSuccess(reader: Reader) = result.success(reader.toApi()) - } + }, ) } - override fun onGetConnectedReader(): ReaderApi? = _terminal.connectedReader?.toApi() + override fun onGetConnectedReader(): ReaderApi? = terminal.connectedReader?.toApi() override fun onCancelReaderReconnection(result: Result) { - if (_readerReconnectionDelegate.cancelReconnect == null) { + if (readerReconnectionDelegate.cancelReconnect == null) { result.success(Unit) } - _readerReconnectionDelegate.cancelReconnect?.cancel(object : Callback, - TerminalErrorHandler(result::error) { - override fun onSuccess() = result.success(Unit) - }) + readerReconnectionDelegate.cancelReconnect?.cancel( + object : Callback, TerminalErrorHandler(result::error) { + override fun onSuccess() = result.success(Unit) + }, + ) } override fun onListLocations( @@ -253,66 +264,76 @@ class TerminalPlugin : FlutterPlugin, ActivityAware, TerminalPlatformApi { params.endingBefore = endingBefore params.startingAfter = startingAfter params.limit = limit?.toInt() - _terminal.listLocations(params.build(), + terminal.listLocations( + params.build(), object : TerminalErrorHandler(result::error), LocationListCallback { - override fun onSuccess(locations: List, hasMore: Boolean) = - result.success(locations.map { it.toApi() }) - }) + override fun onSuccess( + locations: List, + hasMore: Boolean, + ) = result.success(locations.map { it.toApi() }) + }, + ) } - override fun onInstallAvailableUpdate() = _terminal.installAvailableUpdate() + override fun onInstallAvailableUpdate() = terminal.installAvailableUpdate() override fun onCancelReaderUpdate(result: Result) { - if (_readerDelegate.cancelUpdate == null) { + if (readerDelegate.cancelUpdate == null) { result.success(Unit) } - _readerDelegate.cancelUpdate?.cancel(object : Callback, - TerminalErrorHandler(result::error) { - override fun onSuccess() = result.success(Unit) - }) + readerDelegate.cancelUpdate?.cancel( + object : Callback, TerminalErrorHandler(result::error) { + override fun onSuccess() = result.success(Unit) + }, + ) } override fun onDisconnectReader(result: Result) { - _terminal.disconnectReader(object : TerminalErrorHandler(result::error), Callback { - override fun onSuccess() = result.success(Unit) - }) + terminal.disconnectReader( + object : TerminalErrorHandler(result::error), Callback { + override fun onSuccess() = result.success(Unit) + }, + ) } - //endregion + // endregion - //region Taking Payment - private var _paymentIntents = HashMap() + // region Taking Payment + private var paymentIntents = HashMap() - override fun onGetPaymentStatus(): PaymentStatusApi = _terminal.paymentStatus.toApi() + override fun onGetPaymentStatus(): PaymentStatusApi = terminal.paymentStatus.toApi() override fun onCreatePaymentIntent( result: Result, - parameters: PaymentIntentParametersApi + parameters: PaymentIntentParametersApi, ) { - _terminal.createPaymentIntent( + terminal.createPaymentIntent( params = parameters.toHost(), - callback = object : TerminalErrorHandler(result::error), PaymentIntentCallback { - override fun onSuccess(paymentIntent: PaymentIntent) { - _paymentIntents[paymentIntent.id!!] = paymentIntent - result.success(paymentIntent.toApi()) - } - } + callback = + object : TerminalErrorHandler(result::error), PaymentIntentCallback { + override fun onSuccess(paymentIntent: PaymentIntent) { + paymentIntents[paymentIntent.id!!] = paymentIntent + result.success(paymentIntent.toApi()) + } + }, ) } override fun onRetrievePaymentIntent( result: Result, - clientSecret: String + clientSecret: String, ) { - _terminal.retrievePaymentIntent(clientSecret, + terminal.retrievePaymentIntent( + clientSecret, object : TerminalErrorHandler(result::error), PaymentIntentCallback { override fun onSuccess(paymentIntent: PaymentIntent) { - _paymentIntents[paymentIntent.id!!] = paymentIntent + paymentIntents[paymentIntent.id!!] = paymentIntent result.success(paymentIntent.toApi()) } - }) + }, + ) } - private var _cancelablesCollectPaymentMethod = HashMap() + private var cancelablesCollectPaymentMethod = HashMap() override fun onStartCollectPaymentMethod( result: Result, @@ -324,34 +345,44 @@ class TerminalPlugin : FlutterPlugin, ActivityAware, TerminalPlatformApi { customerCancellationEnabled: Boolean, ) { val paymentIntent = findPaymentIntent(paymentIntentId) - val config = CollectConfiguration.Builder() - .skipTipping(skipTipping) - .setTippingConfiguration(tippingConfiguration?.toHost()) - .updatePaymentIntent(shouldUpdatePaymentIntent) - .setEnableCustomerCancellation(customerCancellationEnabled) - - _cancelablesCollectPaymentMethod[operationId] = _terminal.collectPaymentMethod( - paymentIntent, - config = config.build(), - callback = object : TerminalErrorHandler(result::error), PaymentIntentCallback { - override fun onFailure(e: TerminalException) { - _cancelablesCollectPaymentMethod.remove(operationId) - super.onFailure(e) - } - - override fun onSuccess(paymentIntent: PaymentIntent) { - _cancelablesCollectPaymentMethod.remove(operationId) - result.success(paymentIntent.toApi()) - _paymentIntents[paymentIntent.id!!] = paymentIntent - } - }) - } - - override fun onStopCollectPaymentMethod(result: Result, operationId: Long) { - _cancelablesCollectPaymentMethod.remove(operationId) - ?.cancel(object : TerminalErrorHandler(result::error), Callback { - override fun onSuccess() = result.success(Unit) - }) + val config = + CollectConfiguration.Builder() + .skipTipping(skipTipping) + .setTippingConfiguration(tippingConfiguration?.toHost()) + .updatePaymentIntent(shouldUpdatePaymentIntent) + .setEnableCustomerCancellation(customerCancellationEnabled) + + cancelablesCollectPaymentMethod[operationId] = + terminal.collectPaymentMethod( + paymentIntent, + config = config.build(), + callback = + object : TerminalErrorHandler(result::error), PaymentIntentCallback { + override fun onFailure(e: TerminalException) { + cancelablesCollectPaymentMethod.remove(operationId) + super.onFailure(e) + } + + override fun onSuccess(paymentIntent: PaymentIntent) { + cancelablesCollectPaymentMethod.remove(operationId) + result.success(paymentIntent.toApi()) + paymentIntents[paymentIntent.id!!] = paymentIntent + } + }, + ) + } + + override fun onStopCollectPaymentMethod( + result: Result, + operationId: Long, + ) { + cancelablesCollectPaymentMethod + .remove(operationId) + ?.cancel( + object : TerminalErrorHandler(result::error), Callback { + override fun onSuccess() = result.success(Unit) + }, + ) } override fun onConfirmPaymentIntent( @@ -359,40 +390,45 @@ class TerminalPlugin : FlutterPlugin, ActivityAware, TerminalPlatformApi { paymentIntentId: String, ) { val paymentIntent = findPaymentIntent(paymentIntentId) - _terminal.confirmPaymentIntent( + terminal.confirmPaymentIntent( paymentIntent, object : TerminalErrorHandler(result::error), PaymentIntentCallback { override fun onFailure(e: TerminalException) { - val paymentIntentUpdated = e.paymentIntent; + val paymentIntentUpdated = e.paymentIntent if (paymentIntentUpdated != null) { - _paymentIntents[paymentIntentUpdated.id!!] = paymentIntentUpdated + paymentIntents[paymentIntentUpdated.id!!] = paymentIntentUpdated } super.onFailure(e) } override fun onSuccess(paymentIntent: PaymentIntent) { result.success(paymentIntent.toApi()) - _paymentIntents.remove(paymentIntent.id) + paymentIntents.remove(paymentIntent.id) } - }) + }, + ) } - override fun onCancelPaymentIntent(result: Result, paymentIntentId: String) { + override fun onCancelPaymentIntent( + result: Result, + paymentIntentId: String, + ) { val paymentIntent = findPaymentIntent(paymentIntentId) - _terminal.cancelPaymentIntent( + terminal.cancelPaymentIntent( paymentIntent, object : TerminalErrorHandler(result::error), PaymentIntentCallback { override fun onSuccess(paymentIntent: PaymentIntent) { - _paymentIntents.remove(paymentIntentId) + paymentIntents.remove(paymentIntentId) result.success(paymentIntent.toApi()) } - }) + }, + ) } - //endregion + // endregion - //region Saving payment details for later use - private var _setupIntents = HashMap() - private var _cancelablesCollectSetupIntentPaymentMethod = HashMap() + // region Saving payment details for later use + private var setupIntents = HashMap() + private var cancelablesCollectSetupIntentPaymentMethod = HashMap() override fun onCreateSetupIntent( result: Result, @@ -400,9 +436,9 @@ class TerminalPlugin : FlutterPlugin, ActivityAware, TerminalPlatformApi { metadata: HashMap?, onBehalfOf: String?, description: String?, - usage: SetupIntentUsageApi? + usage: SetupIntentUsageApi?, ) { - _terminal.createSetupIntent( + terminal.createSetupIntent( SetupIntentParameters.Builder() .setCustomer(customerId) .setMetadata(metadata) @@ -412,22 +448,26 @@ class TerminalPlugin : FlutterPlugin, ActivityAware, TerminalPlatformApi { .build(), object : TerminalErrorHandler(result::error), SetupIntentCallback { override fun onSuccess(setupIntent: SetupIntent) { - _setupIntents[setupIntent.id] = setupIntent + setupIntents[setupIntent.id] = setupIntent result.success(setupIntent.toApi()) } - } + }, ) } - override fun onRetrieveSetupIntent(result: Result, clientSecret: String) { - _terminal.retrieveSetupIntent( + override fun onRetrieveSetupIntent( + result: Result, + clientSecret: String, + ) { + terminal.retrieveSetupIntent( clientSecret, object : TerminalErrorHandler(result::error), SetupIntentCallback { override fun onSuccess(setupIntent: SetupIntent) { - _setupIntents[setupIntent.id] = setupIntent + setupIntents[setupIntent.id] = setupIntent result.success(setupIntent.toApi()) } - }) + }, + ) } override fun onStartCollectSetupIntentPaymentMethod( @@ -438,63 +478,80 @@ class TerminalPlugin : FlutterPlugin, ActivityAware, TerminalPlatformApi { customerCancellationEnabled: Boolean, ) { val setupIntent = findSetupIntent(setupIntentId) - val config = SetupIntentConfiguration.Builder() - .setEnableCustomerCancellation(customerCancellationEnabled) + val config = + SetupIntentConfiguration.Builder() + .setEnableCustomerCancellation(customerCancellationEnabled) - _cancelablesCollectSetupIntentPaymentMethod[operationId] = - _terminal.collectSetupIntentPaymentMethod( + cancelablesCollectSetupIntentPaymentMethod[operationId] = + terminal.collectSetupIntentPaymentMethod( setupIntent, customerConsentCollected = customerConsentCollected, config = config.build(), - callback = object : TerminalErrorHandler(result::error), SetupIntentCallback { - override fun onFailure(e: TerminalException) { - _cancelablesCollectSetupIntentPaymentMethod.remove(operationId) - super.onFailure(e) - } - - override fun onSuccess(setupIntent: SetupIntent) { - _cancelablesCollectSetupIntentPaymentMethod.remove(operationId) - _setupIntents[setupIntent.id] = setupIntent - result.success(setupIntent.toApi()) - } - }) - } - - override fun onStopCollectSetupIntentPaymentMethod(result: Result, operationId: Long) { - _cancelablesCollectSetupIntentPaymentMethod.remove(operationId) - ?.cancel(object : TerminalErrorHandler(result::error), Callback { - override fun onSuccess() = result.success(Unit) - }) + callback = + object : TerminalErrorHandler(result::error), SetupIntentCallback { + override fun onFailure(e: TerminalException) { + cancelablesCollectSetupIntentPaymentMethod.remove(operationId) + super.onFailure(e) + } + + override fun onSuccess(setupIntent: SetupIntent) { + cancelablesCollectSetupIntentPaymentMethod.remove(operationId) + setupIntents[setupIntent.id] = setupIntent + result.success(setupIntent.toApi()) + } + }, + ) + } + + override fun onStopCollectSetupIntentPaymentMethod( + result: Result, + operationId: Long, + ) { + cancelablesCollectSetupIntentPaymentMethod + .remove(operationId) + ?.cancel( + object : TerminalErrorHandler(result::error), Callback { + override fun onSuccess() = result.success(Unit) + }, + ) } - override fun onConfirmSetupIntent(result: Result, setupIntentId: String) { + override fun onConfirmSetupIntent( + result: Result, + setupIntentId: String, + ) { val setupIntent = findSetupIntent(setupIntentId) - _terminal.confirmSetupIntent( + terminal.confirmSetupIntent( setupIntent, object : TerminalErrorHandler(result::error), SetupIntentCallback { override fun onSuccess(setupIntent: SetupIntent) { - _setupIntents[setupIntent.id] = setupIntent + setupIntents[setupIntent.id] = setupIntent result.success(setupIntent.toApi()) } - }) + }, + ) } - override fun onCancelSetupIntent(result: Result, setupIntentId: String) { + override fun onCancelSetupIntent( + result: Result, + setupIntentId: String, + ) { val setupIntent = findSetupIntent(setupIntentId) - _terminal.cancelSetupIntent( + terminal.cancelSetupIntent( setupIntent, SetupIntentCancellationParameters.Builder().build(), object : TerminalErrorHandler(result::error), SetupIntentCallback { override fun onSuccess(setupIntent: SetupIntent) { - _setupIntents.remove(setupIntent.id) + setupIntents.remove(setupIntent.id) result.success(setupIntent.toApi()) } - }) + }, + ) } - //endregion + // endregion - //region Saving payment details for later use - private var _cancelablesCollectRefundPaymentMethod = HashMap() + // region Saving payment details for later use + private var cancelablesCollectRefundPaymentMethod = HashMap() override fun onStartCollectRefundPaymentMethod( result: Result, @@ -507,69 +564,88 @@ class TerminalPlugin : FlutterPlugin, ActivityAware, TerminalPlatformApi { refundApplicationFee: Boolean?, customerCancellationEnabled: Boolean, ) { - val config = RefundConfiguration.Builder() - .setEnableCustomerCancellation(customerCancellationEnabled) - - _cancelablesCollectRefundPaymentMethod[operationId] = _terminal.collectRefundPaymentMethod( - RefundParameters.Builder( - chargeId = chargeId, - amount = amount, - currency = currency, - ).let { - metadata?.let(it::setMetadata) - reverseTransfer?.let(it::setReverseTransfer) - refundApplicationFee?.let(it::setRefundApplicationFee) - it.build() - }, - config = config.build(), - callback = object : TerminalErrorHandler(result::error), Callback { - override fun onFailure(e: TerminalException) { - _cancelablesCollectRefundPaymentMethod.remove(operationId) - super.onFailure(e) - } - - override fun onSuccess() { - _cancelablesCollectRefundPaymentMethod.remove(operationId) - result.success(Unit) - } - }) - } - - override fun onStopCollectRefundPaymentMethod(result: Result, operationId: Long) { - _cancelablesCollectRefundPaymentMethod.remove(operationId) - ?.cancel(object : TerminalErrorHandler(result::error), Callback { - override fun onSuccess() = result.success(Unit) - }) + val config = + RefundConfiguration.Builder().setEnableCustomerCancellation(customerCancellationEnabled) + + cancelablesCollectRefundPaymentMethod[operationId] = + terminal.collectRefundPaymentMethod( + RefundParameters.Builder( + chargeId = chargeId, + amount = amount, + currency = currency, + ) + .let { + metadata?.let(it::setMetadata) + reverseTransfer?.let(it::setReverseTransfer) + refundApplicationFee?.let(it::setRefundApplicationFee) + it.build() + }, + config = config.build(), + callback = + object : TerminalErrorHandler(result::error), Callback { + override fun onFailure(e: TerminalException) { + cancelablesCollectRefundPaymentMethod.remove(operationId) + super.onFailure(e) + } + + override fun onSuccess() { + cancelablesCollectRefundPaymentMethod.remove(operationId) + result.success(Unit) + } + }, + ) + } + + override fun onStopCollectRefundPaymentMethod( + result: Result, + operationId: Long, + ) { + cancelablesCollectRefundPaymentMethod + .remove(operationId) + ?.cancel( + object : TerminalErrorHandler(result::error), Callback { + override fun onSuccess() = result.success(Unit) + }, + ) } override fun onConfirmRefund(result: Result) { - _terminal.confirmRefund(object : TerminalErrorHandler(result::error), RefundCallback { - override fun onSuccess(refund: Refund) = result.success(refund.toApi()) - }) + terminal.confirmRefund( + object : TerminalErrorHandler(result::error), RefundCallback { + override fun onSuccess(refund: Refund) = result.success(refund.toApi()) + }, + ) } - //endregion + // endregion - //region Display information to customers - override fun onSetReaderDisplay(result: Result, cart: CartApi) { - _terminal.setReaderDisplay(cart.toHost(), + // region Display information to customers + override fun onSetReaderDisplay( + result: Result, + cart: CartApi, + ) { + terminal.setReaderDisplay( + cart.toHost(), object : TerminalErrorHandler(result::error), Callback { override fun onSuccess() = result.success(Unit) - }) + }, + ) } override fun onClearReaderDisplay(result: Result) { - _terminal.clearReaderDisplay(object : TerminalErrorHandler(result::error), Callback { - override fun onSuccess() = result.success(Unit) - }) + terminal.clearReaderDisplay( + object : TerminalErrorHandler(result::error), Callback { + override fun onSuccess() = result.success(Unit) + }, + ) } - //endregion + // endregion override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { val binaryMessenger = flutterPluginBinding.binaryMessenger TerminalPlatformApi.setHandler(binaryMessenger, this) - _handlers = TerminalHandlersApi(binaryMessenger) - _readerDelegate = ReaderDelegatePlugin(_handlers) - _readerReconnectionDelegate = ReaderReconnectionListenerPlugin(_handlers) + handlers = TerminalHandlersApi(binaryMessenger) + readerDelegate = ReaderDelegatePlugin(handlers) + readerReconnectionDelegate = ReaderReconnectionListenerPlugin(handlers) setupDiscoverReadersController(binaryMessenger) } @@ -577,65 +653,68 @@ class TerminalPlugin : FlutterPlugin, ActivityAware, TerminalPlatformApi { override fun onDetachedFromEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { if (Terminal.isInitialized()) clean() - _discoverReadersController.removeHandler() + discoverReadersController.removeHandler() TerminalPlatformApi.removeHandler() } override fun onAttachedToActivity(binding: ActivityPluginBinding) { - _activity = binding.activity + activity = binding.activity } override fun onDetachedFromActivityForConfigChanges() { - _activity = null + activity = null } override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { - _activity = binding.activity + activity = binding.activity } override fun onDetachedFromActivity() { - _activity = null + activity = null } // ======================== INTERNAL METHODS private fun findActiveReader(serialNumber: String): Reader { - val reader = _discoveredReaders.firstOrNull { it.serialNumber == serialNumber } + val reader = discoveredReaders.firstOrNull { it.serialNumber == serialNumber } return reader ?: throw createApiError(TerminalExceptionCodeApi.READER_NOT_RECOVERED).toPlatformError() } private fun findPaymentIntent(paymentIntentId: String): PaymentIntent { - val paymentIntent = _paymentIntents[paymentIntentId] + val paymentIntent = paymentIntents[paymentIntentId] return paymentIntent - ?: throw createApiError(TerminalExceptionCodeApi.PAYMENT_INTENT_NOT_RECOVERED).toPlatformError() + ?: throw createApiError(TerminalExceptionCodeApi.PAYMENT_INTENT_NOT_RECOVERED) + .toPlatformError() } private fun findSetupIntent(setupIntentId: String): SetupIntent { - val setupIntent = _setupIntents[setupIntentId] + val setupIntent = setupIntents[setupIntentId] return setupIntent - ?: throw createApiError(TerminalExceptionCodeApi.SETUP_INTENT_NOT_RECOVERED).toPlatformError() + ?: throw createApiError(TerminalExceptionCodeApi.SETUP_INTENT_NOT_RECOVERED) + .toPlatformError() } private fun clean() { - if (_terminal.connectedReader != null) _terminal.disconnectReader(EmptyCallback()) + if (terminal.connectedReader != null) terminal.disconnectReader(EmptyCallback()) - _discoverReadersSubject.clear() + discoverReadersSubject.clear() - _cancelablesCollectPaymentMethod.values.forEach { it.cancel(EmptyCallback()) } - _cancelablesCollectPaymentMethod = hashMapOf() - _paymentIntents = hashMapOf() + cancelablesCollectPaymentMethod.values.forEach { it.cancel(EmptyCallback()) } + cancelablesCollectPaymentMethod = hashMapOf() + paymentIntents = hashMapOf() - _cancelablesCollectSetupIntentPaymentMethod.values.forEach { it.cancel(EmptyCallback()) } - _cancelablesCollectSetupIntentPaymentMethod = hashMapOf() - _setupIntents = hashMapOf() + cancelablesCollectSetupIntentPaymentMethod.values.forEach { it.cancel(EmptyCallback()) } + cancelablesCollectSetupIntentPaymentMethod = hashMapOf() + setupIntents = hashMapOf() - _cancelablesCollectRefundPaymentMethod.values.forEach { it.cancel(EmptyCallback()) } - _cancelablesCollectRefundPaymentMethod = hashMapOf() + cancelablesCollectRefundPaymentMethod.values.forEach { it.cancel(EmptyCallback()) } + cancelablesCollectRefundPaymentMethod = hashMapOf() } } class EmptyCallback : Callback { override fun onFailure(e: TerminalException) {} + override fun onSuccess() {} } diff --git a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/Utils.kt b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/Utils.kt index 95f25b5..6b0d317 100644 --- a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/Utils.kt +++ b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/Utils.kt @@ -15,7 +15,10 @@ fun microsecondsToSeconds(value: Long): Int { return (value * 1000000).toInt() } -fun createApiError(code: TerminalExceptionCodeApi, message: String? = null): TerminalExceptionApi { +fun createApiError( + code: TerminalExceptionCodeApi, + message: String? = null, +): TerminalExceptionApi { return TerminalExceptionApi( code = code, message = message ?: "", @@ -23,4 +26,4 @@ fun createApiError(code: TerminalExceptionCodeApi, message: String? = null): Ter paymentIntent = null, apiError = null, ) -} \ No newline at end of file +} diff --git a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/api/TerminalApi.kt b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/api/TerminalApi.kt index 6d3c59a..53385e2 100644 --- a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/api/TerminalApi.kt +++ b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/api/TerminalApi.kt @@ -7,9 +7,6 @@ import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import kotlinx.coroutines.CoroutineScope -import kotlin.coroutines.resume -import kotlin.coroutines.resumeWithException -import kotlin.coroutines.suspendCoroutine import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel @@ -20,20 +17,15 @@ class PlatformError( val code: String, message: String?, val details: Any? = null, -): RuntimeException(message ?: code) - +) : RuntimeException(message ?: code) class Result( private val result: MethodChannel.Result, private val serializer: (data: T) -> Any?, ) { - fun success( - data: T, - ) = result.success(serializer(data)) + fun success(data: T) = result.success(serializer(data)) - fun error( - error: PlatformError, - ) { + fun error(error: PlatformError) { result.error(error.code, error.message, error.details) } } @@ -42,21 +34,15 @@ class ControllerSink( private val sink: EventChannel.EventSink, private val serializer: (data: T) -> Any?, ) { - fun success( - data: T, - ) = sink.success(serializer(data)) + fun success(data: T) = sink.success(serializer(data)) - fun error( - error: PlatformError, - ) = sink.error(error.code, error.message, error.details) + fun error(error: PlatformError) = sink.error(error.code, error.message, error.details) fun endOfStream() = sink.endOfStream() } interface TerminalPlatformApi { - fun onInit( - shouldPrintLogs: Boolean, - ) + fun onInit(shouldPrintLogs: Boolean) fun onClearCachedCredentials() @@ -100,9 +86,7 @@ interface TerminalPlatformApi { fun onGetConnectedReader(): ReaderApi? - fun onCancelReaderReconnection( - result: Result, - ) + fun onCancelReaderReconnection(result: Result) fun onListLocations( result: Result>, @@ -113,13 +97,9 @@ interface TerminalPlatformApi { fun onInstallAvailableUpdate() - fun onCancelReaderUpdate( - result: Result, - ) + fun onCancelReaderUpdate(result: Result) - fun onDisconnectReader( - result: Result, - ) + fun onDisconnectReader(result: Result) fun onGetPaymentStatus(): PaymentStatusApi @@ -212,18 +192,14 @@ interface TerminalPlatformApi { operationId: Long, ) - fun onConfirmRefund( - result: Result, - ) + fun onConfirmRefund(result: Result) fun onSetReaderDisplay( result: Result, cart: CartApi, ) - fun onClearReaderDisplay( - result: Result, - ) + fun onClearReaderDisplay(result: Result) private fun onMethodCall( call: MethodCall, @@ -231,6 +207,7 @@ interface TerminalPlatformApi { ) { try { val args = call.arguments>()!! + fun runAsync(callback: suspend () -> Any?) { coroutineScope.launch { val res = callback() @@ -251,7 +228,11 @@ interface TerminalPlatformApi { result.success(res.ordinal) } "supportsReadersOfType" -> { - val res = onSupportsReadersOfType((args[0] as Int?)?.let { DeviceTypeApi.values()[it] }, (args[1] as List).let { DiscoveryConfigurationApi.deserialize(it) }) + val res = + onSupportsReadersOfType( + (args[0] as Int?)?.let { DeviceTypeApi.values()[it] }, + (args[1] as List).let { DiscoveryConfigurationApi.deserialize(it) }, + ) result.success(res) } "connectBluetoothReader" -> { @@ -283,8 +264,13 @@ interface TerminalPlatformApi { onCancelReaderReconnection(res) } "listLocations" -> { - val res = Result>(result) { it.map { it.serialize()} } - onListLocations(res, args[0] as String?, (args[1] as? Number)?.toLong(), args[2] as String?) + val res = Result>(result) { it.map { it.serialize() } } + onListLocations( + res, + args[0] as String?, + (args[1] as? Number)?.toLong(), + args[2] as String?, + ) } "installAvailableUpdate" -> { onInstallAvailableUpdate() @@ -304,7 +290,10 @@ interface TerminalPlatformApi { } "createPaymentIntent" -> { val res = Result(result) { it.serialize() } - onCreatePaymentIntent(res, (args[0] as List).let { PaymentIntentParametersApi.deserialize(it) }) + onCreatePaymentIntent( + res, + (args[0] as List).let { PaymentIntentParametersApi.deserialize(it) }, + ) } "retrievePaymentIntent" -> { val res = Result(result) { it.serialize() } @@ -312,7 +301,15 @@ interface TerminalPlatformApi { } "startCollectPaymentMethod" -> { val res = Result(result) { it.serialize() } - onStartCollectPaymentMethod(res, (args[0] as Number).toLong(), args[1] as String, args[2] as Boolean, (args[3] as List?)?.let { TippingConfigurationApi.deserialize(it) }, args[4] as Boolean, args[5] as Boolean) + onStartCollectPaymentMethod( + res, + (args[0] as Number).toLong(), + args[1] as String, + args[2] as Boolean, + (args[3] as List?)?.let { TippingConfigurationApi.deserialize(it) }, + args[4] as Boolean, + args[5] as Boolean, + ) } "stopCollectPaymentMethod" -> { val res = Result(result) { null } @@ -328,7 +325,20 @@ interface TerminalPlatformApi { } "createSetupIntent" -> { val res = Result(result) { it.serialize() } - onCreateSetupIntent(res, args[0] as String?, args[1]?.let { hashMapOf(*(it as HashMap<*, *>).map { (k, v) -> k as String to v as String }.toTypedArray()) }, args[2] as String?, args[3] as String?, (args[4] as Int?)?.let { SetupIntentUsageApi.values()[it] }) + onCreateSetupIntent( + res, + args[0] as String?, + args[1]?.let { + hashMapOf( + *(it as HashMap<*, *>) + .map { (k, v) -> k as String to v as String } + .toTypedArray(), + ) + }, + args[2] as String?, + args[3] as String?, + (args[4] as Int?)?.let { SetupIntentUsageApi.values()[it] }, + ) } "retrieveSetupIntent" -> { val res = Result(result) { it.serialize() } @@ -336,7 +346,13 @@ interface TerminalPlatformApi { } "startCollectSetupIntentPaymentMethod" -> { val res = Result(result) { it.serialize() } - onStartCollectSetupIntentPaymentMethod(res, (args[0] as Number).toLong(), args[1] as String, args[2] as Boolean, args[3] as Boolean) + onStartCollectSetupIntentPaymentMethod( + res, + (args[0] as Number).toLong(), + args[1] as String, + args[2] as Boolean, + args[3] as Boolean, + ) } "stopCollectSetupIntentPaymentMethod" -> { val res = Result(result) { null } @@ -352,7 +368,23 @@ interface TerminalPlatformApi { } "startCollectRefundPaymentMethod" -> { val res = Result(result) { null } - onStartCollectRefundPaymentMethod(res, (args[0] as Number).toLong(), args[1] as String, (args[2] as Number).toLong(), args[3] as String, args[4]?.let { hashMapOf(*(it as HashMap<*, *>).map { (k, v) -> k as String to v as String }.toTypedArray()) }, args[5] as Boolean?, args[6] as Boolean?, args[7] as Boolean) + onStartCollectRefundPaymentMethod( + res, + (args[0] as Number).toLong(), + args[1] as String, + (args[2] as Number).toLong(), + args[3] as String, + args[4]?.let { + hashMapOf( + *(it as HashMap<*, *>) + .map { (k, v) -> k as String to v as String } + .toTypedArray(), + ) + }, + args[5] as Boolean?, + args[6] as Boolean?, + args[7] as Boolean, + ) } "stopCollectRefundPaymentMethod" -> { val res = Result(result) { null } @@ -400,20 +432,30 @@ interface TerminalPlatformApi { class DiscoverReadersControllerApi( binaryMessenger: BinaryMessenger, ) { - private val channel: EventChannel = EventChannel(binaryMessenger, "mek_stripe_terminal#TerminalPlatform#discoverReaders") + private val channel: EventChannel = + EventChannel(binaryMessenger, "mek_stripe_terminal#TerminalPlatform#discoverReaders") fun setHandler( onListen: (sink: ControllerSink>, configuration: DiscoveryConfigurationApi) -> Unit, onCancel: () -> Unit, ) { - channel.setStreamHandler(object : EventChannel.StreamHandler { - override fun onListen(arguments: Any?, events: EventChannel.EventSink) { - val args = arguments as List - val sink = ControllerSink>(events) {it.map { it.serialize()} } - onListen(sink, (args[0] as List).let { DiscoveryConfigurationApi.deserialize(it) }) - } - override fun onCancel(arguments: Any?) = onCancel() - }) + channel.setStreamHandler( + object : EventChannel.StreamHandler { + override fun onListen( + arguments: Any?, + events: EventChannel.EventSink, + ) { + val args = arguments as List + val sink = ControllerSink>(events) { it.map { it.serialize() } } + onListen( + sink, + (args[0] as List).let { DiscoveryConfigurationApi.deserialize(it) }, + ) + } + + override fun onCancel(arguments: Any?) = onCancel() + }, + ) } fun removeHandler() = channel.setStreamHandler(null) @@ -422,7 +464,8 @@ class DiscoverReadersControllerApi( class TerminalHandlersApi( binaryMessenger: BinaryMessenger, ) { - private val channel: MethodChannel = MethodChannel(binaryMessenger, "mek_stripe_terminal#TerminalHandlers") + private val channel: MethodChannel = + MethodChannel(binaryMessenger, "mek_stripe_terminal#TerminalHandlers") fun requestConnectionToken( onError: (error: PlatformError) -> Unit, @@ -433,48 +476,40 @@ class TerminalHandlersApi( listOf(), object : MethodChannel.Result { override fun notImplemented() {} - override fun error(code: String, message: String?, details: Any?) = - onError(PlatformError(code, message, details)) - override fun success(result: Any?) = - onSuccess(result as String) - } + + override fun error( + code: String, + message: String?, + details: Any?, + ) = onError(PlatformError(code, message, details)) + + override fun success(result: Any?) = onSuccess(result as String) + }, ) } - fun unexpectedReaderDisconnect( - reader: ReaderApi, - ) { + fun unexpectedReaderDisconnect(reader: ReaderApi) { channel.invokeMethod("_onUnexpectedReaderDisconnect", listOf(reader.serialize())) } - fun connectionStatusChange( - connectionStatus: ConnectionStatusApi, - ) { + fun connectionStatusChange(connectionStatus: ConnectionStatusApi) { channel.invokeMethod("_onConnectionStatusChange", listOf(connectionStatus.ordinal)) } - fun paymentStatusChange( - paymentStatus: PaymentStatusApi, - ) { + fun paymentStatusChange(paymentStatus: PaymentStatusApi) { channel.invokeMethod("_onPaymentStatusChange", listOf(paymentStatus.ordinal)) } - fun readerReportEvent( - event: ReaderEventApi, - ) { + fun readerReportEvent(event: ReaderEventApi) { channel.invokeMethod("_onReaderReportEvent", listOf(event.ordinal)) } - fun readerRequestDisplayMessage( - message: ReaderDisplayMessageApi, - ) { + fun readerRequestDisplayMessage(message: ReaderDisplayMessageApi) { channel.invokeMethod("_onReaderRequestDisplayMessage", listOf(message.ordinal)) } - fun readerRequestInput( - options: List, - ) { - channel.invokeMethod("_onReaderRequestInput", listOf(options.map { it.ordinal} )) + fun readerRequestInput(options: List) { + channel.invokeMethod("_onReaderRequestInput", listOf(options.map { it.ordinal })) } fun readerBatteryLevelUpdate( @@ -482,28 +517,25 @@ class TerminalHandlersApi( batteryStatus: BatteryStatusApi?, isCharging: Boolean, ) { - channel.invokeMethod("_onReaderBatteryLevelUpdate", listOf(batteryLevel, batteryStatus?.ordinal, isCharging)) + channel.invokeMethod( + "_onReaderBatteryLevelUpdate", + listOf(batteryLevel, batteryStatus?.ordinal, isCharging), + ) } fun readerReportLowBatteryWarning() { channel.invokeMethod("_onReaderReportLowBatteryWarning", listOf()) } - fun readerReportAvailableUpdate( - update: ReaderSoftwareUpdateApi, - ) { + fun readerReportAvailableUpdate(update: ReaderSoftwareUpdateApi) { channel.invokeMethod("_onReaderReportAvailableUpdate", listOf(update.serialize())) } - fun readerStartInstallingUpdate( - update: ReaderSoftwareUpdateApi, - ) { + fun readerStartInstallingUpdate(update: ReaderSoftwareUpdateApi) { channel.invokeMethod("_onReaderStartInstallingUpdate", listOf(update.serialize())) } - fun readerReportSoftwareUpdateProgress( - progress: Double, - ) { + fun readerReportSoftwareUpdateProgress(progress: Double) { channel.invokeMethod("_onReaderReportSoftwareUpdateProgress", listOf(progress)) } @@ -511,24 +543,21 @@ class TerminalHandlersApi( update: ReaderSoftwareUpdateApi?, exception: TerminalExceptionApi?, ) { - channel.invokeMethod("_onReaderFinishInstallingUpdate", listOf(update?.serialize(), exception?.serialize())) + channel.invokeMethod( + "_onReaderFinishInstallingUpdate", + listOf(update?.serialize(), exception?.serialize()), + ) } - fun readerReconnectFailed( - reader: ReaderApi, - ) { + fun readerReconnectFailed(reader: ReaderApi) { channel.invokeMethod("_onReaderReconnectFailed", listOf(reader.serialize())) } - fun readerReconnectStarted( - reader: ReaderApi, - ) { + fun readerReconnectStarted(reader: ReaderApi) { channel.invokeMethod("_onReaderReconnectStarted", listOf(reader.serialize())) } - fun readerReconnectSucceeded( - reader: ReaderApi, - ) { + fun readerReconnectSucceeded(reader: ReaderApi) { channel.invokeMethod("_onReaderReconnectSucceeded", listOf(reader.serialize())) } } @@ -564,15 +593,26 @@ data class AmountDetailsApi( } enum class BatteryStatusApi { - CRITICAL, LOW, NOMINAL; + CRITICAL, + LOW, + NOMINAL, } enum class CaptureMethodApi { - AUTOMATIC, MANUAL; + AUTOMATIC, + MANUAL, } enum class CardBrandApi { - AMEX, DINERS_CLUB, DISCOVER, JCB, MASTER_CARD, UNION_PAY, VISA, INTERAC, EFTPOS_AU; + AMEX, + DINERS_CLUB, + DISCOVER, + JCB, + MASTER_CARD, + UNION_PAY, + VISA, + INTERAC, + EFTPOS_AU, } data class CardDetailsApi( @@ -596,7 +636,9 @@ data class CardDetailsApi( } enum class CardFundingTypeApi { - CREDIT, DEBIT, PREPAID; + CREDIT, + DEBIT, + PREPAID, } data class CardNetworksApi( @@ -605,14 +647,14 @@ data class CardNetworksApi( ) { fun serialize(): List { return listOf( - available.map { it.ordinal} , + available.map { it.ordinal }, preferred, ) } } enum class CardPresentCaptureMethodApi { - MANUAL_PREFERRED; + MANUAL_PREFERRED, } data class CardPresentDetailsApi( @@ -654,9 +696,7 @@ data class CardPresentParametersApi( val requestedPriority: CardPresentRoutingApi?, ) { companion object { - fun deserialize( - serialized: List, - ): CardPresentParametersApi { + fun deserialize(serialized: List): CardPresentParametersApi { return CardPresentParametersApi( captureMethod = (serialized[0] as Int?)?.let { CardPresentCaptureMethodApi.values()[it] }, requestExtendedAuthorization = serialized[1] as Boolean?, @@ -668,7 +708,8 @@ data class CardPresentParametersApi( } enum class CardPresentRoutingApi { - DOMESTIC, INTERNATIONAL; + DOMESTIC, + INTERNATIONAL, } data class CartApi( @@ -678,14 +719,15 @@ data class CartApi( val lineItems: List, ) { companion object { - fun deserialize( - serialized: List, - ): CartApi { + fun deserialize(serialized: List): CartApi { return CartApi( currency = serialized[0] as String, tax = (serialized[1] as Number).toLong(), total = (serialized[2] as Number).toLong(), - lineItems = (serialized[3] as List<*>).map { (it as List).let { CartLineItemApi.deserialize(it) } }, + lineItems = + (serialized[3] as List<*>).map { + (it as List).let { CartLineItemApi.deserialize(it) } + }, ) } } @@ -697,9 +739,7 @@ data class CartLineItemApi( val amount: Long, ) { companion object { - fun deserialize( - serialized: List, - ): CartLineItemApi { + fun deserialize(serialized: List): CartLineItemApi { return CartLineItemApi( description = serialized[0] as String, quantity = (serialized[1] as Number).toLong(), @@ -738,32 +778,53 @@ data class ChargeApi( } enum class ChargeStatusApi { - SUCCEEDED, PENDING, FAILED; + SUCCEEDED, + PENDING, + FAILED, } enum class ConfirmationMethodApi { - AUTOMATIC, MANUAL; + AUTOMATIC, + MANUAL, } enum class ConnectionStatusApi { - NOT_CONNECTED, CONNECTED, CONNECTING; + NOT_CONNECTED, + CONNECTED, + CONNECTING, } enum class DeviceTypeApi { - CHIPPER1_X, CHIPPER2_X, STRIPE_M2, COTS_DEVICE, VERIFONE_P400, WISE_CUBE, WISE_PAD3, WISE_PAD3S, WISE_POS_E, WISE_POS_E_DEVKIT, ETNA, STRIPE_S700, STRIPE_S700_DEVKIT, APPLE_BUILT_IN; + CHIPPER1_X, + CHIPPER2_X, + STRIPE_M2, + COTS_DEVICE, + VERIFONE_P400, + WISE_CUBE, + WISE_PAD3, + WISE_PAD3S, + WISE_POS_E, + WISE_POS_E_DEVKIT, + ETNA, + STRIPE_S700, + STRIPE_S700_DEVKIT, + APPLE_BUILT_IN, } sealed class DiscoveryConfigurationApi { companion object { - fun deserialize( - serialized: List, - ): DiscoveryConfigurationApi { + fun deserialize(serialized: List): DiscoveryConfigurationApi { return when (serialized[0]) { - "BluetoothDiscoveryConfiguration" -> BluetoothDiscoveryConfigurationApi.deserialize(serialized.drop(1)) - "BluetoothProximityDiscoveryConfiguration" -> BluetoothProximityDiscoveryConfigurationApi.deserialize(serialized.drop(1)) - "HandoffDiscoveryConfiguration" -> HandoffDiscoveryConfigurationApi.deserialize(serialized.drop(1)) - "InternetDiscoveryConfiguration" -> InternetDiscoveryConfigurationApi.deserialize(serialized.drop(1)) - "LocalMobileDiscoveryConfiguration" -> LocalMobileDiscoveryConfigurationApi.deserialize(serialized.drop(1)) + "BluetoothDiscoveryConfiguration" -> + BluetoothDiscoveryConfigurationApi.deserialize(serialized.drop(1)) + "BluetoothProximityDiscoveryConfiguration" -> + BluetoothProximityDiscoveryConfigurationApi.deserialize(serialized.drop(1)) + "HandoffDiscoveryConfiguration" -> + HandoffDiscoveryConfigurationApi.deserialize(serialized.drop(1)) + "InternetDiscoveryConfiguration" -> + InternetDiscoveryConfigurationApi.deserialize(serialized.drop(1)) + "LocalMobileDiscoveryConfiguration" -> + LocalMobileDiscoveryConfigurationApi.deserialize(serialized.drop(1)) "UsbDiscoveryConfiguration" -> UsbDiscoveryConfigurationApi.deserialize(serialized.drop(1)) else -> throw Error() } @@ -774,11 +835,9 @@ sealed class DiscoveryConfigurationApi { data class BluetoothDiscoveryConfigurationApi( val isSimulated: Boolean, val timeout: Long?, -): DiscoveryConfigurationApi() { +) : DiscoveryConfigurationApi() { companion object { - fun deserialize( - serialized: List, - ): BluetoothDiscoveryConfigurationApi { + fun deserialize(serialized: List): BluetoothDiscoveryConfigurationApi { return BluetoothDiscoveryConfigurationApi( isSimulated = serialized[0] as Boolean, timeout = serialized[1] as Long?, @@ -789,11 +848,9 @@ data class BluetoothDiscoveryConfigurationApi( data class BluetoothProximityDiscoveryConfigurationApi( val isSimulated: Boolean, -): DiscoveryConfigurationApi() { +) : DiscoveryConfigurationApi() { companion object { - fun deserialize( - serialized: List, - ): BluetoothProximityDiscoveryConfigurationApi { + fun deserialize(serialized: List): BluetoothProximityDiscoveryConfigurationApi { return BluetoothProximityDiscoveryConfigurationApi( isSimulated = serialized[0] as Boolean, ) @@ -801,13 +858,10 @@ data class BluetoothProximityDiscoveryConfigurationApi( } } -class HandoffDiscoveryConfigurationApi: DiscoveryConfigurationApi() { +class HandoffDiscoveryConfigurationApi : DiscoveryConfigurationApi() { companion object { - fun deserialize( - serialized: List, - ): HandoffDiscoveryConfigurationApi { - return HandoffDiscoveryConfigurationApi( - ) + fun deserialize(serialized: List): HandoffDiscoveryConfigurationApi { + return HandoffDiscoveryConfigurationApi() } } } @@ -815,11 +869,9 @@ class HandoffDiscoveryConfigurationApi: DiscoveryConfigurationApi() { data class InternetDiscoveryConfigurationApi( val isSimulated: Boolean, val locationId: String?, -): DiscoveryConfigurationApi() { +) : DiscoveryConfigurationApi() { companion object { - fun deserialize( - serialized: List, - ): InternetDiscoveryConfigurationApi { + fun deserialize(serialized: List): InternetDiscoveryConfigurationApi { return InternetDiscoveryConfigurationApi( isSimulated = serialized[0] as Boolean, locationId = serialized[1] as String?, @@ -830,11 +882,9 @@ data class InternetDiscoveryConfigurationApi( data class LocalMobileDiscoveryConfigurationApi( val isSimulated: Boolean, -): DiscoveryConfigurationApi() { +) : DiscoveryConfigurationApi() { companion object { - fun deserialize( - serialized: List, - ): LocalMobileDiscoveryConfigurationApi { + fun deserialize(serialized: List): LocalMobileDiscoveryConfigurationApi { return LocalMobileDiscoveryConfigurationApi( isSimulated = serialized[0] as Boolean, ) @@ -845,11 +895,9 @@ data class LocalMobileDiscoveryConfigurationApi( data class UsbDiscoveryConfigurationApi( val isSimulated: Boolean, val timeout: Long?, -): DiscoveryConfigurationApi() { +) : DiscoveryConfigurationApi() { companion object { - fun deserialize( - serialized: List, - ): UsbDiscoveryConfigurationApi { + fun deserialize(serialized: List): UsbDiscoveryConfigurationApi { return UsbDiscoveryConfigurationApi( isSimulated = serialized[0] as Boolean, timeout = serialized[1] as Long?, @@ -859,7 +907,8 @@ data class UsbDiscoveryConfigurationApi( } enum class IncrementalAuthorizationStatusApi { - NOT_SUPPORTED, SUPPORTED; + NOT_SUPPORTED, + SUPPORTED, } data class LocationApi( @@ -881,7 +930,8 @@ data class LocationApi( } enum class LocationStatusApi { - SET, NOT_SET; + SET, + NOT_SET, } data class PaymentIntentApi( @@ -925,7 +975,7 @@ data class PaymentIntentApi( captureMethod.ordinal, currency, hashMapOf(*metadata.map { (k, v) -> k to v }.toTypedArray()), - charges.map { it.serialize()} , + charges.map { it.serialize() }, paymentMethod?.serialize(), paymentMethodId, amountDetails?.serialize(), @@ -971,15 +1021,21 @@ data class PaymentIntentParametersApi( val paymentMethodOptionsParameters: PaymentMethodOptionsParametersApi?, ) { companion object { - fun deserialize( - serialized: List, - ): PaymentIntentParametersApi { + fun deserialize(serialized: List): PaymentIntentParametersApi { return PaymentIntentParametersApi( amount = (serialized[0] as Number).toLong(), currency = serialized[1] as String, captureMethod = (serialized[2] as Int).let { CaptureMethodApi.values()[it] }, - paymentMethodTypes = (serialized[3] as List<*>).map { (it as Int).let { PaymentMethodTypeApi.values()[it] } }, - metadata = hashMapOf(*(serialized[4] as HashMap<*, *>).map { (k, v) -> k as String to v as String }.toTypedArray()), + paymentMethodTypes = + (serialized[3] as List<*>).map { + (it as Int).let { PaymentMethodTypeApi.values()[it] } + }, + metadata = + hashMapOf( + *(serialized[4] as HashMap<*, *>) + .map { (k, v) -> k as String to v as String } + .toTypedArray(), + ), description = serialized[5] as String?, statementDescriptor = serialized[6] as String?, statementDescriptorSuffix = serialized[7] as String?, @@ -990,18 +1046,28 @@ data class PaymentIntentParametersApi( transferGroup = serialized[12] as String?, onBehalfOf = serialized[13] as String?, setupFutureUsage = (serialized[14] as Int?)?.let { PaymentIntentUsageApi.values()[it] }, - paymentMethodOptionsParameters = (serialized[15] as List?)?.let { PaymentMethodOptionsParametersApi.deserialize(it) }, + paymentMethodOptionsParameters = + (serialized[15] as List?)?.let { + PaymentMethodOptionsParametersApi.deserialize(it) + }, ) } } } enum class PaymentIntentStatusApi { - CANCELED, PROCESSING, REQUIRES_CAPTURE, REQUIRES_CONFIRMATION, REQUIRES_PAYMENT_METHOD, REQUIRES_ACTION, SUCCEEDED; + CANCELED, + PROCESSING, + REQUIRES_CAPTURE, + REQUIRES_CONFIRMATION, + REQUIRES_PAYMENT_METHOD, + REQUIRES_ACTION, + SUCCEEDED, } enum class PaymentIntentUsageApi { - ON_SESSION, OFF_SESSION; + ON_SESSION, + OFF_SESSION, } data class PaymentMethodApi( @@ -1040,22 +1106,26 @@ data class PaymentMethodOptionsParametersApi( val cardPresentParameters: CardPresentParametersApi, ) { companion object { - fun deserialize( - serialized: List, - ): PaymentMethodOptionsParametersApi { + fun deserialize(serialized: List): PaymentMethodOptionsParametersApi { return PaymentMethodOptionsParametersApi( - cardPresentParameters = (serialized[0] as List).let { CardPresentParametersApi.deserialize(it) }, + cardPresentParameters = + (serialized[0] as List).let { CardPresentParametersApi.deserialize(it) }, ) } } } enum class PaymentMethodTypeApi { - CARD_PRESENT, CARD, INTERACT_PRESENT; + CARD_PRESENT, + CARD, + INTERACT_PRESENT, } enum class PaymentStatusApi { - NOT_READY, READY, WAITING_FOR_INPUT, PROCESSING; + NOT_READY, + READY, + WAITING_FOR_INPUT, + PROCESSING, } data class ReaderApi( @@ -1085,15 +1155,28 @@ data class ReaderApi( } enum class ReaderDisplayMessageApi { - CHECK_MOBILE_DEVICE, RETRY_CARD, INSERT_CARD, INSERT_OR_SWIPE_CARD, SWIPE_CARD, REMOVE_CARD, MULTIPLE_CONTACTLESS_CARDS_DETECTED, TRY_ANOTHER_READ_METHOD, TRY_ANOTHER_CARD, CARD_REMOVED_TOO_EARLY; + CHECK_MOBILE_DEVICE, + RETRY_CARD, + INSERT_CARD, + INSERT_OR_SWIPE_CARD, + SWIPE_CARD, + REMOVE_CARD, + MULTIPLE_CONTACTLESS_CARDS_DETECTED, + TRY_ANOTHER_READ_METHOD, + TRY_ANOTHER_CARD, + CARD_REMOVED_TOO_EARLY, } enum class ReaderEventApi { - CARD_INSERTED, CARD_REMOVED; + CARD_INSERTED, + CARD_REMOVED, } enum class ReaderInputOptionApi { - INSERT_CARD, SWIPE_CARD, TAP_CARD, MANUAL_ENTRY; + INSERT_CARD, + SWIPE_CARD, + TAP_CARD, + MANUAL_ENTRY, } data class ReaderSoftwareUpdateApi( @@ -1107,7 +1190,7 @@ data class ReaderSoftwareUpdateApi( ) { fun serialize(): List { return listOf( - components.map { it.ordinal} , + components.map { it.ordinal }, keyProfileName, onlyInstallRequiredUpdates, requiredAt, @@ -1171,7 +1254,9 @@ data class RefundApi( } enum class RefundStatusApi { - SUCCEEDED, PENDING, FAILED; + SUCCEEDED, + PENDING, + FAILED, } data class SetupAttemptApi( @@ -1225,7 +1310,12 @@ data class SetupAttemptPaymentMethodDetailsApi( } enum class SetupAttemptStatusApi { - REQUIRES_CONFIRMATION, REQUIRES_ACTION, PROCESSING, SUCCEEDED, FAILED, ABANDONED; + REQUIRES_CONFIRMATION, + REQUIRES_ACTION, + PROCESSING, + SUCCEEDED, + FAILED, + ABANDONED, } data class SetupIntentApi( @@ -1251,11 +1341,17 @@ data class SetupIntentApi( } enum class SetupIntentStatusApi { - REQUIRES_PAYMENT_METHOD, REQUIRES_CONFIRMATION, REQUIRES_ACTION, PROCESSING, SUCCEEDED, CANCELLED; + REQUIRES_PAYMENT_METHOD, + REQUIRES_CONFIRMATION, + REQUIRES_ACTION, + PROCESSING, + SUCCEEDED, + CANCELLED, } enum class SetupIntentUsageApi { - ON_SESSION, OFF_SESSION; + ON_SESSION, + OFF_SESSION, } data class TerminalExceptionApi( @@ -1277,7 +1373,126 @@ data class TerminalExceptionApi( } enum class TerminalExceptionCodeApi { - UNKNOWN, READER_NOT_RECOVERED, PAYMENT_INTENT_NOT_RECOVERED, SETUP_INTENT_NOT_RECOVERED, CANCEL_FAILED, NOT_CONNECTED_TO_READER, ALREADY_CONNECTED_TO_READER, BLUETOOTH_DISABLED, BLUETOOTH_PERMISSION_DENIED, CONFIRM_INVALID_PAYMENT_INTENT, INVALID_CLIENT_SECRET, INVALID_READER_FOR_UPDATE, UNSUPPORTED_OPERATION, UNEXPECTED_OPERATION, UNSUPPORTED_SDK, FEATURE_NOT_AVAILABLE_WITH_CONNECTED_READER, USB_PERMISSION_DENIED, USB_DISCOVERY_TIMED_OUT, INVALID_PARAMETER, INVALID_REQUIRED_PARAMETER, INVALID_TIP_PARAMETER, LOCAL_MOBILE_UNSUPPORTED_DEVICE, LOCAL_MOBILE_UNSUPPORTED_OPERATING_SYSTEM_VERSION, LOCAL_MOBILE_DEVICE_TAMPERED, LOCAL_MOBILE_DEBUG_NOT_SUPPORTED, OFFLINE_MODE_UNSUPPORTED_OPERATING_SYSTEM_VERSION, CANCELED, LOCATION_SERVICES_DISABLED, BLUETOOTH_SCAN_TIMED_OUT, BLUETOOTH_LOW_ENERGY_UNSUPPORTED, READER_SOFTWARE_UPDATE_FAILED_BATTERY_LOW, READER_SOFTWARE_UPDATE_FAILED_INTERRUPTED, READER_SOFTWARE_UPDATE_FAILED_EXPIRED_UPDATE, BLUETOOTH_CONNECTION_FAILED_BATTERY_CRITICALLY_LOW, CARD_INSERT_NOT_READ, CARD_SWIPE_NOT_READ, CARD_READ_TIMED_OUT, CARD_REMOVED, CUSTOMER_CONSENT_REQUIRED, CARD_LEFT_IN_READER, FEATURE_NOT_ENABLED_ON_ACCOUNT, PASSCODE_NOT_ENABLED, COMMAND_NOT_ALLOWED_DURING_CALL, INVALID_AMOUNT, INVALID_CURRENCY, APPLE_BUILT_IN_READER_T_O_S_ACCEPTANCE_REQUIRESI_CLOUD_SIGN_IN, APPLE_BUILT_IN_READER_T_O_S_ACCEPTANCE_CANCELED, APPLE_BUILT_IN_READER_FAILED_TO_PREPARE, APPLE_BUILT_IN_READER_DEVICE_BANNED, APPLE_BUILT_IN_READER_T_O_S_NOT_YET_ACCEPTED, APPLE_BUILT_IN_READER_T_O_S_ACCEPTANCE_FAILED, APPLE_BUILT_IN_READER_MERCHANT_BLOCKED, APPLE_BUILT_IN_READER_INVALID_MERCHANT, READER_BUSY, INCOMPATIBLE_READER, READER_COMMUNICATION_ERROR, UNKNOWN_READER_IP_ADDRESS, INTERNET_CONNECT_TIME_OUT, CONNECT_FAILED_READER_IS_IN_USE, READER_NOT_ACCESSIBLE_IN_BACKGROUND, BLUETOOTH_ERROR, BLUETOOTH_CONNECT_TIMED_OUT, BLUETOOTH_DISCONNECTED, BLUETOOTH_PEER_REMOVED_PAIRING_INFORMATION, BLUETOOTH_ALREADY_PAIRED_WITH_ANOTHER_DEVICE, BLUETOOTH_RECONNECT_STARTED, USB_DISCONNECTED, USB_RECONNECT_STARTED, READER_CONNECTED_TO_ANOTHER_DEVICE, READER_SOFTWARE_UPDATE_FAILED, READER_SOFTWARE_UPDATE_FAILED_READER_ERROR, READER_SOFTWARE_UPDATE_FAILED_SERVER_ERROR, NFC_DISABLED, UNSUPPORTED_READER_VERSION, UNEXPECTED_SDK_ERROR, UNEXPECTED_READER_ERROR, ENCRYPTION_KEY_FAILURE, ENCRYPTION_KEY_STILL_INITIALIZING, DECLINED_BY_STRIPE_API, DECLINED_BY_READER, NOT_CONNECTED_TO_INTERNET, REQUEST_TIMED_OUT, STRIPE_API_CONNECTION_ERROR, STRIPE_API_ERROR, STRIPE_API_RESPONSE_DECODING_ERROR, INTERNAL_NETWORK_ERROR, CONNECTION_TOKEN_PROVIDER_ERROR, SESSION_EXPIRED, UNSUPPORTED_MOBILE_DEVICE_CONFIGURATION, COMMAND_NOT_ALLOWED, AMOUNT_EXCEEDS_MAX_OFFLINE_AMOUNT, OFFLINE_PAYMENTS_DATABASE_TOO_LARGE, READER_CONNECTION_NOT_AVAILABLE_OFFLINE, READER_CONNECTION_OFFLINE_LOCATION_MISMATCH, READER_CONNECTION_OFFLINE_NEEDS_UPDATE, LOCATION_CONNECTION_NOT_AVAILABLE_OFFLINE, NO_LAST_SEEN_ACCOUNT, INVALID_OFFLINE_CURRENCY, REFUND_FAILED, CARD_SWIPE_NOT_AVAILABLE, INTERAC_NOT_SUPPORTED_OFFLINE, ONLINE_PIN_NOT_SUPPORTED_OFFLINE, OFFLINE_AND_CARD_EXPIRED, OFFLINE_TRANSACTION_DECLINED, OFFLINE_COLLECT_AND_CONFIRM_MISMATCH, FORWARDING_TEST_MODE_PAYMENT_IN_LIVE_MODE, FORWARDING_LIVE_MODE_PAYMENT_IN_TEST_MODE, OFFLINE_PAYMENT_INTENT_NOT_FOUND, UPDATE_PAYMENT_INTENT_UNAVAILABLE_WHILE_OFFLINE, UPDATE_PAYMENT_INTENT_UNAVAILABLE_WHILE_OFFLINE_MODE_ENABLED, MISSING_EMV_DATA, CONNECTION_TOKEN_PROVIDER_ERROR_WHILE_FORWARDING, CONNECTION_TOKEN_PROVIDER_TIMED_OUT, ACCOUNT_ID_MISMATCH_WHILE_FORWARDING, OFFLINE_BEHAVIOR_FORCE_OFFLINE_WITH_FEATURE_DISABLED, NOT_CONNECTED_TO_INTERNET_AND_OFFLINE_BEHAVIOR_REQUIRE_ONLINE, TEST_CARD_IN_LIVE_MODE, COLLECT_INPUTS_APPLICATION_ERROR, COLLECT_INPUTS_TIMED_OUT, COLLECT_INPUTS_UNSUPPORTED; + UNKNOWN, + READER_NOT_RECOVERED, + PAYMENT_INTENT_NOT_RECOVERED, + SETUP_INTENT_NOT_RECOVERED, + CANCEL_FAILED, + NOT_CONNECTED_TO_READER, + ALREADY_CONNECTED_TO_READER, + BLUETOOTH_DISABLED, + BLUETOOTH_PERMISSION_DENIED, + CONFIRM_INVALID_PAYMENT_INTENT, + INVALID_CLIENT_SECRET, + INVALID_READER_FOR_UPDATE, + UNSUPPORTED_OPERATION, + UNEXPECTED_OPERATION, + UNSUPPORTED_SDK, + FEATURE_NOT_AVAILABLE_WITH_CONNECTED_READER, + USB_PERMISSION_DENIED, + USB_DISCOVERY_TIMED_OUT, + INVALID_PARAMETER, + INVALID_REQUIRED_PARAMETER, + INVALID_TIP_PARAMETER, + LOCAL_MOBILE_UNSUPPORTED_DEVICE, + LOCAL_MOBILE_UNSUPPORTED_OPERATING_SYSTEM_VERSION, + LOCAL_MOBILE_DEVICE_TAMPERED, + LOCAL_MOBILE_DEBUG_NOT_SUPPORTED, + OFFLINE_MODE_UNSUPPORTED_OPERATING_SYSTEM_VERSION, + CANCELED, + LOCATION_SERVICES_DISABLED, + BLUETOOTH_SCAN_TIMED_OUT, + BLUETOOTH_LOW_ENERGY_UNSUPPORTED, + READER_SOFTWARE_UPDATE_FAILED_BATTERY_LOW, + READER_SOFTWARE_UPDATE_FAILED_INTERRUPTED, + READER_SOFTWARE_UPDATE_FAILED_EXPIRED_UPDATE, + BLUETOOTH_CONNECTION_FAILED_BATTERY_CRITICALLY_LOW, + CARD_INSERT_NOT_READ, + CARD_SWIPE_NOT_READ, + CARD_READ_TIMED_OUT, + CARD_REMOVED, + CUSTOMER_CONSENT_REQUIRED, + CARD_LEFT_IN_READER, + FEATURE_NOT_ENABLED_ON_ACCOUNT, + PASSCODE_NOT_ENABLED, + COMMAND_NOT_ALLOWED_DURING_CALL, + INVALID_AMOUNT, + INVALID_CURRENCY, + APPLE_BUILT_IN_READER_T_O_S_ACCEPTANCE_REQUIRESI_CLOUD_SIGN_IN, + APPLE_BUILT_IN_READER_T_O_S_ACCEPTANCE_CANCELED, + APPLE_BUILT_IN_READER_FAILED_TO_PREPARE, + APPLE_BUILT_IN_READER_DEVICE_BANNED, + APPLE_BUILT_IN_READER_T_O_S_NOT_YET_ACCEPTED, + APPLE_BUILT_IN_READER_T_O_S_ACCEPTANCE_FAILED, + APPLE_BUILT_IN_READER_MERCHANT_BLOCKED, + APPLE_BUILT_IN_READER_INVALID_MERCHANT, + READER_BUSY, + INCOMPATIBLE_READER, + READER_COMMUNICATION_ERROR, + UNKNOWN_READER_IP_ADDRESS, + INTERNET_CONNECT_TIME_OUT, + CONNECT_FAILED_READER_IS_IN_USE, + READER_NOT_ACCESSIBLE_IN_BACKGROUND, + BLUETOOTH_ERROR, + BLUETOOTH_CONNECT_TIMED_OUT, + BLUETOOTH_DISCONNECTED, + BLUETOOTH_PEER_REMOVED_PAIRING_INFORMATION, + BLUETOOTH_ALREADY_PAIRED_WITH_ANOTHER_DEVICE, + BLUETOOTH_RECONNECT_STARTED, + USB_DISCONNECTED, + USB_RECONNECT_STARTED, + READER_CONNECTED_TO_ANOTHER_DEVICE, + READER_SOFTWARE_UPDATE_FAILED, + READER_SOFTWARE_UPDATE_FAILED_READER_ERROR, + READER_SOFTWARE_UPDATE_FAILED_SERVER_ERROR, + NFC_DISABLED, + UNSUPPORTED_READER_VERSION, + UNEXPECTED_SDK_ERROR, + UNEXPECTED_READER_ERROR, + ENCRYPTION_KEY_FAILURE, + ENCRYPTION_KEY_STILL_INITIALIZING, + DECLINED_BY_STRIPE_API, + DECLINED_BY_READER, + NOT_CONNECTED_TO_INTERNET, + REQUEST_TIMED_OUT, + STRIPE_API_CONNECTION_ERROR, + STRIPE_API_ERROR, + STRIPE_API_RESPONSE_DECODING_ERROR, + INTERNAL_NETWORK_ERROR, + CONNECTION_TOKEN_PROVIDER_ERROR, + SESSION_EXPIRED, + UNSUPPORTED_MOBILE_DEVICE_CONFIGURATION, + COMMAND_NOT_ALLOWED, + AMOUNT_EXCEEDS_MAX_OFFLINE_AMOUNT, + OFFLINE_PAYMENTS_DATABASE_TOO_LARGE, + READER_CONNECTION_NOT_AVAILABLE_OFFLINE, + READER_CONNECTION_OFFLINE_LOCATION_MISMATCH, + READER_CONNECTION_OFFLINE_NEEDS_UPDATE, + LOCATION_CONNECTION_NOT_AVAILABLE_OFFLINE, + NO_LAST_SEEN_ACCOUNT, + INVALID_OFFLINE_CURRENCY, + REFUND_FAILED, + CARD_SWIPE_NOT_AVAILABLE, + INTERAC_NOT_SUPPORTED_OFFLINE, + ONLINE_PIN_NOT_SUPPORTED_OFFLINE, + OFFLINE_AND_CARD_EXPIRED, + OFFLINE_TRANSACTION_DECLINED, + OFFLINE_COLLECT_AND_CONFIRM_MISMATCH, + FORWARDING_TEST_MODE_PAYMENT_IN_LIVE_MODE, + FORWARDING_LIVE_MODE_PAYMENT_IN_TEST_MODE, + OFFLINE_PAYMENT_INTENT_NOT_FOUND, + UPDATE_PAYMENT_INTENT_UNAVAILABLE_WHILE_OFFLINE, + UPDATE_PAYMENT_INTENT_UNAVAILABLE_WHILE_OFFLINE_MODE_ENABLED, + MISSING_EMV_DATA, + CONNECTION_TOKEN_PROVIDER_ERROR_WHILE_FORWARDING, + CONNECTION_TOKEN_PROVIDER_TIMED_OUT, + ACCOUNT_ID_MISMATCH_WHILE_FORWARDING, + OFFLINE_BEHAVIOR_FORCE_OFFLINE_WITH_FEATURE_DISABLED, + NOT_CONNECTED_TO_INTERNET_AND_OFFLINE_BEHAVIOR_REQUIRE_ONLINE, + TEST_CARD_IN_LIVE_MODE, + COLLECT_INPUTS_APPLICATION_ERROR, + COLLECT_INPUTS_TIMED_OUT, + COLLECT_INPUTS_UNSUPPORTED, } data class TipApi( @@ -1294,9 +1509,7 @@ data class TippingConfigurationApi( val eligibleAmount: Long, ) { companion object { - fun deserialize( - serialized: List, - ): TippingConfigurationApi { + fun deserialize(serialized: List): TippingConfigurationApi { return TippingConfigurationApi( eligibleAmount = (serialized[0] as Number).toLong(), ) @@ -1305,9 +1518,15 @@ data class TippingConfigurationApi( } enum class UpdateComponentApi { - INCREMENTAL, FIRMWARE, CONFIG, KEYS; + INCREMENTAL, + FIRMWARE, + CONFIG, + KEYS, } enum class UpdateTimeEstimateApi { - LESS_THAN_ONE_MINUTE, ONE_TO_TWO_MINUTES, TWO_TO_FIVE_MINUTES, FIVE_TO_FIFTEEN_MINUTES; + LESS_THAN_ONE_MINUTE, + ONE_TO_TWO_MINUTES, + TWO_TO_FIVE_MINUTES, + FIVE_TO_FIFTEEN_MINUTES, } diff --git a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/api/ToApiExtensions.kt b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/api/ToApiExtensions.kt index f429701..a48e11e 100644 --- a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/api/ToApiExtensions.kt +++ b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/api/ToApiExtensions.kt @@ -1,21 +1,43 @@ package mek.stripeterminal.api -import mek.stripeterminal.toHashMap -import com.stripe.stripeterminal.external.models.* +import com.stripe.stripeterminal.external.models.Address +import com.stripe.stripeterminal.external.models.BatteryStatus +import com.stripe.stripeterminal.external.models.CardNetworks +import com.stripe.stripeterminal.external.models.CardPresentDetails +import com.stripe.stripeterminal.external.models.ConnectionStatus +import com.stripe.stripeterminal.external.models.DeviceType +import com.stripe.stripeterminal.external.models.IncrementalAuthorizationStatus +import com.stripe.stripeterminal.external.models.Location +import com.stripe.stripeterminal.external.models.LocationStatus +import com.stripe.stripeterminal.external.models.PaymentIntent +import com.stripe.stripeterminal.external.models.PaymentIntentStatus +import com.stripe.stripeterminal.external.models.PaymentMethodDetails +import com.stripe.stripeterminal.external.models.PaymentStatus +import com.stripe.stripeterminal.external.models.Reader +import com.stripe.stripeterminal.external.models.ReaderDisplayMessage +import com.stripe.stripeterminal.external.models.ReaderEvent +import com.stripe.stripeterminal.external.models.ReaderInputOptions +import com.stripe.stripeterminal.external.models.ReaderSoftwareUpdate +import com.stripe.stripeterminal.external.models.ReceiptDetails +import com.stripe.stripeterminal.external.models.Refund +import com.stripe.stripeterminal.external.models.SetupAttempt +import com.stripe.stripeterminal.external.models.SetupAttemptStatus +import com.stripe.stripeterminal.external.models.SetupIntent +import com.stripe.stripeterminal.external.models.SetupIntentCardPresentDetails +import com.stripe.stripeterminal.external.models.SetupIntentPaymentMethodDetails +import com.stripe.stripeterminal.external.models.SetupIntentStatus +import com.stripe.stripeterminal.external.models.SetupIntentUsage +import com.stripe.stripeterminal.external.models.TerminalException import com.stripe.stripeterminal.external.models.TerminalException.TerminalErrorCode -import mek.stripeterminal.createApiError import mek.stripeterminal.mappings.toApi +import mek.stripeterminal.toHashMap fun TerminalException.toPlatformError(): PlatformError { return toApi().toPlatformError() } fun TerminalExceptionApi.toPlatformError(): PlatformError { - return PlatformError( - code = "mek_stripe_terminal", - message = null, - details = serialize() - ) + return PlatformError(code = "mek_stripe_terminal", message = null, details = serialize()) } fun TerminalException.toApi(): TerminalExceptionApi { @@ -33,9 +55,12 @@ private fun TerminalErrorCode.toApiCode(): TerminalExceptionCodeApi? { return when (this) { TerminalErrorCode.CANCEL_FAILED -> TerminalExceptionCodeApi.CANCEL_FAILED TerminalErrorCode.NOT_CONNECTED_TO_READER -> TerminalExceptionCodeApi.NOT_CONNECTED_TO_READER - TerminalErrorCode.ALREADY_CONNECTED_TO_READER -> TerminalExceptionCodeApi.ALREADY_CONNECTED_TO_READER - TerminalErrorCode.BLUETOOTH_PERMISSION_DENIED -> TerminalExceptionCodeApi.BLUETOOTH_PERMISSION_DENIED - TerminalErrorCode.CONFIRM_INVALID_PAYMENT_INTENT -> TerminalExceptionCodeApi.CONFIRM_INVALID_PAYMENT_INTENT + TerminalErrorCode.ALREADY_CONNECTED_TO_READER -> + TerminalExceptionCodeApi.ALREADY_CONNECTED_TO_READER + TerminalErrorCode.BLUETOOTH_PERMISSION_DENIED -> + TerminalExceptionCodeApi.BLUETOOTH_PERMISSION_DENIED + TerminalErrorCode.CONFIRM_INVALID_PAYMENT_INTENT -> + TerminalExceptionCodeApi.CONFIRM_INVALID_PAYMENT_INTENT TerminalErrorCode.INVALID_CLIENT_SECRET -> TerminalExceptionCodeApi.INVALID_CLIENT_SECRET TerminalErrorCode.UNSUPPORTED_OPERATION -> TerminalExceptionCodeApi.UNSUPPORTED_OPERATION TerminalErrorCode.UNEXPECTED_OPERATION -> TerminalExceptionCodeApi.UNEXPECTED_OPERATION @@ -43,76 +68,116 @@ private fun TerminalErrorCode.toApiCode(): TerminalExceptionCodeApi? { TerminalErrorCode.USB_PERMISSION_DENIED -> TerminalExceptionCodeApi.USB_PERMISSION_DENIED TerminalErrorCode.MISSING_PREREQUISITE -> null TerminalErrorCode.MISSING_REQUIRED_PARAMETER -> TerminalExceptionCodeApi.INVALID_PARAMETER - TerminalErrorCode.INVALID_REQUIRED_PARAMETER -> TerminalExceptionCodeApi.INVALID_REQUIRED_PARAMETER + TerminalErrorCode.INVALID_REQUIRED_PARAMETER -> + TerminalExceptionCodeApi.INVALID_REQUIRED_PARAMETER TerminalErrorCode.INVALID_TIP_PARAMETER -> TerminalExceptionCodeApi.INVALID_TIP_PARAMETER TerminalErrorCode.LOCAL_MOBILE_LIBRARY_NOT_INCLUDED -> null - TerminalErrorCode.LOCAL_MOBILE_UNSUPPORTED_DEVICE -> TerminalExceptionCodeApi.LOCAL_MOBILE_UNSUPPORTED_DEVICE - TerminalErrorCode.LOCAL_MOBILE_UNSUPPORTED_ANDROID_VERSION -> TerminalExceptionCodeApi.LOCAL_MOBILE_UNSUPPORTED_OPERATING_SYSTEM_VERSION - TerminalErrorCode.LOCAL_MOBILE_DEVICE_TAMPERED -> TerminalExceptionCodeApi.LOCAL_MOBILE_DEVICE_TAMPERED - TerminalErrorCode.LOCAL_MOBILE_DEBUG_NOT_SUPPORTED -> TerminalExceptionCodeApi.LOCAL_MOBILE_DEBUG_NOT_SUPPORTED - TerminalErrorCode.OFFLINE_MODE_UNSUPPORTED_ANDROID_VERSION -> TerminalExceptionCodeApi.OFFLINE_MODE_UNSUPPORTED_OPERATING_SYSTEM_VERSION + TerminalErrorCode.LOCAL_MOBILE_UNSUPPORTED_DEVICE -> + TerminalExceptionCodeApi.LOCAL_MOBILE_UNSUPPORTED_DEVICE + TerminalErrorCode.LOCAL_MOBILE_UNSUPPORTED_ANDROID_VERSION -> + TerminalExceptionCodeApi.LOCAL_MOBILE_UNSUPPORTED_OPERATING_SYSTEM_VERSION + TerminalErrorCode.LOCAL_MOBILE_DEVICE_TAMPERED -> + TerminalExceptionCodeApi.LOCAL_MOBILE_DEVICE_TAMPERED + TerminalErrorCode.LOCAL_MOBILE_DEBUG_NOT_SUPPORTED -> + TerminalExceptionCodeApi.LOCAL_MOBILE_DEBUG_NOT_SUPPORTED + TerminalErrorCode.OFFLINE_MODE_UNSUPPORTED_ANDROID_VERSION -> + TerminalExceptionCodeApi.OFFLINE_MODE_UNSUPPORTED_OPERATING_SYSTEM_VERSION TerminalErrorCode.CANCELED -> TerminalExceptionCodeApi.CANCELED - TerminalErrorCode.LOCATION_SERVICES_DISABLED -> TerminalExceptionCodeApi.LOCATION_SERVICES_DISABLED + TerminalErrorCode.LOCATION_SERVICES_DISABLED -> + TerminalExceptionCodeApi.LOCATION_SERVICES_DISABLED TerminalErrorCode.BLUETOOTH_SCAN_TIMED_OUT -> TerminalExceptionCodeApi.BLUETOOTH_SCAN_TIMED_OUT - TerminalErrorCode.BLUETOOTH_LOW_ENERGY_UNSUPPORTED -> TerminalExceptionCodeApi.BLUETOOTH_LOW_ENERGY_UNSUPPORTED - TerminalErrorCode.READER_SOFTWARE_UPDATE_FAILED_BATTERY_LOW -> TerminalExceptionCodeApi.READER_SOFTWARE_UPDATE_FAILED_BATTERY_LOW - TerminalErrorCode.READER_SOFTWARE_UPDATE_FAILED_INTERRUPTED -> TerminalExceptionCodeApi.READER_SOFTWARE_UPDATE_FAILED_INTERRUPTED + TerminalErrorCode.BLUETOOTH_LOW_ENERGY_UNSUPPORTED -> + TerminalExceptionCodeApi.BLUETOOTH_LOW_ENERGY_UNSUPPORTED + TerminalErrorCode.READER_SOFTWARE_UPDATE_FAILED_BATTERY_LOW -> + TerminalExceptionCodeApi.READER_SOFTWARE_UPDATE_FAILED_BATTERY_LOW + TerminalErrorCode.READER_SOFTWARE_UPDATE_FAILED_INTERRUPTED -> + TerminalExceptionCodeApi.READER_SOFTWARE_UPDATE_FAILED_INTERRUPTED TerminalErrorCode.CARD_INSERT_NOT_READ -> TerminalExceptionCodeApi.CARD_INSERT_NOT_READ TerminalErrorCode.CARD_SWIPE_NOT_READ -> TerminalExceptionCodeApi.CARD_SWIPE_NOT_READ TerminalErrorCode.CARD_READ_TIMED_OUT -> TerminalExceptionCodeApi.CARD_READ_TIMED_OUT TerminalErrorCode.CARD_REMOVED -> TerminalExceptionCodeApi.CARD_REMOVED - TerminalErrorCode.CUSTOMER_CONSENT_REQUIRED -> TerminalExceptionCodeApi.CUSTOMER_CONSENT_REQUIRED + TerminalErrorCode.CUSTOMER_CONSENT_REQUIRED -> + TerminalExceptionCodeApi.CUSTOMER_CONSENT_REQUIRED TerminalErrorCode.CARD_LEFT_IN_READER -> TerminalExceptionCodeApi.CARD_LEFT_IN_READER TerminalErrorCode.USB_DISCOVERY_TIMED_OUT -> TerminalExceptionCodeApi.USB_DISCOVERY_TIMED_OUT - TerminalErrorCode.FEATURE_NOT_ENABLED_ON_ACCOUNT -> TerminalExceptionCodeApi.FEATURE_NOT_ENABLED_ON_ACCOUNT + TerminalErrorCode.FEATURE_NOT_ENABLED_ON_ACCOUNT -> + TerminalExceptionCodeApi.FEATURE_NOT_ENABLED_ON_ACCOUNT TerminalErrorCode.READER_BUSY -> TerminalExceptionCodeApi.READER_BUSY - TerminalErrorCode.READER_COMMUNICATION_ERROR -> TerminalExceptionCodeApi.READER_COMMUNICATION_ERROR + TerminalErrorCode.READER_COMMUNICATION_ERROR -> + TerminalExceptionCodeApi.READER_COMMUNICATION_ERROR TerminalErrorCode.BLUETOOTH_ERROR -> TerminalExceptionCodeApi.BLUETOOTH_ERROR TerminalErrorCode.BLUETOOTH_DISCONNECTED -> TerminalExceptionCodeApi.BLUETOOTH_DISCONNECTED - TerminalErrorCode.BLUETOOTH_RECONNECT_STARTED -> TerminalExceptionCodeApi.BLUETOOTH_RECONNECT_STARTED + TerminalErrorCode.BLUETOOTH_RECONNECT_STARTED -> + TerminalExceptionCodeApi.BLUETOOTH_RECONNECT_STARTED TerminalErrorCode.USB_DISCONNECTED -> TerminalExceptionCodeApi.USB_DISCONNECTED TerminalErrorCode.USB_RECONNECT_STARTED -> TerminalExceptionCodeApi.USB_RECONNECT_STARTED - TerminalErrorCode.READER_CONNECTED_TO_ANOTHER_DEVICE -> TerminalExceptionCodeApi.READER_CONNECTED_TO_ANOTHER_DEVICE - TerminalErrorCode.READER_SOFTWARE_UPDATE_FAILED -> TerminalExceptionCodeApi.READER_SOFTWARE_UPDATE_FAILED - TerminalErrorCode.READER_SOFTWARE_UPDATE_FAILED_READER_ERROR -> TerminalExceptionCodeApi.READER_SOFTWARE_UPDATE_FAILED_READER_ERROR - TerminalErrorCode.READER_SOFTWARE_UPDATE_FAILED_SERVER_ERROR -> TerminalExceptionCodeApi.READER_SOFTWARE_UPDATE_FAILED_SERVER_ERROR + TerminalErrorCode.READER_CONNECTED_TO_ANOTHER_DEVICE -> + TerminalExceptionCodeApi.READER_CONNECTED_TO_ANOTHER_DEVICE + TerminalErrorCode.READER_SOFTWARE_UPDATE_FAILED -> + TerminalExceptionCodeApi.READER_SOFTWARE_UPDATE_FAILED + TerminalErrorCode.READER_SOFTWARE_UPDATE_FAILED_READER_ERROR -> + TerminalExceptionCodeApi.READER_SOFTWARE_UPDATE_FAILED_READER_ERROR + TerminalErrorCode.READER_SOFTWARE_UPDATE_FAILED_SERVER_ERROR -> + TerminalExceptionCodeApi.READER_SOFTWARE_UPDATE_FAILED_SERVER_ERROR TerminalErrorCode.LOCAL_MOBILE_NFC_DISABLED -> TerminalExceptionCodeApi.NFC_DISABLED - TerminalErrorCode.UNSUPPORTED_READER_VERSION -> TerminalExceptionCodeApi.UNSUPPORTED_READER_VERSION + TerminalErrorCode.UNSUPPORTED_READER_VERSION -> + TerminalExceptionCodeApi.UNSUPPORTED_READER_VERSION TerminalErrorCode.UNEXPECTED_SDK_ERROR -> TerminalExceptionCodeApi.UNEXPECTED_SDK_ERROR TerminalErrorCode.DECLINED_BY_STRIPE_API -> TerminalExceptionCodeApi.DECLINED_BY_STRIPE_API TerminalErrorCode.DECLINED_BY_READER -> TerminalExceptionCodeApi.DECLINED_BY_READER TerminalErrorCode.REQUEST_TIMED_OUT -> TerminalExceptionCodeApi.REQUEST_TIMED_OUT - TerminalErrorCode.STRIPE_API_CONNECTION_ERROR -> TerminalExceptionCodeApi.STRIPE_API_CONNECTION_ERROR + TerminalErrorCode.STRIPE_API_CONNECTION_ERROR -> + TerminalExceptionCodeApi.STRIPE_API_CONNECTION_ERROR TerminalErrorCode.STRIPE_API_ERROR -> TerminalExceptionCodeApi.STRIPE_API_ERROR - TerminalErrorCode.STRIPE_API_RESPONSE_DECODING_ERROR -> TerminalExceptionCodeApi.STRIPE_API_RESPONSE_DECODING_ERROR - TerminalErrorCode.CONNECTION_TOKEN_PROVIDER_ERROR -> TerminalExceptionCodeApi.CONNECTION_TOKEN_PROVIDER_ERROR + TerminalErrorCode.STRIPE_API_RESPONSE_DECODING_ERROR -> + TerminalExceptionCodeApi.STRIPE_API_RESPONSE_DECODING_ERROR + TerminalErrorCode.CONNECTION_TOKEN_PROVIDER_ERROR -> + TerminalExceptionCodeApi.CONNECTION_TOKEN_PROVIDER_ERROR TerminalErrorCode.SESSION_EXPIRED -> TerminalExceptionCodeApi.SESSION_EXPIRED - TerminalErrorCode.ANDROID_API_LEVEL_ERROR -> TerminalExceptionCodeApi.UNSUPPORTED_MOBILE_DEVICE_CONFIGURATION - TerminalErrorCode.AMOUNT_EXCEEDS_MAX_OFFLINE_AMOUNT -> TerminalExceptionCodeApi.AMOUNT_EXCEEDS_MAX_OFFLINE_AMOUNT - TerminalErrorCode.OFFLINE_PAYMENTS_DATABASE_TOO_LARGE -> TerminalExceptionCodeApi.OFFLINE_PAYMENTS_DATABASE_TOO_LARGE - TerminalErrorCode.READER_CONNECTION_NOT_AVAILABLE_OFFLINE -> TerminalExceptionCodeApi.READER_CONNECTION_NOT_AVAILABLE_OFFLINE - TerminalErrorCode.LOCATION_CONNECTION_NOT_AVAILABLE_OFFLINE -> TerminalExceptionCodeApi.LOCATION_CONNECTION_NOT_AVAILABLE_OFFLINE + TerminalErrorCode.ANDROID_API_LEVEL_ERROR -> + TerminalExceptionCodeApi.UNSUPPORTED_MOBILE_DEVICE_CONFIGURATION + TerminalErrorCode.AMOUNT_EXCEEDS_MAX_OFFLINE_AMOUNT -> + TerminalExceptionCodeApi.AMOUNT_EXCEEDS_MAX_OFFLINE_AMOUNT + TerminalErrorCode.OFFLINE_PAYMENTS_DATABASE_TOO_LARGE -> + TerminalExceptionCodeApi.OFFLINE_PAYMENTS_DATABASE_TOO_LARGE + TerminalErrorCode.READER_CONNECTION_NOT_AVAILABLE_OFFLINE -> + TerminalExceptionCodeApi.READER_CONNECTION_NOT_AVAILABLE_OFFLINE + TerminalErrorCode.LOCATION_CONNECTION_NOT_AVAILABLE_OFFLINE -> + TerminalExceptionCodeApi.LOCATION_CONNECTION_NOT_AVAILABLE_OFFLINE TerminalErrorCode.NO_LAST_SEEN_ACCOUNT -> TerminalExceptionCodeApi.NO_LAST_SEEN_ACCOUNT TerminalErrorCode.INVALID_OFFLINE_CURRENCY -> TerminalExceptionCodeApi.INVALID_OFFLINE_CURRENCY TerminalErrorCode.CARD_SWIPE_NOT_AVAILABLE -> TerminalExceptionCodeApi.CARD_SWIPE_NOT_AVAILABLE - TerminalErrorCode.INTERAC_NOT_SUPPORTED_OFFLINE -> TerminalExceptionCodeApi.INTERAC_NOT_SUPPORTED_OFFLINE - TerminalErrorCode.ONLINE_PIN_NOT_SUPPORTED_OFFLINE -> TerminalExceptionCodeApi.ONLINE_PIN_NOT_SUPPORTED_OFFLINE + TerminalErrorCode.INTERAC_NOT_SUPPORTED_OFFLINE -> + TerminalExceptionCodeApi.INTERAC_NOT_SUPPORTED_OFFLINE + TerminalErrorCode.ONLINE_PIN_NOT_SUPPORTED_OFFLINE -> + TerminalExceptionCodeApi.ONLINE_PIN_NOT_SUPPORTED_OFFLINE TerminalErrorCode.OFFLINE_AND_CARD_EXPIRED -> TerminalExceptionCodeApi.OFFLINE_AND_CARD_EXPIRED - TerminalErrorCode.OFFLINE_TRANSACTION_DECLINED -> TerminalExceptionCodeApi.OFFLINE_TRANSACTION_DECLINED - TerminalErrorCode.OFFLINE_COLLECT_AND_CONFIRM_MISMATCH -> TerminalExceptionCodeApi.OFFLINE_COLLECT_AND_CONFIRM_MISMATCH - TerminalErrorCode.OFFLINE_TESTMODE_PAYMENT_IN_LIVEMODE -> TerminalExceptionCodeApi.FORWARDING_TEST_MODE_PAYMENT_IN_LIVE_MODE - TerminalErrorCode.OFFLINE_LIVEMODE_PAYMENT_IN_TESTMODE -> TerminalExceptionCodeApi.FORWARDING_LIVE_MODE_PAYMENT_IN_TEST_MODE - TerminalErrorCode.OFFLINE_PAYMENT_INTENT_NOT_FOUND -> TerminalExceptionCodeApi.OFFLINE_PAYMENT_INTENT_NOT_FOUND + TerminalErrorCode.OFFLINE_TRANSACTION_DECLINED -> + TerminalExceptionCodeApi.OFFLINE_TRANSACTION_DECLINED + TerminalErrorCode.OFFLINE_COLLECT_AND_CONFIRM_MISMATCH -> + TerminalExceptionCodeApi.OFFLINE_COLLECT_AND_CONFIRM_MISMATCH + TerminalErrorCode.OFFLINE_TESTMODE_PAYMENT_IN_LIVEMODE -> + TerminalExceptionCodeApi.FORWARDING_TEST_MODE_PAYMENT_IN_LIVE_MODE + TerminalErrorCode.OFFLINE_LIVEMODE_PAYMENT_IN_TESTMODE -> + TerminalExceptionCodeApi.FORWARDING_LIVE_MODE_PAYMENT_IN_TEST_MODE + TerminalErrorCode.OFFLINE_PAYMENT_INTENT_NOT_FOUND -> + TerminalExceptionCodeApi.OFFLINE_PAYMENT_INTENT_NOT_FOUND TerminalErrorCode.MISSING_EMV_DATA -> TerminalExceptionCodeApi.MISSING_EMV_DATA - TerminalErrorCode.CONNECTION_TOKEN_PROVIDER_ERROR_WHILE_FORWARDING -> TerminalExceptionCodeApi.CONNECTION_TOKEN_PROVIDER_ERROR_WHILE_FORWARDING - TerminalErrorCode.ACCOUNT_ID_MISMATCH_WHILE_FORWARDING -> TerminalExceptionCodeApi.ACCOUNT_ID_MISMATCH_WHILE_FORWARDING - TerminalErrorCode.FORCE_OFFLINE_WITH_FEATURE_DISABLED -> TerminalExceptionCodeApi.OFFLINE_BEHAVIOR_FORCE_OFFLINE_WITH_FEATURE_DISABLED - TerminalErrorCode.NOT_CONNECTED_TO_INTERNET_AND_REQUIRE_ONLINE_SET -> TerminalExceptionCodeApi.NOT_CONNECTED_TO_INTERNET_AND_OFFLINE_BEHAVIOR_REQUIRE_ONLINE + TerminalErrorCode.CONNECTION_TOKEN_PROVIDER_ERROR_WHILE_FORWARDING -> + TerminalExceptionCodeApi.CONNECTION_TOKEN_PROVIDER_ERROR_WHILE_FORWARDING + TerminalErrorCode.ACCOUNT_ID_MISMATCH_WHILE_FORWARDING -> + TerminalExceptionCodeApi.ACCOUNT_ID_MISMATCH_WHILE_FORWARDING + TerminalErrorCode.FORCE_OFFLINE_WITH_FEATURE_DISABLED -> + TerminalExceptionCodeApi.OFFLINE_BEHAVIOR_FORCE_OFFLINE_WITH_FEATURE_DISABLED + TerminalErrorCode.NOT_CONNECTED_TO_INTERNET_AND_REQUIRE_ONLINE_SET -> + TerminalExceptionCodeApi.NOT_CONNECTED_TO_INTERNET_AND_OFFLINE_BEHAVIOR_REQUIRE_ONLINE TerminalErrorCode.TEST_CARD_IN_LIVEMODE -> TerminalExceptionCodeApi.TEST_CARD_IN_LIVE_MODE - TerminalErrorCode.COLLECT_INPUTS_APPLICATION_ERROR -> TerminalExceptionCodeApi.COLLECT_INPUTS_APPLICATION_ERROR + TerminalErrorCode.COLLECT_INPUTS_APPLICATION_ERROR -> + TerminalExceptionCodeApi.COLLECT_INPUTS_APPLICATION_ERROR TerminalErrorCode.COLLECT_INPUTS_TIMED_OUT -> TerminalExceptionCodeApi.COLLECT_INPUTS_TIMED_OUT TerminalErrorCode.COLLECT_INPUTS_INVALID_PARAMETER -> TerminalExceptionCodeApi.INVALID_PARAMETER - TerminalErrorCode.COLLECT_INPUTS_UNSUPPORTED -> TerminalExceptionCodeApi.COLLECT_INPUTS_UNSUPPORTED + TerminalErrorCode.COLLECT_INPUTS_UNSUPPORTED -> + TerminalExceptionCodeApi.COLLECT_INPUTS_UNSUPPORTED } } @@ -180,7 +245,8 @@ fun ReaderDisplayMessage.toApi(): ReaderDisplayMessageApi { ReaderDisplayMessage.INSERT_OR_SWIPE_CARD -> ReaderDisplayMessageApi.INSERT_OR_SWIPE_CARD ReaderDisplayMessage.SWIPE_CARD -> ReaderDisplayMessageApi.SWIPE_CARD ReaderDisplayMessage.REMOVE_CARD -> ReaderDisplayMessageApi.REMOVE_CARD - ReaderDisplayMessage.MULTIPLE_CONTACTLESS_CARDS_DETECTED -> ReaderDisplayMessageApi.MULTIPLE_CONTACTLESS_CARDS_DETECTED + ReaderDisplayMessage.MULTIPLE_CONTACTLESS_CARDS_DETECTED -> + ReaderDisplayMessageApi.MULTIPLE_CONTACTLESS_CARDS_DETECTED ReaderDisplayMessage.TRY_ANOTHER_READ_METHOD -> ReaderDisplayMessageApi.TRY_ANOTHER_READ_METHOD ReaderDisplayMessage.TRY_ANOTHER_CARD -> ReaderDisplayMessageApi.TRY_ANOTHER_CARD ReaderDisplayMessage.CARD_REMOVED_TOO_EARLY -> ReaderDisplayMessageApi.CARD_REMOVED_TOO_EARLY @@ -229,10 +295,14 @@ fun ReaderSoftwareUpdate.UpdateComponent.toApi(): UpdateComponentApi { fun ReaderSoftwareUpdate.UpdateTimeEstimate.toApi(): UpdateTimeEstimateApi { return when (this) { - ReaderSoftwareUpdate.UpdateTimeEstimate.LESS_THAN_ONE_MINUTE -> UpdateTimeEstimateApi.LESS_THAN_ONE_MINUTE - ReaderSoftwareUpdate.UpdateTimeEstimate.ONE_TO_TWO_MINUTES -> UpdateTimeEstimateApi.ONE_TO_TWO_MINUTES - ReaderSoftwareUpdate.UpdateTimeEstimate.TWO_TO_FIVE_MINUTES -> UpdateTimeEstimateApi.TWO_TO_FIVE_MINUTES - ReaderSoftwareUpdate.UpdateTimeEstimate.FIVE_TO_FIFTEEN_MINUTES -> UpdateTimeEstimateApi.FIVE_TO_FIFTEEN_MINUTES + ReaderSoftwareUpdate.UpdateTimeEstimate.LESS_THAN_ONE_MINUTE -> + UpdateTimeEstimateApi.LESS_THAN_ONE_MINUTE + ReaderSoftwareUpdate.UpdateTimeEstimate.ONE_TO_TWO_MINUTES -> + UpdateTimeEstimateApi.ONE_TO_TWO_MINUTES + ReaderSoftwareUpdate.UpdateTimeEstimate.TWO_TO_FIVE_MINUTES -> + UpdateTimeEstimateApi.TWO_TO_FIVE_MINUTES + ReaderSoftwareUpdate.UpdateTimeEstimate.FIVE_TO_FIFTEEN_MINUTES -> + UpdateTimeEstimateApi.FIVE_TO_FIFTEEN_MINUTES } } @@ -292,8 +362,11 @@ fun ReceiptDetails.toApi(): ReceiptDetailsApi { fun CardNetworks.toApi(): CardNetworksApi { return CardNetworksApi( - available = available.map { cardBrandToApi(it)!! }, - preferred = preferred + available = + available.map { + cardBrandToApi(it)!! + }, + preferred = preferred, ) } @@ -311,11 +384,15 @@ fun PaymentIntent.toApi(): PaymentIntentApi { created = created, status = status!!.toApi(), amount = amount.toDouble(), - captureMethod = when (captureMethod!!) { - "automatic" -> CaptureMethodApi.AUTOMATIC - "manual" -> CaptureMethodApi.MANUAL - else -> throw IllegalArgumentException("Not supported CaptureMethod '${captureMethod}' on PaymentIntent $id") - }, + captureMethod = + when (captureMethod!!) { + "automatic" -> CaptureMethodApi.AUTOMATIC + "manual" -> CaptureMethodApi.MANUAL + else -> + throw IllegalArgumentException( + "Not supported CaptureMethod '$captureMethod' on PaymentIntent $id", + ) + }, currency = currency!!, metadata = metadata?.toHashMap() ?: hashMapOf(), charges = getCharges().map { it.toApi() }, @@ -333,21 +410,23 @@ fun PaymentIntent.toApi(): PaymentIntentApi { canceledAt = canceledAt, cancellationReason = cancellationReason, clientSecret = clientSecret, - confirmationMethod = when (confirmationMethod) { - "automatic" -> ConfirmationMethodApi.AUTOMATIC - "manual" -> ConfirmationMethodApi.MANUAL - else -> null - }, + confirmationMethod = + when (confirmationMethod) { + "automatic" -> ConfirmationMethodApi.AUTOMATIC + "manual" -> ConfirmationMethodApi.MANUAL + else -> null + }, description = description, invoiceId = invoice, onBehalfOf = onBehalfOf, receiptEmail = receiptEmail, reviewId = review, - setupFutureUsage = when (setupFutureUsage) { - "on_session" -> PaymentIntentUsageApi.ON_SESSION - "off_session" -> PaymentIntentUsageApi.OFF_SESSION - else -> null - }, + setupFutureUsage = + when (setupFutureUsage) { + "on_session" -> PaymentIntentUsageApi.ON_SESSION + "off_session" -> PaymentIntentUsageApi.OFF_SESSION + else -> null + }, transferGroup = transferGroup, customerId = customer, ) @@ -452,7 +531,7 @@ fun SetupAttemptStatus.toApi(): SetupAttemptStatusApi { fun SetupIntentPaymentMethodDetails.toApi(): SetupAttemptPaymentMethodDetailsApi { return SetupAttemptPaymentMethodDetailsApi( cardPresent = cardPresentDetails?.toApi(), - interacPresent = interacPresentDetails?.toApi() + interacPresent = interacPresentDetails?.toApi(), ) } @@ -472,12 +551,13 @@ fun Refund.toApi(): RefundApi { currency = currency!!, metadata = metadata?.toHashMap() ?: HashMap(), reason = reason, - status = when (status) { - "succeeded" -> RefundStatusApi.SUCCEEDED - "pending" -> RefundStatusApi.PENDING - "failed" -> RefundStatusApi.FAILED - else -> null - }, + status = + when (status) { + "succeeded" -> RefundStatusApi.SUCCEEDED + "pending" -> RefundStatusApi.PENDING + "failed" -> RefundStatusApi.FAILED + else -> null + }, paymentMethodDetails = paymentMethodDetails?.toApi(), failureReason = failureReason, ) @@ -486,6 +566,6 @@ fun Refund.toApi(): RefundApi { fun PaymentMethodDetails.toApi(): PaymentMethodDetailsApi { return PaymentMethodDetailsApi( cardPresent = cardPresentDetails?.toApi(), - interacPresent = interacPresentDetails?.toApi() + interacPresent = interacPresentDetails?.toApi(), ) -} \ No newline at end of file +} diff --git a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/api/ToHostExtensions.kt b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/api/ToHostExtensions.kt index ad25099..5ac8481 100644 --- a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/api/ToHostExtensions.kt +++ b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/api/ToHostExtensions.kt @@ -1,30 +1,43 @@ package mek.stripeterminal.api -import com.stripe.stripeterminal.external.models.* +import com.stripe.stripeterminal.external.models.CaptureMethod +import com.stripe.stripeterminal.external.models.CardPresentCaptureMethod +import com.stripe.stripeterminal.external.models.CardPresentParameters +import com.stripe.stripeterminal.external.models.CardPresentRoutingOptionParameters +import com.stripe.stripeterminal.external.models.Cart +import com.stripe.stripeterminal.external.models.CartLineItem +import com.stripe.stripeterminal.external.models.DeviceType +import com.stripe.stripeterminal.external.models.DiscoveryConfiguration +import com.stripe.stripeterminal.external.models.PaymentIntentParameters +import com.stripe.stripeterminal.external.models.PaymentMethodOptionsParameters +import com.stripe.stripeterminal.external.models.PaymentMethodType +import com.stripe.stripeterminal.external.models.RoutingPriority +import com.stripe.stripeterminal.external.models.TippingConfiguration import mek.stripeterminal.microsecondsToSeconds fun DiscoveryConfigurationApi.toHost(): DiscoveryConfiguration? { return when (this) { - is BluetoothDiscoveryConfigurationApi -> DiscoveryConfiguration.BluetoothDiscoveryConfiguration( - isSimulated = isSimulated, - timeout = timeout?.let { microsecondsToSeconds(it) } ?: 0, - ) - + is BluetoothDiscoveryConfigurationApi -> + DiscoveryConfiguration.BluetoothDiscoveryConfiguration( + isSimulated = isSimulated, + timeout = timeout?.let { microsecondsToSeconds(it) } ?: 0, + ) is BluetoothProximityDiscoveryConfigurationApi -> null is HandoffDiscoveryConfigurationApi -> DiscoveryConfiguration.HandoffDiscoveryConfiguration() - is InternetDiscoveryConfigurationApi -> DiscoveryConfiguration.InternetDiscoveryConfiguration( - isSimulated = isSimulated, - location = locationId, - ) - - is LocalMobileDiscoveryConfigurationApi -> DiscoveryConfiguration.LocalMobileDiscoveryConfiguration( - isSimulated = isSimulated, - ) - - is UsbDiscoveryConfigurationApi -> DiscoveryConfiguration.UsbDiscoveryConfiguration( - isSimulated = isSimulated, - timeout = timeout?.let { microsecondsToSeconds(it) } ?: 0, - ) + is InternetDiscoveryConfigurationApi -> + DiscoveryConfiguration.InternetDiscoveryConfiguration( + isSimulated = isSimulated, + location = locationId, + ) + is LocalMobileDiscoveryConfigurationApi -> + DiscoveryConfiguration.LocalMobileDiscoveryConfiguration( + isSimulated = isSimulated, + ) + is UsbDiscoveryConfigurationApi -> + DiscoveryConfiguration.UsbDiscoveryConfiguration( + isSimulated = isSimulated, + timeout = timeout?.let { microsecondsToSeconds(it) } ?: 0, + ) } } @@ -52,16 +65,18 @@ fun CartApi.toHost(): Cart { currency = currency, tax = tax, total = total, - lineItems = lineItems.map { it.toHost() } - ).build() + lineItems = lineItems.map { it.toHost() }, + ) + .build() } fun CartLineItemApi.toHost(): CartLineItem { return CartLineItem.Builder( description = description, quantity = quantity.toInt(), - amount = amount - ).build() + amount = amount, + ) + .build() } fun PaymentIntentUsageApi.toHost(): String { @@ -72,21 +87,24 @@ fun PaymentIntentUsageApi.toHost(): String { } fun PaymentIntentParametersApi.toHost(): PaymentIntentParameters { - val b = PaymentIntentParameters.Builder( - amount = amount, - currency = currency, - captureMethod = when (captureMethod) { - CaptureMethodApi.MANUAL -> CaptureMethod.Manual - CaptureMethodApi.AUTOMATIC -> CaptureMethod.Automatic - }, - allowedPaymentMethodTypes = paymentMethodTypes.map { - when (it) { - PaymentMethodTypeApi.CARD_PRESENT -> PaymentMethodType.CARD_PRESENT - PaymentMethodTypeApi.CARD -> PaymentMethodType.CARD - PaymentMethodTypeApi.INTERACT_PRESENT -> PaymentMethodType.INTERAC_PRESENT - } - }, - ) + val b = + PaymentIntentParameters.Builder( + amount = amount, + currency = currency, + captureMethod = + when (captureMethod) { + CaptureMethodApi.MANUAL -> CaptureMethod.Manual + CaptureMethodApi.AUTOMATIC -> CaptureMethod.Automatic + }, + allowedPaymentMethodTypes = + paymentMethodTypes.map { + when (it) { + PaymentMethodTypeApi.CARD_PRESENT -> PaymentMethodType.CARD_PRESENT + PaymentMethodTypeApi.CARD -> PaymentMethodType.CARD + PaymentMethodTypeApi.INTERACT_PRESENT -> PaymentMethodType.INTERAC_PRESENT + } + }, + ) b.setMetadata(metadata) description?.let(b::setDescription) statementDescriptor?.let(b::setStatementDescriptor) @@ -109,9 +127,7 @@ fun PaymentMethodOptionsParametersApi.toHost(): PaymentMethodOptionsParameters { } fun TippingConfigurationApi.toHost(): TippingConfiguration { - return TippingConfiguration.Builder() - .setEligibleAmount(eligibleAmount) - .build() + return TippingConfiguration.Builder().setEligibleAmount(eligibleAmount).build() } fun CardPresentParametersApi.toHost(): CardPresentParameters { @@ -141,4 +157,4 @@ fun SetupIntentUsageApi.toHost(): String { SetupIntentUsageApi.ON_SESSION -> "on_session" SetupIntentUsageApi.OFF_SESSION -> "off_session" } -} \ No newline at end of file +} diff --git a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/mappings/ChargeMappings.kt b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/mappings/ChargeMappings.kt index 5246733..4c672d0 100644 --- a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/mappings/ChargeMappings.kt +++ b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/mappings/ChargeMappings.kt @@ -10,12 +10,13 @@ fun Charge.toApi(): ChargeApi { return ChargeApi( amount = amount, currency = currency!!, - status = when (status) { - "pending" -> ChargeStatusApi.PENDING - "failed" -> ChargeStatusApi.FAILED - "succeeded" -> ChargeStatusApi.SUCCEEDED - else -> throw Error("Unsupported $status") - }, + status = + when (status) { + "pending" -> ChargeStatusApi.PENDING + "failed" -> ChargeStatusApi.FAILED + "succeeded" -> ChargeStatusApi.SUCCEEDED + else -> throw Error("Unsupported $status") + }, paymentMethodDetails = paymentMethodDetails?.toApi(), description = description!!, id = id, diff --git a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/DiscoverReadersSubject.kt b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/DiscoverReadersSubject.kt index b41b105..a85ead7 100644 --- a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/DiscoverReadersSubject.kt +++ b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/DiscoverReadersSubject.kt @@ -19,10 +19,11 @@ import mek.stripeterminal.createApiError import mek.stripeterminal.runOnMainThread class DiscoverReadersSubject { - private var _cancelable: Cancelable? = null + private var cancelable: Cancelable? = null private var _readers: List = arrayListOf() - val readers: List get() = _readers + val readers: List + get() = _readers fun clear() { cancel() @@ -30,10 +31,16 @@ class DiscoverReadersSubject { } @SuppressLint("MissingPermission") - fun onListen(sink: ControllerSink>, configuration: DiscoveryConfigurationApi) { + fun onListen( + sink: ControllerSink>, + configuration: DiscoveryConfigurationApi, + ) { val hostConfiguration = configuration.toHost() if (hostConfiguration == null) { - sink.error(createApiError(TerminalExceptionCodeApi.UNKNOWN, "Discovery method not supported").toPlatformError()) + sink.error( + createApiError(TerminalExceptionCodeApi.UNKNOWN, "Discovery method not supported") + .toPlatformError(), + ) sink.endOfStream() return } @@ -41,34 +48,41 @@ class DiscoverReadersSubject { // Ignore error, the previous stream can no longer receive events cancel() - _cancelable = Terminal.getInstance().discoverReaders( - config = hostConfiguration, - discoveryListener = object : DiscoveryListener { - override fun onUpdateDiscoveredReaders(readers: List) { - _readers = readers - runOnMainThread { sink.success(readers.map { it.toApi() }) } - } - }, - callback = object : Callback { - override fun onFailure(e: TerminalException) = runOnMainThread { - if (e.errorCode == TerminalException.TerminalErrorCode.CANCELED) return@runOnMainThread + cancelable = + Terminal.getInstance() + .discoverReaders( + config = hostConfiguration, + discoveryListener = + object : DiscoveryListener { + override fun onUpdateDiscoveredReaders(readers: List) { + _readers = readers + runOnMainThread { sink.success(readers.map { it.toApi() }) } + } + }, + callback = + object : Callback { + override fun onFailure(e: TerminalException) = + runOnMainThread { + if (e.errorCode == TerminalException.TerminalErrorCode.CANCELED) { + return@runOnMainThread + } - _cancelable = null - sink.error(e.toPlatformError()) - sink.endOfStream() - } + cancelable = null + sink.error(e.toPlatformError()) + sink.endOfStream() + } - override fun onSuccess() = runOnMainThread { sink.endOfStream() } - }, - ) + override fun onSuccess() = runOnMainThread { sink.endOfStream() } + }, + ) } fun onCancel() = cancel() private fun cancel() { - val cancelable = _cancelable - _cancelable = null + val cancelable = cancelable + this.cancelable = null // Ignore error, flutter stream already closed cancelable?.cancel(EmptyCallback()) } -} \ No newline at end of file +} diff --git a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/ReaderDelegatePlugin.kt b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/ReaderDelegatePlugin.kt index b981792..da178b0 100644 --- a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/ReaderDelegatePlugin.kt +++ b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/ReaderDelegatePlugin.kt @@ -17,22 +17,25 @@ class ReaderDelegatePlugin(private val _handlers: TerminalHandlersApi) : ReaderListener, HandoffReaderListener { var cancelUpdate: Cancelable? = null - override fun onReportReaderEvent(event: ReaderEvent) = runOnMainThread { - _handlers.readerReportEvent(event.toApi()) - } + override fun onReportReaderEvent(event: ReaderEvent) = + runOnMainThread { + _handlers.readerReportEvent(event.toApi()) + } - override fun onRequestReaderDisplayMessage(message: ReaderDisplayMessage) = runOnMainThread { - _handlers.readerRequestDisplayMessage(message.toApi()) - } + override fun onRequestReaderDisplayMessage(message: ReaderDisplayMessage) = + runOnMainThread { + _handlers.readerRequestDisplayMessage(message.toApi()) + } - override fun onRequestReaderInput(options: ReaderInputOptions) = runOnMainThread { - _handlers.readerRequestInput(options.options.mapNotNull { it.toApi() }) - } + override fun onRequestReaderInput(options: ReaderInputOptions) = + runOnMainThread { + _handlers.readerRequestInput(options.options.mapNotNull { it.toApi() }) + } override fun onBatteryLevelUpdate( batteryLevel: Float, batteryStatus: BatteryStatus, - isCharging: Boolean + isCharging: Boolean, ) = runOnMainThread { _handlers.readerBatteryLevelUpdate( batteryLevel = batteryLevel.toDouble(), @@ -41,13 +44,15 @@ class ReaderDelegatePlugin(private val _handlers: TerminalHandlersApi) : ) } - override fun onReportLowBatteryWarning() = runOnMainThread { - _handlers.readerReportLowBatteryWarning() - } + override fun onReportLowBatteryWarning() = + runOnMainThread { + _handlers.readerReportLowBatteryWarning() + } - override fun onReportAvailableUpdate(update: ReaderSoftwareUpdate) = runOnMainThread { - _handlers.readerReportAvailableUpdate(update.toApi()) - } + override fun onReportAvailableUpdate(update: ReaderSoftwareUpdate) = + runOnMainThread { + _handlers.readerReportAvailableUpdate(update.toApi()) + } override fun onStartInstallingUpdate( update: ReaderSoftwareUpdate, @@ -57,9 +62,10 @@ class ReaderDelegatePlugin(private val _handlers: TerminalHandlersApi) : _handlers.readerStartInstallingUpdate(update.toApi()) } - override fun onReportReaderSoftwareUpdateProgress(progress: Float) = runOnMainThread { - _handlers.readerReportSoftwareUpdateProgress(progress.toDouble()) - } + override fun onReportReaderSoftwareUpdateProgress(progress: Float) = + runOnMainThread { + _handlers.readerReportSoftwareUpdateProgress(progress.toDouble()) + } override fun onFinishInstallingUpdate( update: ReaderSoftwareUpdate?, @@ -69,4 +75,3 @@ class ReaderDelegatePlugin(private val _handlers: TerminalHandlersApi) : _handlers.readerFinishInstallingUpdate(update?.toApi(), e?.toApi()) } } - diff --git a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/ReaderReconnectionDelegatePlugin.kt b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/ReaderReconnectionListenerPlugin.kt similarity index 62% rename from stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/ReaderReconnectionDelegatePlugin.kt rename to stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/ReaderReconnectionListenerPlugin.kt index 82dfb92..684db4c 100644 --- a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/ReaderReconnectionDelegatePlugin.kt +++ b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/ReaderReconnectionListenerPlugin.kt @@ -15,17 +15,19 @@ class ReaderReconnectionListenerPlugin(private val _handlers: TerminalHandlersAp reader: Reader, cancelReconnect: Cancelable, ) = runOnMainThread { - this.cancelReconnect = cancelReconnect; + this.cancelReconnect = cancelReconnect _handlers.readerReconnectStarted(reader.toApi()) } - override fun onReaderReconnectFailed(reader: Reader) = runOnMainThread { - cancelReconnect = null - _handlers.readerReconnectFailed(reader.toApi()) - } + override fun onReaderReconnectFailed(reader: Reader) = + runOnMainThread { + cancelReconnect = null + _handlers.readerReconnectFailed(reader.toApi()) + } - override fun onReaderReconnectSucceeded(reader: Reader) = runOnMainThread { - cancelReconnect = null - _handlers.readerReconnectSucceeded(reader.toApi()) - } -} \ No newline at end of file + override fun onReaderReconnectSucceeded(reader: Reader) = + runOnMainThread { + cancelReconnect = null + _handlers.readerReconnectSucceeded(reader.toApi()) + } +} diff --git a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/TerminalDelegatePlugin.kt b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/TerminalDelegatePlugin.kt index a7fbc4e..1032de2 100644 --- a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/TerminalDelegatePlugin.kt +++ b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/TerminalDelegatePlugin.kt @@ -11,29 +11,30 @@ import mek.stripeterminal.api.TerminalHandlersApi import mek.stripeterminal.api.toApi import mek.stripeterminal.runOnMainThread -class TerminalDelegatePlugin( - private val _handlers: TerminalHandlersApi -) : ConnectionTokenProvider, TerminalListener { +class TerminalDelegatePlugin(private val _handlers: TerminalHandlersApi) : + ConnectionTokenProvider, TerminalListener { + override fun fetchConnectionToken(callback: ConnectionTokenCallback) = + runOnMainThread { + _handlers.requestConnectionToken( + { error -> callback.onFailure(ConnectionTokenException(error.message ?: "", error)) }, + { token -> callback.onSuccess(token) }, + ) + } - override fun fetchConnectionToken(callback: ConnectionTokenCallback) = runOnMainThread { - _handlers.requestConnectionToken({ error -> - callback.onFailure(ConnectionTokenException(error.message ?: "", error)) - }, { token -> - callback.onSuccess(token) - }) - } + // region Terminal listeners + override fun onConnectionStatusChange(status: ConnectionStatus) = + runOnMainThread { + _handlers.connectionStatusChange(status.toApi()) + } - //region Terminal listeners - override fun onConnectionStatusChange(status: ConnectionStatus) = runOnMainThread { - _handlers.connectionStatusChange(status.toApi()) - } + override fun onUnexpectedReaderDisconnect(reader: Reader) = + runOnMainThread { + _handlers.unexpectedReaderDisconnect(reader.toApi()) + } - override fun onUnexpectedReaderDisconnect(reader: Reader) = runOnMainThread { - _handlers.unexpectedReaderDisconnect(reader.toApi()) - } - - override fun onPaymentStatusChange(status: PaymentStatus) = runOnMainThread { - _handlers.paymentStatusChange(status.toApi()) - } - //endregion -} \ No newline at end of file + override fun onPaymentStatusChange(status: PaymentStatus) = + runOnMainThread { + _handlers.paymentStatusChange(status.toApi()) + } + // endregion +} diff --git a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/TerminalErrorHandler.kt b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/TerminalErrorHandler.kt index d405bb5..d63030b 100644 --- a/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/TerminalErrorHandler.kt +++ b/stripe_terminal/android/src/main/kotlin/mek/stripeterminal/plugin/TerminalErrorHandler.kt @@ -6,9 +6,10 @@ import mek.stripeterminal.api.PlatformError import mek.stripeterminal.api.toPlatformError import mek.stripeterminal.runOnMainThread -abstract class TerminalErrorHandler(private val handler: (error: PlatformError) -> Unit) : ErrorCallback { +abstract class TerminalErrorHandler(private val handler: (error: PlatformError) -> Unit) : + ErrorCallback { override fun onFailure(e: TerminalException) { val error = e.toPlatformError() runOnMainThread { handler(error) } } -} \ No newline at end of file +} diff --git a/stripe_terminal/android/src/test/kotlin/mek/stripeterminal/StripeTerminalPluginTest.kt b/stripe_terminal/android/src/test/kotlin/mek/stripeterminal/StripeTerminalPluginTest.kt index 8e97bfb..06299a6 100644 --- a/stripe_terminal/android/src/test/kotlin/mek/stripeterminal/StripeTerminalPluginTest.kt +++ b/stripe_terminal/android/src/test/kotlin/mek/stripeterminal/StripeTerminalPluginTest.kt @@ -2,8 +2,8 @@ package mek.stripeterminal import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel -import kotlin.test.Test import org.mockito.Mockito +import kotlin.test.Test /* * This demonstrates a simple unit test of the Kotlin portion of this plugin's implementation. @@ -14,14 +14,14 @@ import org.mockito.Mockito */ internal class StripeTerminalPluginTest { - @Test - fun onMethodCall_getPlatformVersion_returnsExpectedValue() { - val plugin = TerminalPlugin() + @Test + fun onMethodCall_getPlatformVersion_returnsExpectedValue() { + val plugin = TerminalPlugin() - val call = MethodCall("getPlatformVersion", null) - val mockResult: MethodChannel.Result = Mockito.mock(MethodChannel.Result::class.java) - plugin.onMethodCall(call, mockResult) + val call = MethodCall("getPlatformVersion", null) + val mockResult: MethodChannel.Result = Mockito.mock(MethodChannel.Result::class.java) + plugin.onMethodCall(call, mockResult) - Mockito.verify(mockResult).success("Android " + android.os.Build.VERSION.RELEASE) - } + Mockito.verify(mockResult).success("Android " + android.os.Build.VERSION.RELEASE) + } }