package com.bilimway.payme import android.util.Base64 import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext /** * Repository handling all Payme billing processing, card authorization, and receipts. * Uses Kotlin Coroutines (Dispatchers.IO) for safe background networking. */ class PaymeRepository( private val paymeApi: PaymeApi, private val merchantId: String = "61ebf7c02b9e67ca081b312b", // Placeholder Sandbox Merchant ID private val secretKey: String = "mU_sh9zLsnr7&76kZ2vWsc_fP76" // Placeholder Sandbox Secret Key ) { // Helper to generate the Base64 X-Auth Header required by Payme Merchants API private val authHeader: String get() { val credentials = "$merchantId:$secretKey" return "Basic " + Base64.encodeToString(credentials.toByteArray(), Base64.NO_WRAP) } /** * Step 1: Register input card details to obtain a secure card token. * Note: Card info is sent directly to Payme servers. We do not store card numbers locally! */ suspend fun registerCard(cardNumber: String, cardExpiry: String): Result = withContext(Dispatchers.IO) { try { val cleanCard = cardNumber.replace(" ", "") val cleanExpiry = cardExpiry.replace("/", "") val params = mapOf( "card" to mapOf( "number" to cleanCard, "expire" to cleanExpiry ), "save" to true // Save token for quick checkout ) val request = PaymeRpcRequest(method = "cards.create", params = params) val response = paymeApi.executeJsonRpc(authHeader, request) if (response.error != null) { Result.failure(Exception("Payme Error ${response.error.code}: ${response.error.message}")) } else { val cardToken = (response.result?.get("card") as? Map<*, *>)?.get("token") as? String ?: return@withContext Result.failure(Exception("Karta tokeni qabul qilinmadi.")) Result.success(cardToken) } } catch (e: Exception) { Result.failure(e) } } /** * Step 2: Trigger the SMS OTP 6-digit confirmation stream for the specific card token. */ suspend fun getVerifyCode(cardToken: String): Result = withContext(Dispatchers.IO) { try { val params = mapOf("token" to cardToken) val request = PaymeRpcRequest(method = "cards.get_verify_code", params = params) val response = paymeApi.executeJsonRpc(authHeader, request) if (response.error != null) { Result.failure(Exception("OTP Error ${response.error.code}: ${response.error.message}")) } else { val sent = response.result?.get("sent") as? Boolean ?: false Result.success(sent) } } catch (e: Exception) { Result.failure(e) } } /** * Step 3: Complete verification of the card using the 6-digit verification OTP code. */ suspend fun verifyCard(cardToken: String, otpCode: String): Result = withContext(Dispatchers.IO) { try { val params = mapOf( "token" to cardToken, "code" to otpCode ) val request = PaymeRpcRequest(method = "cards.verify", params = params) val response = paymeApi.executeJsonRpc(authHeader, request) if (response.error != null) { Result.failure(Exception("Kodni tekshirishda xatolik: ${response.error.message}")) } else { Result.success(Unit) } } catch (e: Exception) { Result.failure(e) } } /** * Step 4: Create a receipt representing the transaction in UZS. * Note: Payme amount is represented in Tiyins (1 UZS = 100 tiyins). */ suspend fun createAndPayReceipt(cardToken: String, amountUzs: Long): Result = withContext(Dispatchers.IO) { try { val amountInTiyins = amountUzs * 100 // Create Receipt val createParams = mapOf( "amount" to amountInTiyins, "account" to mapOf("service_id" to "bilimway_topup") ) val createRequest = PaymeRpcRequest(method = "receipts.create", params = createParams) val createResponse = paymeApi.executeJsonRpc(authHeader, createRequest) if (createResponse.error != null) { return@withContext Result.failure(Exception("Receipt error: ${createResponse.error.message}")) } val receiptId = (createResponse.result?.get("receipt") as? Map<*, *>)?.get("_id") as? String ?: return@withContext Result.failure(Exception("Kvitansiya ID olinmadi.")) // Pay Receipt immediately with verified card token val payParams = mapOf( "id" to receiptId, "token" to cardToken ) val payRequest = PaymeRpcRequest(method = "receipts.pay", params = payParams) val payResponse = paymeApi.executeJsonRpc(authHeader, payRequest) if (payResponse.error != null) { Result.failure(Exception("To'lov xatoligi: ${payResponse.error.message}")) } else { Result.success(true) } } catch (e: Exception) { Result.failure(e) } } }