From 13e5a3588484047a966f359c4ece833a37e4fb44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 29 Sep 2026 15:17:12 -0600 Subject: [PATCH 01/21] feat: multi-module project structure with openpay-sdk library - Add :openpay-sdk Android library module (Compose-enabled, minSdk 26, AGP 9 built-in Kotlin, kotlinx.serialization plugin) - Expand libs.versions.toml with Kotlin, Compose BOM, Koin, Ktor, kotlinx libraries, Mockito, Robolectric and JaCoCo versions - Add shared JaCoCo convention in the root build: per-module jacocoTestReport and jacocoCoverageVerification (80% line minimum) - Convert :app to Kotlin + Compose with a placeholder screen consuming the SDK, Material 3 theme and edge-to-edge activity - Pin androidx.core to 1.17.0 (1.19.0 requires compileSdk 37 / AGP 9.1) Co-Authored-By: Claude Fable 5 --- app/build.gradle.kts | 43 ++++++++- app/src/main/AndroidManifest.xml | 15 ++- .../main/java/mx/dev1/openpay/MainActivity.kt | 47 ++++++++++ app/src/main/res/values-night/themes.xml | 16 ---- app/src/main/res/values/strings.xml | 3 +- app/src/main/res/values/themes.xml | 19 +--- build.gradle.kts | 87 +++++++++++++++++- gradle/libs.versions.toml | 66 ++++++++++++-- openpay-sdk/.gitignore | 1 + openpay-sdk/build.gradle.kts | 91 +++++++++++++++++++ openpay-sdk/consumer-rules.pro | 9 ++ openpay-sdk/proguard-rules.pro | 3 + openpay-sdk/src/main/AndroidManifest.xml | 6 ++ .../kotlin/mx/dev1/openpay/sdk/OpenpaySdk.kt | 18 ++++ .../mx/dev1/openpay/sdk/OpenpaySdkTest.kt | 27 ++++++ settings.gradle.kts | 1 + 16 files changed, 410 insertions(+), 42 deletions(-) create mode 100644 app/src/main/java/mx/dev1/openpay/MainActivity.kt delete mode 100644 app/src/main/res/values-night/themes.xml create mode 100644 openpay-sdk/.gitignore create mode 100644 openpay-sdk/build.gradle.kts create mode 100644 openpay-sdk/consumer-rules.pro create mode 100644 openpay-sdk/proguard-rules.pro create mode 100644 openpay-sdk/src/main/AndroidManifest.xml create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/OpenpaySdk.kt create mode 100644 openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/OpenpaySdkTest.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index c31fec5..f186e9f 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,52 @@ 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.activity.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.mockito.core) + testImplementation(libs.mockito.kotlin) + testImplementation(libs.robolectric) + testImplementation(libs.kotlinx.coroutines.test) + 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..42663f1 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -10,6 +10,17 @@ android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" - android:theme="@style/Theme.Openpay" /> + 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..d4042f3 --- /dev/null +++ b/app/src/main/java/mx/dev1/openpay/MainActivity.kt @@ -0,0 +1,47 @@ +package mx.dev1.openpay + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import mx.dev1.openpay.sdk.OpenpaySdk + +class MainActivity : ComponentActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + setContent { + MaterialTheme { + SampleHomeScreen() + } + } + } +} + +@Composable +fun SampleHomeScreen(modifier: Modifier = Modifier) { + Scaffold(modifier = modifier.fillMaxSize()) { innerPadding -> + Text( + text = stringResource(R.string.sdk_version_label, OpenpaySdk.VERSION), + modifier = Modifier.padding(innerPadding), + ) + } +} + +@Preview(showBackground = true) +@Composable +private fun SampleHomeScreenPreview() { + MaterialTheme { + SampleHomeScreen() + } +} 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..f033526 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,3 +1,4 @@ Openpay - \ No newline at end of file + Openpay SDK %1$s + 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/build.gradle.kts b/build.gradle.kts index 3756278..11cd0ee 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,4 +1,89 @@ // 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*Kt*.*", +) + +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/gradle/libs.versions.toml b/gradle/libs.versions.toml index 75c5705..69a5a01 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,20 +1,74 @@ [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" +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-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" } + +# 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..4654f6c --- /dev/null +++ b/openpay-sdk/build.gradle.kts @@ -0,0 +1,91 @@ +plugins { + alias(libs.plugins.android.library) + alias(libs.plugins.kotlin.compose) + alias(libs.plugins.kotlin.serialization) +} + +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 + } + } +} + +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.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) + + 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/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/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/settings.gradle.kts b/settings.gradle.kts index 532955b..9c4252d 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -24,4 +24,5 @@ dependencyResolutionManagement { rootProject.name = "Openpay" include(":app") +include(":openpay-sdk") \ No newline at end of file From 2e5304d36b47eb87bee70745700e6c98bffcd4bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 29 Sep 2026 15:22:02 -0600 Subject: [PATCH 02/21] feat: core layer with domain models, errors, Ktor networking and Koin DI - Domain models: Card (with API-formatted expiration), Address, Token, TokenizedCard as immutable data classes - OpenpayConfig + OpenpayCountry (MX/CO/PE) + OpenpayEnvironment resolve the API base URL, matching the legacy SDK endpoints - OpenpayException sealed hierarchy: ServiceError (API error body) and ConnectionError (transport failures) - Ktor HttpClient factory (CIO engine): Basic auth with public key, SDK user agent, JSON content negotiation, 60s timeouts - OpenpayResponseHandler maps non-2xx responses to ServiceError parsing the documented Openpay error body - Serialization DTOs + mappers between DTOs and domain models - Isolated Koin container (OpenpayKoinContext) so the SDK graph never clashes with a host app using Koin Tests: 23 new unit tests, module line coverage 95.9% Co-Authored-By: Claude Fable 5 --- .../mx/dev1/openpay/sdk/core/OpenpayConfig.kt | 25 +++++ .../dev1/openpay/sdk/core/OpenpayCountry.kt | 20 ++++ .../openpay/sdk/core/OpenpayEnvironment.kt | 10 ++ .../dev1/openpay/sdk/core/OpenpayException.kt | 33 +++++++ .../openpay/sdk/data/mapper/AddressMapper.kt | 31 ++++++ .../openpay/sdk/data/mapper/CardMapper.kt | 30 ++++++ .../openpay/sdk/data/mapper/TokenMapper.kt | 10 ++ .../data/remote/OpenpayHttpClientFactory.kt | 59 +++++++++++ .../sdk/data/remote/OpenpayResponseHandler.kt | 46 +++++++++ .../openpay/sdk/data/remote/dto/AddressDto.kt | 15 +++ .../openpay/sdk/data/remote/dto/CardDto.kt | 25 +++++ .../sdk/data/remote/dto/OpenpayApiErrorDto.kt | 17 ++++ .../openpay/sdk/data/remote/dto/TokenDto.kt | 10 ++ .../dev1/openpay/sdk/di/OpenpayCoreModule.kt | 29 ++++++ .../dev1/openpay/sdk/di/OpenpayKoinContext.kt | 37 +++++++ .../dev1/openpay/sdk/domain/model/Address.kt | 14 +++ .../mx/dev1/openpay/sdk/domain/model/Card.kt | 28 ++++++ .../mx/dev1/openpay/sdk/domain/model/Token.kt | 28 ++++++ .../openpay/sdk/core/OpenpayConfigTest.kt | 43 ++++++++ .../openpay/sdk/core/OpenpayCountryTest.kt | 43 ++++++++ .../openpay/sdk/data/mapper/MapperTest.kt | 98 +++++++++++++++++++ .../remote/OpenpayHttpClientFactoryTest.kt | 70 +++++++++++++ .../data/remote/OpenpayResponseHandlerTest.kt | 77 +++++++++++++++ .../openpay/sdk/di/OpenpayKoinContextTest.kt | 65 ++++++++++++ .../dev1/openpay/sdk/domain/model/CardTest.kt | 40 ++++++++ 25 files changed, 903 insertions(+) create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayConfig.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayCountry.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayEnvironment.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayException.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/mapper/AddressMapper.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/mapper/CardMapper.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/mapper/TokenMapper.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayHttpClientFactory.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayResponseHandler.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/AddressDto.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/CardDto.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/OpenpayApiErrorDto.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/data/remote/dto/TokenDto.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayCoreModule.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/di/OpenpayKoinContext.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/model/Address.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/model/Card.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/model/Token.kt create mode 100644 openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/core/OpenpayConfigTest.kt create mode 100644 openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/core/OpenpayCountryTest.kt create mode 100644 openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/mapper/MapperTest.kt create mode 100644 openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayHttpClientFactoryTest.kt create mode 100644 openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/data/remote/OpenpayResponseHandlerTest.kt create mode 100644 openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/di/OpenpayKoinContextTest.kt create mode 100644 openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/model/CardTest.kt 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..9cbe6b1 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/core/OpenpayException.kt @@ -0,0 +1,33 @@ +package mx.dev1.openpay.sdk.core + +/** + * Base type for every error surfaced by the Openpay SDK. + */ +sealed class OpenpayException(message: String, cause: Throwable? = null) : Exception(message, cause) { + + /** + * 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/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/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/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/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) + } +} From 74cb2b68e77f3f2ed83cdeb8ce97c9078735e4a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 29 Sep 2026 15:24:17 -0600 Subject: [PATCH 03/21] feat: card validation domain logic - CardBrand detection from IIN prefixes: Visa, Mastercard (51-55 and 2221-2720 series), American Express, with per-brand CVV length - CardValidator: Luhn check with separator tolerance, holder name rules supporting accented names, brand-aware security code validation and clock-injectable expiration validation (current month .. +20 years) - CardValidationResult reports every invalid field so UIs can point errors to the exact input Tests: 27 new unit tests with a frozen clock, module coverage 95.7% Co-Authored-By: Claude Fable 5 --- .../sdk/domain/validation/CardBrand.kt | 34 ++++ .../sdk/domain/validation/CardField.kt | 11 ++ .../domain/validation/CardValidationResult.kt | 13 ++ .../sdk/domain/validation/CardValidator.kt | 93 ++++++++++ .../sdk/domain/validation/CardBrandTest.kt | 58 ++++++ .../domain/validation/CardValidatorTest.kt | 169 ++++++++++++++++++ 6 files changed, 378 insertions(+) create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardBrand.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardField.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardValidationResult.kt create mode 100644 openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardValidator.kt create mode 100644 openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/validation/CardBrandTest.kt create mode 100644 openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/validation/CardValidatorTest.kt 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..9b087d3 --- /dev/null +++ b/openpay-sdk/src/main/kotlin/mx/dev1/openpay/sdk/domain/validation/CardBrand.kt @@ -0,0 +1,34 @@ +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") + + /** + * 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 + } + } + } +} 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/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..66a18c5 --- /dev/null +++ b/openpay-sdk/src/test/kotlin/mx/dev1/openpay/sdk/domain/validation/CardBrandTest.kt @@ -0,0 +1,58 @@ +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 `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