Documentation/Kotlin SDK
KOTLIN 2.0 / JVM 17+ CLIENT

PayCow
Kotlin SDK

Idiomatic Kotlin client for the PayCow non-custodial USDT payment API with typed data classes, BigDecimal precision, Kotlin Coroutines async support, and timing-safe HMAC-SHA256 webhook verification.

KT

net.paycow:paycow-kotlin-sdk

Gradle Kotlin DSL project with Jackson Kotlin module, Kotlinx Coroutines, and JUnit 5 tests.

KOTLIN 2.0+JVM 17+COROUTINESBIGDECIMAL

Installation

Extract paycow-kotlin-sdk.zip and publish the artifact to your local Maven repository using Gradle:

cd paycow-kotlin-sdk
./gradlew test publishToMavenLocal

Add mavenLocal() and the SDK dependency in your application's build.gradle.kts:

repositories {
    mavenCentral()
    mavenLocal()
}

dependencies {
    implementation("net.paycow:paycow-kotlin-sdk:1.0.0")
}

Client configuration

Use PayCowConfig when you want explicit connect/request timeouts or a custom base URL, or use the convenience constructor for defaults (https://paycow.net, 10s connect, 20s request timeout):

import net.paycow.sdk.PayCowClient
import net.paycow.sdk.PayCowConfig
import java.time.Duration

val config = PayCowConfig(
    apiKey = System.getenv("PAYCOW_API_KEY"),
    apiSecret = System.getenv("PAYCOW_API_SECRET"),
    baseUrl = "https://paycow.net",
    connectTimeout = Duration.ofSeconds(10),
    requestTimeout = Duration.ofSeconds(25)
)

val paycow = PayCowClient(config)

Create a payment

createPayment validates inputs locally, sends POST /api/payment/create with Idempotency-Key, and returns a typed PaymentSession.

import net.paycow.sdk.*
import java.math.BigDecimal

val session = paycow.createPayment(
    CreatePaymentRequest(
        userId = "customer-2048",
        amount = BigDecimal("50.00"),
        network = PayCowNetwork.TRC20,
        paymentMethod = PaymentMethod.ONCHAIN,
        addressSerialNo = "WAL-1002",
        idempotencyKey = "order-2048-001"
    )
)

println("Session ID: ${session.sessionId}")
println("Checkout URL: ${session.paymentUrl}")
println("Exact Payable USDT: ${session.payableAmount}")
println("Deposit Address: ${session.depositAddress}")
Always instruct the customer (or on-ramp provider) to send session.payableAmount rather than amountRequested so micro-amount matching succeeds cleanly. Use PaymentMethod.ONRAMP only on eligible Pro, Scale, or Enterprise merchant accounts.

Coroutines & CompletableFuture

For Ktor, Spring WebFlux, or non-blocking services, use createPaymentAsync and getPaymentStatusAsync inside any coroutine scope, or createPaymentFuture for Java interop:

import kotlinx.coroutines.runBlocking

runBlocking {
    val session = paycow.createPaymentAsync(
        CreatePaymentRequest(
            userId = "customer-2048",
            amount = BigDecimal("50.00"),
            network = PayCowNetwork.ERC20,
            idempotencyKey = "order-2048-002"
        )
    )
    val status = paycow.getPaymentStatusAsync(session.sessionId)
    println("Current status: ${status.status}")
}

Retrieve payment status

Poll getPaymentStatus(sessionId) when reconciling pending orders or displaying live confirmation counts:

val payment = paycow.getPaymentStatus("66ce30d74c0c51a48f2d2903")

when {
    payment.isPaid() -> creditOrderOnce(payment.userId, payment.paymentReference)
    payment.isConfirming() -> logger.info("Confirmations: ${payment.confirmations}")
    payment.isExpired() -> markOrderExpired(payment.paymentReference)
}

Verify webhooks (Ktor / Spring)

Read the raw unchanged request body bytes before JSON parsing, then pass the timestamp and signature headers to WebhookVerifier.verify:

import net.paycow.sdk.WebhookVerifier

// Example inside a Ktor route or Spring @PostMapping
val rawBodyBytes: ByteArray = call.receive<ByteArray>()
val timestamp = call.request.headers["X-PayCow-Timestamp"]
    ?: call.request.headers["PayCow-Timestamp"].orEmpty()
val signature = call.request.headers["X-PayCow-Signature"]
    ?: call.request.headers["PayCow-Signature"].orEmpty()

val event = WebhookVerifier.verify(
    rawBody = rawBodyBytes,
    timestamp = timestamp,
    signature = signature,
    secret = System.getenv("PAYCOW_WEBHOOK_SECRET")
)

if (event.status.equals("PAID", ignoreCase = true)) {
    creditOrderOnce(event.userId, event.paymentReference)
}

WebhookVerifier enforces the v1=<64 hex> signature format, signs timestamp.rawBody with HMAC-SHA256, compares digests using MessageDigest.isEqual, and rejects timestamps older than 300 seconds.

Error hierarchy

All SDK exceptions extend PayCowException:

  • PayCowValidationException: Invalid local arguments (blank credentials, non-positive amount, empty session ID).
  • PayCowApiException: Non-2xx HTTP response from PayCow (exposes statusCode and responseBody).
  • PayCowWebhookException: Missing headers, expired timestamp, invalid signature format, or signature mismatch.
try {
    paycow.createPayment(request)
} catch (ex: PayCowValidationException) {
    // Fix caller input before retrying
} catch (ex: PayCowApiException) {
    logger.error("PayCow HTTP ${ex.statusCode}: ${ex.responseBody}")
}

Security best practices

Mobile / Android apps: Never ship PAYCOW_API_SECRET or PAYCOW_WEBHOOK_SECRET inside an Android APK. Run paycow-kotlin-sdk on your backend (Ktor, Spring Boot, Micronaut) and return only paymentUrl or sessionId to mobile clients.

API contract

SDK methodBackend endpointRequired values
createPayment / createPaymentAsyncPOST /api/payment/createuserId, amount, network
getPaymentStatus / getPaymentStatusAsyncGET /api/payment/status/:idsessionId
WebhookVerifier.verifyLocal verificationrawBody, timestamp, signature, secret