diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml new file mode 100644 index 0000000..3e08018 --- /dev/null +++ b/.github/workflows/cd.yml @@ -0,0 +1,97 @@ +name: CD + +on: + push: + tags: + - 'v*' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: cd-${{ github.ref }} + cancel-in-progress: false + +jobs: + test: + name: Tests and coverage gate + runs-on: ubuntu-latest + steps: + - name: Check out the repository + uses: actions/checkout@v7 + + - name: Set up JDK 17 + uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: 17 + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v6 + + - name: Run unit tests and the coverage gate + run: ./gradlew testDebugUnitTest :openpay-sdk:jacocoCoverageVerification + + publish: + name: Publish to Maven Central + runs-on: ubuntu-latest + needs: test + steps: + - name: Check out the repository + uses: actions/checkout@v7 + + - name: Verify the tag matches the library version + if: github.ref_type == 'tag' + run: | + tag_version="${GITHUB_REF_NAME#v}" + gradle_version="$(grep '^VERSION_NAME=' gradle.properties | cut -d= -f2)" + if [ "$tag_version" != "$gradle_version" ]; then + echo "::error::Tag $GITHUB_REF_NAME does not match VERSION_NAME=$gradle_version in gradle.properties" + exit 1 + fi + + - name: Set up JDK 17 + uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: 17 + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v6 + + - name: Publish the signed artifacts to the Central Portal staging API + env: + MAVEN_REPOSITORY_URL: https://ossrh-staging-api.central.sonatype.com/service/local/staging/deploy/maven2/ + MAVEN_REPOSITORY_USERNAME: ${{ secrets.MAVEN_REPOSITORY_USERNAME }} + MAVEN_REPOSITORY_PASSWORD: ${{ secrets.MAVEN_REPOSITORY_PASSWORD }} + SIGNING_KEY: ${{ secrets.SIGNING_KEY }} + SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }} + run: ./gradlew :openpay-sdk:publishReleasePublicationToRemoteRepository + + - name: Remind about the manual portal release step + run: | + { + echo "## Deployment staged" + echo "" + echo "The signed artifacts were uploaded to the Central Portal." + echo "Go to https://central.sonatype.com → Publish → Deployments," + echo "wait for validation to pass and press **Publish** to release" + echo "to Maven Central. Nothing is public until that button is pressed." + } >> "$GITHUB_STEP_SUMMARY" + + github-release: + name: Create the GitHub release + runs-on: ubuntu-latest + needs: publish + if: github.ref_type == 'tag' + permissions: + contents: write + steps: + - name: Check out the repository + uses: actions/checkout@v7 + + - name: Create the release with generated notes + env: + GH_TOKEN: ${{ github.token }} + run: gh release create "$GITHUB_REF_NAME" --verify-tag --generate-notes diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..a976ad3 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,103 @@ +name: CI + +on: + push: + branches: + - develop + - master + pull_request: + branches: + - develop + - master + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + unit-tests: + name: Unit tests and coverage + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write + steps: + - name: Check out the repository + uses: actions/checkout@v7 + + - name: Set up JDK 17 + uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: 17 + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v6 + + - name: Run unit tests with coverage + run: ./gradlew testDebugUnitTest jacocoTestReport :openpay-sdk:jacocoCoverageVerification + + - name: Publish coverage on the pull request + if: github.event_name == 'pull_request' + uses: Madrapps/jacoco-report@v1.8.0 + with: + paths: ${{ github.workspace }}/**/build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml + token: ${{ secrets.GITHUB_TOKEN }} + title: Unit test coverage + update-comment: true + min-coverage-overall: 80 + min-coverage-changed-files: 80 + + - name: Upload coverage reports + if: always() + uses: actions/upload-artifact@v7 + with: + name: coverage-reports + path: '**/build/reports/jacoco/jacocoTestReport/' + + - name: Upload unit test results + if: always() + uses: actions/upload-artifact@v7 + with: + name: unit-test-results + path: '**/build/reports/tests/testDebugUnitTest/' + + instrumented-tests: + name: Instrumented tests + runs-on: ubuntu-latest + steps: + - name: Check out the repository + uses: actions/checkout@v7 + + - name: Enable KVM for the emulator + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + + - name: Set up JDK 17 + uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: 17 + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v6 + + - name: Run instrumented tests on an emulator + uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: 34 + arch: x86_64 + disable-animations: true + script: ./gradlew connectedDebugAndroidTest + + - name: Upload instrumented test results + if: always() + uses: actions/upload-artifact@v7 + with: + name: instrumented-test-results + path: '**/build/reports/androidTests/connected/' diff --git a/.gitignore b/.gitignore index 2fdc689..45fa00f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,7 @@ *.iml .gradle /local.properties -/.idea/caches -/.idea/libraries -/.idea/modules.xml -/.idea/workspace.xml -/.idea/navEditor.xml -/.idea/assetWizardSettings.xml +/.idea/ .DS_Store /build /captures diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 26d3352..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml diff --git a/.idea/.name b/.idea/.name deleted file mode 100644 index 8ff6da9..0000000 --- a/.idea/.name +++ /dev/null @@ -1 +0,0 @@ -Openpay \ No newline at end of file diff --git a/.idea/AndroidProjectSystem.xml b/.idea/AndroidProjectSystem.xml deleted file mode 100644 index 4a53bee..0000000 --- a/.idea/AndroidProjectSystem.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml deleted file mode 100644 index b86273d..0000000 --- a/.idea/compiler.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/deploymentTargetSelector.xml b/.idea/deploymentTargetSelector.xml deleted file mode 100644 index b268ef3..0000000 --- a/.idea/deploymentTargetSelector.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml deleted file mode 100644 index cdbc250..0000000 --- a/.idea/gradle.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/markdown.xml b/.idea/markdown.xml deleted file mode 100644 index c61ea33..0000000 --- a/.idea/markdown.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index a4f09e2..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml deleted file mode 100644 index 16660f1..0000000 --- a/.idea/runConfigurations.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 94a25f7..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..de65cd8 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 DEV1 Softworks + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b46325e --- /dev/null +++ b/README.md @@ -0,0 +1,105 @@ +# Openpay Android SDK + +Modern, Kotlin-first Android SDK for [Openpay](https://www.openpay.mx): +card tokenization, validation, antifraud device sessions and ready-made +Jetpack Compose UI — so card data goes straight from the user's device to +Openpay and never touches your servers. + +**Documentation languages:** +[English](docs/en/getting-started.md) · +[Español](docs/es/getting-started.md) · +[Français](docs/fr/getting-started.md) · +[Português](docs/pt/getting-started.md) + +## Features + +- **100% Kotlin**, coroutines-first API with a callback flavor for + non-coroutine consumers +- **Compose-first UI**: a complete, themeable card form with live brand + detection, input formatting and full accessibility — plus an + `AbstractComposeView` wrapper for XML apps +- **Card validation**: Luhn, brand detection (Visa, Mastercard incl. + 2-series, Amex), brand-aware CVV and expiration rules +- **Tokenization** against the Openpay API for Mexico, Colombia and Peru, + sandbox and production +- **Antifraud device sessions** matching the legacy fingerprint flow +- **4 languages** (en, es, pt, fr) with automatic device-locale resolution + and a runtime override API +- **Clean architecture + Koin** in an isolated container that never + clashes with the host app +- **Tested**: JUnit, Mockito and Robolectric with a JaCoCo-enforced 80% + minimum line coverage + +## Installation + +```kotlin +dependencies { + implementation("mx.dev1.openpay:openpay-sdk:1.0.0") +} +``` + +Minimum Android version: 8.0 (API 26). + +## Quick start + +```kotlin +// 1. Configure once +val openpay = Openpay( + OpenpayConfig( + merchantId = "your-merchant-id", + publicApiKey = "pk_your_public_key", + country = OpenpayCountry.MEXICO, + environment = OpenpayEnvironment.SANDBOX, + ) +) + +// 2. Capture the card with the built-in form and tokenize it +OpenpayCardForm( + onCardValidated = { card -> + scope.launch { + openpay.createToken(card) + .onSuccess { token -> sendToBackend(token.tokenId) } + .onFailure { error -> showError(error) } + } + } +) + +// 3. Antifraud device session (send it to your backend with the token) +val deviceSessionId = openpay.setupDeviceSession(activity) +``` + +A full walkthrough lives in +[docs/en/getting-started.md](docs/en/getting-started.md), and the `:app` +module is a runnable sample of every feature. + +## Documentation + +| Guide | en | es | fr | pt | +|---|---|---|---|---| +| Getting started | [en](docs/en/getting-started.md) | [es](docs/es/getting-started.md) | [fr](docs/fr/getting-started.md) | [pt](docs/pt/getting-started.md) | +| Architecture (with diagrams) | [en](docs/en/architecture.md) | [es](docs/es/architecture.md) | [fr](docs/fr/architecture.md) | [pt](docs/pt/architecture.md) | +| UI components & accessibility | [en](docs/en/ui-components.md) | [es](docs/es/ui-components.md) | [fr](docs/fr/ui-components.md) | [pt](docs/pt/ui-components.md) | +| Internationalization | [en](docs/en/internationalization.md) | [es](docs/es/internationalization.md) | [fr](docs/fr/internationalization.md) | [pt](docs/pt/internationalization.md) | +| Contributing | [en](docs/en/contributing.md) | [es](docs/es/contributing.md) | [fr](docs/fr/contributing.md) | [pt](docs/pt/contributing.md) | +| Continuous integration | [en](docs/en/ci.md) | [es](docs/es/ci.md) | [fr](docs/fr/ci.md) | [pt](docs/pt/ci.md) | + +## Repository layout + +``` +openpay-android/ +├── openpay-sdk/ # the published library (Maven: mx.dev1.openpay:openpay-sdk) +├── app/ # sample application consuming the SDK +├── docs/ # documentation in en / es / fr / pt +└── gradle/libs.versions.toml # every dependency version, in one place +``` + +## Contributing + +Pull requests are welcome — the project uses Git Flow (`develop` as the +integration branch, `master` as production). Start with +[docs/en/contributing.md](docs/en/contributing.md); it assumes no Android +experience. + +## License + +Licensed under the [Apache License, Version 2.0](LICENSE.md). diff --git a/app/build.gradle.kts b/app/build.gradle.kts index c31fec5..ec9c968 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,5 +1,6 @@ plugins { alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.compose) } android { @@ -12,7 +13,7 @@ android { defaultConfig { applicationId = "mx.dev1.openpay" - minSdk = 28 + minSdk = 26 targetSdk = 36 versionCode = 1 versionName = "1.0" @@ -21,6 +22,9 @@ android { } buildTypes { + debug { + enableUnitTestCoverage = true + } release { isMinifyEnabled = false proguardFiles( @@ -29,17 +33,57 @@ android { ) } } + + buildFeatures { + compose = true + } + compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } + + testOptions { + unitTests { + isIncludeAndroidResources = true + } + } } dependencies { + implementation(project(":openpay-sdk")) + implementation(libs.androidx.core.ktx) implementation(libs.androidx.appcompat) implementation(libs.material) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.androidx.lifecycle.viewmodel.compose) + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.navigation.compose) + + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.graphics) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.compose.material3) + debugImplementation(libs.androidx.compose.ui.tooling) + debugImplementation(libs.androidx.compose.ui.test.manifest) + + implementation(platform(libs.koin.bom)) + implementation(libs.koin.android) + implementation(libs.koin.androidx.compose) + testImplementation(libs.junit) + testImplementation(libs.androidx.junit) + testImplementation(libs.mockito.core) + testImplementation(libs.mockito.kotlin) + testImplementation(libs.robolectric) + testImplementation(libs.kotlinx.coroutines.test) + testImplementation(platform(libs.androidx.compose.bom)) + testImplementation(libs.androidx.compose.ui.test.junit4) + androidTestImplementation(libs.androidx.junit) androidTestImplementation(libs.androidx.espresso.core) -} \ No newline at end of file + androidTestImplementation(platform(libs.androidx.compose.bom)) + androidTestImplementation(libs.androidx.compose.ui.test.junit4) +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index b5e2ddd..cf467ea 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -3,6 +3,7 @@ xmlns:tools="http://schemas.android.com/tools"> + android:theme="@style/Theme.Openpay"> - \ No newline at end of file + + + + + + + + + + diff --git a/app/src/main/java/mx/dev1/openpay/MainActivity.kt b/app/src/main/java/mx/dev1/openpay/MainActivity.kt new file mode 100644 index 0000000..6872f92 --- /dev/null +++ b/app/src/main/java/mx/dev1/openpay/MainActivity.kt @@ -0,0 +1,55 @@ +package mx.dev1.openpay + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.navigation.compose.NavHost +import androidx.navigation.compose.composable +import androidx.navigation.compose.rememberNavController +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme +import mx.dev1.openpay.ui.addcard.AddCardScreen +import mx.dev1.openpay.ui.checkout.CheckoutScreen +import mx.dev1.openpay.ui.checkout.CheckoutViewModel +import org.koin.androidx.compose.koinViewModel + +private object SampleDestinations { + const val CHECKOUT = "checkout" + const val ADD_CARD = "add-card" +} + +class MainActivity : ComponentActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + setContent { + OpenpayTheme { + // Resolved at the activity level so both screens share the + // same configuration and tokenization state. + val sharedViewModel: CheckoutViewModel = koinViewModel() + val navController = rememberNavController() + + NavHost( + navController = navController, + startDestination = SampleDestinations.CHECKOUT, + ) { + composable(SampleDestinations.CHECKOUT) { + CheckoutScreen( + onAddCardClick = { + navController.navigate(SampleDestinations.ADD_CARD) + }, + viewModel = sharedViewModel, + ) + } + composable(SampleDestinations.ADD_CARD) { + AddCardScreen( + onNavigateBack = { navController.popBackStack() }, + viewModel = sharedViewModel, + ) + } + } + } + } + } +} diff --git a/app/src/main/java/mx/dev1/openpay/SampleApplication.kt b/app/src/main/java/mx/dev1/openpay/SampleApplication.kt new file mode 100644 index 0000000..c0f0032 --- /dev/null +++ b/app/src/main/java/mx/dev1/openpay/SampleApplication.kt @@ -0,0 +1,22 @@ +package mx.dev1.openpay + +import android.app.Application +import mx.dev1.openpay.di.sampleAppModule +import org.koin.android.ext.koin.androidContext +import org.koin.core.context.GlobalContext +import org.koin.core.context.startKoin + +class SampleApplication : Application() { + + override fun onCreate() { + super.onCreate() + // The guard keeps test runners that recreate the Application (for + // example Robolectric) from starting Koin twice in the same process. + if (GlobalContext.getOrNull() == null) { + startKoin { + androidContext(this@SampleApplication) + modules(sampleAppModule) + } + } + } +} diff --git a/app/src/main/java/mx/dev1/openpay/di/SampleAppModule.kt b/app/src/main/java/mx/dev1/openpay/di/SampleAppModule.kt new file mode 100644 index 0000000..5026630 --- /dev/null +++ b/app/src/main/java/mx/dev1/openpay/di/SampleAppModule.kt @@ -0,0 +1,9 @@ +package mx.dev1.openpay.di + +import mx.dev1.openpay.ui.checkout.CheckoutViewModel +import org.koin.core.module.dsl.viewModel +import org.koin.dsl.module + +val sampleAppModule = module { + viewModel { CheckoutViewModel() } +} diff --git a/app/src/main/java/mx/dev1/openpay/ui/addcard/AddCardScreen.kt b/app/src/main/java/mx/dev1/openpay/ui/addcard/AddCardScreen.kt new file mode 100644 index 0000000..f25854d --- /dev/null +++ b/app/src/main/java/mx/dev1/openpay/ui/addcard/AddCardScreen.kt @@ -0,0 +1,146 @@ +package mx.dev1.openpay.ui.addcard + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.Card +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import mx.dev1.openpay.R +import mx.dev1.openpay.sdk.domain.model.Card as OpenpayCard +import mx.dev1.openpay.sdk.domain.validation.CardBrand +import mx.dev1.openpay.sdk.ui.components.OpenpayCardBrandLogo +import mx.dev1.openpay.sdk.ui.components.OpenpayCardForm +import mx.dev1.openpay.ui.checkout.CheckoutUiState +import mx.dev1.openpay.ui.checkout.CheckoutViewModel +import org.koin.androidx.compose.koinViewModel + +object AddCardScreenTags { + const val BACK_BUTTON = "sample_add_card_back_button" + const val TOKEN_RESULT = "sample_token_result" + const val ERROR_MESSAGE = "sample_add_card_error_message" +} + +/** + * Independent screen hosting the SDK card form, separated from the merchant + * configuration so the sample mirrors a real checkout flow: configure once, + * then capture cards on a dedicated screen. + */ +@Composable +fun AddCardScreen( + onNavigateBack: () -> Unit, + viewModel: CheckoutViewModel = koinViewModel(), +) { + val uiState by viewModel.uiState.collectAsState() + + AddCardScreenContent( + uiState = uiState, + onCardValidated = viewModel::tokenize, + onNavigateBack = onNavigateBack, + ) +} + +/** + * Stateless layout of the add-card screen, extracted so previews and tests + * can render it with a fabricated [CheckoutUiState]. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun AddCardScreenContent( + uiState: CheckoutUiState, + onCardValidated: (OpenpayCard) -> Unit, + onNavigateBack: () -> Unit, +) { + Scaffold( + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.sample_add_card_title)) }, + navigationIcon = { + IconButton( + onClick = onNavigateBack, + modifier = Modifier.testTag(AddCardScreenTags.BACK_BUTTON), + ) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.sample_back), + ) + } + }, + ) + }, + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + .padding(16.dp) + // Shrinks the scrollable viewport when the keyboard opens so the + // focused field can always scroll into view above the IME. + .imePadding() + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + OpenpayCardForm(onCardValidated = onCardValidated) + + if (uiState.isProcessing) { + CircularProgressIndicator(modifier = Modifier.align(Alignment.CenterHorizontally)) + } + + uiState.createdToken?.let { token -> + Card( + modifier = Modifier + .fillMaxWidth() + .testTag(AddCardScreenTags.TOKEN_RESULT), + ) { + Column(modifier = Modifier.padding(12.dp)) { + Text(stringResource(R.string.sample_token_created, token.tokenId)) + token.card?.let { tokenizedCard -> + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + OpenpayCardBrandLogo( + brand = CardBrand.fromBrandName(tokenizedCard.brand), + ) + Text( + text = "${tokenizedCard.brand ?: ""} ${tokenizedCard.maskedCardNumber ?: ""}".trim(), + style = MaterialTheme.typography.bodySmall, + ) + } + } + } + } + } + + uiState.errorMessage?.let { errorMessage -> + Text( + text = errorMessage, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.testTag(AddCardScreenTags.ERROR_MESSAGE), + ) + } + } + } +} diff --git a/app/src/main/java/mx/dev1/openpay/ui/addcard/AddCardScreenPreviews.kt b/app/src/main/java/mx/dev1/openpay/ui/addcard/AddCardScreenPreviews.kt new file mode 100644 index 0000000..3ab473e --- /dev/null +++ b/app/src/main/java/mx/dev1/openpay/ui/addcard/AddCardScreenPreviews.kt @@ -0,0 +1,63 @@ +package mx.dev1.openpay.ui.addcard + +import androidx.compose.runtime.Composable +import androidx.compose.ui.tooling.preview.Preview +import mx.dev1.openpay.sdk.domain.model.Token +import mx.dev1.openpay.sdk.domain.model.TokenizedCard +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme +import mx.dev1.openpay.ui.checkout.CheckoutUiState + +@Preview(name = "Add card – empty form", showBackground = true) +@Composable +private fun EmptyAddCardScreenPreview() { + OpenpayTheme { + AddCardScreenContent( + uiState = CheckoutUiState(), + onCardValidated = {}, + onNavigateBack = {}, + ) + } +} + +@Preview(name = "Add card – token created", showBackground = true) +@Composable +private fun TokenCreatedAddCardScreenPreview() { + OpenpayTheme { + AddCardScreenContent( + uiState = CheckoutUiState( + createdToken = Token( + tokenId = "k1nsxpxqhyhnbjr3qfhr", + card = TokenizedCard( + maskedCardNumber = "411111XXXXXX1111", + holderName = "Juan Pérez Ramírez", + expirationMonth = "12", + expirationYear = "30", + brand = "visa", + cardType = "debit", + bankName = null, + bankCode = null, + allowsCharges = true, + allowsPayouts = false, + address = null, + ), + ), + ), + onCardValidated = {}, + onNavigateBack = {}, + ) + } +} + +@Preview(name = "Add card – tokenization error", showBackground = true) +@Composable +private fun ErrorAddCardScreenPreview() { + OpenpayTheme { + AddCardScreenContent( + uiState = CheckoutUiState( + errorMessage = "Openpay rejected the request (3001): the card was declined", + ), + onCardValidated = {}, + onNavigateBack = {}, + ) + } +} diff --git a/app/src/main/java/mx/dev1/openpay/ui/checkout/CheckoutScreen.kt b/app/src/main/java/mx/dev1/openpay/ui/checkout/CheckoutScreen.kt new file mode 100644 index 0000000..44c8fbd --- /dev/null +++ b/app/src/main/java/mx/dev1/openpay/ui/checkout/CheckoutScreen.kt @@ -0,0 +1,227 @@ +package mx.dev1.openpay.ui.checkout + +import android.app.Activity +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import mx.dev1.openpay.R +import mx.dev1.openpay.sdk.core.OpenpayCountry +import mx.dev1.openpay.sdk.i18n.OpenpayLanguage +import org.koin.androidx.compose.koinViewModel + +object CheckoutScreenTags { + const val MERCHANT_ID_FIELD = "sample_merchant_id_field" + const val PUBLIC_KEY_FIELD = "sample_public_key_field" + const val DEVICE_SESSION_BUTTON = "sample_device_session_button" + const val ADD_CARD_BUTTON = "sample_add_card_button" + const val ERROR_MESSAGE = "sample_error_message" +} + +/** + * Configuration screen of the sample: merchant credentials, SDK language and + * antifraud device session. The card form lives in its own screen, reached + * through [onAddCardClick] once the configuration is complete. + */ +@Composable +fun CheckoutScreen( + onAddCardClick: () -> Unit, + viewModel: CheckoutViewModel = koinViewModel(), +) { + val uiState by viewModel.uiState.collectAsState() + val hostActivity = LocalContext.current as? Activity + + CheckoutScreenContent( + uiState = uiState, + onMerchantIdChange = viewModel::updateMerchantId, + onPublicApiKeyChange = viewModel::updatePublicApiKey, + onCountryChange = viewModel::updateCountry, + onProductionModeChange = viewModel::updateProductionMode, + onLanguageChange = viewModel::updateLanguage, + onStartDeviceSession = { hostActivity?.let(viewModel::startDeviceSession) }, + onAddCardClick = onAddCardClick, + ) +} + +/** + * Stateless layout of the configuration screen, extracted so previews and + * tests can render it with a fabricated [CheckoutUiState]. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun CheckoutScreenContent( + uiState: CheckoutUiState, + onMerchantIdChange: (String) -> Unit, + onPublicApiKeyChange: (String) -> Unit, + onCountryChange: (OpenpayCountry) -> Unit, + onProductionModeChange: (Boolean) -> Unit, + onLanguageChange: (OpenpayLanguage?) -> Unit, + onStartDeviceSession: () -> Unit, + onAddCardClick: () -> Unit, +) { + Scaffold( + topBar = { TopAppBar(title = { Text(stringResource(R.string.app_name)) }) }, + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + .padding(16.dp) + // Shrinks the scrollable viewport when the keyboard opens so the + // focused field can always scroll into view above the IME. + .imePadding() + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + MerchantConfigurationSection( + uiState = uiState, + onMerchantIdChange = onMerchantIdChange, + onPublicApiKeyChange = onPublicApiKeyChange, + onCountryChange = onCountryChange, + onProductionModeChange = onProductionModeChange, + ) + LanguageSection( + selectedLanguage = uiState.selectedLanguage, + onLanguageChange = onLanguageChange, + ) + + OutlinedButton( + onClick = onStartDeviceSession, + modifier = Modifier + .fillMaxWidth() + .testTag(CheckoutScreenTags.DEVICE_SESSION_BUTTON), + ) { + Text(stringResource(R.string.sample_start_device_session)) + } + uiState.deviceSessionId?.let { deviceSessionId -> + Text( + text = stringResource(R.string.sample_device_session_result, deviceSessionId), + style = MaterialTheme.typography.bodySmall, + ) + } + + Button( + onClick = onAddCardClick, + enabled = uiState.isConfigurationComplete, + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .testTag(CheckoutScreenTags.ADD_CARD_BUTTON), + ) { + Text(stringResource(R.string.sample_add_card_button)) + } + + uiState.errorMessage?.let { errorMessage -> + Text( + text = errorMessage, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.testTag(CheckoutScreenTags.ERROR_MESSAGE), + ) + } + } + } +} + +@Composable +private fun MerchantConfigurationSection( + uiState: CheckoutUiState, + onMerchantIdChange: (String) -> Unit, + onPublicApiKeyChange: (String) -> Unit, + onCountryChange: (OpenpayCountry) -> Unit, + onProductionModeChange: (Boolean) -> Unit, +) { + Text( + text = stringResource(R.string.sample_configuration_title), + style = MaterialTheme.typography.titleMedium, + ) + OutlinedTextField( + value = uiState.merchantId, + onValueChange = onMerchantIdChange, + modifier = Modifier + .fillMaxWidth() + .testTag(CheckoutScreenTags.MERCHANT_ID_FIELD), + label = { Text(stringResource(R.string.sample_merchant_id_label)) }, + singleLine = true, + ) + OutlinedTextField( + value = uiState.publicApiKey, + onValueChange = onPublicApiKeyChange, + modifier = Modifier + .fillMaxWidth() + .testTag(CheckoutScreenTags.PUBLIC_KEY_FIELD), + label = { Text(stringResource(R.string.sample_public_key_label)) }, + singleLine = true, + ) + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + OpenpayCountry.entries.forEach { country -> + FilterChip( + selected = uiState.country == country, + onClick = { onCountryChange(country) }, + label = { Text(country.name) }, + ) + } + } + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Switch( + checked = uiState.isProductionMode, + onCheckedChange = onProductionModeChange, + ) + Text(stringResource(R.string.sample_production_mode)) + } +} + +@Composable +private fun LanguageSection( + selectedLanguage: OpenpayLanguage?, + onLanguageChange: (OpenpayLanguage?) -> Unit, +) { + Text( + text = stringResource(R.string.sample_language_title), + style = MaterialTheme.typography.titleMedium, + ) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + FilterChip( + selected = selectedLanguage == null, + onClick = { onLanguageChange(null) }, + label = { Text(stringResource(R.string.sample_language_automatic)) }, + ) + OpenpayLanguage.entries.forEach { language -> + FilterChip( + selected = selectedLanguage == language, + onClick = { onLanguageChange(language) }, + label = { Text(language.languageTag.uppercase()) }, + ) + } + } +} diff --git a/app/src/main/java/mx/dev1/openpay/ui/checkout/CheckoutScreenPreviews.kt b/app/src/main/java/mx/dev1/openpay/ui/checkout/CheckoutScreenPreviews.kt new file mode 100644 index 0000000..4eb22ad --- /dev/null +++ b/app/src/main/java/mx/dev1/openpay/ui/checkout/CheckoutScreenPreviews.kt @@ -0,0 +1,45 @@ +package mx.dev1.openpay.ui.checkout + +import androidx.compose.runtime.Composable +import androidx.compose.ui.tooling.preview.Preview +import mx.dev1.openpay.sdk.core.OpenpayCountry +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme + +@Preview(name = "Checkout – empty configuration", showBackground = true) +@Composable +private fun EmptyCheckoutScreenPreview() { + OpenpayTheme { + CheckoutScreenContent( + uiState = CheckoutUiState(), + onMerchantIdChange = {}, + onPublicApiKeyChange = {}, + onCountryChange = {}, + onProductionModeChange = {}, + onLanguageChange = {}, + onStartDeviceSession = {}, + onAddCardClick = {}, + ) + } +} + +@Preview(name = "Checkout – configured with device session", showBackground = true) +@Composable +private fun ConfiguredCheckoutScreenPreview() { + OpenpayTheme { + CheckoutScreenContent( + uiState = CheckoutUiState( + merchantId = "mzdtln0bmtms6o3kck8f", + publicApiKey = "pk_f0660ad5a39f4912872e24a7a660370c", + country = OpenpayCountry.MEXICO, + deviceSessionId = "8d467eee6c8c14bd8d769b8c1c395d5a", + ), + onMerchantIdChange = {}, + onPublicApiKeyChange = {}, + onCountryChange = {}, + onProductionModeChange = {}, + onLanguageChange = {}, + onStartDeviceSession = {}, + onAddCardClick = {}, + ) + } +} diff --git a/app/src/main/java/mx/dev1/openpay/ui/checkout/CheckoutViewModel.kt b/app/src/main/java/mx/dev1/openpay/ui/checkout/CheckoutViewModel.kt new file mode 100644 index 0000000..2cf69c6 --- /dev/null +++ b/app/src/main/java/mx/dev1/openpay/ui/checkout/CheckoutViewModel.kt @@ -0,0 +1,152 @@ +package mx.dev1.openpay.ui.checkout + +import android.app.Activity +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import mx.dev1.openpay.sdk.Openpay +import mx.dev1.openpay.sdk.core.OpenpayConfig +import mx.dev1.openpay.sdk.core.OpenpayCountry +import mx.dev1.openpay.sdk.core.OpenpayEnvironment +import mx.dev1.openpay.sdk.core.OpenpayException +import mx.dev1.openpay.sdk.domain.model.Card +import mx.dev1.openpay.sdk.domain.model.Token +import mx.dev1.openpay.sdk.i18n.OpenpayLanguage +import mx.dev1.openpay.sdk.i18n.OpenpayLocale + +data class CheckoutUiState( + val merchantId: String = "", + val publicApiKey: String = "", + val country: OpenpayCountry = OpenpayCountry.MEXICO, + val isProductionMode: Boolean = false, + val selectedLanguage: OpenpayLanguage? = null, + val deviceSessionId: String? = null, + val createdToken: Token? = null, + val errorMessage: String? = null, + val isProcessing: Boolean = false, +) { + val isConfigurationComplete: Boolean + get() = merchantId.isNotBlank() && publicApiKey.isNotBlank() +} + +/** + * Drives the sample checkout: merchant configuration, device session and + * tokenization through the Openpay SDK. + * + * @param openpayFactory indirection over building the SDK entry point so + * tests can inject a mock. + */ +class CheckoutViewModel( + private val openpayFactory: (OpenpayConfig) -> Openpay = { config -> Openpay(config) }, +) : ViewModel() { + + private val mutableUiState = MutableStateFlow(CheckoutUiState()) + val uiState: StateFlow = mutableUiState.asStateFlow() + + private var openpayInstance: Openpay? = null + private var instanceConfig: OpenpayConfig? = null + + fun updateMerchantId(newValue: String) { + mutableUiState.update { state -> state.copy(merchantId = newValue) } + } + + fun updatePublicApiKey(newValue: String) { + mutableUiState.update { state -> state.copy(publicApiKey = newValue) } + } + + fun updateCountry(newValue: OpenpayCountry) { + mutableUiState.update { state -> state.copy(country = newValue) } + } + + fun updateProductionMode(enabled: Boolean) { + mutableUiState.update { state -> state.copy(isProductionMode = enabled) } + } + + /** Forces an SDK language, or returns to automatic resolution with null. */ + fun updateLanguage(language: OpenpayLanguage?) { + OpenpayLocale.override = language + mutableUiState.update { state -> state.copy(selectedLanguage = language) } + } + + fun startDeviceSession(activity: Activity) { + runWithOpenpay { openpay -> + val deviceSessionId = openpay.setupDeviceSession(activity) + mutableUiState.update { state -> + state.copy(deviceSessionId = deviceSessionId, errorMessage = null) + } + } + } + + fun tokenize(card: Card) { + runWithOpenpay { openpay -> + mutableUiState.update { state -> + state.copy(isProcessing = true, createdToken = null, errorMessage = null) + } + viewModelScope.launch { + val tokenResult = openpay.createToken(card) + mutableUiState.update { state -> + tokenResult.fold( + onSuccess = { token -> + state.copy(isProcessing = false, createdToken = token) + }, + onFailure = { failure -> + state.copy(isProcessing = false, errorMessage = describeError(failure)) + }, + ) + } + } + } + } + + override fun onCleared() { + openpayInstance?.shutdown() + } + + private fun runWithOpenpay(action: (Openpay) -> Unit) { + val state = mutableUiState.value + if (!state.isConfigurationComplete) { + mutableUiState.update { currentState -> + currentState.copy(errorMessage = "Configure the merchant id and public key first") + } + return + } + action(resolveOpenpay(state)) + } + + private fun resolveOpenpay(state: CheckoutUiState): Openpay { + val requestedConfig = OpenpayConfig( + merchantId = state.merchantId.trim(), + publicApiKey = state.publicApiKey.trim(), + country = state.country, + environment = if (state.isProductionMode) { + OpenpayEnvironment.PRODUCTION + } else { + OpenpayEnvironment.SANDBOX + }, + ) + val existingInstance = openpayInstance + if (existingInstance != null && instanceConfig == requestedConfig) { + return existingInstance + } + existingInstance?.shutdown() + return openpayFactory(requestedConfig).also { newInstance -> + openpayInstance = newInstance + instanceConfig = requestedConfig + } + } + + private fun describeError(failure: Throwable): String = + when (failure) { + is OpenpayException.ValidationError -> + "Invalid card fields: ${failure.validationResult.invalidFields}" + is OpenpayException.ServiceError -> + "Openpay rejected the request (${failure.errorCode}): ${failure.message}" + is OpenpayException.ConnectionError -> + "Could not reach Openpay, check your connection" + else -> "Unexpected error: ${failure.message}" + } +} diff --git a/app/src/main/res/values-night/themes.xml b/app/src/main/res/values-night/themes.xml deleted file mode 100644 index a08ffe1..0000000 --- a/app/src/main/res/values-night/themes.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index b730e26..20bdd50 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,3 +1,15 @@ - Openpay - \ No newline at end of file + Openpay Sample + Merchant configuration + Merchant ID + Public API key + Production mode + SDK language + Auto + Start antifraud device session + Device session: %1$s + Token created: %1$s + Add card + Add card + Back + diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml index 2f18f64..101d6b7 100644 --- a/app/src/main/res/values/themes.xml +++ b/app/src/main/res/values/themes.xml @@ -1,16 +1,7 @@ - - - \ No newline at end of file + diff --git a/app/src/test/java/mx/dev1/openpay/ExampleUnitTest.kt b/app/src/test/java/mx/dev1/openpay/ExampleUnitTest.kt deleted file mode 100644 index 8f352f3..0000000 --- a/app/src/test/java/mx/dev1/openpay/ExampleUnitTest.kt +++ /dev/null @@ -1,17 +0,0 @@ -package mx.dev1.openpay - -import org.junit.Test - -import org.junit.Assert.* - -/** - * Example local unit test, which will execute on the development machine (host). - * - * See [testing documentation](http://d.android.com/tools/testing). - */ -class ExampleUnitTest { - @Test - fun addition_isCorrect() { - assertEquals(4, 2 + 2) - } -} \ No newline at end of file diff --git a/app/src/test/java/mx/dev1/openpay/ui/addcard/AddCardScreenComposeTest.kt b/app/src/test/java/mx/dev1/openpay/ui/addcard/AddCardScreenComposeTest.kt new file mode 100644 index 0000000..0a43cec --- /dev/null +++ b/app/src/test/java/mx/dev1/openpay/ui/addcard/AddCardScreenComposeTest.kt @@ -0,0 +1,122 @@ +package mx.dev1.openpay.ui.addcard + +import androidx.compose.ui.test.assertContentDescriptionEquals +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import mx.dev1.openpay.sdk.domain.model.Card +import mx.dev1.openpay.sdk.domain.model.Token +import mx.dev1.openpay.sdk.domain.model.TokenizedCard +import mx.dev1.openpay.sdk.ui.components.OpenpayFormTags +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme +import mx.dev1.openpay.ui.checkout.CheckoutUiState +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class AddCardScreenComposeTest { + + @get:Rule + val composeRule = createComposeRule() + + private var backRequested = false + private var validatedCard: Card? = null + + private fun renderScreen(uiState: CheckoutUiState = CheckoutUiState()) { + composeRule.setContent { + OpenpayTheme { + AddCardScreenContent( + uiState = uiState, + onCardValidated = { card -> validatedCard = card }, + onNavigateBack = { backRequested = true }, + ) + } + } + } + + @Test + fun `the sdk card form with its preview is embedded in the screen`() { + renderScreen() + + composeRule.onNodeWithTag(OpenpayFormTags.CARD_PREVIEW).assertIsDisplayed() + composeRule.onNodeWithText("Card number").assertExists() + } + + @Test + fun `the back button asks for navigation back`() { + renderScreen() + + composeRule.onNodeWithTag(AddCardScreenTags.BACK_BUTTON).performClick() + + assertTrue(backRequested) + } + + @Test + fun `a created token is displayed with its masked card`() { + renderScreen( + uiState = CheckoutUiState( + createdToken = Token( + tokenId = "tok-123", + card = TokenizedCard( + maskedCardNumber = "411111XXXXXX1111", + holderName = "Juan Pérez", + expirationMonth = "12", + expirationYear = "30", + brand = "visa", + cardType = "debit", + bankName = null, + bankCode = null, + allowsCharges = true, + allowsPayouts = false, + address = null, + ), + ), + ), + ) + + composeRule.onNodeWithTag(AddCardScreenTags.TOKEN_RESULT).assertExists() + composeRule.onNodeWithText("visa 411111XXXXXX1111").assertExists() + composeRule.onNodeWithTag(OpenpayFormTags.CARD_BRAND_LOGO, useUnmergedTree = true) + .assertContentDescriptionEquals("Visa") + } + + @Test + fun `a token with an unrecognized brand shows no logo`() { + renderScreen( + uiState = CheckoutUiState( + createdToken = Token( + tokenId = "tok-456", + card = TokenizedCard( + maskedCardNumber = "601100XXXXXX0004", + holderName = "Juan Pérez", + expirationMonth = "12", + expirationYear = "30", + brand = "carnet", + cardType = "debit", + bankName = null, + bankCode = null, + allowsCharges = true, + allowsPayouts = false, + address = null, + ), + ), + ), + ) + + composeRule.onNodeWithTag(OpenpayFormTags.CARD_BRAND_LOGO, useUnmergedTree = true) + .assertDoesNotExist() + } + + @Test + fun `a tokenization error is displayed`() { + renderScreen(uiState = CheckoutUiState(errorMessage = "the card was declined")) + + composeRule.onNodeWithTag(AddCardScreenTags.ERROR_MESSAGE).assertExists() + composeRule.onNodeWithText("the card was declined").assertExists() + } +} diff --git a/app/src/test/java/mx/dev1/openpay/ui/checkout/CheckoutScreenComposeTest.kt b/app/src/test/java/mx/dev1/openpay/ui/checkout/CheckoutScreenComposeTest.kt new file mode 100644 index 0000000..4838b2f --- /dev/null +++ b/app/src/test/java/mx/dev1/openpay/ui/checkout/CheckoutScreenComposeTest.kt @@ -0,0 +1,102 @@ +package mx.dev1.openpay.ui.checkout + +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.test.performTextInput +import mx.dev1.openpay.sdk.Openpay +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.mock +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class CheckoutScreenComposeTest { + + @get:Rule + val composeRule = createComposeRule() + + private val openpay: Openpay = mock() + private val viewModel = CheckoutViewModel(openpayFactory = { openpay }) + private var addCardRequested = false + + private fun renderScreen() { + composeRule.setContent { + OpenpayTheme { + CheckoutScreen( + onAddCardClick = { addCardRequested = true }, + viewModel = viewModel, + ) + } + } + } + + private fun fillConfiguration() { + composeRule.onNodeWithTag(CheckoutScreenTags.MERCHANT_ID_FIELD) + .performTextInput("merchant-id") + composeRule.onNodeWithTag(CheckoutScreenTags.PUBLIC_KEY_FIELD) + .performTextInput("pk_test") + } + + @Test + fun `typing the merchant configuration updates the state`() { + renderScreen() + + fillConfiguration() + + assert(viewModel.uiState.value.merchantId == "merchant-id") + assert(viewModel.uiState.value.publicApiKey == "pk_test") + } + + @Test + fun `requesting a device session without configuration shows the error`() { + renderScreen() + + composeRule.onNodeWithTag(CheckoutScreenTags.DEVICE_SESSION_BUTTON) + .performScrollTo() + .performClick() + + composeRule.onNodeWithTag(CheckoutScreenTags.ERROR_MESSAGE).assertExists() + } + + @Test + fun `the card form is not embedded in the configuration screen`() { + renderScreen() + + composeRule.onNodeWithText("Merchant configuration").assertIsDisplayed() + composeRule.onNodeWithText("Card number").assertDoesNotExist() + } + + @Test + fun `add card stays disabled until the configuration is complete`() { + renderScreen() + + composeRule.onNodeWithTag(CheckoutScreenTags.ADD_CARD_BUTTON) + .performScrollTo() + .assertIsNotEnabled() + + fillConfiguration() + + composeRule.onNodeWithTag(CheckoutScreenTags.ADD_CARD_BUTTON).assertIsEnabled() + } + + @Test + fun `tapping add card asks for the card form screen`() { + renderScreen() + fillConfiguration() + + composeRule.onNodeWithTag(CheckoutScreenTags.ADD_CARD_BUTTON) + .performScrollTo() + .performClick() + + assertTrue(addCardRequested) + } +} diff --git a/app/src/test/java/mx/dev1/openpay/ui/checkout/CheckoutViewModelTest.kt b/app/src/test/java/mx/dev1/openpay/ui/checkout/CheckoutViewModelTest.kt new file mode 100644 index 0000000..b014fcd --- /dev/null +++ b/app/src/test/java/mx/dev1/openpay/ui/checkout/CheckoutViewModelTest.kt @@ -0,0 +1,169 @@ +package mx.dev1.openpay.ui.checkout + +import android.app.Activity +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import mx.dev1.openpay.sdk.Openpay +import mx.dev1.openpay.sdk.core.OpenpayConfig +import mx.dev1.openpay.sdk.core.OpenpayCountry +import mx.dev1.openpay.sdk.core.OpenpayEnvironment +import mx.dev1.openpay.sdk.core.OpenpayException +import mx.dev1.openpay.sdk.domain.model.Card +import mx.dev1.openpay.sdk.domain.model.Token +import mx.dev1.openpay.sdk.i18n.OpenpayLanguage +import mx.dev1.openpay.sdk.i18n.OpenpayLocale +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +@OptIn(ExperimentalCoroutinesApi::class) +class CheckoutViewModelTest { + + private val testDispatcher = StandardTestDispatcher() + + private val openpay: Openpay = mock() + private var builtConfigs = mutableListOf() + + private val viewModel = CheckoutViewModel( + openpayFactory = { config -> + builtConfigs.add(config) + openpay + }, + ) + + private val validCard = Card( + holderName = "Juan Pérez Ramírez", + cardNumber = "4111111111111111", + expirationMonth = 12, + expirationYear = 30, + securityCode = "110", + ) + + @Before + fun setUp() { + Dispatchers.setMain(testDispatcher) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + OpenpayLocale.override = null + } + + private fun configureMerchant() { + viewModel.updateMerchantId("merchant-id") + viewModel.updatePublicApiKey("pk_test") + } + + @Test + fun `tokenizing without configuration reports an error and builds nothing`() = runTest(testDispatcher.scheduler) { + viewModel.tokenize(validCard) + + assertNotNull(viewModel.uiState.value.errorMessage) + assertTrue(builtConfigs.isEmpty()) + verify(openpay, never()).createToken(any()) + } + + @Test + fun `successful tokenization publishes the token`() = runTest(testDispatcher.scheduler) { + configureMerchant() + val expectedToken = Token(tokenId = "tok_123", card = null) + whenever(openpay.createToken(validCard)).thenReturn(Result.success(expectedToken)) + + viewModel.tokenize(validCard) + advanceUntilIdle() + + val state = viewModel.uiState.value + assertEquals(expectedToken, state.createdToken) + assertNull(state.errorMessage) + assertEquals(false, state.isProcessing) + } + + @Test + fun `service rejections surface as readable errors`() = runTest(testDispatcher.scheduler) { + configureMerchant() + val rejection = OpenpayException.ServiceError( + errorCode = 3001, + category = "request", + httpStatus = 402, + requestId = null, + description = "The card was declined", + ) + whenever(openpay.createToken(validCard)).thenReturn(Result.failure(rejection)) + + viewModel.tokenize(validCard) + advanceUntilIdle() + + val state = viewModel.uiState.value + assertNull(state.createdToken) + assertTrue(checkNotNull(state.errorMessage).contains("3001")) + } + + @Test + fun `device session id is published on state`() = runTest(testDispatcher.scheduler) { + configureMerchant() + val activity: Activity = mock() + whenever(openpay.setupDeviceSession(activity)).thenReturn("device-session-id") + + viewModel.startDeviceSession(activity) + + assertEquals("device-session-id", viewModel.uiState.value.deviceSessionId) + } + + @Test + fun `the sdk instance is reused while the configuration stays the same`() = runTest(testDispatcher.scheduler) { + configureMerchant() + whenever(openpay.createToken(any())).thenReturn(Result.success(Token("tok", null))) + + viewModel.tokenize(validCard) + advanceUntilIdle() + viewModel.tokenize(validCard) + advanceUntilIdle() + + assertEquals(1, builtConfigs.size) + } + + @Test + fun `changing the configuration rebuilds the sdk`() = runTest(testDispatcher.scheduler) { + configureMerchant() + whenever(openpay.createToken(any())).thenReturn(Result.success(Token("tok", null))) + + viewModel.tokenize(validCard) + advanceUntilIdle() + viewModel.updateCountry(OpenpayCountry.PERU) + viewModel.updateProductionMode(true) + viewModel.tokenize(validCard) + advanceUntilIdle() + + assertEquals(2, builtConfigs.size) + verify(openpay).shutdown() + assertEquals(OpenpayCountry.PERU, builtConfigs.last().country) + assertEquals(OpenpayEnvironment.PRODUCTION, builtConfigs.last().environment) + } + + @Test + fun `language selection drives the sdk locale override`() { + viewModel.updateLanguage(OpenpayLanguage.FRENCH) + + assertEquals(OpenpayLanguage.FRENCH, OpenpayLocale.override) + assertEquals(OpenpayLanguage.FRENCH, viewModel.uiState.value.selectedLanguage) + + viewModel.updateLanguage(null) + + assertNull(OpenpayLocale.override) + } +} diff --git a/build.gradle.kts b/build.gradle.kts index 3756278..858bf31 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,4 +1,91 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. plugins { alias(libs.plugins.android.application) apply false -} \ No newline at end of file + alias(libs.plugins.android.library) apply false + alias(libs.plugins.kotlin.android) apply false + alias(libs.plugins.kotlin.compose) apply false + alias(libs.plugins.kotlin.serialization) apply false +} + +// JaCoCo coverage convention shared by every Android module. Each module gets: +// - jacocoTestReport: XML + HTML coverage report from the debug unit tests +// - jacocoCoverageVerification: fails the build when line coverage drops below 80% +val jacocoVersion = libs.versions.jacoco.get() + +val coverageExclusions = listOf( + "**/R.class", + "**/R\$*.class", + "**/BuildConfig.*", + "**/Manifest*.*", + "**/*Test*.*", + "android/**/*.*", + "**/*ComposableSingletons*.*", + // @Preview functions live in *Previews.kt files; the pattern must not + // catch real components such as OpenpayCardPreview. + "**/*PreviewsKt*.*", +) + +subprojects { + apply(plugin = "jacoco") + + configure { + toolVersion = jacocoVersion + } + + tasks.withType().configureEach { + configure { + // Required so Robolectric-instrumented classes are measured correctly. + isIncludeNoLocationClasses = true + excludes = listOf("jdk.internal.*") + } + } + + plugins.withId("com.android.base") { + val moduleBuildDir = layout.buildDirectory + + // AGP 9 built-in Kotlin compiles into built_in_kotlinc; javac output stays in javac. + val coverageClassDirectories = files( + fileTree(moduleBuildDir.dir("intermediates/built_in_kotlinc/debug/compileDebugKotlin/classes")) { + exclude(coverageExclusions) + }, + fileTree(moduleBuildDir.dir("intermediates/javac/debug/classes")) { + exclude(coverageExclusions) + }, + ) + val coverageSourceDirectories = files("src/main/java", "src/main/kotlin") + val coverageExecutionData = + moduleBuildDir.file("outputs/unit_test_code_coverage/debugUnitTest/testDebugUnitTest.exec") + + tasks.register("jacocoTestReport") { + group = "verification" + description = "Generates the JaCoCo coverage report for debug unit tests." + dependsOn("testDebugUnitTest") + reports { + xml.required.set(true) + html.required.set(true) + } + classDirectories.setFrom(coverageClassDirectories) + sourceDirectories.setFrom(coverageSourceDirectories) + executionData.setFrom(coverageExecutionData) + } + + tasks.register("jacocoCoverageVerification") { + group = "verification" + description = "Fails when debug unit test line coverage is below 80%." + dependsOn("testDebugUnitTest") + mustRunAfter("jacocoTestReport") + violationRules { + rule { + limit { + counter = "LINE" + value = "COVEREDRATIO" + minimum = "0.80".toBigDecimal() + } + } + } + classDirectories.setFrom(coverageClassDirectories) + sourceDirectories.setFrom(coverageSourceDirectories) + executionData.setFrom(coverageExecutionData) + } + } +} diff --git a/docs/en/architecture.md b/docs/en/architecture.md new file mode 100644 index 0000000..e998dbe --- /dev/null +++ b/docs/en/architecture.md @@ -0,0 +1,135 @@ +# Architecture + +The SDK follows **clean architecture**: the domain rules sit at the center +and never depend on Android, the network or any framework. Outer layers +depend inward, which keeps the business logic testable in plain JVM tests. + +## Modules + +```mermaid +flowchart LR + subgraph Repository + app[":app — sample application"] + sdk[":openpay-sdk — the published library"] + end + app -->|consumes| sdk + sdk -->|published as| maven[("Maven: mx.dev1.openpay:openpay-sdk")] +``` + +- **`:openpay-sdk`** — everything a merchant app needs: networking, + tokenization, validation, antifraud, Compose UI and translations. +- **`:app`** — a runnable sample that demonstrates every SDK feature. + +## Layers inside the SDK + +```mermaid +flowchart TB + subgraph presentation["UI layer (Compose)"] + form["OpenpayCardForm / fields"] + formState["OpenpayCardFormState"] + xml["OpenpayCardFormView (XML interop)"] + end + subgraph facade["Public facade"] + openpayFacade["Openpay"] + end + subgraph domain["Domain layer (pure Kotlin)"] + models["Card / Token / Address"] + validator["CardValidator / CardBrand"] + usecase["CreateTokenUseCase"] + repoInterface["TokenRepository (interface)"] + end + subgraph data["Data layer"] + repoImpl["RemoteTokenRepository"] + http["Ktor HttpClient (CIO)"] + dto["DTOs + mappers"] + end + subgraph antifraud["Antifraud"] + collector["WebViewDeviceSessionCollector"] + end + + form --> formState --> validator + openpayFacade --> usecase + openpayFacade --> collector + usecase --> validator + usecase --> repoInterface + repoImpl -.implements.-> repoInterface + repoImpl --> http + repoImpl --> dto +``` + +Key rules: + +- The **domain layer** (`domain/`) has no Android imports. `CardValidator` + and `CreateTokenUseCase` run in milliseconds on any JVM. +- The **data layer** (`data/`) implements the domain interfaces using Ktor + and kotlinx.serialization. Swapping the HTTP stack would touch only this + layer. +- The **UI layer** (`ui/`) is Compose-first. The XML wrapper exists purely + for legacy host apps. +- **Koin** wires everything inside an *isolated* container + (`OpenpayKoinContext`), so the SDK never conflicts with a host app that + also uses Koin. + +## Tokenization flow + +```mermaid +sequenceDiagram + actor User + participant Form as OpenpayCardForm + participant Facade as Openpay + participant UseCase as CreateTokenUseCase + participant Validator as CardValidator + participant Repo as RemoteTokenRepository + participant API as Openpay API + + User->>Form: types card data + Form->>Form: live filtering + brand detection + User->>Form: taps "Save card" + Form->>Facade: createToken(card) + Facade->>UseCase: invoke(card) + UseCase->>Validator: validate(card) + alt card invalid + Validator-->>UseCase: invalid fields + UseCase-->>Facade: ValidationError (no network call) + else card valid + UseCase->>Repo: createToken(card) + Repo->>API: POST /v1/{merchantId}/tokens + API-->>Repo: token JSON + Repo-->>UseCase: Token + UseCase-->>Facade: Token + end + Facade-->>Form: Result +``` + +## Antifraud flow + +```mermaid +sequenceDiagram + participant App as Merchant app + participant Facade as Openpay + participant Collector as WebViewDeviceSessionCollector + participant API as Openpay fingerprint page + + App->>Facade: setupDeviceSession(activity) + Facade->>Collector: collect(activity) + Collector->>Collector: generate 32-char session id + Collector->>API: hidden WebView loads /oa/logo.htm?m={merchant}&s={session} + Collector-->>Facade: session id (immediately) + Note over Collector: WebView destroys itself when the page finishes + Facade-->>App: deviceSessionId → send to your backend with the token +``` + +## Package map + +| Package | Contents | +|---|---| +| `mx.dev1.openpay.sdk` | `Openpay` facade, `OpenpayCallback`, `OpenpaySdk` | +| `...sdk.core` | `OpenpayConfig`, countries, environments, `OpenpayException` | +| `...sdk.domain.model` | `Card`, `Token`, `TokenizedCard`, `Address` | +| `...sdk.domain.validation` | `CardValidator`, `CardBrand`, `CardValidationResult` | +| `...sdk.domain.usecase` / `repository` | `CreateTokenUseCase`, `TokenRepository` | +| `...sdk.data` | Ktor client factory, DTOs, mappers, `RemoteTokenRepository` | +| `...sdk.antifraud` | Device session collection | +| `...sdk.ui` | Theme, form, fields, visual transformations, XML view | +| `...sdk.i18n` | `OpenpayLanguage`, `OpenpayLocale` override | +| `...sdk.di` | Koin modules and the isolated container | diff --git a/docs/en/ci.md b/docs/en/ci.md new file mode 100644 index 0000000..265961e --- /dev/null +++ b/docs/en/ci.md @@ -0,0 +1,77 @@ +# Continuous integration + +The repository runs a GitHub Actions pipeline (`.github/workflows/ci.yml`) on every push and pull request that targets `develop` or `master`. You do not need to install anything: GitHub runs it automatically when you open a pull request. + +## What the pipeline does + +```mermaid +flowchart LR + A[Push or pull request] --> B[Unit tests and coverage] + A --> C[Instrumented tests] + B --> D[JaCoCo XML + HTML reports] + D --> E[Coverage comment on the pull request] + D --> F[80% line coverage gate for openpay-sdk] + C --> G[Emulator test reports] +``` + +### Unit tests and coverage + +This job runs on every push and pull request: + +1. Compiles the project with JDK 17 and runs `testDebugUnitTest` for every module. +2. Generates JaCoCo coverage reports (`jacocoTestReport`). +3. Enforces the 80% line coverage minimum on `openpay-sdk` (`jacocoCoverageVerification`). The build fails when coverage drops below that threshold. +4. On pull requests, posts (and keeps updated) a comment with the overall coverage and the coverage of the files changed by the pull request, using [Madrapps/jacoco-report](https://github.com/Madrapps/jacoco-report). +5. Uploads the HTML coverage and test reports as build artifacts, so you can download and browse them from the run page. + +### Instrumented tests + +This job boots an Android 14 (API 34) emulator on the runner and executes `connectedDebugAndroidTest`. The emulator needs hardware acceleration, which is why the job enables KVM before starting it. Test reports are uploaded as artifacts. + +## Reading the coverage comment + +Every pull request receives a single comment titled **Unit test coverage** that is refreshed on each push. It shows: + +- **Overall coverage** of the project, marked with ✅ when it is at or above 80%. +- **Coverage of changed files**, so reviewers can see whether the new code is tested without opening the full report. + +## Running the same checks locally + +```bash +./gradlew testDebugUnitTest jacocoTestReport :openpay-sdk:jacocoCoverageVerification +./gradlew connectedDebugAndroidTest # requires a device or emulator +``` + +The HTML report is generated at `/build/reports/jacoco/jacocoTestReport/html/index.html`. + +## Continuous deployment + +A second workflow (`.github/workflows/cd.yml`) releases the library to +Maven Central. It runs when a version tag (`v1.2.3`) is pushed — normally +the tag on the `master` merge commit of a release — and can also be +started manually from the Actions tab. + +```mermaid +flowchart LR + A[Push tag v*] --> B[Unit tests + coverage gate] + B --> C[Check tag == VERSION_NAME] + C --> D[Sign and upload to the Central Portal] + D --> E[Manual Publish in central.sonatype.com] + D --> F[GitHub release with generated notes] +``` + +1. **Tests first** — the release is blocked unless the unit tests and the + 80% coverage gate pass. +2. **Version guard** — the workflow fails if the tag does not match + `VERSION_NAME` in `gradle.properties`, so a mistagged release cannot + ship. +3. **Signed upload** — artifacts are PGP-signed and uploaded to the + Sonatype Central Portal staging area. Credentials and the signing key + come from the repository secrets (`MAVEN_REPOSITORY_USERNAME`, + `MAVEN_REPOSITORY_PASSWORD`, `SIGNING_KEY`, `SIGNING_PASSWORD`); they + never live in the repository. +4. **Manual confirmation** — nothing becomes public automatically: a + maintainer must press **Publish** on the validated deployment at + [central.sonatype.com](https://central.sonatype.com). The run summary + links the step. +5. A GitHub release with generated notes is created for the tag. \ No newline at end of file diff --git a/docs/en/contributing.md b/docs/en/contributing.md new file mode 100644 index 0000000..cb899b1 --- /dev/null +++ b/docs/en/contributing.md @@ -0,0 +1,83 @@ +# Contributing + +This guide assumes **no Android experience**. Follow it top to bottom and +you will be able to build, test and propose changes. + +## 1. Set up your machine + +1. Install [Android Studio](https://developer.android.com/studio) (it + bundles the JDK and the Android SDK). +2. Clone the repository: + ```bash + git clone git@github.com:DEV1-Softworks/openpay-android.git + cd openpay-android + ``` +3. Open the folder in Android Studio and let it sync, or work entirely + from the terminal with the commands below. The project downloads its own + Gradle and JDK toolchain automatically on first build. + +## 2. Everyday commands + +| What | Command | +|---|---| +| Build everything | `./gradlew assembleDebug` | +| Run all unit tests | `./gradlew testDebugUnitTest` | +| Coverage report (HTML + XML) | `./gradlew :openpay-sdk:jacocoTestReport` | +| Enforce the 80% coverage gate | `./gradlew :openpay-sdk:jacocoCoverageVerification` | +| Install the sample app on a device | `./gradlew :app:installDebug` | +| Publish the SDK to your local Maven | `./gradlew :openpay-sdk:publishToMavenLocal` | + +The coverage report lands in +`openpay-sdk/build/reports/jacoco/jacocoTestReport/html/index.html` — open +it in a browser. + +## 3. Project rules + +- **Language**: Kotlin only. UI is Jetpack Compose; XML exists only for + legacy interop. +- **Architecture**: clean architecture. Domain code + (`openpay-sdk/src/main/kotlin/.../domain`) must not import Android or + Ktor types. +- **Dependency injection**: Koin. SDK definitions live in `di/` modules + inside the isolated `OpenpayKoinContext`. +- **Versions**: every dependency version lives in + `gradle/libs.versions.toml`, nowhere else. +- **Naming**: no ambiguous names. Loop counters are the only exception. +- **Tests**: every change ships with unit tests (JUnit + Mockito + + Robolectric). Line coverage must stay at **80% or above** — the + `jacocoCoverageVerification` task fails otherwise. Run the tests before + every commit. + +## 4. Git workflow (Git Flow) + +```mermaid +gitGraph + commit id: "initial" + branch develop + commit id: "work" + branch feature/my-feature + commit id: "feat: ..." + commit id: "test: ..." + checkout develop + merge feature/my-feature + commit id: "release prep" + checkout main + merge develop tag: "v1.x" +``` + +- `master` is **production**. Nothing is pushed to it directly. +- `develop` is the integration branch and the base of every feature. +- Create a branch per feature: `feature/`. +- Open a **pull request to `develop`** for every change, small PRs over + big ones. A PR must build and pass `testDebugUnitTest` + + `jacocoCoverageVerification`. +- Releases merge `develop` into `master` through a release PR. + +## 5. Pull request checklist + +- [ ] Code follows the architecture and naming rules above +- [ ] New/changed code has tests, coverage ≥ 80% +- [ ] `./gradlew testDebugUnitTest jacocoCoverageVerification` passes locally +- [ ] User-facing SDK strings exist in **all four** languages + (`values`, `values-es`, `values-pt`, `values-fr`) +- [ ] Documentation updated (all four languages under `docs/`) diff --git a/docs/en/getting-started.md b/docs/en/getting-started.md new file mode 100644 index 0000000..03ede33 --- /dev/null +++ b/docs/en/getting-started.md @@ -0,0 +1,130 @@ +# Getting started + +This guide takes you from zero to your first card token. No prior Android +experience is required: every step is spelled out. + +> **What is a token?** Card data is sensitive, so your app never sends it to +> your own servers. Instead, the SDK exchanges the card for a one-time +> **token** directly with Openpay. Your backend then uses that token to +> create the charge. Your servers never see the card number. + +## Requirements + +| Requirement | Minimum | +|---|---| +| Android Studio | Narwhal (2025.1) or newer | +| JDK | 17 (Android Studio bundles one) | +| Android device / emulator | Android 8.0 (API 26) or newer | +| Openpay account | Merchant ID + **public** API key from the [Openpay dashboard](https://www.openpay.mx) | + +## 1. Install the SDK + +Add the dependency to your module's `build.gradle.kts`: + +```kotlin +dependencies { + implementation("mx.dev1.openpay:openpay-sdk:1.0.0") +} +``` + +The SDK already declares the `INTERNET` permission in its manifest; you do +not need to add anything else. + +## 2. Configure the SDK + +Create one `Openpay` instance with your merchant credentials: + +```kotlin +import mx.dev1.openpay.sdk.Openpay +import mx.dev1.openpay.sdk.core.OpenpayConfig +import mx.dev1.openpay.sdk.core.OpenpayCountry +import mx.dev1.openpay.sdk.core.OpenpayEnvironment + +val openpay = Openpay( + OpenpayConfig( + merchantId = "your-merchant-id", + publicApiKey = "pk_your_public_key", + country = OpenpayCountry.MEXICO, // MEXICO, COLOMBIA or PERU + environment = OpenpayEnvironment.SANDBOX, // SANDBOX while testing + ) +) +``` + +> **Never** ship your *private* API key inside the app. Only the public key +> is safe on devices. + +## 3. Capture the card and create a token + +The fastest path is the ready-made Compose form, which validates every +field and hands you a `Card` object only when the data is correct: + +```kotlin +import mx.dev1.openpay.sdk.ui.components.OpenpayCardForm + +OpenpayCardForm( + onCardValidated = { card -> + scope.launch { + openpay.createToken(card) + .onSuccess { token -> sendToBackend(token.tokenId) } + .onFailure { error -> showError(error) } + } + } +) +``` + +Prefer to build your own UI? Create the `Card` yourself and validate it +with `CardValidator`: + +```kotlin +import mx.dev1.openpay.sdk.domain.model.Card + +val card = Card( + holderName = "Juan Pérez Ramírez", + cardNumber = "4111111111111111", + expirationMonth = 12, + expirationYear = 30, + securityCode = "110", +) +val result = openpay.createToken(card) // suspend fun returning Result +``` + +Consumers without coroutines can use the callback flavor, +`openpay.createToken(card, callback)`; the callback runs on the main thread. + +## 4. Start the antifraud device session + +Openpay's risk engine needs a device fingerprint per checkout. Collect it +once per payment screen and send the returned id to your backend together +with the token: + +```kotlin +val deviceSessionId = openpay.setupDeviceSession(activity) +``` + +## 5. Handle errors + +Every failure is an `OpenpayException`: + +| Type | Meaning | Typical reaction | +|---|---|---| +| `ValidationError` | The card failed local validation; no network call happened | Highlight `validationResult.invalidFields` | +| `ServiceError` | Openpay rejected the request (`errorCode`, `category`, `requestId`) | Show a message, log the `requestId` | +| `ConnectionError` | The API was unreachable | Offer a retry | + +## 6. Test cards (sandbox) + +| Number | Brand | +|---|---| +| 4111 1111 1111 1111 | Visa | +| 5555 5555 5555 4444 | Mastercard | +| 3782 822463 10005 | American Express | + +Any future expiration date and any well-formed security code work in +sandbox. + +## Next steps + +- [Architecture](architecture.md) — how the SDK is organized inside +- [UI components](ui-components.md) — the Compose form, XML interop and accessibility +- [Internationalization](internationalization.md) — languages and overrides +- [Contributing](contributing.md) — building and testing the project yourself diff --git a/docs/en/internationalization.md b/docs/en/internationalization.md new file mode 100644 index 0000000..163777c --- /dev/null +++ b/docs/en/internationalization.md @@ -0,0 +1,65 @@ +# Internationalization + +Every text the SDK shows — labels, validation errors, accessibility +descriptions — is available in: + +| Language | Tag | +|---|---| +| English (default and fallback) | `en` | +| Spanish | `es` | +| Portuguese | `pt` | +| French | `fr` | + +## Automatic resolution + +By default the SDK follows the **device language**, including regional +variants (`es-MX`, `pt-BR`, `fr-CA`, …). Devices set to any other language +fall back to English. There is nothing to configure. + +## Forcing a language + +Some apps let users pick a language independently of the system settings. +Set the override once and every SDK component on screen updates +immediately: + +```kotlin +import mx.dev1.openpay.sdk.i18n.OpenpayLanguage +import mx.dev1.openpay.sdk.i18n.OpenpayLocale + +OpenpayLocale.override = OpenpayLanguage.PORTUGUESE // force Portuguese +OpenpayLocale.override = null // back to automatic +``` + +The override is observable Compose state: SDK composables recompose live +when it changes, no restart needed. + +## View-based apps + +If you show SDK strings from your own view code, resolve them through a +localized context: + +```kotlin +val localizedContext = OpenpayLocale.localize(context) +val label = localizedContext.getString(R.string.openpay_card_number_label) +``` + +`localize` returns the context untouched when no override is set. + +## Flow + +```mermaid +flowchart TD + start([SDK needs a string]) --> hasOverride{OpenpayLocale.override set?} + hasOverride -- yes --> forced[Resolve resources in the forced language] + hasOverride -- no --> device{Device language bundled?} + device -- "es / pt / fr / en" --> auto[Resolve resources in the device language] + device -- other --> fallback[Fall back to English] +``` + +## Adding a language + +Translations live in the SDK's Android resources +(`openpay-sdk/src/main/res/values-/strings.xml`). To propose a new +language, copy `values/strings.xml`, translate every entry, add the tag to +`OpenpayLanguage` and open a pull request — see +[Contributing](contributing.md). diff --git a/docs/en/ui-components.md b/docs/en/ui-components.md new file mode 100644 index 0000000..c24314c --- /dev/null +++ b/docs/en/ui-components.md @@ -0,0 +1,185 @@ +# UI components + +The SDK ships a Compose-first card capture kit. You can use the whole form, +individual fields, or wrap the form inside an XML layout. + +## The complete form + +```kotlin +import mx.dev1.openpay.sdk.ui.components.OpenpayCardForm +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme + +OpenpayTheme { // optional: inherit your own MaterialTheme instead + OpenpayCardForm( + onCardValidated = { card -> /* tokenize it */ }, + ) +} +``` + +The form contains the cardholder name, card number (with live brand +detection), MM/YY expiration and masked security code, plus a submit +button. `onCardValidated` fires **only** when every field passes +validation; invalid fields are highlighted with translated error messages. + +### Implementing with the native form + +The callback hands you a validated `Card`; tokenize it and send the token +id to your backend: + +```kotlin +val scope = rememberCoroutineScope() + +OpenpayCardForm( + onCardValidated = { card -> + scope.launch { + openpay.createToken(card) + .onSuccess { token -> /* send token.tokenId to your backend */ } + .onFailure { error -> /* show the error */ } + } + }, +) +``` + +See [Getting started](getting-started.md) for how to build the `openpay` +instance with your merchant id and public key. + +### Controlling the state yourself + +```kotlin +val formState = rememberOpenpayCardFormState() + +OpenpayCardForm( + state = formState, + onCardValidated = { card -> ... }, +) + +// elsewhere: formState.cardNumber, formState.detectedBrand, +// formState.validate(), formState.isFieldInvalid(CardField.CARD_NUMBER) +``` + +For security, the form state is **not** persisted across process death — +card data never touches disk. + +## Implementing with custom inputs + +Each field is public and can be composed into your own layout while +keeping the SDK's formatting and validation: + +- `OpenpayHolderNameField` +- `OpenpayCardNumberField` — grouped formatting (4-4-4-4, Amex 4-6-5) +- `OpenpayExpirationField` — MM/YY visual formatting over MMYY digits +- `OpenpaySecurityCodeField` — masked input, brand-aware length (4 for + Amex, 3 otherwise) + +Wire them to `rememberOpenpayCardFormState()`, which keeps digits-only +values, detects the brand and validates every field: + +```kotlin +val formState = rememberOpenpayCardFormState() + +Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OpenpayCardPreview( // optional: brand colors and logo included + holderName = formState.holderName, + cardNumber = formState.cardNumber, + expiration = formState.expiration, + ) + OpenpayHolderNameField( + value = formState.holderName, + onValueChange = formState::updateHolderName, + isError = formState.isFieldInvalid(CardField.HOLDER_NAME), + ) + OpenpayCardNumberField( + value = formState.cardNumber, + onValueChange = formState::updateCardNumber, + isError = formState.isFieldInvalid(CardField.CARD_NUMBER), + ) + OpenpayExpirationField( + value = formState.expiration, + onValueChange = formState::updateExpiration, + isError = formState.isFieldInvalid(CardField.EXPIRATION), + ) + OpenpaySecurityCodeField( + value = formState.securityCode, + onValueChange = formState::updateSecurityCode, + isError = formState.isFieldInvalid(CardField.SECURITY_CODE), + ) + Button(onClick = { + formState.validate()?.let { card -> /* createToken(card) as above */ } + }) { + Text("Pay") + } +} +``` + +`formState.validate()` returns the `Card` ready for tokenization when +every field is valid; otherwise it returns null and flags the failing +fields so `isFieldInvalid` highlights them. + +## Brand identity on the card preview + +The live card preview reacts to the detected brand: + +| Brand | Card background | Logo | +|---|---|---| +| Visa | Navy blue → yellow gradient (70% navy) | Visa wordmark | +| Mastercard | Orange → yellow gradient | Mastercard circles | +| American Express | Solid blue | Amex logo | +| Unknown | Neutral gray gradient | none | + +The logo sits at the top-right corner of the preview and appears as soon +as the number prefix identifies the brand. + +To show the same logo next to a tokenization result (the API echoes the +brand as a string such as `"visa"`), use the public badge: + +```kotlin +import mx.dev1.openpay.sdk.domain.validation.CardBrand +import mx.dev1.openpay.sdk.ui.components.OpenpayCardBrandLogo + +OpenpayCardBrandLogo(brand = CardBrand.fromBrandName(token.card?.brand)) +``` + +The badge draws the white logo over its brand color, renders nothing for +unknown brands, and announces the brand name ("Visa", "Mastercard", +"American Express") to screen readers. + +## XML interop + +View-based apps get the same form without any Compose code: + +```xml + +``` + +```kotlin +findViewById(R.id.openpay_card_form).onCardValidated = { card -> + // tokenize it +} +``` + +## Accessibility + +The components are designed so assistive technologies lose nothing: + +- Every field exposes its **label and error text through semantics**, so + TalkBack announces "Card number, error, enter a valid card number". +- The detected brand badge has a content description ("Detected card + brand: VISA"). +- The security code is masked visually **and** described as hidden to the + screen reader; the keyboard switches to `NumberPassword`. +- Touch targets keep the Material minimum of **48dp**. +- Error colors come from the Material 3 error roles, preserving contrast + in light and dark themes. +- All texts are translated (see + [Internationalization](internationalization.md)), including the + accessibility descriptions. + +## Theming + +`OpenpayTheme` applies the Openpay palette on Material 3 with automatic +light/dark support. If your app already defines a `MaterialTheme`, simply +drop `OpenpayTheme` and the SDK components inherit your colors, typography +and shapes. diff --git a/docs/es/architecture.md b/docs/es/architecture.md new file mode 100644 index 0000000..06bb26a --- /dev/null +++ b/docs/es/architecture.md @@ -0,0 +1,138 @@ +# Arquitectura + +El SDK sigue la **arquitectura limpia**: las reglas de dominio están en el +centro y nunca dependen de Android, de la red ni de ningún framework. Las +capas externas dependen hacia adentro, lo que mantiene la lógica de negocio +testeable en pruebas de JVM puras. + +## Módulos + +```mermaid +flowchart LR + subgraph Repositorio + app[":app — aplicación de ejemplo"] + sdk[":openpay-sdk — la librería publicada"] + end + app -->|consume| sdk + sdk -->|publicada como| maven[("Maven: mx.dev1.openpay:openpay-sdk")] +``` + +- **`:openpay-sdk`** — todo lo que necesita la app de un comercio: red, + tokenización, validación, antifraude, UI de Compose y traducciones. +- **`:app`** — un ejemplo ejecutable que demuestra cada funcionalidad del + SDK. + +## Capas dentro del SDK + +```mermaid +flowchart TB + subgraph presentation["Capa de UI (Compose)"] + form["OpenpayCardForm / campos"] + formState["OpenpayCardFormState"] + xml["OpenpayCardFormView (interoperabilidad con XML)"] + end + subgraph facade["Fachada pública"] + openpayFacade["Openpay"] + end + subgraph domain["Capa de dominio (Kotlin puro)"] + models["Card / Token / Address"] + validator["CardValidator / CardBrand"] + usecase["CreateTokenUseCase"] + repoInterface["TokenRepository (interfaz)"] + end + subgraph data["Capa de datos"] + repoImpl["RemoteTokenRepository"] + http["Ktor HttpClient (CIO)"] + dto["DTOs + mappers"] + end + subgraph antifraud["Antifraude"] + collector["WebViewDeviceSessionCollector"] + end + + form --> formState --> validator + openpayFacade --> usecase + openpayFacade --> collector + usecase --> validator + usecase --> repoInterface + repoImpl -.implementa.-> repoInterface + repoImpl --> http + repoImpl --> dto +``` + +Reglas clave: + +- La **capa de dominio** (`domain/`) no tiene imports de Android. + `CardValidator` y `CreateTokenUseCase` se ejecutan en milisegundos en + cualquier JVM. +- La **capa de datos** (`data/`) implementa las interfaces del dominio + usando Ktor y kotlinx.serialization. Cambiar el stack HTTP tocaría solo + esta capa. +- La **capa de UI** (`ui/`) es Compose-first. El wrapper de XML existe + únicamente para apps anfitrionas legadas. +- **Koin** conecta todo dentro de un contenedor *aislado* + (`OpenpayKoinContext`), de modo que el SDK nunca entra en conflicto con + una app anfitriona que también use Koin. + +## Flujo de tokenización + +```mermaid +sequenceDiagram + actor Usuario + participant Form as OpenpayCardForm + participant Facade as Openpay + participant UseCase as CreateTokenUseCase + participant Validator as CardValidator + participant Repo as RemoteTokenRepository + participant API as Openpay API + + Usuario->>Form: escribe los datos de la tarjeta + Form->>Form: filtrado en vivo + detección de marca + Usuario->>Form: pulsa "Guardar tarjeta" + Form->>Facade: createToken(card) + Facade->>UseCase: invoke(card) + UseCase->>Validator: validate(card) + alt tarjeta inválida + Validator-->>UseCase: campos inválidos + UseCase-->>Facade: ValidationError (sin llamada de red) + else tarjeta válida + UseCase->>Repo: createToken(card) + Repo->>API: POST /v1/{merchantId}/tokens + API-->>Repo: JSON del token + Repo-->>UseCase: Token + UseCase-->>Facade: Token + end + Facade-->>Form: Result +``` + +## Flujo antifraude + +```mermaid +sequenceDiagram + participant App as App del comercio + participant Facade as Openpay + participant Collector as WebViewDeviceSessionCollector + participant API as Página de huella de Openpay + + App->>Facade: setupDeviceSession(activity) + Facade->>Collector: collect(activity) + Collector->>Collector: genera un id de sesión de 32 caracteres + Collector->>API: un WebView oculto carga /oa/logo.htm?m={merchant}&s={session} + Collector-->>Facade: id de sesión (de inmediato) + Note over Collector: el WebView se destruye a sí mismo cuando la página termina + Facade-->>App: deviceSessionId → envíalo a tu backend con el token +``` + +## Mapa de paquetes + +| Paquete | Contenido | +|---|---| +| `mx.dev1.openpay.sdk` | Fachada `Openpay`, `OpenpayCallback`, `OpenpaySdk` | +| `...sdk.core` | `OpenpayConfig`, países, entornos, `OpenpayException` | +| `...sdk.domain.model` | `Card`, `Token`, `TokenizedCard`, `Address` | +| `...sdk.domain.validation` | `CardValidator`, `CardBrand`, `CardValidationResult` | +| `...sdk.domain.usecase` / `repository` | `CreateTokenUseCase`, `TokenRepository` | +| `...sdk.data` | Fábrica del cliente Ktor, DTOs, mappers, `RemoteTokenRepository` | +| `...sdk.antifraud` | Recolección de la sesión de dispositivo | +| `...sdk.ui` | Tema, formulario, campos, transformaciones visuales, vista XML | +| `...sdk.i18n` | `OpenpayLanguage`, override de `OpenpayLocale` | +| `...sdk.di` | Módulos de Koin y el contenedor aislado | diff --git a/docs/es/ci.md b/docs/es/ci.md new file mode 100644 index 0000000..ed1265e --- /dev/null +++ b/docs/es/ci.md @@ -0,0 +1,77 @@ +# Integración continua + +El repositorio ejecuta un pipeline de GitHub Actions (`.github/workflows/ci.yml`) en cada push y pull request dirigidos a `develop` o `master`. No necesitas instalar nada: GitHub lo ejecuta automáticamente cuando abres un pull request. + +## Qué hace el pipeline + +```mermaid +flowchart LR + A[Push o pull request] --> B[Pruebas unitarias y cobertura] + A --> C[Pruebas instrumentadas] + B --> D[Reportes JaCoCo XML + HTML] + D --> E[Comentario de cobertura en el pull request] + D --> F[Umbral de 80% de cobertura de líneas para openpay-sdk] + C --> G[Reportes de pruebas en emulador] +``` + +### Pruebas unitarias y cobertura + +Este job se ejecuta en cada push y pull request: + +1. Compila el proyecto con JDK 17 y ejecuta `testDebugUnitTest` en todos los módulos. +2. Genera los reportes de cobertura de JaCoCo (`jacocoTestReport`). +3. Aplica el mínimo de 80% de cobertura de líneas en `openpay-sdk` (`jacocoCoverageVerification`). El build falla cuando la cobertura queda por debajo de ese umbral. +4. En los pull requests publica (y mantiene actualizado) un comentario con la cobertura general y la cobertura de los archivos modificados por el pull request, usando [Madrapps/jacoco-report](https://github.com/Madrapps/jacoco-report). +5. Sube los reportes HTML de cobertura y de pruebas como artefactos del build, para que puedas descargarlos y revisarlos desde la página de la ejecución. + +### Pruebas instrumentadas + +Este job arranca un emulador de Android 14 (API 34) en el runner y ejecuta `connectedDebugAndroidTest`. El emulador necesita aceleración por hardware, por eso el job habilita KVM antes de iniciarlo. Los reportes de pruebas se suben como artefactos. + +## Cómo leer el comentario de cobertura + +Cada pull request recibe un único comentario titulado **Unit test coverage** que se actualiza en cada push. Muestra: + +- **Cobertura general** del proyecto, marcada con ✅ cuando está en 80% o más. +- **Cobertura de los archivos modificados**, para que quienes revisan vean si el código nuevo está probado sin abrir el reporte completo. + +## Ejecutar las mismas verificaciones en local + +```bash +./gradlew testDebugUnitTest jacocoTestReport :openpay-sdk:jacocoCoverageVerification +./gradlew connectedDebugAndroidTest # requiere un dispositivo o emulador +``` + +El reporte HTML se genera en `/build/reports/jacoco/jacocoTestReport/html/index.html`. + +## Despliegue continuo + +Un segundo workflow (`.github/workflows/cd.yml`) libera la librería a +Maven Central. Se ejecuta cuando se hace push de un tag de versión +(`v1.2.3`) — normalmente el tag del commit de merge de un release en +`master` — y también puede iniciarse manualmente desde la pestaña Actions. + +```mermaid +flowchart LR + A[Push del tag v*] --> B[Pruebas unitarias + umbral de cobertura] + B --> C[Verificar tag == VERSION_NAME] + C --> D[Firmar y subir al Central Portal] + D --> E[Publish manual en central.sonatype.com] + D --> F[Release de GitHub con notas generadas] +``` + +1. **Primero las pruebas** — el release se bloquea si las pruebas + unitarias o el umbral de cobertura del 80% fallan. +2. **Guarda de versión** — el workflow falla si el tag no coincide con + `VERSION_NAME` en `gradle.properties`, así un release mal etiquetado no + puede salir. +3. **Subida firmada** — los artefactos se firman con PGP y se suben al + área de staging del Central Portal de Sonatype. Las credenciales y la + llave de firma vienen de los secretos del repositorio + (`MAVEN_REPOSITORY_USERNAME`, `MAVEN_REPOSITORY_PASSWORD`, + `SIGNING_KEY`, `SIGNING_PASSWORD`); nunca viven en el repositorio. +4. **Confirmación manual** — nada se hace público automáticamente: una + persona mantenedora debe presionar **Publish** sobre el despliegue + validado en [central.sonatype.com](https://central.sonatype.com). El + resumen de la ejecución enlaza el paso. +5. Se crea un release de GitHub con notas generadas para el tag. \ No newline at end of file diff --git a/docs/es/contributing.md b/docs/es/contributing.md new file mode 100644 index 0000000..d2fb5fa --- /dev/null +++ b/docs/es/contributing.md @@ -0,0 +1,85 @@ +# Contribuir + +Esta guía asume que **no tienes experiencia en Android**. Síguela de +principio a fin y podrás compilar, probar y proponer cambios. + +## 1. Prepara tu máquina + +1. Instala [Android Studio](https://developer.android.com/studio) (incluye + el JDK y el SDK de Android). +2. Clona el repositorio: + ```bash + git clone git@github.com:DEV1-Softworks/openpay-android.git + cd openpay-android + ``` +3. Abre la carpeta en Android Studio y deja que sincronice, o trabaja por + completo desde la terminal con los comandos de abajo. El proyecto + descarga automáticamente su propio toolchain de Gradle y JDK en la + primera compilación. + +## 2. Comandos del día a día + +| Qué | Comando | +|---|---| +| Compilar todo | `./gradlew assembleDebug` | +| Ejecutar todas las pruebas unitarias | `./gradlew testDebugUnitTest` | +| Reporte de cobertura (HTML + XML) | `./gradlew :openpay-sdk:jacocoTestReport` | +| Verificar el umbral de cobertura del 80% | `./gradlew :openpay-sdk:jacocoCoverageVerification` | +| Instalar la app de ejemplo en un dispositivo | `./gradlew :app:installDebug` | +| Publicar el SDK en tu Maven local | `./gradlew :openpay-sdk:publishToMavenLocal` | + +El reporte de cobertura se genera en +`openpay-sdk/build/reports/jacoco/jacocoTestReport/html/index.html` — ábrelo +en un navegador. + +## 3. Reglas del proyecto + +- **Lenguaje**: solo Kotlin. La UI es Jetpack Compose; el XML existe solo + para interoperabilidad con código legado. +- **Arquitectura**: arquitectura limpia. El código de dominio + (`openpay-sdk/src/main/kotlin/.../domain`) no debe importar tipos de + Android ni de Ktor. +- **Inyección de dependencias**: Koin. Las definiciones del SDK viven en + módulos `di/` dentro del contenedor aislado `OpenpayKoinContext`. +- **Versiones**: toda versión de dependencia vive en + `gradle/libs.versions.toml`, en ningún otro lugar. +- **Nombres**: sin nombres ambiguos. Los contadores de bucles son la única + excepción. +- **Pruebas**: todo cambio se entrega con pruebas unitarias (JUnit + + Mockito + Robolectric). La cobertura de líneas debe mantenerse en **80% o + más** — de lo contrario, la tarea `jacocoCoverageVerification` falla. + Ejecuta las pruebas antes de cada commit. + +## 4. Flujo de trabajo de Git (Git Flow) + +```mermaid +gitGraph + commit id: "initial" + branch develop + commit id: "work" + branch feature/my-feature + commit id: "feat: ..." + commit id: "test: ..." + checkout develop + merge feature/my-feature + commit id: "release prep" + checkout main + merge develop tag: "v1.x" +``` + +- `master` es **producción**. Nada se envía a ella directamente. +- `develop` es la rama de integración y la base de cada funcionalidad. +- Crea una rama por funcionalidad: `feature/`. +- Abre un **pull request hacia `develop`** por cada cambio; PRs pequeños + antes que grandes. Un PR debe compilar y pasar `testDebugUnitTest` + + `jacocoCoverageVerification`. +- Los releases fusionan `develop` en `master` mediante un PR de release. + +## 5. Lista de verificación del pull request + +- [ ] El código sigue las reglas de arquitectura y de nombres de arriba +- [ ] El código nuevo o modificado tiene pruebas, cobertura ≥ 80% +- [ ] `./gradlew testDebugUnitTest jacocoCoverageVerification` pasa localmente +- [ ] Las cadenas del SDK visibles para el usuario existen en **los cuatro** + idiomas (`values`, `values-es`, `values-pt`, `values-fr`) +- [ ] Documentación actualizada (los cuatro idiomas bajo `docs/`) diff --git a/docs/es/getting-started.md b/docs/es/getting-started.md new file mode 100644 index 0000000..6375807 --- /dev/null +++ b/docs/es/getting-started.md @@ -0,0 +1,133 @@ +# Primeros pasos + +Esta guía te lleva desde cero hasta tu primer token de tarjeta. No se +requiere experiencia previa en Android: cada paso está explicado en detalle. + +> **¿Qué es un token?** Los datos de la tarjeta son sensibles, por lo que tu +> app nunca los envía a tus propios servidores. En su lugar, el SDK +> intercambia la tarjeta por un **token** de un solo uso directamente con +> Openpay. Tu backend usa después ese token para crear el cargo. Tus +> servidores nunca ven el número de tarjeta. + +## Requisitos + +| Requisito | Mínimo | +|---|---| +| Android Studio | Narwhal (2025.1) o más reciente | +| JDK | 17 (Android Studio incluye uno) | +| Dispositivo / emulador Android | Android 8.0 (API 26) o más reciente | +| Cuenta de Openpay | Merchant ID + clave de API **pública** desde el [panel de Openpay](https://www.openpay.mx) | + +## 1. Instala el SDK + +Agrega la dependencia al `build.gradle.kts` de tu módulo: + +```kotlin +dependencies { + implementation("mx.dev1.openpay:openpay-sdk:1.0.0") +} +``` + +El SDK ya declara el permiso `INTERNET` en su manifiesto; no necesitas +agregar nada más. + +## 2. Configura el SDK + +Crea una instancia de `Openpay` con las credenciales de tu comercio: + +```kotlin +import mx.dev1.openpay.sdk.Openpay +import mx.dev1.openpay.sdk.core.OpenpayConfig +import mx.dev1.openpay.sdk.core.OpenpayCountry +import mx.dev1.openpay.sdk.core.OpenpayEnvironment + +val openpay = Openpay( + OpenpayConfig( + merchantId = "your-merchant-id", + publicApiKey = "pk_your_public_key", + country = OpenpayCountry.MEXICO, // MEXICO, COLOMBIA o PERU + environment = OpenpayEnvironment.SANDBOX, // SANDBOX mientras pruebas + ) +) +``` + +> **Nunca** incluyas tu clave de API *privada* dentro de la app. Solo la +> clave pública es segura en los dispositivos. + +## 3. Captura la tarjeta y crea un token + +El camino más rápido es el formulario de Compose listo para usar, que valida +cada campo y te entrega un objeto `Card` solo cuando los datos son +correctos: + +```kotlin +import mx.dev1.openpay.sdk.ui.components.OpenpayCardForm + +OpenpayCardForm( + onCardValidated = { card -> + scope.launch { + openpay.createToken(card) + .onSuccess { token -> sendToBackend(token.tokenId) } + .onFailure { error -> showError(error) } + } + } +) +``` + +¿Prefieres construir tu propia UI? Crea el `Card` tú mismo y valídalo con +`CardValidator`: + +```kotlin +import mx.dev1.openpay.sdk.domain.model.Card + +val card = Card( + holderName = "Juan Pérez Ramírez", + cardNumber = "4111111111111111", + expirationMonth = 12, + expirationYear = 30, + securityCode = "110", +) +val result = openpay.createToken(card) // suspend fun que devuelve Result +``` + +Los consumidores sin corrutinas pueden usar la variante con callback, +`openpay.createToken(card, callback)`; el callback se ejecuta en el hilo +principal. + +## 4. Inicia la sesión de dispositivo antifraude + +El motor de riesgo de Openpay necesita una huella del dispositivo por cada +checkout. Recoléctala una vez por pantalla de pago y envía el id devuelto a +tu backend junto con el token: + +```kotlin +val deviceSessionId = openpay.setupDeviceSession(activity) +``` + +## 5. Maneja los errores + +Toda falla es una `OpenpayException`: + +| Tipo | Significado | Reacción típica | +|---|---|---| +| `ValidationError` | La tarjeta no pasó la validación local; no hubo llamada de red | Resaltar `validationResult.invalidFields` | +| `ServiceError` | Openpay rechazó la solicitud (`errorCode`, `category`, `requestId`) | Mostrar un mensaje, registrar el `requestId` | +| `ConnectionError` | No se pudo alcanzar la API | Ofrecer un reintento | + +## 6. Tarjetas de prueba (sandbox) + +| Número | Marca | +|---|---| +| 4111 1111 1111 1111 | Visa | +| 5555 5555 5555 4444 | Mastercard | +| 3782 822463 10005 | American Express | + +Cualquier fecha de vencimiento futura y cualquier código de seguridad bien +formado funcionan en sandbox. + +## Próximos pasos + +- [Arquitectura](architecture.md) — cómo está organizado el SDK por dentro +- [Componentes de UI](ui-components.md) — el formulario de Compose, interoperabilidad con XML y accesibilidad +- [Internacionalización](internationalization.md) — idiomas y overrides +- [Contribuir](contributing.md) — compilar y probar el proyecto tú mismo diff --git a/docs/es/internationalization.md b/docs/es/internationalization.md new file mode 100644 index 0000000..515979e --- /dev/null +++ b/docs/es/internationalization.md @@ -0,0 +1,67 @@ +# Internacionalización + +Todo texto que muestra el SDK — etiquetas, errores de validación, +descripciones de accesibilidad — está disponible en: + +| Idioma | Etiqueta | +|---|---| +| Inglés (predeterminado y de respaldo) | `en` | +| Español | `es` | +| Portugués | `pt` | +| Francés | `fr` | + +## Resolución automática + +De forma predeterminada el SDK sigue el **idioma del dispositivo**, +incluidas las variantes regionales (`es-MX`, `pt-BR`, `fr-CA`, …). Los +dispositivos configurados en cualquier otro idioma recurren al inglés. No +hay nada que configurar. + +## Forzar un idioma + +Algunas apps permiten a los usuarios elegir un idioma independientemente de +la configuración del sistema. Establece el override una vez y todos los +componentes del SDK en pantalla se actualizan de inmediato: + +```kotlin +import mx.dev1.openpay.sdk.i18n.OpenpayLanguage +import mx.dev1.openpay.sdk.i18n.OpenpayLocale + +OpenpayLocale.override = OpenpayLanguage.PORTUGUESE // forzar portugués +OpenpayLocale.override = null // volver a automático +``` + +El override es estado observable de Compose: los composables del SDK se +recomponen en vivo cuando cambia, sin necesidad de reiniciar. + +## Apps basadas en vistas + +Si muestras cadenas del SDK desde tu propio código de vistas, resuélvelas a +través de un contexto localizado: + +```kotlin +val localizedContext = OpenpayLocale.localize(context) +val label = localizedContext.getString(R.string.openpay_card_number_label) +``` + +`localize` devuelve el contexto sin cambios cuando no hay ningún override +establecido. + +## Flujo + +```mermaid +flowchart TD + start([El SDK necesita una cadena]) --> hasOverride{¿OpenpayLocale.override establecido?} + hasOverride -- sí --> forced[Resolver los recursos en el idioma forzado] + hasOverride -- no --> device{¿Idioma del dispositivo incluido?} + device -- "es / pt / fr / en" --> auto[Resolver los recursos en el idioma del dispositivo] + device -- otro --> fallback[Recurrir al inglés] +``` + +## Agregar un idioma + +Las traducciones viven en los recursos de Android del SDK +(`openpay-sdk/src/main/res/values-/strings.xml`). Para proponer un +nuevo idioma, copia `values/strings.xml`, traduce cada entrada, agrega la +etiqueta a `OpenpayLanguage` y abre un pull request — ver +[Contribuir](contributing.md). diff --git a/docs/es/ui-components.md b/docs/es/ui-components.md new file mode 100644 index 0000000..65ba5b9 --- /dev/null +++ b/docs/es/ui-components.md @@ -0,0 +1,190 @@ +# Componentes de UI + +El SDK incluye un kit de captura de tarjeta con enfoque Compose-first. +Puedes usar el formulario completo, campos individuales, o envolver el +formulario dentro de un layout XML. + +## El formulario completo + +```kotlin +import mx.dev1.openpay.sdk.ui.components.OpenpayCardForm +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme + +OpenpayTheme { // opcional: hereda tu propio MaterialTheme en su lugar + OpenpayCardForm( + onCardValidated = { card -> /* tokenízala */ }, + ) +} +``` + +El formulario contiene el nombre del titular, el número de tarjeta (con +detección de marca en vivo), la fecha de vencimiento MM/AA y el código de +seguridad enmascarado, además de un botón de envío. `onCardValidated` se +dispara **solo** cuando todos los campos pasan la validación; los campos +inválidos se resaltan con mensajes de error traducidos. + +### Implementación con el formulario nativo + +El callback te entrega una `Card` validada; tokenízala y envía el id del +token a tu backend: + +```kotlin +val scope = rememberCoroutineScope() + +OpenpayCardForm( + onCardValidated = { card -> + scope.launch { + openpay.createToken(card) + .onSuccess { token -> /* envía token.tokenId a tu backend */ } + .onFailure { error -> /* muestra el error */ } + } + }, +) +``` + +Consulta [Primeros pasos](getting-started.md) para construir la instancia +`openpay` con tu id de comercio y llave pública. + +### Controlar el estado tú mismo + +```kotlin +val formState = rememberOpenpayCardFormState() + +OpenpayCardForm( + state = formState, + onCardValidated = { card -> ... }, +) + +// en otro lugar: formState.cardNumber, formState.detectedBrand, +// formState.validate(), formState.isFieldInvalid(CardField.CARD_NUMBER) +``` + +Por seguridad, el estado del formulario **no** se persiste al morir el +proceso: los datos de la tarjeta nunca tocan el disco. + +## Implementación con inputs personalizados + +Cada campo es público y puede componerse dentro de tu propio layout +conservando el formato y la validación del SDK: + +- `OpenpayHolderNameField` +- `OpenpayCardNumberField` — formato agrupado (4-4-4-4, Amex 4-6-5) +- `OpenpayExpirationField` — formato visual MM/AA sobre los dígitos MMAA +- `OpenpaySecurityCodeField` — entrada enmascarada, longitud según la marca + (4 para Amex, 3 en los demás casos) + +Conéctalos a `rememberOpenpayCardFormState()`, que guarda solo dígitos, +detecta la marca y valida todos los campos: + +```kotlin +val formState = rememberOpenpayCardFormState() + +Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OpenpayCardPreview( // opcional: incluye colores y logo de la marca + holderName = formState.holderName, + cardNumber = formState.cardNumber, + expiration = formState.expiration, + ) + OpenpayHolderNameField( + value = formState.holderName, + onValueChange = formState::updateHolderName, + isError = formState.isFieldInvalid(CardField.HOLDER_NAME), + ) + OpenpayCardNumberField( + value = formState.cardNumber, + onValueChange = formState::updateCardNumber, + isError = formState.isFieldInvalid(CardField.CARD_NUMBER), + ) + OpenpayExpirationField( + value = formState.expiration, + onValueChange = formState::updateExpiration, + isError = formState.isFieldInvalid(CardField.EXPIRATION), + ) + OpenpaySecurityCodeField( + value = formState.securityCode, + onValueChange = formState::updateSecurityCode, + isError = formState.isFieldInvalid(CardField.SECURITY_CODE), + ) + Button(onClick = { + formState.validate()?.let { card -> /* createToken(card) como arriba */ } + }) { + Text("Pagar") + } +} +``` + +`formState.validate()` devuelve la `Card` lista para tokenizar cuando +todos los campos son válidos; si no, devuelve null y marca los campos +fallidos para que `isFieldInvalid` los resalte. + +## Identidad de marca en la vista previa + +La vista previa de la tarjeta reacciona a la marca detectada: + +| Marca | Fondo de la tarjeta | Logo | +|---|---|---| +| Visa | Degradado azul marino → amarillo (70% azul) | Logotipo de Visa | +| Mastercard | Degradado naranja → amarillo | Círculos de Mastercard | +| American Express | Azul sólido | Logo de Amex | +| Desconocida | Degradado gris neutro | ninguno | + +El logo se muestra en la esquina superior derecha de la vista previa y +aparece en cuanto el prefijo del número identifica la marca. + +Para mostrar el mismo logo junto al resultado de la tokenización (la API +devuelve la marca como cadena, por ejemplo `"visa"`), usa el badge público: + +```kotlin +import mx.dev1.openpay.sdk.domain.validation.CardBrand +import mx.dev1.openpay.sdk.ui.components.OpenpayCardBrandLogo + +OpenpayCardBrandLogo(brand = CardBrand.fromBrandName(token.card?.brand)) +``` + +El badge dibuja el logo blanco sobre el color de su marca, no muestra nada +para marcas desconocidas y anuncia el nombre de la marca ("Visa", +"Mastercard", "American Express") a los lectores de pantalla. + +## Interoperabilidad con XML + +Las apps basadas en vistas obtienen el mismo formulario sin nada de código +Compose: + +```xml + +``` + +```kotlin +findViewById(R.id.openpay_card_form).onCardValidated = { card -> + // tokenízala +} +``` + +## Accesibilidad + +Los componentes están diseñados para que las tecnologías de asistencia no +pierdan nada: + +- Cada campo expone su **etiqueta y texto de error mediante semántica**, + por lo que TalkBack anuncia "Número de tarjeta, error, ingresa un número + de tarjeta válido". +- La insignia de la marca detectada tiene una descripción de contenido + ("Marca de tarjeta detectada: VISA"). +- El código de seguridad se enmascara visualmente **y** se describe como + oculto al lector de pantalla; el teclado cambia a `NumberPassword`. +- Los objetivos táctiles mantienen el mínimo de Material de **48dp**. +- Los colores de error provienen de los roles de error de Material 3, + preservando el contraste en los temas claro y oscuro. +- Todos los textos están traducidos (ver + [Internacionalización](internationalization.md)), incluidas las + descripciones de accesibilidad. + +## Temas + +`OpenpayTheme` aplica la paleta de Openpay sobre Material 3 con soporte +automático de tema claro/oscuro. Si tu app ya define un `MaterialTheme`, +simplemente omite `OpenpayTheme` y los componentes del SDK heredan tus +colores, tipografía y formas. diff --git a/docs/fr/architecture.md b/docs/fr/architecture.md new file mode 100644 index 0000000..cda06cd --- /dev/null +++ b/docs/fr/architecture.md @@ -0,0 +1,139 @@ +# Architecture + +Le SDK suit les principes de la **clean architecture** : les règles du +domaine sont au centre et ne dépendent jamais d'Android, du réseau ni +d'aucun framework. Les couches externes dépendent vers l'intérieur, ce qui +garde la logique métier testable dans de simples tests JVM. + +## Modules + +```mermaid +flowchart LR + subgraph Repository["Dépôt"] + app[":app — application d'exemple"] + sdk[":openpay-sdk — la bibliothèque publiée"] + end + app -->|consomme| sdk + sdk -->|publié sous| maven[("Maven: mx.dev1.openpay:openpay-sdk")] +``` + +- **`:openpay-sdk`** — tout ce dont une application marchande a besoin : + réseau, tokenisation, validation, antifraude, interface Compose et + traductions. +- **`:app`** — un exemple exécutable qui illustre chaque fonctionnalité du + SDK. + +## Couches à l'intérieur du SDK + +```mermaid +flowchart TB + subgraph presentation["Couche UI (Compose)"] + form["OpenpayCardForm / champs"] + formState["OpenpayCardFormState"] + xml["OpenpayCardFormView (interop XML)"] + end + subgraph facade["Façade publique"] + openpayFacade["Openpay"] + end + subgraph domain["Couche domaine (Kotlin pur)"] + models["Card / Token / Address"] + validator["CardValidator / CardBrand"] + usecase["CreateTokenUseCase"] + repoInterface["TokenRepository (interface)"] + end + subgraph data["Couche données"] + repoImpl["RemoteTokenRepository"] + http["Ktor HttpClient (CIO)"] + dto["DTO + mappers"] + end + subgraph antifraud["Antifraude"] + collector["WebViewDeviceSessionCollector"] + end + + form --> formState --> validator + openpayFacade --> usecase + openpayFacade --> collector + usecase --> validator + usecase --> repoInterface + repoImpl -.implémente.-> repoInterface + repoImpl --> http + repoImpl --> dto +``` + +Règles clés : + +- La **couche domaine** (`domain/`) ne contient aucun import Android. + `CardValidator` et `CreateTokenUseCase` s'exécutent en quelques + millisecondes sur n'importe quelle JVM. +- La **couche données** (`data/`) implémente les interfaces du domaine + avec Ktor et kotlinx.serialization. Remplacer la pile HTTP ne toucherait + que cette couche. +- La **couche UI** (`ui/`) est pensée d'abord pour Compose. Le wrapper XML + existe uniquement pour les applications hôtes historiques. +- **Koin** assemble le tout dans un conteneur *isolé* + (`OpenpayKoinContext`), de sorte que le SDK n'entre jamais en conflit + avec une application hôte qui utilise elle aussi Koin. + +## Flux de tokenisation + +```mermaid +sequenceDiagram + actor User as Utilisateur + participant Form as OpenpayCardForm + participant Facade as Openpay + participant UseCase as CreateTokenUseCase + participant Validator as CardValidator + participant Repo as RemoteTokenRepository + participant API as API Openpay + + User->>Form: saisit les données de la carte + Form->>Form: filtrage en direct + détection de la marque + User->>Form: appuie sur « Enregistrer la carte » + Form->>Facade: createToken(card) + Facade->>UseCase: invoke(card) + UseCase->>Validator: validate(card) + alt carte invalide + Validator-->>UseCase: champs invalides + UseCase-->>Facade: ValidationError (aucun appel réseau) + else carte valide + UseCase->>Repo: createToken(card) + Repo->>API: POST /v1/{merchantId}/tokens + API-->>Repo: JSON du token + Repo-->>UseCase: Token + UseCase-->>Facade: Token + end + Facade-->>Form: Result +``` + +## Flux antifraude + +```mermaid +sequenceDiagram + participant App as Application marchande + participant Facade as Openpay + participant Collector as WebViewDeviceSessionCollector + participant API as Page d'empreinte Openpay + + App->>Facade: setupDeviceSession(activity) + Facade->>Collector: collect(activity) + Collector->>Collector: génère un id de session de 32 caractères + Collector->>API: une WebView cachée charge /oa/logo.htm?m={merchant}&s={session} + Collector-->>Facade: id de session (immédiatement) + Note over Collector: La WebView se détruit elle-même quand la page a fini de charger + Facade-->>App: deviceSessionId → à envoyer à votre backend avec le token +``` + +## Carte des packages + +| Package | Contenu | +|---|---| +| `mx.dev1.openpay.sdk` | Façade `Openpay`, `OpenpayCallback`, `OpenpaySdk` | +| `...sdk.core` | `OpenpayConfig`, pays, environnements, `OpenpayException` | +| `...sdk.domain.model` | `Card`, `Token`, `TokenizedCard`, `Address` | +| `...sdk.domain.validation` | `CardValidator`, `CardBrand`, `CardValidationResult` | +| `...sdk.domain.usecase` / `repository` | `CreateTokenUseCase`, `TokenRepository` | +| `...sdk.data` | Fabrique de client Ktor, DTO, mappers, `RemoteTokenRepository` | +| `...sdk.antifraud` | Collecte de la session d'appareil | +| `...sdk.ui` | Thème, formulaire, champs, transformations visuelles, vue XML | +| `...sdk.i18n` | `OpenpayLanguage`, forçage `OpenpayLocale` | +| `...sdk.di` | Modules Koin et le conteneur isolé | diff --git a/docs/fr/ci.md b/docs/fr/ci.md new file mode 100644 index 0000000..cf63f47 --- /dev/null +++ b/docs/fr/ci.md @@ -0,0 +1,77 @@ +# Intégration continue + +Le dépôt exécute un pipeline GitHub Actions (`.github/workflows/ci.yml`) à chaque push et pull request ciblant `develop` ou `master`. Vous n'avez rien à installer : GitHub l'exécute automatiquement quand vous ouvrez une pull request. + +## Ce que fait le pipeline + +```mermaid +flowchart LR + A[Push ou pull request] --> B[Tests unitaires et couverture] + A --> C[Tests instrumentés] + B --> D[Rapports JaCoCo XML + HTML] + D --> E[Commentaire de couverture sur la pull request] + D --> F[Seuil de 80 % de couverture de lignes pour openpay-sdk] + C --> G[Rapports des tests sur émulateur] +``` + +### Tests unitaires et couverture + +Ce job s'exécute à chaque push et pull request : + +1. Compile le projet avec le JDK 17 et exécute `testDebugUnitTest` pour tous les modules. +2. Génère les rapports de couverture JaCoCo (`jacocoTestReport`). +3. Applique le minimum de 80 % de couverture de lignes sur `openpay-sdk` (`jacocoCoverageVerification`). Le build échoue quand la couverture passe sous ce seuil. +4. Sur les pull requests, publie (et maintient à jour) un commentaire avec la couverture globale et celle des fichiers modifiés par la pull request, via [Madrapps/jacoco-report](https://github.com/Madrapps/jacoco-report). +5. Téléverse les rapports HTML de couverture et de tests comme artefacts du build, afin que vous puissiez les télécharger et les consulter depuis la page de l'exécution. + +### Tests instrumentés + +Ce job démarre un émulateur Android 14 (API 34) sur le runner et exécute `connectedDebugAndroidTest`. L'émulateur a besoin de l'accélération matérielle, c'est pourquoi le job active KVM avant de le lancer. Les rapports de tests sont téléversés comme artefacts. + +## Lire le commentaire de couverture + +Chaque pull request reçoit un seul commentaire intitulé **Unit test coverage**, actualisé à chaque push. Il affiche : + +- **La couverture globale** du projet, marquée d'un ✅ quand elle atteint 80 % ou plus. +- **La couverture des fichiers modifiés**, pour que les relecteurs voient si le nouveau code est testé sans ouvrir le rapport complet. + +## Exécuter les mêmes vérifications en local + +```bash +./gradlew testDebugUnitTest jacocoTestReport :openpay-sdk:jacocoCoverageVerification +./gradlew connectedDebugAndroidTest # nécessite un appareil ou un émulateur +``` + +Le rapport HTML est généré dans `/build/reports/jacoco/jacocoTestReport/html/index.html`. + +## Déploiement continu + +Un second workflow (`.github/workflows/cd.yml`) publie la bibliothèque sur +Maven Central. Il s'exécute quand un tag de version (`v1.2.3`) est poussé — +normalement le tag du commit de merge d'une release sur `master` — et peut +aussi être lancé manuellement depuis l'onglet Actions. + +```mermaid +flowchart LR + A[Push du tag v*] --> B[Tests unitaires + seuil de couverture] + B --> C[Vérifier tag == VERSION_NAME] + C --> D[Signer et téléverser vers le Central Portal] + D --> E[Publish manuel sur central.sonatype.com] + D --> F[Release GitHub avec notes générées] +``` + +1. **Les tests d'abord** — la release est bloquée si les tests unitaires + ou le seuil de couverture de 80 % échouent. +2. **Garde de version** — le workflow échoue si le tag ne correspond pas à + `VERSION_NAME` dans `gradle.properties` ; une release mal étiquetée ne + peut donc pas partir. +3. **Téléversement signé** — les artefacts sont signés en PGP et envoyés + vers la zone de staging du Central Portal de Sonatype. Les identifiants + et la clé de signature proviennent des secrets du dépôt + (`MAVEN_REPOSITORY_USERNAME`, `MAVEN_REPOSITORY_PASSWORD`, + `SIGNING_KEY`, `SIGNING_PASSWORD`) ; ils ne vivent jamais dans le dépôt. +4. **Confirmation manuelle** — rien ne devient public automatiquement : + une personne mainteneuse doit appuyer sur **Publish** sur le déploiement + validé dans [central.sonatype.com](https://central.sonatype.com). Le + résumé de l'exécution pointe vers cette étape. +5. Une release GitHub avec notes générées est créée pour le tag. \ No newline at end of file diff --git a/docs/fr/contributing.md b/docs/fr/contributing.md new file mode 100644 index 0000000..ec22d3f --- /dev/null +++ b/docs/fr/contributing.md @@ -0,0 +1,87 @@ +# Contribuer + +Ce guide ne suppose **aucune expérience Android**. Suivez-le de haut en +bas et vous serez en mesure de compiler, tester et proposer des +modifications. + +## 1. Préparer votre machine + +1. Installez [Android Studio](https://developer.android.com/studio) (il + inclut le JDK et le SDK Android). +2. Clonez le dépôt : + ```bash + git clone git@github.com:DEV1-Softworks/openpay-android.git + cd openpay-android + ``` +3. Ouvrez le dossier dans Android Studio et laissez-le se synchroniser, ou + travaillez entièrement depuis le terminal avec les commandes + ci-dessous. Le projet télécharge automatiquement sa propre chaîne + d'outils Gradle et JDK lors de la première compilation. + +## 2. Commandes du quotidien + +| Quoi | Commande | +|---|---| +| Tout compiler | `./gradlew assembleDebug` | +| Lancer tous les tests unitaires | `./gradlew testDebugUnitTest` | +| Rapport de couverture (HTML + XML) | `./gradlew :openpay-sdk:jacocoTestReport` | +| Faire respecter le seuil de couverture de 80 % | `./gradlew :openpay-sdk:jacocoCoverageVerification` | +| Installer l'application d'exemple sur un appareil | `./gradlew :app:installDebug` | +| Publier le SDK dans votre Maven local | `./gradlew :openpay-sdk:publishToMavenLocal` | + +Le rapport de couverture est généré dans +`openpay-sdk/build/reports/jacoco/jacocoTestReport/html/index.html` — +ouvrez-le dans un navigateur. + +## 3. Règles du projet + +- **Langage** : Kotlin uniquement. L'interface est en Jetpack Compose ; le + XML n'existe que pour l'interopérabilité avec l'existant. +- **Architecture** : clean architecture. Le code du domaine + (`openpay-sdk/src/main/kotlin/.../domain`) ne doit importer aucun type + Android ni Ktor. +- **Injection de dépendances** : Koin. Les définitions du SDK vivent dans + les modules `di/` à l'intérieur du conteneur isolé `OpenpayKoinContext`. +- **Versions** : chaque version de dépendance vit dans + `gradle/libs.versions.toml`, et nulle part ailleurs. +- **Nommage** : pas de noms ambigus. Les compteurs de boucle sont la seule + exception. +- **Tests** : chaque modification s'accompagne de tests unitaires (JUnit + + Mockito + Robolectric). La couverture de lignes doit rester à **80 % ou + plus** — sinon la tâche `jacocoCoverageVerification` échoue. Lancez les + tests avant chaque commit. + +## 4. Flux de travail Git (Git Flow) + +```mermaid +gitGraph + commit id: "initial" + branch develop + commit id: "travail" + branch feature/my-feature + commit id: "feat: ..." + commit id: "test: ..." + checkout develop + merge feature/my-feature + commit id: "préparation de release" + checkout main + merge develop tag: "v1.x" +``` + +- `master` est la **production**. Rien n'y est poussé directement. +- `develop` est la branche d'intégration et la base de chaque + fonctionnalité. +- Créez une branche par fonctionnalité : `feature/`. +- Ouvrez une **pull request vers `develop`** pour chaque modification, en + privilégiant les petites PR aux grosses. Une PR doit compiler et passer + `testDebugUnitTest` + `jacocoCoverageVerification`. +- Les releases fusionnent `develop` dans `master` via une PR de release. + +## 5. Liste de vérification des pull requests + +- [ ] Le code respecte les règles d'architecture et de nommage ci-dessus +- [ ] Le code nouveau/modifié a des tests, couverture ≥ 80 % +- [ ] `./gradlew testDebugUnitTest jacocoCoverageVerification` passe en local +- [ ] Les chaînes du SDK visibles par l'utilisateur existent dans **les + quatre** langues (`values`, `values-es`, `values-pt`, `values-fr`) +- [ ] La documentation est à jour (les quatre langues sous `docs/`) diff --git a/docs/fr/getting-started.md b/docs/fr/getting-started.md new file mode 100644 index 0000000..e19a21b --- /dev/null +++ b/docs/fr/getting-started.md @@ -0,0 +1,134 @@ +# Premiers pas + +Ce guide vous accompagne de zéro jusqu'à votre premier token de carte. +Aucune expérience Android préalable n'est requise : chaque étape est +détaillée. + +> **Qu'est-ce qu'un token ?** Les données de carte sont sensibles, votre +> application ne les envoie donc jamais à vos propres serveurs. À la place, +> le SDK échange la carte contre un **token** à usage unique directement +> auprès d'Openpay. Votre backend utilise ensuite ce token pour créer le +> paiement. Vos serveurs ne voient jamais le numéro de carte. + +## Prérequis + +| Prérequis | Minimum | +|---|---| +| Android Studio | Narwhal (2025.1) ou plus récent | +| JDK | 17 (Android Studio en inclut un) | +| Appareil / émulateur Android | Android 8.0 (API 26) ou plus récent | +| Compte Openpay | Identifiant marchand + clé API **publique** depuis le [tableau de bord Openpay](https://www.openpay.mx) | + +## 1. Installer le SDK + +Ajoutez la dépendance au fichier `build.gradle.kts` de votre module : + +```kotlin +dependencies { + implementation("mx.dev1.openpay:openpay-sdk:1.0.0") +} +``` + +Le SDK déclare déjà la permission `INTERNET` dans son manifeste ; vous +n'avez rien d'autre à ajouter. + +## 2. Configurer le SDK + +Créez une instance `Openpay` avec vos identifiants marchand : + +```kotlin +import mx.dev1.openpay.sdk.Openpay +import mx.dev1.openpay.sdk.core.OpenpayConfig +import mx.dev1.openpay.sdk.core.OpenpayCountry +import mx.dev1.openpay.sdk.core.OpenpayEnvironment + +val openpay = Openpay( + OpenpayConfig( + merchantId = "your-merchant-id", + publicApiKey = "pk_your_public_key", + country = OpenpayCountry.MEXICO, // MEXICO, COLOMBIA ou PERU + environment = OpenpayEnvironment.SANDBOX, // SANDBOX pendant les tests + ) +) +``` + +> N'embarquez **jamais** votre clé API *privée* dans l'application. Seule +> la clé publique peut être présente en toute sécurité sur les appareils. + +## 3. Saisir la carte et créer un token + +Le chemin le plus rapide est le formulaire Compose prêt à l'emploi, qui +valide chaque champ et ne vous remet un objet `Card` que lorsque les +données sont correctes : + +```kotlin +import mx.dev1.openpay.sdk.ui.components.OpenpayCardForm + +OpenpayCardForm( + onCardValidated = { card -> + scope.launch { + openpay.createToken(card) + .onSuccess { token -> sendToBackend(token.tokenId) } + .onFailure { error -> showError(error) } + } + } +) +``` + +Vous préférez construire votre propre interface ? Créez la `Card` +vous-même et validez-la avec `CardValidator` : + +```kotlin +import mx.dev1.openpay.sdk.domain.model.Card + +val card = Card( + holderName = "Juan Pérez Ramírez", + cardNumber = "4111111111111111", + expirationMonth = 12, + expirationYear = 30, + securityCode = "110", +) +val result = openpay.createToken(card) // suspend fun renvoyant Result +``` + +Les intégrations sans coroutines peuvent utiliser la variante à callback, +`openpay.createToken(card, callback)` ; le callback s'exécute sur le +thread principal. + +## 4. Démarrer la session d'appareil antifraude + +Le moteur de risque d'Openpay a besoin d'une empreinte de l'appareil par +paiement. Collectez-la une fois par écran de paiement et envoyez +l'identifiant retourné à votre backend avec le token : + +```kotlin +val deviceSessionId = openpay.setupDeviceSession(activity) +``` + +## 5. Gérer les erreurs + +Chaque échec est une `OpenpayException` : + +| Type | Signification | Réaction typique | +|---|---|---| +| `ValidationError` | La carte a échoué à la validation locale ; aucun appel réseau n'a eu lieu | Mettre en évidence `validationResult.invalidFields` | +| `ServiceError` | Openpay a rejeté la requête (`errorCode`, `category`, `requestId`) | Afficher un message, journaliser le `requestId` | +| `ConnectionError` | L'API était injoignable | Proposer une nouvelle tentative | + +## 6. Cartes de test (sandbox) + +| Numéro | Marque | +|---|---| +| 4111 1111 1111 1111 | Visa | +| 5555 5555 5555 4444 | Mastercard | +| 3782 822463 10005 | American Express | + +Toute date d'expiration future et tout code de sécurité bien formé +fonctionnent en sandbox. + +## Étapes suivantes + +- [Architecture](architecture.md) — comment le SDK est organisé en interne +- [Composants d'interface](ui-components.md) — le formulaire Compose, l'interopérabilité XML et l'accessibilité +- [Internationalisation](internationalization.md) — langues et forçages +- [Contribuer](contributing.md) — compiler et tester le projet vous-même diff --git a/docs/fr/internationalization.md b/docs/fr/internationalization.md new file mode 100644 index 0000000..1a396c7 --- /dev/null +++ b/docs/fr/internationalization.md @@ -0,0 +1,66 @@ +# Internationalisation + +Chaque texte affiché par le SDK — libellés, erreurs de validation, +descriptions d'accessibilité — est disponible en : + +| Langue | Tag | +|---|---| +| Anglais (par défaut et langue de repli) | `en` | +| Espagnol | `es` | +| Portugais | `pt` | +| Français | `fr` | + +## Résolution automatique + +Par défaut, le SDK suit la **langue de l'appareil**, y compris les +variantes régionales (`es-MX`, `pt-BR`, `fr-CA`, …). Les appareils +configurés dans toute autre langue basculent vers l'anglais. Il n'y a rien +à configurer. + +## Forcer une langue + +Certaines applications laissent les utilisateurs choisir une langue +indépendamment des réglages du système. Définissez le forçage une seule +fois et chaque composant du SDK à l'écran se met à jour immédiatement : + +```kotlin +import mx.dev1.openpay.sdk.i18n.OpenpayLanguage +import mx.dev1.openpay.sdk.i18n.OpenpayLocale + +OpenpayLocale.override = OpenpayLanguage.PORTUGUESE // forcer le portugais +OpenpayLocale.override = null // retour au mode automatique +``` + +Le forçage est un état Compose observable : les composables du SDK se +recomposent en direct quand il change, sans redémarrage nécessaire. + +## Applications basées sur les vues + +Si vous affichez des chaînes du SDK depuis votre propre code de vues, +résolvez-les via un contexte localisé : + +```kotlin +val localizedContext = OpenpayLocale.localize(context) +val label = localizedContext.getString(R.string.openpay_card_number_label) +``` + +`localize` renvoie le contexte inchangé quand aucun forçage n'est défini. + +## Flux + +```mermaid +flowchart TD + start([Le SDK a besoin d'une chaîne]) --> hasOverride{OpenpayLocale.override défini ?} + hasOverride -- oui --> forced[Résoudre les ressources dans la langue forcée] + hasOverride -- non --> device{Langue de l'appareil incluse ?} + device -- "es / pt / fr / en" --> auto[Résoudre les ressources dans la langue de l'appareil] + device -- autre --> fallback[Se replier sur l'anglais] +``` + +## Ajouter une langue + +Les traductions vivent dans les ressources Android du SDK +(`openpay-sdk/src/main/res/values-/strings.xml`). Pour proposer une +nouvelle langue, copiez `values/strings.xml`, traduisez chaque entrée, +ajoutez le tag à `OpenpayLanguage` et ouvrez une pull request — voir +[Contribuer](contributing.md). diff --git a/docs/fr/ui-components.md b/docs/fr/ui-components.md new file mode 100644 index 0000000..307ff70 --- /dev/null +++ b/docs/fr/ui-components.md @@ -0,0 +1,194 @@ +# Composants d'interface + +Le SDK fournit un kit de saisie de carte pensé d'abord pour Compose. Vous +pouvez utiliser le formulaire complet, des champs individuels, ou intégrer +le formulaire dans une mise en page XML. + +## Le formulaire complet + +```kotlin +import mx.dev1.openpay.sdk.ui.components.OpenpayCardForm +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme + +OpenpayTheme { // optionnel : héritez plutôt de votre propre MaterialTheme + OpenpayCardForm( + onCardValidated = { card -> /* le tokeniser */ }, + ) +} +``` + +Le formulaire contient le nom du titulaire, le numéro de carte (avec +détection de la marque en direct), l'expiration MM/AA et le code de +sécurité masqué, ainsi qu'un bouton de validation (« Enregistrer la +carte »). `onCardValidated` ne se déclenche **que** lorsque tous les +champs passent la validation ; les champs invalides sont mis en évidence +avec des messages d'erreur traduits. + +### Implémentation avec le formulaire natif + +Le callback vous remet une `Card` validée ; tokenisez-la et envoyez l'id +du token à votre backend : + +```kotlin +val scope = rememberCoroutineScope() + +OpenpayCardForm( + onCardValidated = { card -> + scope.launch { + openpay.createToken(card) + .onSuccess { token -> /* envoyez token.tokenId à votre backend */ } + .onFailure { error -> /* affichez l'erreur */ } + } + }, +) +``` + +Consultez [Premiers pas](getting-started.md) pour construire l'instance +`openpay` avec votre id marchand et votre clé publique. + +### Contrôler l'état vous-même + +```kotlin +val formState = rememberOpenpayCardFormState() + +OpenpayCardForm( + state = formState, + onCardValidated = { card -> ... }, +) + +// ailleurs : formState.cardNumber, formState.detectedBrand, +// formState.validate(), formState.isFieldInvalid(CardField.CARD_NUMBER) +``` + +Pour des raisons de sécurité, l'état du formulaire n'est **pas** conservé +après la mort du processus — les données de carte ne touchent jamais le +disque. + +## Implémentation avec des champs personnalisés + +Chaque champ est public et peut être composé dans votre propre mise en +page tout en conservant le formatage et la validation du SDK : + +- `OpenpayHolderNameField` +- `OpenpayCardNumberField` — formatage par groupes (4-4-4-4, Amex 4-6-5) +- `OpenpayExpirationField` — formatage visuel MM/AA sur les chiffres MMAA +- `OpenpaySecurityCodeField` — saisie masquée, longueur adaptée à la + marque (4 pour Amex, 3 sinon) + +Reliez-les à `rememberOpenpayCardFormState()`, qui ne conserve que les +chiffres, détecte la marque et valide tous les champs : + +```kotlin +val formState = rememberOpenpayCardFormState() + +Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OpenpayCardPreview( // optionnel : couleurs et logo de la marque inclus + holderName = formState.holderName, + cardNumber = formState.cardNumber, + expiration = formState.expiration, + ) + OpenpayHolderNameField( + value = formState.holderName, + onValueChange = formState::updateHolderName, + isError = formState.isFieldInvalid(CardField.HOLDER_NAME), + ) + OpenpayCardNumberField( + value = formState.cardNumber, + onValueChange = formState::updateCardNumber, + isError = formState.isFieldInvalid(CardField.CARD_NUMBER), + ) + OpenpayExpirationField( + value = formState.expiration, + onValueChange = formState::updateExpiration, + isError = formState.isFieldInvalid(CardField.EXPIRATION), + ) + OpenpaySecurityCodeField( + value = formState.securityCode, + onValueChange = formState::updateSecurityCode, + isError = formState.isFieldInvalid(CardField.SECURITY_CODE), + ) + Button(onClick = { + formState.validate()?.let { card -> /* createToken(card) comme ci-dessus */ } + }) { + Text("Payer") + } +} +``` + +`formState.validate()` renvoie la `Card` prête pour la tokenisation quand +tous les champs sont valides ; sinon elle renvoie null et signale les +champs en échec pour que `isFieldInvalid` les mette en évidence. + +## Identité de marque sur l'aperçu de la carte + +L'aperçu de la carte réagit à la marque détectée : + +| Marque | Fond de la carte | Logo | +|---|---|---| +| Visa | Dégradé bleu marine → jaune (70 % bleu) | Logotype Visa | +| Mastercard | Dégradé orange → jaune | Cercles Mastercard | +| American Express | Bleu uni | Logo Amex | +| Inconnue | Dégradé gris neutre | aucun | + +Le logo s'affiche dans le coin supérieur droit de l'aperçu et apparaît dès +que le préfixe du numéro identifie la marque. + +Pour afficher le même logo à côté du résultat de la tokenisation (l'API +renvoie la marque sous forme de chaîne, par exemple `"visa"`), utilisez le +badge public : + +```kotlin +import mx.dev1.openpay.sdk.domain.validation.CardBrand +import mx.dev1.openpay.sdk.ui.components.OpenpayCardBrandLogo + +OpenpayCardBrandLogo(brand = CardBrand.fromBrandName(token.card?.brand)) +``` + +Le badge dessine le logo blanc sur la couleur de sa marque, n'affiche rien +pour les marques inconnues et annonce le nom de la marque (« Visa », +« Mastercard », « American Express ») aux lecteurs d'écran. + +## Interopérabilité XML + +Les applications basées sur les vues obtiennent le même formulaire sans +aucun code Compose : + +```xml + +``` + +```kotlin +findViewById(R.id.openpay_card_form).onCardValidated = { card -> + // le tokeniser +} +``` + +## Accessibilité + +Les composants sont conçus pour que les technologies d'assistance ne +perdent aucune information : + +- Chaque champ expose son **libellé et son texte d'erreur via la + sémantique**, si bien que TalkBack annonce « Numéro de carte, erreur, + saisissez un numéro de carte valide ». +- Le badge de la marque détectée possède une description de contenu + (« Marque de carte détectée : VISA »). +- Le code de sécurité est masqué visuellement **et** décrit comme masqué + au lecteur d'écran ; le clavier bascule en `NumberPassword`. +- Les zones tactiles respectent le minimum Material de **48dp**. +- Les couleurs d'erreur proviennent des rôles d'erreur de Material 3, ce + qui préserve le contraste dans les thèmes clair et sombre. +- Tous les textes sont traduits (voir + [Internationalisation](internationalization.md)), y compris les + descriptions d'accessibilité. + +## Thématisation + +`OpenpayTheme` applique la palette Openpay sur Material 3 avec une prise +en charge automatique des modes clair et sombre. Si votre application +définit déjà un `MaterialTheme`, retirez simplement `OpenpayTheme` et les +composants du SDK hériteront de vos couleurs, de votre typographie et de +vos formes. diff --git a/docs/pt/architecture.md b/docs/pt/architecture.md new file mode 100644 index 0000000..dc3d78c --- /dev/null +++ b/docs/pt/architecture.md @@ -0,0 +1,137 @@ +# Arquitetura + +O SDK segue a **arquitetura limpa** (clean architecture): as regras de +domínio ficam no centro e nunca dependem do Android, da rede ou de qualquer +framework. As camadas externas dependem das internas, o que mantém a lógica +de negócio testável em testes JVM puros. + +## Módulos + +```mermaid +flowchart LR + subgraph Repository["Repositório"] + app[":app — aplicativo de exemplo"] + sdk[":openpay-sdk — a biblioteca publicada"] + end + app -->|consome| sdk + sdk -->|publicado como| maven[("Maven: mx.dev1.openpay:openpay-sdk")] +``` + +- **`:openpay-sdk`** — tudo o que o app de um comércio precisa: rede, + tokenização, validação, antifraude, UI em Compose e traduções. +- **`:app`** — um exemplo executável que demonstra todos os recursos do SDK. + +## Camadas dentro do SDK + +```mermaid +flowchart TB + subgraph presentation["Camada de UI (Compose)"] + form["OpenpayCardForm / campos"] + formState["OpenpayCardFormState"] + xml["OpenpayCardFormView (interop XML)"] + end + subgraph facade["Fachada pública"] + openpayFacade["Openpay"] + end + subgraph domain["Camada de domínio (Kotlin puro)"] + models["Card / Token / Address"] + validator["CardValidator / CardBrand"] + usecase["CreateTokenUseCase"] + repoInterface["TokenRepository (interface)"] + end + subgraph data["Camada de dados"] + repoImpl["RemoteTokenRepository"] + http["Ktor HttpClient (CIO)"] + dto["DTOs + mappers"] + end + subgraph antifraud["Antifraude"] + collector["WebViewDeviceSessionCollector"] + end + + form --> formState --> validator + openpayFacade --> usecase + openpayFacade --> collector + usecase --> validator + usecase --> repoInterface + repoImpl -.implementa.-> repoInterface + repoImpl --> http + repoImpl --> dto +``` + +Regras principais: + +- A **camada de domínio** (`domain/`) não tem imports do Android. + `CardValidator` e `CreateTokenUseCase` executam em milissegundos em + qualquer JVM. +- A **camada de dados** (`data/`) implementa as interfaces do domínio usando + Ktor e kotlinx.serialization. Trocar a pilha HTTP afetaria apenas esta + camada. +- A **camada de UI** (`ui/`) é Compose em primeiro lugar. O wrapper XML + existe apenas para apps hospedeiros legados. +- O **Koin** conecta tudo dentro de um contêiner *isolado* + (`OpenpayKoinContext`), de modo que o SDK nunca entra em conflito com um + app hospedeiro que também use Koin. + +## Fluxo de tokenização + +```mermaid +sequenceDiagram + actor User as Usuário + participant Form as OpenpayCardForm + participant Facade as Openpay + participant UseCase as CreateTokenUseCase + participant Validator as CardValidator + participant Repo as RemoteTokenRepository + participant API as Openpay API + + User->>Form: digita os dados do cartão + Form->>Form: filtragem em tempo real + detecção de bandeira + User->>Form: toca em "Salvar cartão" + Form->>Facade: createToken(card) + Facade->>UseCase: invoke(card) + UseCase->>Validator: validate(card) + alt cartão inválido + Validator-->>UseCase: campos inválidos + UseCase-->>Facade: ValidationError (sem chamada de rede) + else cartão válido + UseCase->>Repo: createToken(card) + Repo->>API: POST /v1/{merchantId}/tokens + API-->>Repo: JSON do token + Repo-->>UseCase: Token + UseCase-->>Facade: Token + end + Facade-->>Form: Result +``` + +## Fluxo antifraude + +```mermaid +sequenceDiagram + participant App as App do comércio + participant Facade as Openpay + participant Collector as WebViewDeviceSessionCollector + participant API as Página de fingerprint da Openpay + + App->>Facade: setupDeviceSession(activity) + Facade->>Collector: collect(activity) + Collector->>Collector: gera um id de sessão de 32 caracteres + Collector->>API: WebView oculta carrega /oa/logo.htm?m={merchant}&s={session} + Collector-->>Facade: id de sessão (imediatamente) + Note over Collector: a WebView se destrói quando a página termina de carregar + Facade-->>App: deviceSessionId → envie ao seu backend com o token +``` + +## Mapa de pacotes + +| Pacote | Conteúdo | +|---|---| +| `mx.dev1.openpay.sdk` | Fachada `Openpay`, `OpenpayCallback`, `OpenpaySdk` | +| `...sdk.core` | `OpenpayConfig`, países, ambientes, `OpenpayException` | +| `...sdk.domain.model` | `Card`, `Token`, `TokenizedCard`, `Address` | +| `...sdk.domain.validation` | `CardValidator`, `CardBrand`, `CardValidationResult` | +| `...sdk.domain.usecase` / `repository` | `CreateTokenUseCase`, `TokenRepository` | +| `...sdk.data` | Fábrica do cliente Ktor, DTOs, mappers, `RemoteTokenRepository` | +| `...sdk.antifraud` | Coleta da sessão do dispositivo | +| `...sdk.ui` | Tema, formulário, campos, transformações visuais, view XML | +| `...sdk.i18n` | `OpenpayLanguage`, substituição via `OpenpayLocale` | +| `...sdk.di` | Módulos Koin e o contêiner isolado | diff --git a/docs/pt/ci.md b/docs/pt/ci.md new file mode 100644 index 0000000..2d69bfc --- /dev/null +++ b/docs/pt/ci.md @@ -0,0 +1,77 @@ +# Integração contínua + +O repositório executa um pipeline do GitHub Actions (`.github/workflows/ci.yml`) em cada push e pull request direcionados a `develop` ou `master`. Você não precisa instalar nada: o GitHub o executa automaticamente quando você abre um pull request. + +## O que o pipeline faz + +```mermaid +flowchart LR + A[Push ou pull request] --> B[Testes unitários e cobertura] + A --> C[Testes instrumentados] + B --> D[Relatórios JaCoCo XML + HTML] + D --> E[Comentário de cobertura no pull request] + D --> F[Limite de 80% de cobertura de linhas para openpay-sdk] + C --> G[Relatórios dos testes no emulador] +``` + +### Testes unitários e cobertura + +Este job é executado em cada push e pull request: + +1. Compila o projeto com o JDK 17 e executa `testDebugUnitTest` em todos os módulos. +2. Gera os relatórios de cobertura do JaCoCo (`jacocoTestReport`). +3. Aplica o mínimo de 80% de cobertura de linhas no `openpay-sdk` (`jacocoCoverageVerification`). O build falha quando a cobertura fica abaixo desse limite. +4. Nos pull requests, publica (e mantém atualizado) um comentário com a cobertura geral e a cobertura dos arquivos alterados pelo pull request, usando [Madrapps/jacoco-report](https://github.com/Madrapps/jacoco-report). +5. Envia os relatórios HTML de cobertura e de testes como artefatos do build, para que você possa baixá-los e consultá-los na página da execução. + +### Testes instrumentados + +Este job inicia um emulador Android 14 (API 34) no runner e executa `connectedDebugAndroidTest`. O emulador precisa de aceleração por hardware, por isso o job habilita o KVM antes de iniciá-lo. Os relatórios de testes são enviados como artefatos. + +## Como ler o comentário de cobertura + +Cada pull request recebe um único comentário intitulado **Unit test coverage**, atualizado a cada push. Ele mostra: + +- **Cobertura geral** do projeto, marcada com ✅ quando está em 80% ou mais. +- **Cobertura dos arquivos alterados**, para que os revisores vejam se o novo código está testado sem abrir o relatório completo. + +## Executar as mesmas verificações localmente + +```bash +./gradlew testDebugUnitTest jacocoTestReport :openpay-sdk:jacocoCoverageVerification +./gradlew connectedDebugAndroidTest # requer um dispositivo ou emulador +``` + +O relatório HTML é gerado em `/build/reports/jacoco/jacocoTestReport/html/index.html`. + +## Deploy contínuo + +Um segundo workflow (`.github/workflows/cd.yml`) libera a biblioteca no +Maven Central. Ele roda quando um tag de versão (`v1.2.3`) é enviado — +normalmente o tag do commit de merge de um release em `master` — e também +pode ser iniciado manualmente na aba Actions. + +```mermaid +flowchart LR + A[Push do tag v*] --> B[Testes unitários + limite de cobertura] + B --> C[Verificar tag == VERSION_NAME] + C --> D[Assinar e enviar ao Central Portal] + D --> E[Publish manual em central.sonatype.com] + D --> F[Release do GitHub com notas geradas] +``` + +1. **Testes primeiro** — o release é bloqueado se os testes unitários ou o + limite de cobertura de 80% falharem. +2. **Guarda de versão** — o workflow falha se o tag não corresponder ao + `VERSION_NAME` em `gradle.properties`; um release com tag errado não + consegue sair. +3. **Envio assinado** — os artefatos são assinados com PGP e enviados à + área de staging do Central Portal da Sonatype. As credenciais e a chave + de assinatura vêm dos secrets do repositório + (`MAVEN_REPOSITORY_USERNAME`, `MAVEN_REPOSITORY_PASSWORD`, + `SIGNING_KEY`, `SIGNING_PASSWORD`); elas nunca vivem no repositório. +4. **Confirmação manual** — nada se torna público automaticamente: uma + pessoa mantenedora precisa pressionar **Publish** no deployment + validado em [central.sonatype.com](https://central.sonatype.com). O + resumo da execução aponta para essa etapa. +5. Um release do GitHub com notas geradas é criado para o tag. \ No newline at end of file diff --git a/docs/pt/contributing.md b/docs/pt/contributing.md new file mode 100644 index 0000000..d44573e --- /dev/null +++ b/docs/pt/contributing.md @@ -0,0 +1,85 @@ +# Contribuindo + +Este guia pressupõe **nenhuma experiência com Android**. Siga-o do início ao +fim e você será capaz de compilar, testar e propor mudanças. + +## 1. Prepare sua máquina + +1. Instale o [Android Studio](https://developer.android.com/studio) (ele já + inclui o JDK e o Android SDK). +2. Clone o repositório: + ```bash + git clone git@github.com:DEV1-Softworks/openpay-android.git + cd openpay-android + ``` +3. Abra a pasta no Android Studio e deixe-o sincronizar, ou trabalhe + inteiramente pelo terminal com os comandos abaixo. O projeto baixa + automaticamente seu próprio Gradle e a toolchain do JDK na primeira + compilação. + +## 2. Comandos do dia a dia + +| O quê | Comando | +|---|---| +| Compilar tudo | `./gradlew assembleDebug` | +| Executar todos os testes unitários | `./gradlew testDebugUnitTest` | +| Relatório de cobertura (HTML + XML) | `./gradlew :openpay-sdk:jacocoTestReport` | +| Aplicar o limite de 80% de cobertura | `./gradlew :openpay-sdk:jacocoCoverageVerification` | +| Instalar o app de exemplo em um dispositivo | `./gradlew :app:installDebug` | +| Publicar o SDK no seu Maven local | `./gradlew :openpay-sdk:publishToMavenLocal` | + +O relatório de cobertura é gerado em +`openpay-sdk/build/reports/jacoco/jacocoTestReport/html/index.html` — abra-o +em um navegador. + +## 3. Regras do projeto + +- **Linguagem**: apenas Kotlin. A UI é Jetpack Compose; o XML existe apenas + para interoperabilidade legada. +- **Arquitetura**: arquitetura limpa. O código de domínio + (`openpay-sdk/src/main/kotlin/.../domain`) não deve importar tipos do + Android nem do Ktor. +- **Injeção de dependência**: Koin. As definições do SDK vivem em módulos + `di/` dentro do contêiner isolado `OpenpayKoinContext`. +- **Versões**: toda versão de dependência vive em + `gradle/libs.versions.toml`, em nenhum outro lugar. +- **Nomenclatura**: nada de nomes ambíguos. Contadores de laço são a única + exceção. +- **Testes**: toda mudança vem acompanhada de testes unitários (JUnit + + Mockito + Robolectric). A cobertura de linhas deve permanecer em **80% ou + mais** — caso contrário, a tarefa `jacocoCoverageVerification` falha. + Execute os testes antes de cada commit. + +## 4. Fluxo de trabalho com Git (Git Flow) + +```mermaid +gitGraph + commit id: "initial" + branch develop + commit id: "work" + branch feature/my-feature + commit id: "feat: ..." + commit id: "test: ..." + checkout develop + merge feature/my-feature + commit id: "release prep" + checkout main + merge develop tag: "v1.x" +``` + +- `master` é **produção**. Nada é enviado diretamente para ela. +- `develop` é a branch de integração e a base de toda feature. +- Crie uma branch por feature: `feature/`. +- Abra um **pull request para `develop`** a cada mudança, preferindo PRs + pequenos aos grandes. Um PR deve compilar e passar em `testDebugUnitTest` + + `jacocoCoverageVerification`. +- As releases mesclam `develop` em `master` por meio de um PR de release. + +## 5. Checklist do pull request + +- [ ] O código segue as regras de arquitetura e nomenclatura acima +- [ ] Código novo/alterado tem testes, cobertura ≥ 80% +- [ ] `./gradlew testDebugUnitTest jacocoCoverageVerification` passa localmente +- [ ] As strings do SDK visíveis ao usuário existem em **todos os quatro** + idiomas (`values`, `values-es`, `values-pt`, `values-fr`) +- [ ] Documentação atualizada (os quatro idiomas em `docs/`) diff --git a/docs/pt/getting-started.md b/docs/pt/getting-started.md new file mode 100644 index 0000000..e88dbec --- /dev/null +++ b/docs/pt/getting-started.md @@ -0,0 +1,133 @@ +# Primeiros passos + +Este guia leva você do zero ao seu primeiro token de cartão. Não é necessária +experiência prévia com Android: cada passo é explicado em detalhes. + +> **O que é um token?** Os dados do cartão são sensíveis, portanto seu app +> nunca os envia para os seus próprios servidores. Em vez disso, o SDK troca +> o cartão por um **token** de uso único diretamente com a Openpay. Seu +> backend usa então esse token para criar a cobrança. Seus servidores nunca +> veem o número do cartão. + +## Requisitos + +| Requisito | Mínimo | +|---|---| +| Android Studio | Narwhal (2025.1) ou mais recente | +| JDK | 17 (o Android Studio já inclui um) | +| Dispositivo / emulador Android | Android 8.0 (API 26) ou mais recente | +| Conta Openpay | Merchant ID + chave de API **pública** do [painel da Openpay](https://www.openpay.mx) | + +## 1. Instale o SDK + +Adicione a dependência ao `build.gradle.kts` do seu módulo: + +```kotlin +dependencies { + implementation("mx.dev1.openpay:openpay-sdk:1.0.0") +} +``` + +O SDK já declara a permissão `INTERNET` em seu manifesto; você não precisa +adicionar mais nada. + +## 2. Configure o SDK + +Crie uma instância de `Openpay` com as credenciais do seu comércio: + +```kotlin +import mx.dev1.openpay.sdk.Openpay +import mx.dev1.openpay.sdk.core.OpenpayConfig +import mx.dev1.openpay.sdk.core.OpenpayCountry +import mx.dev1.openpay.sdk.core.OpenpayEnvironment + +val openpay = Openpay( + OpenpayConfig( + merchantId = "your-merchant-id", + publicApiKey = "pk_your_public_key", + country = OpenpayCountry.MEXICO, // MEXICO, COLOMBIA ou PERU + environment = OpenpayEnvironment.SANDBOX, // SANDBOX durante os testes + ) +) +``` + +> **Nunca** distribua sua chave de API *privada* dentro do app. Apenas a +> chave pública é segura em dispositivos. + +## 3. Capture o cartão e crie um token + +O caminho mais rápido é o formulário Compose pronto para uso, que valida +todos os campos e entrega um objeto `Card` apenas quando os dados estão +corretos: + +```kotlin +import mx.dev1.openpay.sdk.ui.components.OpenpayCardForm + +OpenpayCardForm( + onCardValidated = { card -> + scope.launch { + openpay.createToken(card) + .onSuccess { token -> sendToBackend(token.tokenId) } + .onFailure { error -> showError(error) } + } + } +) +``` + +Prefere construir sua própria interface? Crie o `Card` você mesmo e +valide-o com o `CardValidator`: + +```kotlin +import mx.dev1.openpay.sdk.domain.model.Card + +val card = Card( + holderName = "Juan Pérez Ramírez", + cardNumber = "4111111111111111", + expirationMonth = 12, + expirationYear = 30, + securityCode = "110", +) +val result = openpay.createToken(card) // suspend fun que retorna Result +``` + +Consumidores sem coroutines podem usar a variante com callback, +`openpay.createToken(card, callback)`; o callback é executado na thread +principal. + +## 4. Inicie a sessão do dispositivo antifraude + +O motor de risco da Openpay precisa de uma impressão digital do dispositivo +por checkout. Colete-a uma vez por tela de pagamento e envie o id retornado +ao seu backend junto com o token: + +```kotlin +val deviceSessionId = openpay.setupDeviceSession(activity) +``` + +## 5. Trate os erros + +Toda falha é uma `OpenpayException`: + +| Tipo | Significado | Reação típica | +|---|---|---| +| `ValidationError` | O cartão falhou na validação local; nenhuma chamada de rede aconteceu | Destacar `validationResult.invalidFields` | +| `ServiceError` | A Openpay rejeitou a requisição (`errorCode`, `category`, `requestId`) | Mostrar uma mensagem, registrar o `requestId` | +| `ConnectionError` | A API estava inacessível | Oferecer uma nova tentativa | + +## 6. Cartões de teste (sandbox) + +| Número | Bandeira | +|---|---| +| 4111 1111 1111 1111 | Visa | +| 5555 5555 5555 4444 | Mastercard | +| 3782 822463 10005 | American Express | + +Qualquer data de validade futura e qualquer código de segurança bem formado +funcionam no sandbox. + +## Próximos passos + +- [Arquitetura](architecture.md) — como o SDK é organizado internamente +- [Componentes de UI](ui-components.md) — o formulário Compose, a interoperabilidade com XML e a acessibilidade +- [Internacionalização](internationalization.md) — idiomas e substituições +- [Contribuindo](contributing.md) — como compilar e testar o projeto você mesmo diff --git a/docs/pt/internationalization.md b/docs/pt/internationalization.md new file mode 100644 index 0000000..ace2ac4 --- /dev/null +++ b/docs/pt/internationalization.md @@ -0,0 +1,66 @@ +# Internacionalização + +Todo texto que o SDK exibe — rótulos, erros de validação, descrições de +acessibilidade — está disponível em: + +| Idioma | Tag | +|---|---| +| Inglês (padrão e fallback) | `en` | +| Espanhol | `es` | +| Português | `pt` | +| Francês | `fr` | + +## Resolução automática + +Por padrão, o SDK segue o **idioma do dispositivo**, incluindo variantes +regionais (`es-MX`, `pt-BR`, `fr-CA`, …). Dispositivos configurados em +qualquer outro idioma recorrem ao inglês. Não há nada a configurar. + +## Forçando um idioma + +Alguns apps permitem que os usuários escolham um idioma independentemente +das configurações do sistema. Defina a substituição uma vez e todos os +componentes do SDK na tela são atualizados imediatamente: + +```kotlin +import mx.dev1.openpay.sdk.i18n.OpenpayLanguage +import mx.dev1.openpay.sdk.i18n.OpenpayLocale + +OpenpayLocale.override = OpenpayLanguage.PORTUGUESE // força o português +OpenpayLocale.override = null // volta ao automático +``` + +A substituição é um estado observável do Compose: os composables do SDK +recompõem ao vivo quando ela muda, sem necessidade de reiniciar. + +## Apps baseados em views + +Se você exibe strings do SDK a partir do seu próprio código de views, +resolva-as por meio de um contexto localizado: + +```kotlin +val localizedContext = OpenpayLocale.localize(context) +val label = localizedContext.getString(R.string.openpay_card_number_label) +``` + +`localize` retorna o contexto sem alterações quando nenhuma substituição +está definida. + +## Fluxo + +```mermaid +flowchart TD + start([O SDK precisa de uma string]) --> hasOverride{OpenpayLocale.override definido?} + hasOverride -- sim --> forced[Resolve os recursos no idioma forçado] + hasOverride -- não --> device{Idioma do dispositivo incluído?} + device -- "es / pt / fr / en" --> auto[Resolve os recursos no idioma do dispositivo] + device -- outro --> fallback[Recorre ao inglês] +``` + +## Adicionando um idioma + +As traduções vivem nos recursos Android do SDK +(`openpay-sdk/src/main/res/values-/strings.xml`). Para propor um novo +idioma, copie `values/strings.xml`, traduza todas as entradas, adicione a +tag em `OpenpayLanguage` e abra um pull request — veja +[Contribuindo](contributing.md). diff --git a/docs/pt/ui-components.md b/docs/pt/ui-components.md new file mode 100644 index 0000000..c1fe4fc --- /dev/null +++ b/docs/pt/ui-components.md @@ -0,0 +1,189 @@ +# Componentes de UI + +O SDK inclui um kit de captura de cartão feito primeiro para Compose. Você +pode usar o formulário completo, campos individuais ou envolver o formulário +em um layout XML. + +## O formulário completo + +```kotlin +import mx.dev1.openpay.sdk.ui.components.OpenpayCardForm +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme + +OpenpayTheme { // opcional: herde seu próprio MaterialTheme em vez disso + OpenpayCardForm( + onCardValidated = { card -> /* tokenize-o */ }, + ) +} +``` + +O formulário contém o nome do titular, o número do cartão (com detecção de +bandeira em tempo real), a validade MM/AA e o código de segurança mascarado, +além de um botão de envio. `onCardValidated` é disparado **apenas** quando +todos os campos passam na validação; campos inválidos são destacados com +mensagens de erro traduzidas. + +### Implementação com o formulário nativo + +O callback entrega um `Card` validado; tokenize-o e envie o id do token +para o seu backend: + +```kotlin +val scope = rememberCoroutineScope() + +OpenpayCardForm( + onCardValidated = { card -> + scope.launch { + openpay.createToken(card) + .onSuccess { token -> /* envie token.tokenId ao seu backend */ } + .onFailure { error -> /* mostre o erro */ } + } + }, +) +``` + +Veja [Primeiros passos](getting-started.md) para construir a instância +`openpay` com o seu id de comerciante e chave pública. + +### Controlando o estado você mesmo + +```kotlin +val formState = rememberOpenpayCardFormState() + +OpenpayCardForm( + state = formState, + onCardValidated = { card -> ... }, +) + +// em outro lugar: formState.cardNumber, formState.detectedBrand, +// formState.validate(), formState.isFieldInvalid(CardField.CARD_NUMBER) +``` + +Por segurança, o estado do formulário **não** é persistido quando o processo +é encerrado — os dados do cartão nunca tocam o disco. + +## Implementação com inputs personalizados + +Cada campo é público e pode ser composto no seu próprio layout mantendo a +formatação e a validação do SDK: + +- `OpenpayHolderNameField` +- `OpenpayCardNumberField` — formatação em grupos (4-4-4-4, Amex 4-6-5) +- `OpenpayExpirationField` — formatação visual MM/AA sobre os dígitos MMAA +- `OpenpaySecurityCodeField` — entrada mascarada, comprimento conforme a + bandeira (4 para Amex, 3 nos demais casos) + +Conecte-os ao `rememberOpenpayCardFormState()`, que guarda apenas dígitos, +detecta a bandeira e valida todos os campos: + +```kotlin +val formState = rememberOpenpayCardFormState() + +Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OpenpayCardPreview( // opcional: inclui cores e logo da bandeira + holderName = formState.holderName, + cardNumber = formState.cardNumber, + expiration = formState.expiration, + ) + OpenpayHolderNameField( + value = formState.holderName, + onValueChange = formState::updateHolderName, + isError = formState.isFieldInvalid(CardField.HOLDER_NAME), + ) + OpenpayCardNumberField( + value = formState.cardNumber, + onValueChange = formState::updateCardNumber, + isError = formState.isFieldInvalid(CardField.CARD_NUMBER), + ) + OpenpayExpirationField( + value = formState.expiration, + onValueChange = formState::updateExpiration, + isError = formState.isFieldInvalid(CardField.EXPIRATION), + ) + OpenpaySecurityCodeField( + value = formState.securityCode, + onValueChange = formState::updateSecurityCode, + isError = formState.isFieldInvalid(CardField.SECURITY_CODE), + ) + Button(onClick = { + formState.validate()?.let { card -> /* createToken(card) como acima */ } + }) { + Text("Pagar") + } +} +``` + +`formState.validate()` retorna o `Card` pronto para tokenização quando +todos os campos são válidos; caso contrário retorna null e marca os campos +com falha para que `isFieldInvalid` os destaque. + +## Identidade de marca na pré-visualização + +A pré-visualização do cartão reage à bandeira detectada: + +| Bandeira | Fundo do cartão | Logo | +|---|---|---| +| Visa | Gradiente azul-marinho → amarelo (70% azul) | Logotipo da Visa | +| Mastercard | Gradiente laranja → amarelo | Círculos da Mastercard | +| American Express | Azul sólido | Logo da Amex | +| Desconhecida | Gradiente cinza neutro | nenhum | + +O logo fica no canto superior direito da pré-visualização e aparece assim +que o prefixo do número identifica a bandeira. + +Para mostrar o mesmo logo ao lado do resultado da tokenização (a API +devolve a bandeira como string, por exemplo `"visa"`), use o badge público: + +```kotlin +import mx.dev1.openpay.sdk.domain.validation.CardBrand +import mx.dev1.openpay.sdk.ui.components.OpenpayCardBrandLogo + +OpenpayCardBrandLogo(brand = CardBrand.fromBrandName(token.card?.brand)) +``` + +O badge desenha o logo branco sobre a cor da sua bandeira, não mostra nada +para bandeiras desconhecidas e anuncia o nome da bandeira ("Visa", +"Mastercard", "American Express") aos leitores de tela. + +## Interoperabilidade com XML + +Apps baseados em views obtêm o mesmo formulário sem nenhum código Compose: + +```xml + +``` + +```kotlin +findViewById(R.id.openpay_card_form).onCardValidated = { card -> + // tokenize-o +} +``` + +## Acessibilidade + +Os componentes são projetados para que as tecnologias assistivas não percam +nada: + +- Cada campo expõe seu **rótulo e texto de erro por meio da semântica**, de + modo que o TalkBack anuncia "Número do cartão, erro, insira um número de + cartão válido". +- O selo da bandeira detectada tem uma descrição de conteúdo ("Marca do + cartão detectada: VISA"). +- O código de segurança é mascarado visualmente **e** descrito como oculto + para o leitor de tela; o teclado muda para `NumberPassword`. +- As áreas de toque respeitam o mínimo de **48dp** do Material. +- As cores de erro vêm dos papéis de erro do Material 3, preservando o + contraste nos temas claro e escuro. +- Todos os textos são traduzidos (veja + [Internacionalização](internationalization.md)), incluindo as descrições + de acessibilidade. + +## Temas + +`OpenpayTheme` aplica a paleta da Openpay sobre o Material 3 com suporte +automático a temas claro e escuro. Se o seu app já define um +`MaterialTheme`, basta omitir o `OpenpayTheme` e os componentes do SDK +herdarão suas cores, tipografia e formas. diff --git a/gradle.properties b/gradle.properties index 20e2a01..201f55b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -20,4 +20,9 @@ kotlin.code.style=official # Enables namespacing of each library's R class so that its R class includes only the # resources declared in the library itself and none from the library's dependencies, # thereby reducing the size of the R class for that library -android.nonTransitiveRClass=true \ No newline at end of file +android.nonTransitiveRClass=true + +# Maven coordinates of the published SDK artifact. +# VERSION_NAME must stay aligned with OpenpaySdk.VERSION. +GROUP=mx.dev1.openpay +VERSION_NAME=1.0.0 \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 75c5705..7223c30 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,20 +1,77 @@ [versions] agp = "9.0.1" -coreKtx = "1.19.0" +kotlin = "2.2.20" +# androidx.core 1.19.0 requires compileSdk 37 / AGP 9.1; 1.17.0 is the newest +# release compatible with compileSdk 36 and AGP 9.0. +coreKtx = "1.17.0" +appcompat = "1.8.0" +material = "1.14.0" +activityCompose = "1.11.0" +composeBom = "2025.09.00" +lifecycleRuntimeKtx = "2.9.2" +navigationCompose = "2.9.4" +koin = "4.1.0" +ktor = "3.2.3" +kotlinxSerializationJson = "1.9.0" +kotlinxCoroutines = "1.10.2" junit = "4.13.2" junitVersion = "1.3.0" espressoCore = "3.7.0" -appcompat = "1.8.0" -material = "1.14.0" +mockitoCore = "5.18.0" +mockitoKotlin = "6.0.0" +robolectric = "4.16" +jacoco = "0.8.13" [libraries] androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } +androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } +material = { group = "com.google.android.material", name = "material", version.ref = "material" } + +# Compose +androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" } +androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" } +androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" } +androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" } +androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" } +androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" } +androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" } +androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" } +androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" } +androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" } +androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" } +androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycleRuntimeKtx" } + +# Koin (dependency injection) +koin-bom = { group = "io.insert-koin", name = "koin-bom", version.ref = "koin" } +koin-android = { group = "io.insert-koin", name = "koin-android" } +koin-androidx-compose = { group = "io.insert-koin", name = "koin-androidx-compose" } +koin-test = { group = "io.insert-koin", name = "koin-test" } +koin-test-junit4 = { group = "io.insert-koin", name = "koin-test-junit4" } + +# Ktor (HTTP client) +ktor-client-core = { group = "io.ktor", name = "ktor-client-core", version.ref = "ktor" } +ktor-client-cio = { group = "io.ktor", name = "ktor-client-cio", version.ref = "ktor" } +ktor-client-content-negotiation = { group = "io.ktor", name = "ktor-client-content-negotiation", version.ref = "ktor" } +ktor-client-logging = { group = "io.ktor", name = "ktor-client-logging", version.ref = "ktor" } +ktor-client-mock = { group = "io.ktor", name = "ktor-client-mock", version.ref = "ktor" } +ktor-serialization-kotlinx-json = { group = "io.ktor", name = "ktor-serialization-kotlinx-json", version.ref = "ktor" } + +# Kotlinx +kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" } +kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" } +kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "kotlinxCoroutines" } + +# Testing junit = { group = "junit", name = "junit", version.ref = "junit" } androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" } androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" } -androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } -material = { group = "com.google.android.material", name = "material", version.ref = "material" } +mockito-core = { group = "org.mockito", name = "mockito-core", version.ref = "mockitoCore" } +mockito-kotlin = { group = "org.mockito.kotlin", name = "mockito-kotlin", version.ref = "mockitoKotlin" } +robolectric = { group = "org.robolectric", name = "robolectric", version.ref = "robolectric" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" } - +android-library = { id = "com.android.library", version.ref = "agp" } +kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } +kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } +kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } diff --git a/openpay-sdk/.gitignore b/openpay-sdk/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/openpay-sdk/.gitignore @@ -0,0 +1 @@ +/build diff --git a/openpay-sdk/build.gradle.kts b/openpay-sdk/build.gradle.kts new file mode 100644 index 0000000..48909ea --- /dev/null +++ b/openpay-sdk/build.gradle.kts @@ -0,0 +1,172 @@ +plugins { + alias(libs.plugins.android.library) + alias(libs.plugins.kotlin.compose) + alias(libs.plugins.kotlin.serialization) + `maven-publish` + signing +} + +android { + namespace = "mx.dev1.openpay.sdk" + compileSdk { + version = release(36) { + minorApiLevel = 1 + } + } + + defaultConfig { + minSdk = 26 + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + consumerProguardFiles("consumer-rules.pro") + } + + buildTypes { + debug { + enableUnitTestCoverage = true + } + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + + buildFeatures { + compose = true + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + + testOptions { + unitTests { + isIncludeAndroidResources = true + } + } + + publishing { + singleVariant("release") { + withSourcesJar() + withJavadocJar() + } + } +} + +publishing { + publications { + register("release") { + groupId = project.property("GROUP").toString() + artifactId = "openpay-sdk" + version = project.property("VERSION_NAME").toString() + + afterEvaluate { + from(components["release"]) + } + + pom { + name.set("Openpay Android SDK") + description.set( + "Kotlin-first Openpay SDK for Android: card tokenization, validation, " + + "antifraud device sessions and Compose UI components." + ) + url.set("https://github.com/DEV1-Softworks/openpay-android") + licenses { + license { + name.set("The Apache License, Version 2.0") + url.set("https://www.apache.org/licenses/LICENSE-2.0.txt") + } + } + developers { + developer { + id.set("dev1-softworks") + name.set("DEV1 Softworks Labs") + url.set("https://labs.dev1.mx") + } + } + scm { + connection.set("scm:git:git://github.com/DEV1-Softworks/openpay-android.git") + developerConnection.set("scm:git:ssh://github.com/DEV1-Softworks/openpay-android.git") + url.set("https://github.com/DEV1-Softworks/openpay-android") + } + } + } + } + + repositories { + // Remote repository configured entirely through environment variables so + // credentials never live in the build. Skipped when the URL is absent + // (publishToMavenLocal keeps working without any setup). + val remoteRepositoryUrl = System.getenv("MAVEN_REPOSITORY_URL") + if (remoteRepositoryUrl != null) { + maven { + name = "remote" + url = uri(remoteRepositoryUrl) + credentials { + username = System.getenv("MAVEN_REPOSITORY_USERNAME") + password = System.getenv("MAVEN_REPOSITORY_PASSWORD") + } + } + } + } +} + +signing { + // In-memory PGP signing, enabled only when the key material is provided + // (for example on the release CI). Local builds stay unsigned. + val signingKey = System.getenv("SIGNING_KEY") + val signingPassword = System.getenv("SIGNING_PASSWORD") + if (signingKey != null) { + useInMemoryPgpKeys(signingKey, signingPassword) + sign(publishing.publications) + } +} + +dependencies { + implementation(libs.androidx.core.ktx) + implementation(libs.kotlinx.coroutines.android) + implementation(libs.kotlinx.serialization.json) + + // HTTP client + implementation(libs.ktor.client.core) + implementation(libs.ktor.client.cio) + implementation(libs.ktor.client.content.negotiation) + implementation(libs.ktor.client.logging) + implementation(libs.ktor.serialization.kotlinx.json) + + // Dependency injection + implementation(platform(libs.koin.bom)) + implementation(libs.koin.android) + implementation(libs.koin.androidx.compose) + + // Compose + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.graphics) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.compose.material3) + debugImplementation(libs.androidx.compose.ui.tooling) + debugImplementation(libs.androidx.compose.ui.test.manifest) + + testImplementation(libs.junit) + testImplementation(libs.androidx.junit) + testImplementation(libs.mockito.core) + testImplementation(libs.mockito.kotlin) + testImplementation(libs.robolectric) + testImplementation(libs.kotlinx.coroutines.test) + testImplementation(libs.ktor.client.mock) + testImplementation(platform(libs.koin.bom)) + testImplementation(libs.koin.test) + testImplementation(libs.koin.test.junit4) + testImplementation(platform(libs.androidx.compose.bom)) + testImplementation(libs.androidx.compose.ui.test.junit4) + + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) + androidTestImplementation(platform(libs.androidx.compose.bom)) + androidTestImplementation(libs.androidx.compose.ui.test.junit4) +} diff --git a/openpay-sdk/consumer-rules.pro b/openpay-sdk/consumer-rules.pro new file mode 100644 index 0000000..875d249 --- /dev/null +++ b/openpay-sdk/consumer-rules.pro @@ -0,0 +1,9 @@ +# Rules applied automatically to consumers of the openpay-sdk AAR. + +# Keep the serializable API models so kotlinx.serialization keeps working after R8. +-keepclassmembers @kotlinx.serialization.Serializable class mx.dev1.openpay.sdk.** { + *** Companion; +} +-keepclasseswithmembers class mx.dev1.openpay.sdk.** { + kotlinx.serialization.KSerializer serializer(...); +} diff --git a/openpay-sdk/proguard-rules.pro b/openpay-sdk/proguard-rules.pro new file mode 100644 index 0000000..bc19667 --- /dev/null +++ b/openpay-sdk/proguard-rules.pro @@ -0,0 +1,3 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle.kts. diff --git a/openpay-sdk/src/main/AndroidManifest.xml b/openpay-sdk/src/main/AndroidManifest.xml new file mode 100644 index 0000000..5e7684f --- /dev/null +++ b/openpay-sdk/src/main/AndroidManifest.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/Openpay.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/Openpay.kt new file mode 100644 index 0000000..5d808e7 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/Openpay.kt @@ -0,0 +1,130 @@ +package mx.dev1.openpay.sdk + +import android.app.Activity +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import mx.dev1.openpay.sdk.antifraud.DeviceSessionCollector +import mx.dev1.openpay.sdk.core.OpenpayConfig +import mx.dev1.openpay.sdk.core.OpenpayCountry +import mx.dev1.openpay.sdk.core.OpenpayEnvironment +import mx.dev1.openpay.sdk.core.OpenpayException +import mx.dev1.openpay.sdk.di.OpenpayKoinContext +import mx.dev1.openpay.sdk.di.openpayAntifraudModule +import mx.dev1.openpay.sdk.di.openpayDataModule +import mx.dev1.openpay.sdk.domain.model.Card +import mx.dev1.openpay.sdk.domain.model.Token +import mx.dev1.openpay.sdk.domain.usecase.CreateTokenUseCase + +/** + * Entry point of the Openpay SDK. + * + * ```kotlin + * val openpay = Openpay( + * OpenpayConfig( + * merchantId = "your-merchant-id", + * publicApiKey = "pk_your_public_key", + * country = OpenpayCountry.MEXICO, + * environment = OpenpayEnvironment.SANDBOX, + * ) + * ) + * val tokenResult = openpay.createToken(card) + * ``` + * + * Only one [Openpay] instance should be alive at a time; creating a new + * instance rebuilds the SDK dependency graph with the new configuration. + */ +class Openpay internal constructor( + private val createTokenUseCase: CreateTokenUseCase, + private val deviceSessionCollector: DeviceSessionCollector, + backgroundDispatcher: CoroutineDispatcher, + private val callbackDispatcher: CoroutineDispatcher, +) { + + /** Creates the SDK from a full [OpenpayConfig]. */ + constructor(config: OpenpayConfig) : this( + createTokenUseCase = bootDependencies(config), + deviceSessionCollector = OpenpayKoinContext.koin.get(), + backgroundDispatcher = Dispatchers.IO, + callbackDispatcher = Dispatchers.Main.immediate, + ) + + /** + * Legacy-style convenience constructor mirroring + * `Openpay(merchantId, publicApiKey, productionMode, country)`. + */ + constructor( + merchantId: String, + publicApiKey: String, + productionMode: Boolean = false, + country: OpenpayCountry = OpenpayCountry.MEXICO, + ) : this( + OpenpayConfig( + merchantId = merchantId, + publicApiKey = publicApiKey, + country = country, + environment = if (productionMode) OpenpayEnvironment.PRODUCTION else OpenpayEnvironment.SANDBOX, + ) + ) + + private val sdkScope = CoroutineScope(SupervisorJob() + backgroundDispatcher) + + /** + * Validates [card] locally and exchanges it for a token. + * The failure inside the returned [Result] is always an [OpenpayException]. + */ + suspend fun createToken(card: Card): Result = + try { + Result.success(createTokenUseCase(card)) + } catch (openpayError: OpenpayException) { + Result.failure(openpayError) + } + + /** + * Callback flavor of [createToken] for consumers without coroutines. + * The callback runs on the Android main thread. + */ + fun createToken(card: Card, callback: OpenpayCallback) { + sdkScope.launch { + val tokenResult = createToken(card) + withContext(callbackDispatcher) { + tokenResult.fold( + onSuccess = callback::onSuccess, + onFailure = { failure -> callback.onError(failure as OpenpayException) }, + ) + } + } + } + + /** + * Starts the antifraud device fingerprint collection and returns the + * device session id. Send this id to your backend together with the + * token when creating the charge. Must be called from the main thread. + */ + fun setupDeviceSession(activity: Activity): String = + deviceSessionCollector.collect(activity) + + /** + * Cancels in-flight operations and releases the SDK dependency graph. + * Call it when the SDK is no longer needed (for example on logout). + */ + fun shutdown() { + sdkScope.cancel() + OpenpayKoinContext.stop() + } + + private companion object { + + fun bootDependencies(config: OpenpayConfig): CreateTokenUseCase { + OpenpayKoinContext.start( + config = config, + extraModules = listOf(openpayDataModule(), openpayAntifraudModule()), + ) + return OpenpayKoinContext.koin.get() + } + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/OpenpayCallback.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/OpenpayCallback.kt new file mode 100644 index 0000000..2d87e56 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/OpenpayCallback.kt @@ -0,0 +1,20 @@ +package mx.dev1.openpay.sdk + +import mx.dev1.openpay.sdk.core.OpenpayException + +/** + * Callback for consumers that do not use coroutines. Both methods are + * invoked on the Android main thread. + */ +interface OpenpayCallback { + + fun onSuccess(result: ResultType) + + /** + * Called with the failure cause: + * [OpenpayException.ValidationError] for local validation failures, + * [OpenpayException.ServiceError] for API rejections and + * [OpenpayException.ConnectionError] for connectivity problems. + */ + fun onError(exception: OpenpayException) +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/OpenpaySdk.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/OpenpaySdk.kt new file mode 100644 index 0000000..a00f790 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/OpenpaySdk.kt @@ -0,0 +1,18 @@ +package mx.dev1.openpay.sdk + +/** + * Global information about the Openpay SDK artifact. + */ +object OpenpaySdk { + + /** Version reported to the Openpay API through the user agent. */ + const val VERSION: String = "1.0.0" + + /** User agent sent on every HTTP request made by the SDK. */ + val userAgent: String = buildUserAgent(VERSION) + + internal fun buildUserAgent(version: String): String { + require(version.isNotBlank()) { "The SDK version must not be blank" } + return "openpay-android/$version" + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/antifraud/DeviceSessionCollector.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/antifraud/DeviceSessionCollector.kt new file mode 100644 index 0000000..bce2879 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/antifraud/DeviceSessionCollector.kt @@ -0,0 +1,17 @@ +package mx.dev1.openpay.sdk.antifraud + +import android.app.Activity + +/** + * Collects the device fingerprint Openpay uses for antifraud analysis. + * The returned session id must be sent to the merchant backend together + * with the token when creating a charge. + */ +interface DeviceSessionCollector { + + /** + * Starts the fingerprint collection and returns the device session id. + * Must be called from the main thread. + */ + fun collect(activity: Activity): String +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/antifraud/DeviceSessionIdGenerator.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/antifraud/DeviceSessionIdGenerator.kt new file mode 100644 index 0000000..a0cc0dd --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/antifraud/DeviceSessionIdGenerator.kt @@ -0,0 +1,13 @@ +package mx.dev1.openpay.sdk.antifraud + +import java.util.UUID + +/** + * Generates the random session identifiers that link a device fingerprint + * with a tokenization request. + */ +internal class DeviceSessionIdGenerator { + + /** Returns a 32 character hexadecimal identifier. */ + fun generate(): String = UUID.randomUUID().toString().replace("-", "") +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/antifraud/WebViewDeviceSessionCollector.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/antifraud/WebViewDeviceSessionCollector.kt new file mode 100644 index 0000000..b3ba9ee --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/antifraud/WebViewDeviceSessionCollector.kt @@ -0,0 +1,42 @@ +package mx.dev1.openpay.sdk.antifraud + +import android.annotation.SuppressLint +import android.app.Activity +import android.webkit.WebView +import android.webkit.WebViewClient +import mx.dev1.openpay.sdk.core.OpenpayConfig + +/** + * Replicates the legacy antifraud collection: a short lived, invisible + * WebView loads the Openpay fingerprint page passing the merchant id and a + * fresh session id. The WebView is destroyed as soon as the page finishes. + * + * @param webViewProvider indirection over `WebView(activity)` so tests can + * observe the WebView the collector drives. + */ +internal class WebViewDeviceSessionCollector( + private val config: OpenpayConfig, + private val sessionIdGenerator: DeviceSessionIdGenerator, + private val webViewProvider: (Activity) -> WebView = ::WebView, +) : DeviceSessionCollector { + + @SuppressLint("SetJavaScriptEnabled") + override fun collect(activity: Activity): String { + val deviceSessionId = sessionIdGenerator.generate() + val fingerprintUrl = buildFingerprintUrl(deviceSessionId) + + val fingerprintWebView = webViewProvider(activity) + fingerprintWebView.settings.javaScriptEnabled = true + fingerprintWebView.webViewClient = object : WebViewClient() { + override fun onPageFinished(finishedView: WebView, url: String) { + finishedView.destroy() + } + } + fingerprintWebView.loadUrl(fingerprintUrl) + + return deviceSessionId + } + + private fun buildFingerprintUrl(deviceSessionId: String): String = + "${config.baseUrl}/oa/logo.htm?m=${config.merchantId}&s=$deviceSessionId" +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayConfig.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayConfig.kt new file mode 100644 index 0000000..404afee --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayConfig.kt @@ -0,0 +1,25 @@ +package mx.dev1.openpay.sdk.core + +/** + * Immutable configuration required to talk to the Openpay API. + * + * @property merchantId Merchant identifier assigned by Openpay when the account was created. + * @property publicApiKey Public API key of the merchant. Never use the private key inside an app. + * @property country Country of the merchant account, defines the API host. + * @property environment Sandbox or production environment. + */ +data class OpenpayConfig( + val merchantId: String, + val publicApiKey: String, + val country: OpenpayCountry = OpenpayCountry.MEXICO, + val environment: OpenpayEnvironment = OpenpayEnvironment.SANDBOX, +) { + + init { + require(merchantId.isNotBlank()) { "merchantId must not be blank" } + require(publicApiKey.isNotBlank()) { "publicApiKey must not be blank" } + } + + /** API base URL resolved from [country] and [environment]. */ + val baseUrl: String = country.baseUrlFor(environment) +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayCountry.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayCountry.kt new file mode 100644 index 0000000..47fbce8 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayCountry.kt @@ -0,0 +1,20 @@ +package mx.dev1.openpay.sdk.core + +/** + * Countries where Openpay operates, each with its own API host. + */ +enum class OpenpayCountry( + private val sandboxBaseUrl: String, + private val productionBaseUrl: String, +) { + MEXICO("https://sandbox-api.openpay.mx", "https://api.openpay.mx"), + COLOMBIA("https://sandbox-api.openpay.co", "https://api.openpay.co"), + PERU("https://sandbox-api.openpay.pe", "https://api.openpay.pe"); + + /** Resolves the API base URL for this country in the given [environment]. */ + fun baseUrlFor(environment: OpenpayEnvironment): String = + when (environment) { + OpenpayEnvironment.SANDBOX -> sandboxBaseUrl + OpenpayEnvironment.PRODUCTION -> productionBaseUrl + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayEnvironment.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayEnvironment.kt new file mode 100644 index 0000000..2738dc0 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayEnvironment.kt @@ -0,0 +1,10 @@ +package mx.dev1.openpay.sdk.core + +/** + * Openpay API environments. Use [SANDBOX] while integrating and testing, + * and [PRODUCTION] for live payments. + */ +enum class OpenpayEnvironment { + SANDBOX, + PRODUCTION, +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayException.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayException.kt new file mode 100644 index 0000000..19981c5 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayException.kt @@ -0,0 +1,43 @@ +package mx.dev1.openpay.sdk.core + +import mx.dev1.openpay.sdk.domain.validation.CardValidationResult + +/** + * Base type for every error surfaced by the Openpay SDK. + */ +sealed class OpenpayException(message: String, cause: Throwable? = null) : Exception(message, cause) { + + /** + * The card failed local validation before any network call was made. + * [validationResult] lists every field that must be corrected. + */ + class ValidationError( + val validationResult: CardValidationResult, + ) : OpenpayException("The card data is not valid: ${validationResult.invalidFields}") + + /** + * The Openpay API rejected the request. Mirrors the error body documented at + * https://documents.openpay.mx/docs/api/#errores + * + * @property errorCode Openpay-specific error code (for example 1001 for a malformed request). + * @property category Error category reported by the API: request, internal or gateway. + * @property httpStatus HTTP status code of the rejected response. + * @property requestId Identifier of the request inside Openpay, useful for support tickets. + */ + class ServiceError( + val errorCode: Int, + val category: String?, + val httpStatus: Int, + val requestId: String?, + description: String, + ) : OpenpayException(description) + + /** + * The Openpay API could not be reached (no connectivity, DNS failure, timeout) + * or returned a response the SDK could not understand. + */ + class ConnectionError( + message: String, + cause: Throwable? = null, + ) : OpenpayException(message, cause) +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/mapper/AddressMapper.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/mapper/AddressMapper.kt new file mode 100644 index 0000000..aa7c661 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/mapper/AddressMapper.kt @@ -0,0 +1,31 @@ +package mx.dev1.openpay.sdk.data.mapper + +import mx.dev1.openpay.sdk.data.remote.dto.AddressDto +import mx.dev1.openpay.sdk.domain.model.Address + +internal fun Address.toDto(): AddressDto = + AddressDto( + line1 = line1, + line2 = line2, + line3 = line3, + postalCode = postalCode, + city = city, + state = state, + countryCode = countryCode, + ) + +internal fun AddressDto.toDomain(): Address? { + val requiredFields = listOf(line1, postalCode, city, state, countryCode) + if (requiredFields.any { it == null }) { + return null + } + return Address( + line1 = checkNotNull(line1), + line2 = line2, + line3 = line3, + postalCode = checkNotNull(postalCode), + city = checkNotNull(city), + state = checkNotNull(state), + countryCode = checkNotNull(countryCode), + ) +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/mapper/CardMapper.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/mapper/CardMapper.kt new file mode 100644 index 0000000..e04fba4 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/mapper/CardMapper.kt @@ -0,0 +1,30 @@ +package mx.dev1.openpay.sdk.data.mapper + +import mx.dev1.openpay.sdk.data.remote.dto.CardDto +import mx.dev1.openpay.sdk.domain.model.Card +import mx.dev1.openpay.sdk.domain.model.TokenizedCard + +internal fun Card.toRequestDto(): CardDto = + CardDto( + cardNumber = cardNumber, + holderName = holderName, + expirationMonth = formattedExpirationMonth, + expirationYear = formattedExpirationYear, + securityCode = securityCode, + address = address?.toDto(), + ) + +internal fun CardDto.toDomain(): TokenizedCard = + TokenizedCard( + maskedCardNumber = cardNumber, + holderName = holderName, + expirationMonth = expirationMonth, + expirationYear = expirationYear, + brand = brand, + cardType = cardType, + bankName = bankName, + bankCode = bankCode, + allowsCharges = allowsCharges, + allowsPayouts = allowsPayouts, + address = address?.toDomain(), + ) diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/mapper/TokenMapper.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/mapper/TokenMapper.kt new file mode 100644 index 0000000..409d5ea --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/mapper/TokenMapper.kt @@ -0,0 +1,10 @@ +package mx.dev1.openpay.sdk.data.mapper + +import mx.dev1.openpay.sdk.data.remote.dto.TokenDto +import mx.dev1.openpay.sdk.domain.model.Token + +internal fun TokenDto.toDomain(): Token = + Token( + tokenId = tokenId, + card = card?.toDomain(), + ) diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayHttpClientFactory.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayHttpClientFactory.kt new file mode 100644 index 0000000..83f0392 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayHttpClientFactory.kt @@ -0,0 +1,59 @@ +package mx.dev1.openpay.sdk.data.remote + +import io.ktor.client.HttpClient +import io.ktor.client.engine.HttpClientEngine +import io.ktor.client.engine.cio.CIO +import io.ktor.client.plugins.HttpTimeout +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.client.plugins.defaultRequest +import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders +import io.ktor.http.contentType +import io.ktor.serialization.kotlinx.json.json +import java.util.Base64 +import kotlinx.serialization.json.Json +import mx.dev1.openpay.sdk.OpenpaySdk +import mx.dev1.openpay.sdk.core.OpenpayConfig + +/** + * Builds the Ktor [HttpClient] used for every Openpay API call. + * Requests authenticate with HTTP Basic using the merchant public key as + * username and an empty password, exactly like the legacy SDK. + */ +internal class OpenpayHttpClientFactory( + private val config: OpenpayConfig, + private val json: Json, +) { + + fun create(engine: HttpClientEngine = CIO.create()): HttpClient = + HttpClient(engine) { + expectSuccess = false + + install(ContentNegotiation) { + json(json) + } + + install(HttpTimeout) { + connectTimeoutMillis = CONNECTION_TIMEOUT_MILLIS + requestTimeoutMillis = CONNECTION_TIMEOUT_MILLIS + socketTimeoutMillis = CONNECTION_TIMEOUT_MILLIS + } + + defaultRequest { + url(config.baseUrl) + contentType(ContentType.Application.Json) + headers.append(HttpHeaders.Authorization, basicAuthorizationHeader(config.publicApiKey)) + headers.append(HttpHeaders.UserAgent, OpenpaySdk.userAgent) + } + } + + private fun basicAuthorizationHeader(publicApiKey: String): String { + val credentials = "$publicApiKey:" + val encodedCredentials = Base64.getEncoder().encodeToString(credentials.toByteArray(Charsets.UTF_8)) + return "Basic $encodedCredentials" + } + + private companion object { + const val CONNECTION_TIMEOUT_MILLIS = 60_000L + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayResponseHandler.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayResponseHandler.kt new file mode 100644 index 0000000..89238c3 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayResponseHandler.kt @@ -0,0 +1,46 @@ +package mx.dev1.openpay.sdk.data.remote + +import io.ktor.client.call.body +import io.ktor.client.statement.HttpResponse +import io.ktor.client.statement.bodyAsText +import kotlinx.serialization.json.Json +import mx.dev1.openpay.sdk.core.OpenpayException +import mx.dev1.openpay.sdk.data.remote.dto.OpenpayApiErrorDto + +/** + * Converts HTTP responses into API payloads or [OpenpayException]s. + */ +internal class OpenpayResponseHandler(private val json: Json) { + + /** + * Returns the deserialized body when the response is successful, otherwise + * throws [OpenpayException.ServiceError] built from the Openpay error body. + */ + suspend inline fun parse(response: HttpResponse): BodyType { + if (response.status.value in SUCCESSFUL_STATUS_RANGE) { + return response.body() + } + throw serviceErrorFrom(response) + } + + suspend fun serviceErrorFrom(response: HttpResponse): OpenpayException.ServiceError { + val rawBody = runCatching { response.bodyAsText() }.getOrDefault("") + val errorBody = runCatching { + json.decodeFromString(OpenpayApiErrorDto.serializer(), rawBody) + }.getOrNull() + + return OpenpayException.ServiceError( + errorCode = errorBody?.errorCode ?: UNKNOWN_ERROR_CODE, + category = errorBody?.category, + httpStatus = response.status.value, + requestId = errorBody?.requestId, + description = errorBody?.description + ?: "Openpay request failed with HTTP ${response.status.value}", + ) + } + + companion object { + val SUCCESSFUL_STATUS_RANGE = 200..299 + const val UNKNOWN_ERROR_CODE = -1 + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/AddressDto.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/AddressDto.kt new file mode 100644 index 0000000..d45cd27 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/AddressDto.kt @@ -0,0 +1,15 @@ +package mx.dev1.openpay.sdk.data.remote.dto + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +@Serializable +internal data class AddressDto( + @SerialName("line1") val line1: String? = null, + @SerialName("line2") val line2: String? = null, + @SerialName("line3") val line3: String? = null, + @SerialName("postal_code") val postalCode: String? = null, + @SerialName("city") val city: String? = null, + @SerialName("state") val state: String? = null, + @SerialName("country_code") val countryCode: String? = null, +) diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/CardDto.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/CardDto.kt new file mode 100644 index 0000000..6998386 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/CardDto.kt @@ -0,0 +1,25 @@ +package mx.dev1.openpay.sdk.data.remote.dto + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +/** + * Card payload for token creation requests and card echo inside token responses. + * Response-only fields stay null when serializing a request because of + * kotlinx.serialization default-value omission. + */ +@Serializable +internal data class CardDto( + @SerialName("card_number") val cardNumber: String? = null, + @SerialName("holder_name") val holderName: String? = null, + @SerialName("expiration_month") val expirationMonth: String? = null, + @SerialName("expiration_year") val expirationYear: String? = null, + @SerialName("cvv2") val securityCode: String? = null, + @SerialName("address") val address: AddressDto? = null, + @SerialName("brand") val brand: String? = null, + @SerialName("type") val cardType: String? = null, + @SerialName("bank_name") val bankName: String? = null, + @SerialName("bank_code") val bankCode: String? = null, + @SerialName("allows_charges") val allowsCharges: Boolean? = null, + @SerialName("allows_payouts") val allowsPayouts: Boolean? = null, +) diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/OpenpayApiErrorDto.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/OpenpayApiErrorDto.kt new file mode 100644 index 0000000..dd1ed67 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/OpenpayApiErrorDto.kt @@ -0,0 +1,17 @@ +package mx.dev1.openpay.sdk.data.remote.dto + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +/** + * Error body returned by the Openpay API. + * See https://documents.openpay.mx/docs/api/#errores + */ +@Serializable +internal data class OpenpayApiErrorDto( + @SerialName("category") val category: String? = null, + @SerialName("error_code") val errorCode: Int? = null, + @SerialName("description") val description: String? = null, + @SerialName("http_code") val httpCode: Int? = null, + @SerialName("request_id") val requestId: String? = null, +) diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/TokenDto.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/TokenDto.kt new file mode 100644 index 0000000..b4af7d7 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/TokenDto.kt @@ -0,0 +1,10 @@ +package mx.dev1.openpay.sdk.data.remote.dto + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +@Serializable +internal data class TokenDto( + @SerialName("id") val tokenId: String, + @SerialName("card") val card: CardDto? = null, +) diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/repository/RemoteTokenRepository.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/repository/RemoteTokenRepository.kt new file mode 100644 index 0000000..f95770c --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/repository/RemoteTokenRepository.kt @@ -0,0 +1,46 @@ +package mx.dev1.openpay.sdk.data.repository + +import io.ktor.client.HttpClient +import io.ktor.client.request.post +import io.ktor.client.request.setBody +import io.ktor.client.statement.HttpResponse +import mx.dev1.openpay.sdk.core.OpenpayConfig +import mx.dev1.openpay.sdk.core.OpenpayException +import mx.dev1.openpay.sdk.data.mapper.toDomain +import mx.dev1.openpay.sdk.data.mapper.toRequestDto +import mx.dev1.openpay.sdk.data.remote.OpenpayResponseHandler +import mx.dev1.openpay.sdk.data.remote.dto.TokenDto +import mx.dev1.openpay.sdk.domain.model.Card +import mx.dev1.openpay.sdk.domain.model.Token +import mx.dev1.openpay.sdk.domain.repository.TokenRepository + +/** + * [TokenRepository] backed by the Openpay REST API: + * POST {baseUrl}/v1/{merchantId}/tokens + */ +internal class RemoteTokenRepository( + private val httpClient: HttpClient, + private val responseHandler: OpenpayResponseHandler, + private val config: OpenpayConfig, +) : TokenRepository { + + override suspend fun createToken(card: Card): Token { + val response = executeTokenRequest(card) + val tokenDto = responseHandler.parse(response) + return tokenDto.toDomain() + } + + private suspend fun executeTokenRequest(card: Card): HttpResponse = + try { + httpClient.post("v1/${config.merchantId}/tokens") { + setBody(card.toRequestDto()) + } + } catch (interruption: kotlinx.coroutines.CancellationException) { + throw interruption + } catch (transportFailure: Exception) { + throw OpenpayException.ConnectionError( + message = "Could not reach the Openpay API", + cause = transportFailure, + ) + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayAntifraudModule.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayAntifraudModule.kt new file mode 100644 index 0000000..4ddd833 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayAntifraudModule.kt @@ -0,0 +1,20 @@ +package mx.dev1.openpay.sdk.di + +import mx.dev1.openpay.sdk.antifraud.DeviceSessionCollector +import mx.dev1.openpay.sdk.antifraud.DeviceSessionIdGenerator +import mx.dev1.openpay.sdk.antifraud.WebViewDeviceSessionCollector +import org.koin.dsl.module + +/** + * Koin definitions for the antifraud device fingerprint collection. + */ +internal fun openpayAntifraudModule() = module { + factory { DeviceSessionIdGenerator() } + + single { + WebViewDeviceSessionCollector( + config = get(), + sessionIdGenerator = get(), + ) + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayCoreModule.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayCoreModule.kt new file mode 100644 index 0000000..f149461 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayCoreModule.kt @@ -0,0 +1,29 @@ +package mx.dev1.openpay.sdk.di + +import kotlinx.serialization.json.Json +import mx.dev1.openpay.sdk.core.OpenpayConfig +import mx.dev1.openpay.sdk.data.remote.OpenpayHttpClientFactory +import mx.dev1.openpay.sdk.data.remote.OpenpayResponseHandler +import org.koin.dsl.module + +/** + * Koin definitions for the SDK core: JSON codec, HTTP client and response handling. + * The [OpenpayConfig] instance is provided by the SDK entry point at start time. + */ +internal fun openpayCoreModule(config: OpenpayConfig) = module { + single { config } + + single { + Json { + ignoreUnknownKeys = true + explicitNulls = false + encodeDefaults = false + } + } + + single { OpenpayHttpClientFactory(config = get(), json = get()) } + + single { get().create() } + + single { OpenpayResponseHandler(json = get()) } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayDataModule.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayDataModule.kt new file mode 100644 index 0000000..29e255e --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayDataModule.kt @@ -0,0 +1,29 @@ +package mx.dev1.openpay.sdk.di + +import java.time.Clock +import mx.dev1.openpay.sdk.data.repository.RemoteTokenRepository +import mx.dev1.openpay.sdk.domain.repository.TokenRepository +import mx.dev1.openpay.sdk.domain.usecase.CreateTokenUseCase +import org.koin.dsl.module + +/** + * Koin definitions for repositories and use cases. + */ +internal fun openpayDataModule() = module { + single { Clock.systemDefaultZone() } + + single { + RemoteTokenRepository( + httpClient = get(), + responseHandler = get(), + config = get(), + ) + } + + factory { + CreateTokenUseCase( + tokenRepository = get(), + clock = get(), + ) + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayKoinContext.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayKoinContext.kt new file mode 100644 index 0000000..d5b0fe8 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayKoinContext.kt @@ -0,0 +1,37 @@ +package mx.dev1.openpay.sdk.di + +import mx.dev1.openpay.sdk.core.OpenpayConfig +import org.koin.core.Koin +import org.koin.core.KoinApplication +import org.koin.core.module.Module +import org.koin.dsl.koinApplication + +/** + * Isolated Koin container for the SDK. Keeping the SDK graph in its own + * [KoinApplication] guarantees it never clashes with a host application + * that also uses Koin globally. + */ +internal object OpenpayKoinContext { + + private var application: KoinApplication? = null + + val koin: Koin + get() = checkNotNull(application) { + "The Openpay SDK has not been started. Create an Openpay instance first." + }.koin + + fun start(config: OpenpayConfig, extraModules: List = emptyList()) { + stop() + application = koinApplication { + modules(listOf(openpayCoreModule(config)) + extraModules) + } + } + + fun stop() { + application?.close() + application = null + } + + val isStarted: Boolean + get() = application != null +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/model/Address.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/model/Address.kt new file mode 100644 index 0000000..9b7f165 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/model/Address.kt @@ -0,0 +1,14 @@ +package mx.dev1.openpay.sdk.domain.model + +/** + * Billing address optionally attached to a card before tokenizing it. + */ +data class Address( + val line1: String, + val line2: String? = null, + val line3: String? = null, + val postalCode: String, + val city: String, + val state: String, + val countryCode: String, +) diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/model/Card.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/model/Card.kt new file mode 100644 index 0000000..48f410d --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/model/Card.kt @@ -0,0 +1,28 @@ +package mx.dev1.openpay.sdk.domain.model + +/** + * Card data captured from the user that will be exchanged for a token. + * + * @property holderName Name printed on the card. + * @property cardNumber Card number without spaces or dashes. + * @property expirationMonth Expiration month between 1 and 12. + * @property expirationYear Expiration year, either two digits (25) or four digits (2025). + * @property securityCode CVV2/CVC2 security code, 3 digits (4 for American Express). + */ +data class Card( + val holderName: String, + val cardNumber: String, + val expirationMonth: Int, + val expirationYear: Int, + val securityCode: String, + val address: Address? = null, +) { + + /** Expiration month as the two digit text expected by the Openpay API. */ + val formattedExpirationMonth: String + get() = expirationMonth.toString().padStart(2, '0') + + /** Expiration year reduced to its last two digits, as expected by the Openpay API. */ + val formattedExpirationYear: String + get() = (expirationYear % 100).toString().padStart(2, '0') +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/model/Token.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/model/Token.kt new file mode 100644 index 0000000..6653b52 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/model/Token.kt @@ -0,0 +1,28 @@ +package mx.dev1.openpay.sdk.domain.model + +/** + * Result of tokenizing a card. The [tokenId] replaces the card data when + * creating charges from the merchant's backend. + */ +data class Token( + val tokenId: String, + val card: TokenizedCard?, +) + +/** + * Card information echoed back by the Openpay API after tokenization. + * The card number comes masked, only the last four digits are visible. + */ +data class TokenizedCard( + val maskedCardNumber: String?, + val holderName: String?, + val expirationMonth: String?, + val expirationYear: String?, + val brand: String?, + val cardType: String?, + val bankName: String?, + val bankCode: String?, + val allowsCharges: Boolean?, + val allowsPayouts: Boolean?, + val address: Address?, +) diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/repository/TokenRepository.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/repository/TokenRepository.kt new file mode 100644 index 0000000..3491725 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/repository/TokenRepository.kt @@ -0,0 +1,18 @@ +package mx.dev1.openpay.sdk.domain.repository + +import mx.dev1.openpay.sdk.domain.model.Card +import mx.dev1.openpay.sdk.domain.model.Token + +/** + * Exchanges card data for Openpay tokens. + */ +interface TokenRepository { + + /** + * Creates a token for [card]. + * + * @throws mx.dev1.openpay.sdk.core.OpenpayException.ServiceError when the API rejects the card. + * @throws mx.dev1.openpay.sdk.core.OpenpayException.ConnectionError when the API cannot be reached. + */ + suspend fun createToken(card: Card): Token +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/usecase/CreateTokenUseCase.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/usecase/CreateTokenUseCase.kt new file mode 100644 index 0000000..7646a2d --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/usecase/CreateTokenUseCase.kt @@ -0,0 +1,31 @@ +package mx.dev1.openpay.sdk.domain.usecase + +import java.time.Clock +import mx.dev1.openpay.sdk.core.OpenpayException +import mx.dev1.openpay.sdk.domain.model.Card +import mx.dev1.openpay.sdk.domain.model.Token +import mx.dev1.openpay.sdk.domain.repository.TokenRepository +import mx.dev1.openpay.sdk.domain.validation.CardValidator + +/** + * Validates the card locally and, when valid, exchanges it for a token. + * Local validation avoids a network round trip for data the API would reject. + */ +class CreateTokenUseCase internal constructor( + private val tokenRepository: TokenRepository, + private val clock: Clock = Clock.systemDefaultZone(), +) { + + /** + * @throws OpenpayException.ValidationError when the card data is invalid. + * @throws OpenpayException.ServiceError when the API rejects the request. + * @throws OpenpayException.ConnectionError when the API cannot be reached. + */ + suspend operator fun invoke(card: Card): Token { + val validationResult = CardValidator.validate(card, clock) + if (!validationResult.isValid) { + throw OpenpayException.ValidationError(validationResult) + } + return tokenRepository.createToken(card) + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardBrand.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardBrand.kt new file mode 100644 index 0000000..794390b --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardBrand.kt @@ -0,0 +1,49 @@ +package mx.dev1.openpay.sdk.domain.validation + +/** + * Card brands recognized by the SDK, with the security code length each one uses. + */ +enum class CardBrand(val securityCodeLength: Int) { + VISA(securityCodeLength = 3), + MASTERCARD(securityCodeLength = 3), + AMERICAN_EXPRESS(securityCodeLength = 4), + UNKNOWN(securityCodeLength = 3); + + companion object { + + private val MASTERCARD_LEGACY_PREFIXES = 51..55 + private val MASTERCARD_2_SERIES_PREFIXES = 2221..2720 + private val AMERICAN_EXPRESS_PREFIXES = setOf("34", "37") + + private val BRAND_NAMES = mapOf( + "visa" to VISA, + "mastercard" to MASTERCARD, + "master_card" to MASTERCARD, + "american_express" to AMERICAN_EXPRESS, + "amex" to AMERICAN_EXPRESS, + ) + + /** + * Detects the brand from the card number prefix (IIN). Works with + * partial input, so UIs can show the brand while the user types. + */ + fun fromCardNumber(cardNumber: String): CardBrand { + val digits = cardNumber.filter(Char::isDigit) + return when { + digits.isEmpty() -> UNKNOWN + digits.startsWith("4") -> VISA + digits.take(2).toIntOrNull() in MASTERCARD_LEGACY_PREFIXES -> MASTERCARD + digits.take(4).toIntOrNull() in MASTERCARD_2_SERIES_PREFIXES -> MASTERCARD + digits.take(2) in AMERICAN_EXPRESS_PREFIXES -> AMERICAN_EXPRESS + else -> UNKNOWN + } + } + + /** + * Maps the brand name echoed by the Openpay API (for example "visa" + * or "american_express") to a [CardBrand], ignoring case. + */ + fun fromBrandName(brandName: String?): CardBrand = + BRAND_NAMES[brandName?.trim()?.lowercase()] ?: UNKNOWN + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardField.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardField.kt new file mode 100644 index 0000000..6d20429 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardField.kt @@ -0,0 +1,11 @@ +package mx.dev1.openpay.sdk.domain.validation + +/** + * Card fields that can fail validation, used to point errors to the right input. + */ +enum class CardField { + HOLDER_NAME, + CARD_NUMBER, + EXPIRATION, + SECURITY_CODE, +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardValidationResult.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardValidationResult.kt new file mode 100644 index 0000000..506ea7b --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardValidationResult.kt @@ -0,0 +1,13 @@ +package mx.dev1.openpay.sdk.domain.validation + +/** + * Outcome of validating a whole card. When [invalidFields] is empty the card + * is ready to be tokenized. + */ +data class CardValidationResult(val invalidFields: Set) { + + val isValid: Boolean + get() = invalidFields.isEmpty() + + fun isFieldValid(field: CardField): Boolean = field !in invalidFields +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardValidator.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardValidator.kt new file mode 100644 index 0000000..e53b22f --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardValidator.kt @@ -0,0 +1,93 @@ +package mx.dev1.openpay.sdk.domain.validation + +import java.time.Clock +import java.time.YearMonth +import mx.dev1.openpay.sdk.domain.model.Card + +/** + * Pure validation rules for card data, equivalent to the legacy SDK's + * CardValidator but with brand-aware security codes and clock injection + * for deterministic tests. + */ +object CardValidator { + + private val CARD_NUMBER_LENGTH_RANGE = 12..19 + private val HOLDER_NAME_LENGTH_RANGE = 2..80 + private val HOLDER_NAME_PATTERN = Regex("""[\p{L}][\p{L}\s.'-]*""") + private const val EXPIRATION_YEAR_CENTURY = 2000 + private const val MAXIMUM_YEARS_IN_FUTURE = 20L + + /** + * A card number is valid when it only contains digits (spaces and dashes + * are tolerated as separators), has a plausible length and passes Luhn. + */ + fun isValidCardNumber(cardNumber: String): Boolean { + val digits = normalizeCardNumber(cardNumber) + if (digits.isEmpty() || digits.any { !it.isDigit() }) { + return false + } + return digits.length in CARD_NUMBER_LENGTH_RANGE && passesLuhn(digits) + } + + /** Holder names accept letters (including accents), spaces, dots, apostrophes and hyphens. */ + fun isValidHolderName(holderName: String): Boolean { + val trimmedName = holderName.trim() + return trimmedName.length in HOLDER_NAME_LENGTH_RANGE && + HOLDER_NAME_PATTERN.matches(trimmedName) + } + + /** + * The security code must be numeric and match the brand length: + * 4 digits for American Express, 3 for every other brand. + */ + fun isValidSecurityCode(securityCode: String, cardNumber: String = ""): Boolean { + val expectedLength = CardBrand.fromCardNumber(cardNumber).securityCodeLength + return securityCode.length == expectedLength && securityCode.all(Char::isDigit) + } + + /** + * The expiration is valid from the current month up to [MAXIMUM_YEARS_IN_FUTURE] + * years ahead. Accepts two digit (27) or four digit (2027) years. + */ + fun isValidExpiration(expirationMonth: Int, expirationYear: Int, clock: Clock = Clock.systemDefaultZone()): Boolean { + if (expirationMonth !in 1..12 || expirationYear < 0) { + return false + } + val fullYear = if (expirationYear < 100) EXPIRATION_YEAR_CENTURY + expirationYear else expirationYear + val expiration = YearMonth.of(fullYear, expirationMonth) + val currentMonth = YearMonth.now(clock) + return !expiration.isBefore(currentMonth) && + expiration.isBefore(currentMonth.plusYears(MAXIMUM_YEARS_IN_FUTURE)) + } + + /** Validates the whole card and reports every field that failed. */ + fun validate(card: Card, clock: Clock = Clock.systemDefaultZone()): CardValidationResult { + val invalidFields = buildSet { + if (!isValidHolderName(card.holderName)) add(CardField.HOLDER_NAME) + if (!isValidCardNumber(card.cardNumber)) add(CardField.CARD_NUMBER) + if (!isValidExpiration(card.expirationMonth, card.expirationYear, clock)) add(CardField.EXPIRATION) + if (!isValidSecurityCode(card.securityCode, card.cardNumber)) add(CardField.SECURITY_CODE) + } + return CardValidationResult(invalidFields) + } + + private fun normalizeCardNumber(cardNumber: String): String = + cardNumber.replace(" ", "").replace("-", "") + + private fun passesLuhn(digits: String): Boolean { + var checksum = 0 + var shouldDoubleDigit = false + for (i in digits.indices.reversed()) { + var digitValue = digits[i] - '0' + if (shouldDoubleDigit) { + digitValue *= 2 + if (digitValue > 9) { + digitValue -= 9 + } + } + checksum += digitValue + shouldDoubleDigit = !shouldDoubleDigit + } + return checksum % 10 == 0 + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/i18n/OpenpayLanguage.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/i18n/OpenpayLanguage.kt new file mode 100644 index 0000000..f45a4d6 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/i18n/OpenpayLanguage.kt @@ -0,0 +1,20 @@ +package mx.dev1.openpay.sdk.i18n + +/** + * Languages bundled with the SDK. + */ +enum class OpenpayLanguage(val languageTag: String) { + ENGLISH("en"), + SPANISH("es"), + PORTUGUESE("pt"), + FRENCH("fr"); + + companion object { + + /** Resolves a language from a BCP-47 tag like "es" or "es-MX". */ + fun fromLanguageTag(languageTag: String): OpenpayLanguage? { + val primarySubtag = languageTag.substringBefore('-').lowercase() + return entries.firstOrNull { language -> language.languageTag == primarySubtag } + } + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/i18n/OpenpayLocale.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/i18n/OpenpayLocale.kt new file mode 100644 index 0000000..da1bfb8 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/i18n/OpenpayLocale.kt @@ -0,0 +1,42 @@ +package mx.dev1.openpay.sdk.i18n + +import android.content.Context +import android.content.res.Configuration +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import java.util.Locale + +/** + * Language selection for every text the SDK shows. + * + * By default the SDK follows the device locale automatically (falling back + * to English when the device language is not bundled). Assign [override] to + * force one of the bundled languages regardless of the device settings: + * + * ```kotlin + * OpenpayLocale.override = OpenpayLanguage.PORTUGUESE // force Portuguese + * OpenpayLocale.override = null // back to automatic + * ``` + * + * The override is observable Compose state, so SDK composables on screen + * recompose immediately when it changes. + */ +object OpenpayLocale { + + /** Forced language, or null to follow the device locale. */ + var override: OpenpayLanguage? by mutableStateOf(null) + + /** + * Returns [context] unchanged when no override is set, otherwise a + * context whose resources resolve in the overridden language. Useful for + * view-based apps; Compose content localizes itself automatically. + */ + fun localize(context: Context): Context { + val overrideLanguage = override ?: return context + val overrideLocale = Locale.forLanguageTag(overrideLanguage.languageTag) + val localizedConfiguration = Configuration(context.resources.configuration) + localizedConfiguration.setLocale(overrideLocale) + return context.createConfigurationContext(localizedConfiguration) + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/i18n/OpenpayLocalized.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/i18n/OpenpayLocalized.kt new file mode 100644 index 0000000..e4a5aa6 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/i18n/OpenpayLocalized.kt @@ -0,0 +1,31 @@ +package mx.dev1.openpay.sdk.i18n + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext + +/** + * Applies the [OpenpayLocale.override] to the composition so every + * stringResource call inside resolves in the overridden language. + * With no override the content composes untouched. + */ +@Composable +internal fun OpenpayLocalized(content: @Composable () -> Unit) { + val overrideLanguage = OpenpayLocale.override + if (overrideLanguage == null) { + content() + return + } + + val baseContext = LocalContext.current + val localizedContext = remember(overrideLanguage, baseContext) { + OpenpayLocale.localize(baseContext) + } + CompositionLocalProvider( + LocalContext provides localizedContext, + LocalConfiguration provides localizedContext.resources.configuration, + content = content, + ) +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/CardBrandVisuals.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/CardBrandVisuals.kt new file mode 100644 index 0000000..dda5834 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/CardBrandVisuals.kt @@ -0,0 +1,130 @@ +package mx.dev1.openpay.sdk.ui.components + +import androidx.annotation.DrawableRes +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import mx.dev1.openpay.sdk.R +import mx.dev1.openpay.sdk.domain.validation.CardBrand + +private val VisaNavyBlue = Color(0xFF1A1F71) +private val VisaYellow = Color(0xFFF7B600) +private val MastercardOrange = Color(0xFFFF5F00) +private val MastercardYellow = Color(0xFFF79E1B) +private val AmericanExpressBlue = Color(0xFF006FCF) +private val UnknownBrandGradientStart = Color(0xFF8E9199) +private val UnknownBrandGradientEnd = Color(0xFF4A4D55) + +/** + * Visual identity of a card brand: the logo asset, how the logo must be + * announced to screen readers, and the card background as color stops + * (fraction of the gradient paired with the color at that point). A single + * stop renders as a solid fill; repeating a color across stops widens its + * share of the gradient. + */ +internal data class CardBrandVisualStyle( + @param:DrawableRes val logoDrawableResId: Int?, + val logoDescription: String?, + val backgroundColorStops: List>, +) + +/** + * Resolves the visual identity used for [brand] by the card preview and the + * brand logo badge. Unknown brands keep the neutral gray card and no logo. + */ +internal fun cardBrandVisualStyle(brand: CardBrand): CardBrandVisualStyle = + when (brand) { + CardBrand.VISA -> CardBrandVisualStyle( + logoDrawableResId = R.drawable.visa, + logoDescription = "Visa", + // Navy blue owns 70% of the card before blending into yellow. + backgroundColorStops = listOf( + 0.0f to VisaNavyBlue, + 0.7f to VisaNavyBlue, + 1.0f to VisaYellow, + ), + ) + CardBrand.MASTERCARD -> CardBrandVisualStyle( + logoDrawableResId = R.drawable.mastercard, + logoDescription = "Mastercard", + backgroundColorStops = listOf( + 0.0f to MastercardOrange, + 1.0f to MastercardYellow, + ), + ) + CardBrand.AMERICAN_EXPRESS -> CardBrandVisualStyle( + logoDrawableResId = R.drawable.amex, + logoDescription = "American Express", + backgroundColorStops = listOf(0.0f to AmericanExpressBlue), + ) + CardBrand.UNKNOWN -> CardBrandVisualStyle( + logoDrawableResId = null, + logoDescription = null, + backgroundColorStops = listOf( + 0.0f to UnknownBrandGradientStart, + 1.0f to UnknownBrandGradientEnd, + ), + ) + } + +/** + * Builds the card background for this style: a solid fill when every stop + * shares one color, a linear gradient otherwise. + */ +internal fun CardBrandVisualStyle.backgroundBrush(): Brush { + val distinctColors = backgroundColorStops.map { stop -> stop.second }.distinct() + return if (distinctColors.size == 1) { + SolidColor(distinctColors.single()) + } else { + Brush.linearGradient(colorStops = backgroundColorStops.toTypedArray()) + } +} + +/** + * Badge with the brand logo over its brand color, meant for token or charge + * outputs where the brand comes back from the API. Renders nothing when the + * brand is [CardBrand.UNKNOWN]. + * + * Accessibility: the badge announces the brand name (for example "Visa"), + * so screen reader users get the same information the logo conveys. + * + * @param brand detected or API-reported brand, see [CardBrand.fromBrandName]. + */ +@Composable +fun OpenpayCardBrandLogo( + brand: CardBrand, + modifier: Modifier = Modifier, +) { + val style = cardBrandVisualStyle(brand) + val logoDrawableResId = style.logoDrawableResId ?: return + + Box( + modifier = modifier + .clip(RoundedCornerShape(6.dp)) + .background(style.backgroundBrush()) + .testTag(OpenpayFormTags.CARD_BRAND_LOGO) + .semantics { contentDescription = style.logoDescription.orEmpty() }, + ) { + Image( + painter = painterResource(logoDrawableResId), + contentDescription = null, + modifier = Modifier + .height(28.dp) + .padding(horizontal = 8.dp, vertical = 4.dp), + ) + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/CardBrandVisualsPreviews.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/CardBrandVisualsPreviews.kt new file mode 100644 index 0000000..36eda5d --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/CardBrandVisualsPreviews.kt @@ -0,0 +1,26 @@ +package mx.dev1.openpay.sdk.ui.components + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import mx.dev1.openpay.sdk.domain.validation.CardBrand +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme + +@Preview(name = "Brand logos", showBackground = true) +@Composable +private fun CardBrandLogosPreview() { + OpenpayTheme { + Row( + modifier = Modifier.padding(16.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + OpenpayCardBrandLogo(brand = CardBrand.VISA) + OpenpayCardBrandLogo(brand = CardBrand.MASTERCARD) + OpenpayCardBrandLogo(brand = CardBrand.AMERICAN_EXPRESS) + } + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardFields.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardFields.kt new file mode 100644 index 0000000..35a613f --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardFields.kt @@ -0,0 +1,135 @@ +package mx.dev1.openpay.sdk.ui.components + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import mx.dev1.openpay.sdk.R +import mx.dev1.openpay.sdk.i18n.OpenpayLocalized +import mx.dev1.openpay.sdk.ui.input.CardNumberVisualTransformation +import mx.dev1.openpay.sdk.ui.input.ExpirationVisualTransformation + +object OpenpayFormTags { + const val CARD_PREVIEW = "openpay_card_preview" + const val HOLDER_NAME_FIELD = "openpay_holder_name_field" + const val CARD_NUMBER_FIELD = "openpay_card_number_field" + const val EXPIRATION_FIELD = "openpay_expiration_field" + const val SECURITY_CODE_FIELD = "openpay_security_code_field" + const val CARD_BRAND_LOGO = "openpay_card_brand_logo" + const val CARD_PREVIEW_BRAND_LOGO = "openpay_card_preview_brand_logo" + const val SUBMIT_BUTTON = "openpay_submit_button" +} + +@Composable +fun OpenpayHolderNameField( + value: String, + onValueChange: (String) -> Unit, + isError: Boolean, + modifier: Modifier = Modifier, +) { + OpenpayLocalized { + OutlinedTextField( + value = value, + onValueChange = onValueChange, + modifier = modifier + .fillMaxWidth() + .testTag(OpenpayFormTags.HOLDER_NAME_FIELD), + label = { Text(stringResource(R.string.openpay_holder_name_label)) }, + isError = isError, + supportingText = errorSupportingText(isError, R.string.openpay_error_holder_name), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text), + ) + } +} + +@Composable +fun OpenpayCardNumberField( + value: String, + onValueChange: (String) -> Unit, + isError: Boolean, + modifier: Modifier = Modifier, +) { + OpenpayLocalized { + OutlinedTextField( + value = value, + onValueChange = onValueChange, + modifier = modifier + .fillMaxWidth() + .testTag(OpenpayFormTags.CARD_NUMBER_FIELD), + label = { Text(stringResource(R.string.openpay_card_number_label)) }, + isError = isError, + supportingText = errorSupportingText(isError, R.string.openpay_error_card_number), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + visualTransformation = CardNumberVisualTransformation(), + ) + } +} + +@Composable +fun OpenpayExpirationField( + value: String, + onValueChange: (String) -> Unit, + isError: Boolean, + modifier: Modifier = Modifier, +) { + OpenpayLocalized { + OutlinedTextField( + value = value, + onValueChange = onValueChange, + modifier = modifier + .fillMaxWidth() + .testTag(OpenpayFormTags.EXPIRATION_FIELD), + label = { Text(stringResource(R.string.openpay_expiration_label)) }, + placeholder = { Text(stringResource(R.string.openpay_expiration_placeholder)) }, + isError = isError, + supportingText = errorSupportingText(isError, R.string.openpay_error_expiration), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + visualTransformation = ExpirationVisualTransformation(), + ) + } +} + +@Composable +fun OpenpaySecurityCodeField( + value: String, + onValueChange: (String) -> Unit, + isError: Boolean, + modifier: Modifier = Modifier, +) { + OpenpayLocalized { + val hiddenCodeDescription = stringResource(R.string.openpay_security_code_hidden_description) + OutlinedTextField( + value = value, + onValueChange = onValueChange, + modifier = modifier + .fillMaxWidth() + .testTag(OpenpayFormTags.SECURITY_CODE_FIELD) + .semantics { contentDescription = hiddenCodeDescription }, + label = { Text(stringResource(R.string.openpay_security_code_label)) }, + isError = isError, + supportingText = errorSupportingText(isError, R.string.openpay_error_security_code), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword), + visualTransformation = PasswordVisualTransformation(), + ) + } +} + +@Composable +private fun errorSupportingText(isError: Boolean, errorTextId: Int): (@Composable () -> Unit)? = + if (isError) { + { Text(stringResource(errorTextId)) } + } else { + null + } diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardFieldsPreviews.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardFieldsPreviews.kt new file mode 100644 index 0000000..883466d --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardFieldsPreviews.kt @@ -0,0 +1,77 @@ +package mx.dev1.openpay.sdk.ui.components + +import androidx.compose.runtime.Composable +import androidx.compose.ui.tooling.preview.Preview +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme + +@Preview(name = "Holder name field", showBackground = true) +@Composable +private fun HolderNameFieldPreview() { + OpenpayTheme { + OpenpayHolderNameField( + value = "Juan Pérez Ramírez", + onValueChange = {}, + isError = false, + ) + } +} + +@Preview(name = "Holder name field – error", showBackground = true) +@Composable +private fun HolderNameFieldErrorPreview() { + OpenpayTheme { + OpenpayHolderNameField( + value = "", + onValueChange = {}, + isError = true, + ) + } +} + +@Preview(name = "Card number field", showBackground = true) +@Composable +private fun CardNumberFieldPreview() { + OpenpayTheme { + OpenpayCardNumberField( + value = "4111111111111111", + onValueChange = {}, + isError = false, + ) + } +} + +@Preview(name = "Card number field – error", showBackground = true) +@Composable +private fun CardNumberFieldErrorPreview() { + OpenpayTheme { + OpenpayCardNumberField( + value = "1234", + onValueChange = {}, + isError = true, + ) + } +} + +@Preview(name = "Expiration field", showBackground = true) +@Composable +private fun ExpirationFieldPreview() { + OpenpayTheme { + OpenpayExpirationField( + value = "1230", + onValueChange = {}, + isError = false, + ) + } +} + +@Preview(name = "Security code field", showBackground = true) +@Composable +private fun SecurityCodeFieldPreview() { + OpenpayTheme { + OpenpaySecurityCodeField( + value = "123", + onValueChange = {}, + isError = false, + ) + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardForm.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardForm.kt new file mode 100644 index 0000000..99bed30 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardForm.kt @@ -0,0 +1,102 @@ +package mx.dev1.openpay.sdk.ui.components + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.material3.Button +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import mx.dev1.openpay.sdk.R +import mx.dev1.openpay.sdk.domain.model.Card +import mx.dev1.openpay.sdk.domain.validation.CardField +import mx.dev1.openpay.sdk.i18n.OpenpayLocalized +import mx.dev1.openpay.sdk.ui.state.OpenpayCardFormState +import mx.dev1.openpay.sdk.ui.state.rememberOpenpayCardFormState + +/** + * Complete card capture form: holder name, card number with live brand + * detection, expiration and security code, plus a submit button. + * + * Accessibility: every field exposes its label and error text through + * semantics, the security code stays masked, touch targets keep at least + * 48dp and the detected brand is announced via content description. + * + * @param onCardValidated invoked with a valid [Card] when the user submits + * and every field passes validation. + * @param submitButtonText optional replacement for the submit button label; + * when null the localized SDK text is used. + * @param showCardPreview whether to render the live card preview above the + * fields; disable it when the host app provides its own card artwork. + */ +@Composable +fun OpenpayCardForm( + onCardValidated: (Card) -> Unit, + modifier: Modifier = Modifier, + state: OpenpayCardFormState = rememberOpenpayCardFormState(), + submitButtonText: String? = null, + showCardPreview: Boolean = true, +) = OpenpayLocalized { + val formDescription = stringResource(R.string.openpay_form_description) + + Column( + modifier = modifier + .fillMaxWidth() + .semantics { contentDescription = formDescription }, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (showCardPreview) { + OpenpayCardPreview( + holderName = state.holderName, + cardNumber = state.cardNumber, + expiration = state.expiration, + ) + } + + OpenpayHolderNameField( + value = state.holderName, + onValueChange = state::updateHolderName, + isError = state.isFieldInvalid(CardField.HOLDER_NAME), + ) + + OpenpayCardNumberField( + value = state.cardNumber, + onValueChange = state::updateCardNumber, + isError = state.isFieldInvalid(CardField.CARD_NUMBER), + ) + + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OpenpayExpirationField( + value = state.expiration, + onValueChange = state::updateExpiration, + isError = state.isFieldInvalid(CardField.EXPIRATION), + modifier = Modifier.weight(1f), + ) + OpenpaySecurityCodeField( + value = state.securityCode, + onValueChange = state::updateSecurityCode, + isError = state.isFieldInvalid(CardField.SECURITY_CODE), + modifier = Modifier.weight(1f), + ) + } + + Button( + onClick = { + state.validate()?.let(onCardValidated) + }, + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .testTag(OpenpayFormTags.SUBMIT_BUTTON), + ) { + Text(submitButtonText ?: stringResource(R.string.openpay_pay_button)) + } + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardFormPreviews.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardFormPreviews.kt new file mode 100644 index 0000000..d54972f --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardFormPreviews.kt @@ -0,0 +1,42 @@ +package mx.dev1.openpay.sdk.ui.components + +import android.content.res.Configuration +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Surface +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme + +@Preview(name = "Card form", showBackground = true) +@Preview( + name = "Card form – dark", + showBackground = true, + uiMode = Configuration.UI_MODE_NIGHT_YES, +) +@Composable +private fun CardFormPreview() { + OpenpayTheme { + Surface { + OpenpayCardForm( + onCardValidated = {}, + modifier = Modifier.padding(16.dp), + ) + } + } +} + +@Preview(name = "Card form – without card preview", showBackground = true) +@Composable +private fun CardFormWithoutCardPreviewPreview() { + OpenpayTheme { + Surface { + OpenpayCardForm( + onCardValidated = {}, + modifier = Modifier.padding(16.dp), + showCardPreview = false, + ) + } + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardPreview.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardPreview.kt new file mode 100644 index 0000000..d271518 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardPreview.kt @@ -0,0 +1,182 @@ +package mx.dev1.openpay.sdk.ui.components + +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import mx.dev1.openpay.sdk.R +import mx.dev1.openpay.sdk.domain.validation.CardBrand +import mx.dev1.openpay.sdk.i18n.OpenpayLocalized + +private val CardPreviewTextColor = Color.White +private val CardPreviewLabelColor = Color(0xFFD6D8DC) + +private val BrandLogoSlotHeight = 28.dp + +private const val MASK_CHARACTER = '•' +private const val AMERICAN_EXPRESS_NUMBER_LENGTH = 15 +private const val DEFAULT_NUMBER_LENGTH = 16 +private const val NUMBER_GROUP_SIZE = 4 +private const val EXPIRATION_PART_LENGTH = 2 + +/** + * Groups the typed digits and masks the missing positions with bullets, so + * the preview always shows the full card number silhouette. American Express + * numbers mask to 15 digits, every other brand to 16. + */ +internal fun formatPreviewCardNumber(cardNumberDigits: String, brand: CardBrand): String { + val expectedLength = if (brand == CardBrand.AMERICAN_EXPRESS) { + AMERICAN_EXPRESS_NUMBER_LENGTH + } else { + DEFAULT_NUMBER_LENGTH + } + val paddedDigits = cardNumberDigits + .take(expectedLength) + .padEnd(expectedLength, MASK_CHARACTER) + return paddedDigits.chunked(NUMBER_GROUP_SIZE).joinToString(separator = " ") +} + +/** + * Formats MMYY digits as MM/YY, masking the missing positions with bullets + * (for example "1" becomes "1•/••"). + */ +internal fun formatPreviewExpiration(expirationDigits: String): String { + val paddedDigits = expirationDigits + .take(EXPIRATION_PART_LENGTH * 2) + .padEnd(EXPIRATION_PART_LENGTH * 2, MASK_CHARACTER) + val month = paddedDigits.take(EXPIRATION_PART_LENGTH) + val year = paddedDigits.drop(EXPIRATION_PART_LENGTH) + return "$month/$year" +} + +/** + * Visual representation of the card being captured, mirroring the form input + * in real time: masked number, holder name and expiration date, plus the + * detected brand. + * + * Accessibility: the preview only mirrors what the form fields already + * announce, so it exposes a single short content description and hides its + * inner texts from screen readers. The card number is never read aloud. + * + * @param holderName raw holder name as typed in the form. + * @param cardNumber card number digits, without separators. + * @param expiration expiration digits in MMYY order. + */ +@Composable +fun OpenpayCardPreview( + holderName: String, + cardNumber: String, + expiration: String, + modifier: Modifier = Modifier, +) = OpenpayLocalized { + val previewDescription = stringResource(R.string.openpay_card_preview_description) + val brand = CardBrand.fromCardNumber(cardNumber) + val brandStyle = cardBrandVisualStyle(brand) + + Box( + modifier = modifier + .fillMaxWidth() + .aspectRatio(ratio = 1.8f) + .clip(RoundedCornerShape(20.dp)) + .background(brandStyle.backgroundBrush()) + .testTag(OpenpayFormTags.CARD_PREVIEW) + .clearAndSetSemantics { contentDescription = previewDescription }, + ) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(20.dp), + verticalArrangement = Arrangement.SpaceBetween, + ) { + // Fixed-height slot so the layout does not jump when the brand + // becomes known and the logo appears. + Box( + modifier = Modifier + .height(BrandLogoSlotHeight) + .align(Alignment.End), + ) { + brandStyle.logoDrawableResId?.let { logoDrawableResId -> + Image( + painter = painterResource(logoDrawableResId), + contentDescription = null, + modifier = Modifier + .fillMaxHeight() + .testTag(OpenpayFormTags.CARD_PREVIEW_BRAND_LOGO), + ) + } + } + + Text( + text = formatPreviewCardNumber(cardNumber, brand), + modifier = Modifier.align(Alignment.CenterHorizontally), + color = CardPreviewTextColor, + fontFamily = FontFamily.Monospace, + fontSize = 18.sp, + fontWeight = FontWeight.Medium, + maxLines = 1, + ) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.Bottom, + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = stringResource(R.string.openpay_card_preview_holder_label), + color = CardPreviewLabelColor, + fontSize = 12.sp, + ) + Text( + text = holderName.trim().uppercase().ifEmpty { + stringResource(R.string.openpay_card_preview_holder_placeholder) + }, + color = CardPreviewTextColor, + fontSize = 16.sp, + fontWeight = FontWeight.Bold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Column(horizontalAlignment = Alignment.End) { + Text( + text = stringResource(R.string.openpay_card_preview_expiration_label), + color = CardPreviewLabelColor, + fontSize = 12.sp, + ) + Text( + text = formatPreviewExpiration(expiration), + color = CardPreviewTextColor, + fontSize = 16.sp, + fontWeight = FontWeight.Bold, + ) + } + } + } + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardPreviewPreviews.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardPreviewPreviews.kt new file mode 100644 index 0000000..2707028 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/components/OpenpayCardPreviewPreviews.kt @@ -0,0 +1,60 @@ +package mx.dev1.openpay.sdk.ui.components + +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme + +@Preview(name = "Card preview – empty", showBackground = true) +@Composable +private fun EmptyCardPreviewPreview() { + OpenpayTheme { + OpenpayCardPreview( + holderName = "", + cardNumber = "", + expiration = "", + modifier = Modifier.padding(16.dp), + ) + } +} + +@Preview(name = "Card preview – Visa in progress", showBackground = true) +@Composable +private fun PartialCardPreviewPreview() { + OpenpayTheme { + OpenpayCardPreview( + holderName = "Juan Pérez", + cardNumber = "41111111", + expiration = "12", + modifier = Modifier.padding(16.dp), + ) + } +} + +@Preview(name = "Card preview – Mastercard complete", showBackground = true) +@Composable +private fun MastercardCardPreviewPreview() { + OpenpayTheme { + OpenpayCardPreview( + holderName = "Ana García", + cardNumber = "5555555555554444", + expiration = "0929", + modifier = Modifier.padding(16.dp), + ) + } +} + +@Preview(name = "Card preview – Amex complete", showBackground = true) +@Composable +private fun AmexCardPreviewPreview() { + OpenpayTheme { + OpenpayCardPreview( + holderName = "María López", + cardNumber = "341111111111111", + expiration = "1230", + modifier = Modifier.padding(16.dp), + ) + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/input/CardNumberVisualTransformation.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/input/CardNumberVisualTransformation.kt new file mode 100644 index 0000000..98935c8 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/input/CardNumberVisualTransformation.kt @@ -0,0 +1,56 @@ +package mx.dev1.openpay.sdk.ui.input + +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.input.OffsetMapping +import androidx.compose.ui.text.input.TransformedText +import androidx.compose.ui.text.input.VisualTransformation +import mx.dev1.openpay.sdk.domain.validation.CardBrand + +/** + * Formats card numbers with the spacing users see on physical cards: + * 4-6-5 for American Express and groups of four for every other brand. + * The underlying editable text stays digits-only. + */ +class CardNumberVisualTransformation : VisualTransformation { + + override fun filter(text: AnnotatedString): TransformedText { + val digits = text.text + + // Digit counts after which a space is shown, e.g. [4, 8, 12] for 16 + // digit cards or [4, 10] for American Express. Boundaries at or past + // the end of the input insert nothing. + val groupBoundaries = groupSizesFor(CardBrand.fromCardNumber(digits)) + .runningReduce(Int::plus) + .dropLast(1) + .filter { boundary -> boundary < digits.length } + + val formattedNumber = buildString { + digits.forEachIndexed { index, digit -> + append(digit) + if (index + 1 in groupBoundaries) append(' ') + } + } + + // Index every space occupies inside the formatted text. + val spacePositions = groupBoundaries.mapIndexed { spaceIndex, boundary -> + boundary + spaceIndex + } + + val offsetMapping = object : OffsetMapping { + override fun originalToTransformed(offset: Int): Int = + offset + groupBoundaries.count { boundary -> boundary <= offset } + + override fun transformedToOriginal(offset: Int): Int = + (offset - spacePositions.count { spacePosition -> spacePosition < offset }) + .coerceIn(0, digits.length) + } + + return TransformedText(AnnotatedString(formattedNumber), offsetMapping) + } + + private fun groupSizesFor(brand: CardBrand): List = + when (brand) { + CardBrand.AMERICAN_EXPRESS -> listOf(4, 6, 5) + else -> listOf(4, 4, 4, 4, 3) + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/input/ExpirationVisualTransformation.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/input/ExpirationVisualTransformation.kt new file mode 100644 index 0000000..4d0990c --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/input/ExpirationVisualTransformation.kt @@ -0,0 +1,31 @@ +package mx.dev1.openpay.sdk.ui.input + +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.input.OffsetMapping +import androidx.compose.ui.text.input.TransformedText +import androidx.compose.ui.text.input.VisualTransformation + +/** + * Shows the expiration as MM/YY while the editable text stays the four + * digits MMYY. + */ +class ExpirationVisualTransformation : VisualTransformation { + + override fun filter(text: AnnotatedString): TransformedText { + val digits = text.text + val showsSeparator = digits.length > 2 + + val formattedExpiration = + if (showsSeparator) "${digits.take(2)}/${digits.drop(2)}" else digits + + val offsetMapping = object : OffsetMapping { + override fun originalToTransformed(offset: Int): Int = + if (showsSeparator && offset > 2) offset + 1 else offset + + override fun transformedToOriginal(offset: Int): Int = + if (showsSeparator && offset > 2) (offset - 1).coerceAtMost(digits.length) else offset + } + + return TransformedText(AnnotatedString(formattedExpiration), offsetMapping) + } +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/state/OpenpayCardFormState.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/state/OpenpayCardFormState.kt new file mode 100644 index 0000000..68dd055 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/state/OpenpayCardFormState.kt @@ -0,0 +1,106 @@ +package mx.dev1.openpay.sdk.ui.state + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import java.time.Clock +import mx.dev1.openpay.sdk.domain.model.Card +import mx.dev1.openpay.sdk.domain.validation.CardBrand +import mx.dev1.openpay.sdk.domain.validation.CardField +import mx.dev1.openpay.sdk.domain.validation.CardValidationResult +import mx.dev1.openpay.sdk.domain.validation.CardValidator + +/** + * State holder for the Openpay card form. Field values are kept digits-only; + * visual formatting happens in the composables. + * + * Card data is intentionally NOT persisted across process death: it is + * sensitive payment information, so the state uses [remember] semantics only. + */ +@Stable +class OpenpayCardFormState internal constructor(private val clock: Clock) { + + var holderName: String by mutableStateOf("") + private set + var cardNumber: String by mutableStateOf("") + private set + var expiration: String by mutableStateOf("") + private set + var securityCode: String by mutableStateOf("") + private set + + var validationResult: CardValidationResult? by mutableStateOf(null) + private set + + val detectedBrand: CardBrand + get() = CardBrand.fromCardNumber(cardNumber) + + fun updateHolderName(newValue: String) { + holderName = newValue.take(MAXIMUM_HOLDER_NAME_LENGTH) + clearFieldError(CardField.HOLDER_NAME) + } + + fun updateCardNumber(newValue: String) { + cardNumber = newValue.filter(Char::isDigit).take(MAXIMUM_CARD_NUMBER_LENGTH) + clearFieldError(CardField.CARD_NUMBER) + } + + /** Expects digits in MMYY order, as typed through the expiration field. */ + fun updateExpiration(newValue: String) { + expiration = newValue.filter(Char::isDigit).take(EXPIRATION_LENGTH) + clearFieldError(CardField.EXPIRATION) + } + + fun updateSecurityCode(newValue: String) { + securityCode = newValue.filter(Char::isDigit).take(detectedBrand.securityCodeLength) + clearFieldError(CardField.SECURITY_CODE) + } + + fun isFieldInvalid(field: CardField): Boolean = + validationResult?.isFieldValid(field) == false + + /** + * Validates every field. Returns the [Card] ready for tokenization when + * everything is valid, or null after publishing the failing fields in + * [validationResult]. + */ + fun validate(): Card? { + val candidateCard = buildCard() + val result = CardValidator.validate(candidateCard, clock) + validationResult = result + return if (result.isValid) candidateCard else null + } + + private fun buildCard(): Card = + Card( + holderName = holderName.trim(), + cardNumber = cardNumber, + expirationMonth = expiration.take(2).toIntOrNull() ?: INVALID_DATE_PART, + expirationYear = if (expiration.length == EXPIRATION_LENGTH) { + expiration.drop(2).toIntOrNull() ?: INVALID_DATE_PART + } else { + INVALID_DATE_PART + }, + securityCode = securityCode, + ) + + private fun clearFieldError(field: CardField) { + val currentResult = validationResult ?: return + validationResult = CardValidationResult(currentResult.invalidFields - field) + } + + private companion object { + const val MAXIMUM_HOLDER_NAME_LENGTH = 80 + const val MAXIMUM_CARD_NUMBER_LENGTH = 19 + const val EXPIRATION_LENGTH = 4 + const val INVALID_DATE_PART = -1 + } +} + +/** Remembers an [OpenpayCardFormState] for the composition. */ +@Composable +fun rememberOpenpayCardFormState(): OpenpayCardFormState = + remember { OpenpayCardFormState(Clock.systemDefaultZone()) } diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/theme/OpenpayTheme.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/theme/OpenpayTheme.kt new file mode 100644 index 0000000..8d6cd91 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/theme/OpenpayTheme.kt @@ -0,0 +1,47 @@ +package mx.dev1.openpay.sdk.ui.theme + +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color + +private val OpenpayBlue = Color(0xFF0072CE) +private val OpenpayBlueDark = Color(0xFF00447C) +private val OpenpayTeal = Color(0xFF00B2A9) + +private val OpenpayLightColorScheme = lightColorScheme( + primary = OpenpayBlue, + onPrimary = Color.White, + primaryContainer = Color(0xFFD0E4FF), + onPrimaryContainer = OpenpayBlueDark, + secondary = OpenpayTeal, + onSecondary = Color.White, + error = Color(0xFFBA1A1A), +) + +private val OpenpayDarkColorScheme = darkColorScheme( + primary = Color(0xFF9CCAFF), + onPrimary = OpenpayBlueDark, + primaryContainer = Color(0xFF00335E), + onPrimaryContainer = Color(0xFFD0E4FF), + secondary = Color(0xFF54DBD2), + onSecondary = Color(0xFF003734), + error = Color(0xFFFFB4AB), +) + +/** + * Material 3 theme with the Openpay brand palette. Wrap SDK components with + * it when the host app does not provide its own MaterialTheme. + */ +@Composable +fun OpenpayTheme( + useDarkTheme: Boolean = isSystemInDarkTheme(), + content: @Composable () -> Unit, +) { + MaterialTheme( + colorScheme = if (useDarkTheme) OpenpayDarkColorScheme else OpenpayLightColorScheme, + content = content, + ) +} diff --git a/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/view/OpenpayCardFormView.kt b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/view/OpenpayCardFormView.kt new file mode 100644 index 0000000..f56a1bc --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/ui/view/OpenpayCardFormView.kt @@ -0,0 +1,41 @@ +package mx.dev1.openpay.sdk.ui.view + +import android.content.Context +import android.util.AttributeSet +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.AbstractComposeView +import mx.dev1.openpay.sdk.domain.model.Card +import mx.dev1.openpay.sdk.ui.components.OpenpayCardForm +import mx.dev1.openpay.sdk.ui.theme.OpenpayTheme + +/** + * XML-friendly wrapper around [OpenpayCardForm] for host apps that still + * use view-based layouts: + * + * ```xml + * + * ``` + * + * Set [onCardValidated] to receive the validated card. + */ +class OpenpayCardFormView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, + defStyleAttr: Int = 0, +) : AbstractComposeView(context, attrs, defStyleAttr) { + + /** Called with the validated card when the user submits the form. */ + var onCardValidated: (Card) -> Unit = {} + + @Composable + override fun Content() { + OpenpayTheme { + OpenpayCardForm( + onCardValidated = { validatedCard -> onCardValidated(validatedCard) }, + ) + } + } +} diff --git a/openpay-sdk/src/main/res/drawable/amex.xml b/openpay-sdk/src/main/res/drawable/amex.xml new file mode 100644 index 0000000..b503841 --- /dev/null +++ b/openpay-sdk/src/main/res/drawable/amex.xml @@ -0,0 +1,24 @@ + + + + + + + + diff --git a/openpay-sdk/src/main/res/drawable/mastercard.xml b/openpay-sdk/src/main/res/drawable/mastercard.xml new file mode 100644 index 0000000..ac0fec3 --- /dev/null +++ b/openpay-sdk/src/main/res/drawable/mastercard.xml @@ -0,0 +1,9 @@ + + + diff --git a/openpay-sdk/src/main/res/drawable/visa.xml b/openpay-sdk/src/main/res/drawable/visa.xml new file mode 100644 index 0000000..05bf6a9 --- /dev/null +++ b/openpay-sdk/src/main/res/drawable/visa.xml @@ -0,0 +1,12 @@ + + + + diff --git a/openpay-sdk/src/main/res/values-es/strings.xml b/openpay-sdk/src/main/res/values-es/strings.xml new file mode 100644 index 0000000..b159f19 --- /dev/null +++ b/openpay-sdk/src/main/res/values-es/strings.xml @@ -0,0 +1,27 @@ + + + Nombre del titular + Número de tarjeta + Fecha de vencimiento + MM/AA + Código de seguridad + + + Escribe el nombre como aparece en la tarjeta + Escribe un número de tarjeta válido + Escribe una fecha de vencimiento válida + Escribe el código de seguridad al reverso de la tarjeta + + + El código de seguridad se oculta mientras escribes + Formulario de tarjeta de pago + + + Vista previa de la tarjeta que estás capturando + Titular + TITULAR + Vence + + + Guardar tarjeta + diff --git a/openpay-sdk/src/main/res/values-fr/strings.xml b/openpay-sdk/src/main/res/values-fr/strings.xml new file mode 100644 index 0000000..930c90b --- /dev/null +++ b/openpay-sdk/src/main/res/values-fr/strings.xml @@ -0,0 +1,27 @@ + + + Nom du titulaire + Numéro de carte + Date d\'expiration + MM/AA + Code de sécurité + + + Saisissez le nom tel qu\'il figure sur la carte + Saisissez un numéro de carte valide + Saisissez une date d\'expiration valide + Saisissez le code de sécurité au dos de la carte + + + Le code de sécurité est masqué pendant la saisie + Formulaire de carte de paiement + + + Aperçu de la carte que vous saisissez + Titulaire + TITULAIRE + Expire + + + Enregistrer la carte + diff --git a/openpay-sdk/src/main/res/values-pt/strings.xml b/openpay-sdk/src/main/res/values-pt/strings.xml new file mode 100644 index 0000000..f7f25fb --- /dev/null +++ b/openpay-sdk/src/main/res/values-pt/strings.xml @@ -0,0 +1,27 @@ + + + Nome do titular + Número do cartão + Data de validade + MM/AA + Código de segurança + + + Digite o nome como está impresso no cartão + Digite um número de cartão válido + Digite uma data de validade válida + Digite o código de segurança no verso do cartão + + + O código de segurança fica oculto enquanto você digita + Formulário do cartão de pagamento + + + Pré-visualização do cartão que você está digitando + Titular + TITULAR + Validade + + + Salvar cartão + diff --git a/openpay-sdk/src/main/res/values/strings.xml b/openpay-sdk/src/main/res/values/strings.xml new file mode 100644 index 0000000..0d50282 --- /dev/null +++ b/openpay-sdk/src/main/res/values/strings.xml @@ -0,0 +1,27 @@ + + + Cardholder name + Card number + Expiration date + MM/YY + Security code + + + Enter the name as printed on the card + Enter a valid card number + Enter a valid expiration date + Enter the security code on the back of the card + + + The security code is hidden while you type + Payment card form + + + Preview of the card you are entering + Cardholder + CARDHOLDER + Expires + + + Save card + diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/OpenpaySdkTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/OpenpaySdkTest.kt new file mode 100644 index 0000000..e055cb6 --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/OpenpaySdkTest.kt @@ -0,0 +1,27 @@ +package mx.dev1.openpay.sdk + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +class OpenpaySdkTest { + + @Test + fun `version follows semantic versioning`() { + val semanticVersionPattern = Regex("""\d+\.\d+\.\d+""") + assertTrue(OpenpaySdk.VERSION.matches(semanticVersionPattern)) + } + + @Test + fun `user agent contains sdk name and version`() { + assertEquals("openpay-android/${OpenpaySdk.VERSION}", OpenpaySdk.userAgent) + } + + @Test + fun `building a user agent with a blank version fails`() { + assertThrows(IllegalArgumentException::class.java) { + OpenpaySdk.buildUserAgent(" ") + } + } +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/OpenpayTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/OpenpayTest.kt new file mode 100644 index 0000000..5e41566 --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/OpenpayTest.kt @@ -0,0 +1,125 @@ +package mx.dev1.openpay.sdk + +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset +import android.app.Activity +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import mx.dev1.openpay.sdk.antifraud.DeviceSessionCollector +import mx.dev1.openpay.sdk.core.OpenpayException +import mx.dev1.openpay.sdk.domain.model.Card +import mx.dev1.openpay.sdk.domain.model.Token +import mx.dev1.openpay.sdk.domain.repository.TokenRepository +import mx.dev1.openpay.sdk.domain.usecase.CreateTokenUseCase +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +class OpenpayTest { + + private val frozenClock: Clock = + Clock.fixed(Instant.parse("2026-06-15T12:00:00Z"), ZoneOffset.UTC) + + private val tokenRepository: TokenRepository = mock() + + private val validCard = Card( + holderName = "Juan Pérez Ramírez", + cardNumber = "4111111111111111", + expirationMonth = 12, + expirationYear = 30, + securityCode = "110", + ) + + private val deviceSessionCollector: DeviceSessionCollector = mock() + + private fun openpayWith(dispatcher: kotlinx.coroutines.CoroutineDispatcher) = Openpay( + createTokenUseCase = CreateTokenUseCase(tokenRepository, frozenClock), + deviceSessionCollector = deviceSessionCollector, + backgroundDispatcher = dispatcher, + callbackDispatcher = dispatcher, + ) + + @Test + fun `suspend createToken returns a successful result`() = runTest { + val expectedToken = Token(tokenId = "tok_123", card = null) + whenever(tokenRepository.createToken(validCard)).thenReturn(expectedToken) + val openpay = openpayWith(StandardTestDispatcher(testScheduler)) + + val tokenResult = openpay.createToken(validCard) + + assertEquals(expectedToken, tokenResult.getOrNull()) + } + + @Test + fun `suspend createToken wraps openpay errors in a failed result`() = runTest { + val invalidCard = validCard.copy(cardNumber = "1234") + val openpay = openpayWith(StandardTestDispatcher(testScheduler)) + + val tokenResult = openpay.createToken(invalidCard) + + assertTrue(tokenResult.exceptionOrNull() is OpenpayException.ValidationError) + } + + @Test + fun `callback createToken reports success on the callback dispatcher`() = runTest { + val expectedToken = Token(tokenId = "tok_456", card = null) + whenever(tokenRepository.createToken(validCard)).thenReturn(expectedToken) + val openpay = openpayWith(StandardTestDispatcher(testScheduler)) + + var receivedToken: Token? = null + var receivedError: OpenpayException? = null + openpay.createToken( + validCard, + object : OpenpayCallback { + override fun onSuccess(result: Token) { + receivedToken = result + } + + override fun onError(exception: OpenpayException) { + receivedError = exception + } + }, + ) + advanceUntilIdle() + + assertEquals(expectedToken, receivedToken) + assertNull(receivedError) + } + + @Test + fun `setupDeviceSession delegates to the device session collector`() = runTest { + val activity: Activity = mock() + whenever(deviceSessionCollector.collect(activity)).thenReturn("device-session-id") + val openpay = openpayWith(StandardTestDispatcher(testScheduler)) + + assertEquals("device-session-id", openpay.setupDeviceSession(activity)) + } + + @Test + fun `callback createToken reports validation errors`() = runTest { + val invalidCard = validCard.copy(securityCode = "1") + val openpay = openpayWith(StandardTestDispatcher(testScheduler)) + + var receivedError: OpenpayException? = null + openpay.createToken( + invalidCard, + object : OpenpayCallback { + override fun onSuccess(result: Token) { + throw AssertionError("An error was expected") + } + + override fun onError(exception: OpenpayException) { + receivedError = exception + } + }, + ) + advanceUntilIdle() + + assertTrue(receivedError is OpenpayException.ValidationError) + } +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/antifraud/DeviceSessionIdGeneratorTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/antifraud/DeviceSessionIdGeneratorTest.kt new file mode 100644 index 0000000..f50fb84 --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/antifraud/DeviceSessionIdGeneratorTest.kt @@ -0,0 +1,25 @@ +package mx.dev1.openpay.sdk.antifraud + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class DeviceSessionIdGeneratorTest { + + private val sessionIdGenerator = DeviceSessionIdGenerator() + + @Test + fun `session ids have 32 hexadecimal characters`() { + val sessionId = sessionIdGenerator.generate() + + assertEquals(32, sessionId.length) + assertTrue(sessionId.all { character -> character in "0123456789abcdef" }) + } + + @Test + fun `session ids are unique`() { + val generatedIds = List(100) { sessionIdGenerator.generate() }.toSet() + + assertEquals(100, generatedIds.size) + } +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/antifraud/WebViewDeviceSessionCollectorTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/antifraud/WebViewDeviceSessionCollectorTest.kt new file mode 100644 index 0000000..bcd1231 --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/antifraud/WebViewDeviceSessionCollectorTest.kt @@ -0,0 +1,77 @@ +package mx.dev1.openpay.sdk.antifraud + +import android.app.Activity +import android.webkit.WebView +import mx.dev1.openpay.sdk.core.OpenpayConfig +import mx.dev1.openpay.sdk.core.OpenpayCountry +import mx.dev1.openpay.sdk.core.OpenpayEnvironment +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf + +@RunWith(RobolectricTestRunner::class) +class WebViewDeviceSessionCollectorTest { + + private val config = OpenpayConfig( + merchantId = "merchant-id", + publicApiKey = "pk_test", + country = OpenpayCountry.MEXICO, + environment = OpenpayEnvironment.SANDBOX, + ) + + private var createdWebView: WebView? = null + + private val collector = WebViewDeviceSessionCollector( + config = config, + sessionIdGenerator = DeviceSessionIdGenerator(), + webViewProvider = { activity -> + WebView(activity).also { createdWebView = it } + }, + ) + + private fun launchActivity(): Activity = + Robolectric.buildActivity(Activity::class.java).setup().get() + + @Test + fun `collect returns a 32 character session id`() { + val deviceSessionId = collector.collect(launchActivity()) + + assertEquals(32, deviceSessionId.length) + assertTrue(deviceSessionId.all { character -> character in "0123456789abcdef" }) + } + + @Test + fun `collect loads the fingerprint url with merchant and session id`() { + val deviceSessionId = collector.collect(launchActivity()) + + val fingerprintWebView = checkNotNull(createdWebView) + assertEquals( + "https://sandbox-api.openpay.mx/oa/logo.htm?m=merchant-id&s=$deviceSessionId", + shadowOf(fingerprintWebView).lastLoadedUrl, + ) + } + + @Test + fun `collect enables javascript for the fingerprint page`() { + collector.collect(launchActivity()) + + val fingerprintWebView = checkNotNull(createdWebView) + assertTrue(fingerprintWebView.settings.javaScriptEnabled) + } + + @Test + fun `each collection uses a fresh session id`() { + val activity = launchActivity() + + val firstSessionId = collector.collect(activity) + val secondSessionId = collector.collect(activity) + + assertNotNull(firstSessionId) + assertTrue(firstSessionId != secondSessionId) + } +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/core/OpenpayConfigTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/core/OpenpayConfigTest.kt new file mode 100644 index 0000000..e853d00 --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/core/OpenpayConfigTest.kt @@ -0,0 +1,43 @@ +package mx.dev1.openpay.sdk.core + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Test + +class OpenpayConfigTest { + + @Test + fun `defaults to mexico sandbox`() { + val config = OpenpayConfig(merchantId = "merchant", publicApiKey = "public-key") + + assertEquals(OpenpayCountry.MEXICO, config.country) + assertEquals(OpenpayEnvironment.SANDBOX, config.environment) + assertEquals("https://sandbox-api.openpay.mx", config.baseUrl) + } + + @Test + fun `base url follows country and environment`() { + val config = OpenpayConfig( + merchantId = "merchant", + publicApiKey = "public-key", + country = OpenpayCountry.PERU, + environment = OpenpayEnvironment.PRODUCTION, + ) + + assertEquals("https://api.openpay.pe", config.baseUrl) + } + + @Test + fun `blank merchant id is rejected`() { + assertThrows(IllegalArgumentException::class.java) { + OpenpayConfig(merchantId = " ", publicApiKey = "public-key") + } + } + + @Test + fun `blank public api key is rejected`() { + assertThrows(IllegalArgumentException::class.java) { + OpenpayConfig(merchantId = "merchant", publicApiKey = "") + } + } +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/core/OpenpayCountryTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/core/OpenpayCountryTest.kt new file mode 100644 index 0000000..1b7ba7e --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/core/OpenpayCountryTest.kt @@ -0,0 +1,43 @@ +package mx.dev1.openpay.sdk.core + +import org.junit.Assert.assertEquals +import org.junit.Test + +class OpenpayCountryTest { + + @Test + fun `mexico resolves sandbox and production urls`() { + assertEquals( + "https://sandbox-api.openpay.mx", + OpenpayCountry.MEXICO.baseUrlFor(OpenpayEnvironment.SANDBOX), + ) + assertEquals( + "https://api.openpay.mx", + OpenpayCountry.MEXICO.baseUrlFor(OpenpayEnvironment.PRODUCTION), + ) + } + + @Test + fun `colombia resolves sandbox and production urls`() { + assertEquals( + "https://sandbox-api.openpay.co", + OpenpayCountry.COLOMBIA.baseUrlFor(OpenpayEnvironment.SANDBOX), + ) + assertEquals( + "https://api.openpay.co", + OpenpayCountry.COLOMBIA.baseUrlFor(OpenpayEnvironment.PRODUCTION), + ) + } + + @Test + fun `peru resolves sandbox and production urls`() { + assertEquals( + "https://sandbox-api.openpay.pe", + OpenpayCountry.PERU.baseUrlFor(OpenpayEnvironment.SANDBOX), + ) + assertEquals( + "https://api.openpay.pe", + OpenpayCountry.PERU.baseUrlFor(OpenpayEnvironment.PRODUCTION), + ) + } +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/mapper/MapperTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/mapper/MapperTest.kt new file mode 100644 index 0000000..825315f --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/mapper/MapperTest.kt @@ -0,0 +1,98 @@ +package mx.dev1.openpay.sdk.data.mapper + +import mx.dev1.openpay.sdk.data.remote.dto.AddressDto +import mx.dev1.openpay.sdk.data.remote.dto.CardDto +import mx.dev1.openpay.sdk.data.remote.dto.TokenDto +import mx.dev1.openpay.sdk.domain.model.Address +import mx.dev1.openpay.sdk.domain.model.Card +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class MapperTest { + + private val billingAddress = Address( + line1 = "Av. Reforma 123", + line2 = "Piso 4", + postalCode = "06600", + city = "Ciudad de Mexico", + state = "CDMX", + countryCode = "MX", + ) + + @Test + fun `card maps to request dto with formatted expiration`() { + val card = Card( + holderName = "Juan Perez Ramirez", + cardNumber = "4111111111111111", + expirationMonth = 4, + expirationYear = 2030, + securityCode = "110", + address = billingAddress, + ) + + val requestDto = card.toRequestDto() + + assertEquals("4111111111111111", requestDto.cardNumber) + assertEquals("Juan Perez Ramirez", requestDto.holderName) + assertEquals("04", requestDto.expirationMonth) + assertEquals("30", requestDto.expirationYear) + assertEquals("110", requestDto.securityCode) + assertEquals("Av. Reforma 123", requestDto.address?.line1) + assertEquals("06600", requestDto.address?.postalCode) + assertNull(requestDto.brand) + assertNull(requestDto.bankName) + } + + @Test + fun `token dto maps to domain token with card details`() { + val tokenDto = TokenDto( + tokenId = "tok_abc123", + card = CardDto( + cardNumber = "411111XXXXXX1111", + holderName = "Juan Perez Ramirez", + expirationMonth = "04", + expirationYear = "30", + brand = "visa", + cardType = "debit", + bankName = "Banamex", + bankCode = "002", + allowsCharges = true, + allowsPayouts = false, + ), + ) + + val token = tokenDto.toDomain() + + assertEquals("tok_abc123", token.tokenId) + assertEquals("411111XXXXXX1111", token.card?.maskedCardNumber) + assertEquals("visa", token.card?.brand) + assertEquals("debit", token.card?.cardType) + assertEquals("Banamex", token.card?.bankName) + assertEquals(true, token.card?.allowsCharges) + assertEquals(false, token.card?.allowsPayouts) + } + + @Test + fun `token dto without card maps to token without card`() { + val token = TokenDto(tokenId = "tok_only").toDomain() + + assertEquals("tok_only", token.tokenId) + assertNull(token.card) + } + + @Test + fun `address dto round trip keeps every field`() { + val addressDto = billingAddress.toDto() + val roundTrippedAddress = addressDto.toDomain() + + assertEquals(billingAddress, roundTrippedAddress) + } + + @Test + fun `address dto missing required fields maps to null`() { + val incompleteAddressDto = AddressDto(line1 = "Av. Reforma 123", city = "CDMX") + + assertNull(incompleteAddressDto.toDomain()) + } +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayHttpClientFactoryTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayHttpClientFactoryTest.kt new file mode 100644 index 0000000..4ab1437 --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayHttpClientFactoryTest.kt @@ -0,0 +1,70 @@ +package mx.dev1.openpay.sdk.data.remote + +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond +import io.ktor.client.request.get +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.http.headersOf +import java.util.Base64 +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import mx.dev1.openpay.sdk.OpenpaySdk +import mx.dev1.openpay.sdk.core.OpenpayConfig +import mx.dev1.openpay.sdk.core.OpenpayCountry +import mx.dev1.openpay.sdk.core.OpenpayEnvironment +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class OpenpayHttpClientFactoryTest { + + private val config = OpenpayConfig( + merchantId = "merchant-id", + publicApiKey = "pk_test_key", + country = OpenpayCountry.MEXICO, + environment = OpenpayEnvironment.SANDBOX, + ) + + private val factory = OpenpayHttpClientFactory(config = config, json = Json) + + @Test + fun `requests carry basic auth with the public key and empty password`() = runTest { + val mockEngine = MockEngine { respond("{}", HttpStatusCode.OK, jsonHeaders()) } + + factory.create(mockEngine).use { httpClient -> + httpClient.get("v1/merchant-id/tokens") + } + + val sentRequest = mockEngine.requestHistory.single() + val expectedCredentials = Base64.getEncoder().encodeToString("pk_test_key:".toByteArray()) + assertEquals("Basic $expectedCredentials", sentRequest.headers[HttpHeaders.Authorization]) + } + + @Test + fun `requests carry the sdk user agent`() = runTest { + val mockEngine = MockEngine { respond("{}", HttpStatusCode.OK, jsonHeaders()) } + + factory.create(mockEngine).use { httpClient -> + httpClient.get("v1/merchant-id/tokens") + } + + val sentRequest = mockEngine.requestHistory.single() + assertEquals(OpenpaySdk.userAgent, sentRequest.headers[HttpHeaders.UserAgent]) + } + + @Test + fun `requests resolve against the configured base url`() = runTest { + val mockEngine = MockEngine { respond("{}", HttpStatusCode.OK, jsonHeaders()) } + + factory.create(mockEngine).use { httpClient -> + httpClient.get("v1/merchant-id/tokens") + } + + val sentRequestUrl = mockEngine.requestHistory.single().url.toString() + assertTrue(sentRequestUrl.startsWith("https://sandbox-api.openpay.mx")) + assertTrue(sentRequestUrl.endsWith("v1/merchant-id/tokens")) + } + + private fun jsonHeaders() = headersOf(HttpHeaders.ContentType, "application/json") +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayResponseHandlerTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayResponseHandlerTest.kt new file mode 100644 index 0000000..3a442b6 --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayResponseHandlerTest.kt @@ -0,0 +1,77 @@ +package mx.dev1.openpay.sdk.data.remote + +import io.ktor.client.HttpClient +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.client.request.get +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.http.headersOf +import io.ktor.serialization.kotlinx.json.json +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import mx.dev1.openpay.sdk.core.OpenpayException +import mx.dev1.openpay.sdk.data.remote.dto.TokenDto +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class OpenpayResponseHandlerTest { + + private val json = Json { ignoreUnknownKeys = true } + private val responseHandler = OpenpayResponseHandler(json) + + private fun clientRespondingWith(body: String, status: HttpStatusCode): HttpClient = + HttpClient(MockEngine { respond(body, status, headersOf(HttpHeaders.ContentType, "application/json")) }) { + expectSuccess = false + install(ContentNegotiation) { json(json) } + } + + @Test + fun `successful response returns the parsed body`() = runTest { + val responseBody = """{"id":"tok_123","card":{"brand":"visa"}}""" + + clientRespondingWith(responseBody, HttpStatusCode.Created).use { httpClient -> + val token = responseHandler.parse(httpClient.get("tokens")) + + assertEquals("tok_123", token.tokenId) + assertEquals("visa", token.card?.brand) + } + } + + @Test + fun `api error body becomes a service error`() = runTest { + val errorBody = """ + {"category":"request","error_code":2005,"description":"The expiration date has already passed", + "http_code":400,"request_id":"req-1"} + """.trimIndent() + + clientRespondingWith(errorBody, HttpStatusCode.BadRequest).use { httpClient -> + try { + responseHandler.parse(httpClient.get("tokens")) + throw AssertionError("A service error was expected") + } catch (serviceError: OpenpayException.ServiceError) { + assertEquals(2005, serviceError.errorCode) + assertEquals("request", serviceError.category) + assertEquals(400, serviceError.httpStatus) + assertEquals("req-1", serviceError.requestId) + assertEquals("The expiration date has already passed", serviceError.message) + } + } + } + + @Test + fun `unparseable error body still becomes a service error`() = runTest { + clientRespondingWith("gateway error", HttpStatusCode.BadGateway).use { httpClient -> + try { + responseHandler.parse(httpClient.get("tokens")) + throw AssertionError("A service error was expected") + } catch (serviceError: OpenpayException.ServiceError) { + assertEquals(OpenpayResponseHandler.UNKNOWN_ERROR_CODE, serviceError.errorCode) + assertEquals(502, serviceError.httpStatus) + assertNull(serviceError.category) + } + } + } +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/repository/RemoteTokenRepositoryTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/repository/RemoteTokenRepositoryTest.kt new file mode 100644 index 0000000..898e284 --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/repository/RemoteTokenRepositoryTest.kt @@ -0,0 +1,117 @@ +package mx.dev1.openpay.sdk.data.repository + +import io.ktor.client.HttpClient +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.client.plugins.defaultRequest +import io.ktor.client.request.HttpRequestData +import io.ktor.content.TextContent +import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpMethod +import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import io.ktor.http.headersOf +import io.ktor.serialization.kotlinx.json.json +import java.io.IOException +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import mx.dev1.openpay.sdk.core.OpenpayConfig +import mx.dev1.openpay.sdk.core.OpenpayException +import mx.dev1.openpay.sdk.data.remote.OpenpayResponseHandler +import mx.dev1.openpay.sdk.domain.model.Card +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class RemoteTokenRepositoryTest { + + private val json = Json { ignoreUnknownKeys = true } + private val config = OpenpayConfig(merchantId = "merchant-id", publicApiKey = "pk_test") + + private val cardToTokenize = Card( + holderName = "Juan Pérez Ramírez", + cardNumber = "4111111111111111", + expirationMonth = 12, + expirationYear = 30, + securityCode = "110", + ) + + private var lastRequest: HttpRequestData? = null + + private fun repositoryWith(handler: MockEngine): RemoteTokenRepository { + val httpClient = HttpClient(handler) { + expectSuccess = false + install(ContentNegotiation) { json(json) } + defaultRequest { contentType(ContentType.Application.Json) } + } + return RemoteTokenRepository( + httpClient = httpClient, + responseHandler = OpenpayResponseHandler(json), + config = config, + ) + } + + @Test + fun `posts the card to the merchant tokens endpoint`() = runTest { + val mockEngine = MockEngine { request -> + lastRequest = request + respond( + """{"id":"tok_123","card":{"card_number":"411111XXXXXX1111","brand":"visa"}}""", + HttpStatusCode.Created, + headersOf(HttpHeaders.ContentType, "application/json"), + ) + } + + val token = repositoryWith(mockEngine).createToken(cardToTokenize) + + assertEquals("tok_123", token.tokenId) + assertEquals("visa", token.card?.brand) + val sentRequest = checkNotNull(lastRequest) + assertEquals(HttpMethod.Post, sentRequest.method) + assertTrue(sentRequest.url.toString().endsWith("v1/merchant-id/tokens")) + val sentBody = (sentRequest.body as TextContent).text + assertTrue(sentBody.contains(""""card_number":"4111111111111111"""")) + assertTrue(sentBody.contains(""""expiration_month":"12"""")) + assertTrue(sentBody.contains(""""expiration_year":"30"""")) + assertTrue(sentBody.contains(""""cvv2":"110"""")) + } + + @Test + fun `api rejection surfaces as service error`() = runTest { + val mockEngine = MockEngine { + respond( + """{"category":"request","error_code":3001,"description":"The card was declined","http_code":402}""", + HttpStatusCode.PaymentRequired, + headersOf(HttpHeaders.ContentType, "application/json"), + ) + } + + try { + repositoryWith(mockEngine).createToken(cardToTokenize) + throw AssertionError("A service error was expected") + } catch (serviceError: OpenpayException.ServiceError) { + assertEquals(3001, serviceError.errorCode) + assertEquals(402, serviceError.httpStatus) + assertEquals("The card was declined", serviceError.message) + } + } + + @Test + fun `transport failures surface as connection error`() = runTest { + val mockEngine = MockEngine { + throw IOException("Network unreachable") + } + + try { + repositoryWith(mockEngine).createToken(cardToTokenize) + throw AssertionError("A connection error was expected") + } catch (connectionError: OpenpayException.ConnectionError) { + val causeMessages = generateSequence(connectionError.cause) { failure -> failure.cause } + .mapNotNull(Throwable::message) + .toList() + assertTrue(causeMessages.any { message -> message.contains("Network unreachable") }) + } + } +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/di/OpenpayKoinContextTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/di/OpenpayKoinContextTest.kt new file mode 100644 index 0000000..90a040c --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/di/OpenpayKoinContextTest.kt @@ -0,0 +1,65 @@ +package mx.dev1.openpay.sdk.di + +import io.ktor.client.HttpClient +import kotlinx.serialization.json.Json +import mx.dev1.openpay.sdk.core.OpenpayConfig +import mx.dev1.openpay.sdk.data.remote.OpenpayHttpClientFactory +import mx.dev1.openpay.sdk.data.remote.OpenpayResponseHandler +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +class OpenpayKoinContextTest { + + private val config = OpenpayConfig(merchantId = "merchant-id", publicApiKey = "pk_test_key") + + @After + fun tearDown() { + OpenpayKoinContext.stop() + } + + @Test + fun `start exposes every core definition`() { + OpenpayKoinContext.start(config) + + assertTrue(OpenpayKoinContext.isStarted) + assertEquals(config, OpenpayKoinContext.koin.get()) + assertNotNull(OpenpayKoinContext.koin.get()) + assertNotNull(OpenpayKoinContext.koin.get()) + assertNotNull(OpenpayKoinContext.koin.get()) + assertNotNull(OpenpayKoinContext.koin.get()) + } + + @Test + fun `starting again replaces the previous container`() { + OpenpayKoinContext.start(config) + val replacementConfig = OpenpayConfig(merchantId = "other-merchant", publicApiKey = "pk_other") + + OpenpayKoinContext.start(replacementConfig) + + assertEquals(replacementConfig, OpenpayKoinContext.koin.get()) + } + + @Test + fun `using the container before starting fails with a clear message`() { + assertFalse(OpenpayKoinContext.isStarted) + + val error = assertThrows(IllegalStateException::class.java) { + OpenpayKoinContext.koin + } + assertTrue(checkNotNull(error.message).contains("has not been started")) + } + + @Test + fun `stop closes the container`() { + OpenpayKoinContext.start(config) + + OpenpayKoinContext.stop() + + assertFalse(OpenpayKoinContext.isStarted) + } +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/model/CardTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/model/CardTest.kt new file mode 100644 index 0000000..f95e84c --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/model/CardTest.kt @@ -0,0 +1,40 @@ +package mx.dev1.openpay.sdk.domain.model + +import org.junit.Assert.assertEquals +import org.junit.Test + +class CardTest { + + private fun cardWithExpiration(month: Int, year: Int) = Card( + holderName = "Juan Perez Ramirez", + cardNumber = "4111111111111111", + expirationMonth = month, + expirationYear = year, + securityCode = "110", + ) + + @Test + fun `single digit month is padded to two digits`() { + assertEquals("03", cardWithExpiration(month = 3, year = 30).formattedExpirationMonth) + } + + @Test + fun `double digit month stays unchanged`() { + assertEquals("12", cardWithExpiration(month = 12, year = 30).formattedExpirationMonth) + } + + @Test + fun `four digit year is reduced to its last two digits`() { + assertEquals("30", cardWithExpiration(month = 1, year = 2030).formattedExpirationYear) + } + + @Test + fun `two digit year stays unchanged`() { + assertEquals("27", cardWithExpiration(month = 1, year = 27).formattedExpirationYear) + } + + @Test + fun `single digit year is padded to two digits`() { + assertEquals("09", cardWithExpiration(month = 1, year = 9).formattedExpirationYear) + } +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/usecase/CreateTokenUseCaseTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/usecase/CreateTokenUseCaseTest.kt new file mode 100644 index 0000000..4dc038f --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/usecase/CreateTokenUseCaseTest.kt @@ -0,0 +1,62 @@ +package mx.dev1.openpay.sdk.domain.usecase + +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset +import kotlinx.coroutines.test.runTest +import mx.dev1.openpay.sdk.core.OpenpayException +import mx.dev1.openpay.sdk.domain.model.Card +import mx.dev1.openpay.sdk.domain.model.Token +import mx.dev1.openpay.sdk.domain.repository.TokenRepository +import mx.dev1.openpay.sdk.domain.validation.CardField +import org.junit.Assert.assertEquals +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +class CreateTokenUseCaseTest { + + private val frozenClock: Clock = + Clock.fixed(Instant.parse("2026-06-15T12:00:00Z"), ZoneOffset.UTC) + + private val tokenRepository: TokenRepository = mock() + private val createToken = CreateTokenUseCase(tokenRepository, frozenClock) + + private val validCard = Card( + holderName = "Juan Pérez Ramírez", + cardNumber = "4111111111111111", + expirationMonth = 12, + expirationYear = 30, + securityCode = "110", + ) + + @Test + fun `a valid card is sent to the repository`() = runTest { + val expectedToken = Token(tokenId = "tok_123", card = null) + whenever(tokenRepository.createToken(validCard)).thenReturn(expectedToken) + + val token = createToken(validCard) + + assertEquals(expectedToken, token) + verify(tokenRepository).createToken(validCard) + } + + @Test + fun `an invalid card fails locally and never reaches the network`() = runTest { + val expiredCard = validCard.copy(expirationMonth = 1, expirationYear = 20) + + try { + createToken(expiredCard) + throw AssertionError("A validation error was expected") + } catch (validationError: OpenpayException.ValidationError) { + assertEquals( + setOf(CardField.EXPIRATION), + validationError.validationResult.invalidFields, + ) + } + verify(tokenRepository, never()).createToken(any()) + } +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/validation/CardBrandTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/validation/CardBrandTest.kt new file mode 100644 index 0000000..0d7a5f9 --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/validation/CardBrandTest.kt @@ -0,0 +1,80 @@ +package mx.dev1.openpay.sdk.domain.validation + +import org.junit.Assert.assertEquals +import org.junit.Test + +class CardBrandTest { + + @Test + fun `numbers starting with 4 are visa`() { + assertEquals(CardBrand.VISA, CardBrand.fromCardNumber("4111111111111111")) + assertEquals(CardBrand.VISA, CardBrand.fromCardNumber("4")) + } + + @Test + fun `numbers starting with 51 to 55 are mastercard`() { + assertEquals(CardBrand.MASTERCARD, CardBrand.fromCardNumber("5105105105105100")) + assertEquals(CardBrand.MASTERCARD, CardBrand.fromCardNumber("5555555555554444")) + } + + @Test + fun `numbers in the 2221 to 2720 series are mastercard`() { + assertEquals(CardBrand.MASTERCARD, CardBrand.fromCardNumber("2221000000000009")) + assertEquals(CardBrand.MASTERCARD, CardBrand.fromCardNumber("2720999999999996")) + } + + @Test + fun `numbers outside the 2 series edges are not mastercard`() { + assertEquals(CardBrand.UNKNOWN, CardBrand.fromCardNumber("2220990000000000")) + assertEquals(CardBrand.UNKNOWN, CardBrand.fromCardNumber("2721000000000000")) + } + + @Test + fun `numbers starting with 34 or 37 are american express`() { + assertEquals(CardBrand.AMERICAN_EXPRESS, CardBrand.fromCardNumber("340000000000009")) + assertEquals(CardBrand.AMERICAN_EXPRESS, CardBrand.fromCardNumber("370000000000002")) + } + + @Test + fun `unrecognized prefixes and empty input are unknown`() { + assertEquals(CardBrand.UNKNOWN, CardBrand.fromCardNumber("6011000000000004")) + assertEquals(CardBrand.UNKNOWN, CardBrand.fromCardNumber("")) + assertEquals(CardBrand.UNKNOWN, CardBrand.fromCardNumber("abc")) + } + + @Test + fun `detection ignores spaces and dashes`() { + assertEquals(CardBrand.VISA, CardBrand.fromCardNumber("4111 1111 1111 1111")) + assertEquals(CardBrand.MASTERCARD, CardBrand.fromCardNumber("5105-1051-0510-5100")) + } + + @Test + fun `api brand names map to their brand ignoring case`() { + assertEquals(CardBrand.VISA, CardBrand.fromBrandName("visa")) + assertEquals(CardBrand.VISA, CardBrand.fromBrandName("VISA")) + assertEquals(CardBrand.MASTERCARD, CardBrand.fromBrandName("mastercard")) + assertEquals(CardBrand.MASTERCARD, CardBrand.fromBrandName("master_card")) + assertEquals(CardBrand.AMERICAN_EXPRESS, CardBrand.fromBrandName("american_express")) + assertEquals(CardBrand.AMERICAN_EXPRESS, CardBrand.fromBrandName("amex")) + } + + @Test + fun `surrounding spaces in the api brand name are ignored`() { + assertEquals(CardBrand.VISA, CardBrand.fromBrandName(" visa ")) + } + + @Test + fun `null, empty and unrecognized brand names are unknown`() { + assertEquals(CardBrand.UNKNOWN, CardBrand.fromBrandName(null)) + assertEquals(CardBrand.UNKNOWN, CardBrand.fromBrandName("")) + assertEquals(CardBrand.UNKNOWN, CardBrand.fromBrandName("carnet")) + } + + @Test + fun `american express expects four digit security codes, the rest three`() { + assertEquals(4, CardBrand.AMERICAN_EXPRESS.securityCodeLength) + assertEquals(3, CardBrand.VISA.securityCodeLength) + assertEquals(3, CardBrand.MASTERCARD.securityCodeLength) + assertEquals(3, CardBrand.UNKNOWN.securityCodeLength) + } +} diff --git a/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/validation/CardValidatorTest.kt b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/validation/CardValidatorTest.kt new file mode 100644 index 0000000..9255c23 --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/validation/CardValidatorTest.kt @@ -0,0 +1,169 @@ +package mx.dev1.openpay.sdk.domain.validation + +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset +import mx.dev1.openpay.sdk.domain.model.Card +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class CardValidatorTest { + + /** Frozen at 2026-06-15 UTC so expiration tests are deterministic. */ + private val frozenClock: Clock = + Clock.fixed(Instant.parse("2026-06-15T12:00:00Z"), ZoneOffset.UTC) + + // Card number + + @Test + fun `valid numbers of every brand pass`() { + assertTrue(CardValidator.isValidCardNumber("4111111111111111")) + assertTrue(CardValidator.isValidCardNumber("5555555555554444")) + assertTrue(CardValidator.isValidCardNumber("378282246310005")) + } + + @Test + fun `separators are tolerated in card numbers`() { + assertTrue(CardValidator.isValidCardNumber("4111 1111 1111 1111")) + assertTrue(CardValidator.isValidCardNumber("4111-1111-1111-1111")) + } + + @Test + fun `luhn failures are rejected`() { + assertFalse(CardValidator.isValidCardNumber("4111111111111112")) + } + + @Test + fun `non numeric and empty input is rejected`() { + assertFalse(CardValidator.isValidCardNumber("")) + assertFalse(CardValidator.isValidCardNumber("4111a11111111111")) + } + + @Test + fun `too short and too long numbers are rejected`() { + assertFalse(CardValidator.isValidCardNumber("41111111111")) + assertFalse(CardValidator.isValidCardNumber("41111111111111111111")) + } + + // Holder name + + @Test + fun `names with accents and common punctuation pass`() { + assertTrue(CardValidator.isValidHolderName("Juan Pérez Ramírez")) + assertTrue(CardValidator.isValidHolderName("Éloïse D'Angelo-Smith")) + assertTrue(CardValidator.isValidHolderName("João da Silva Jr.")) + } + + @Test + fun `blank short and symbol names are rejected`() { + assertFalse(CardValidator.isValidHolderName("")) + assertFalse(CardValidator.isValidHolderName(" ")) + assertFalse(CardValidator.isValidHolderName("J")) + assertFalse(CardValidator.isValidHolderName("Juan