
Serializing JSON into CPCR/OFD protocol frames and decoding raw binary packets to structured JSON; provider-specific protocol modules, centralized JSON→Protobuf mapping, full offline validation, and trilingual localized error messages.
[!IMPORTANT] Disclaimer: This is an unofficial, community-maintained library. It is not officially endorsed by, affiliated with, or sponsored by the State Revenue Committee of the Republic of Kazakhstan or any official OFD provider.
Дисклеймер: Данный проект является неофициальной библиотекой, поддерживаемой сообществом. Он не связан, не спонсируется и не утверждался Комитетом государственных доходов РК или любыми официальными провайдерами ОФД.
A lightweight, robust, and clean-architecture Kotlin Multiplatform (KMP) library for serializing JSON objects into raw CPCR/OFD protocol format (header + payload) and deserializing raw byte arrays back to structured JSON according to provider-specific KKM-to-OFD protocol modules.
The library is provider/version oriented. At the moment, the only implemented provider module is kazakhtelecom/v203; future OFD providers or protocol versions should be added as separate modules without changing the core codec facade.
kazakhtelecom protocol 203.RU: ... | KK: ... | EN: ...).The library is not published to Maven Central. Every GitHub release carries the compiled library as a ready-made Maven repository for Gradle: ofd-proto-codec-maven-<version>.zip. It contains Gradle module metadata, all KMP targets (JVM, Android, iOS klibs) and the exact builds of the protocol libraries (ofd-kt-proto, ofd-kt-proto-v204) and ofd-network-client the codec was built with, none of which is in Maven Central; the remaining dependencies resolve from Maven Central. The codec's own build takes those libraries the same way — as compiled builds from their GitHub releases, never from sources.
ofd-proto-codec-maven-<version>.zip from the release and unzip it into a folder of your project, e.g. libs/maven.settings.gradle.kts (or build.gradle.kts):dependencyResolutionManagement {
repositories {
maven(uri("libs/maven"))
google()
mavenCentral()
}
}commonMain source set inside build.gradle.kts:kotlin {
sourceSets {
commonMain {
dependencies {
implementation("io.github.texport:ofd-proto-codec:<version>")
}
}
}
}<version> is the release number without the v prefix, e.g. 1.3.0 for release v1.3.0.
You can integrate this library directly into your iOS project using Xcode's Swift Package Manager:
https://github.com/texport/ofd-proto-codec.git
1.2.1.Here is how to initialize the codec and use it to encode a JSON request or decode an OFD binary response:
import kz.mybrain.ofdcodec.application.DefaultRegistry
import kz.mybrain.ofdcodec.application.OfdCodec
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import kotlinx.serialization.json.JsonPrimitive
// 1. Initialize the registry and codec facade
val registry = DefaultRegistry.create()
val codec = OfdCodec(registry)
// 2. Encode a JSON request envelope into raw bytes
val requestEnvelope = buildJsonObject {
put("ofdId", "kazakhtelecom")
put("protocolVersion", "203")
put("messageType", "REQUEST")
put("commandType", "COMMAND_SYSTEM")
put("header", buildJsonObject {
put("appCode", 1)
put("deviceId", 12345L)
put("token", 99999L)
put("reqNum", 42)
})
put("payload", buildJsonObject {
put("service", buildJsonObject {
put("getRegInfo", true)
put("offlinePeriod", buildJsonObject {
put("beginTime", buildJsonObject {
put("date", buildJsonObject { put("year", 2026); put("month", 7); put("day", 5) })
put("time", buildJsonObject { put("hour", 22); put("minute", 0); put("second", 0) })
})
put("endTime", buildJsonObject {
put("date", buildJsonObject { put("year", 2026); put("month", 7); put("day", 5) })
put("time", buildJsonObject { put("hour", 22); put("minute", 0); put("second", 0) })
})
})
put("securityStats", buildJsonObject {
put("ticketAdSentCount", 0)
put("ticketAdFailedCount", 0)
})
put("regInfo", buildJsonObject {
put("kkm", buildJsonObject {
put("fnsKkmId", "123")
put("serialNumber", "456")
put("kkmId", "789")
})
put("org", buildJsonObject {
put("title", "My Org")
put("address", "Address")
put("inn", "123456789012")
put("addressKz", "Address KZ")
})
})
})
})
}
val encodeResult = codec.encode(requestEnvelope)
if (encodeResult.isSuccess) {
val resultJson = encodeResult.getOrThrow()
val size = resultJson["size"]
val messageBase64 = resultJson["messageBase64"]
println("Encoded size: $size")
} else {
val exception = encodeResult.exceptionOrNull()
println("Validation failed: ${exception?.message}")
}
// 3. Decode an OFD binary response packet
val rawResponseBytes: ByteArray = ByteArray(0) // received from OFD server
val decodeResult = codec.decode(rawResponseBytes)
if (decodeResult.isSuccess) {
val responseEnvelope = decodeResult.getOrThrow()
println("Decoded envelope: $responseEnvelope")
}The library follows clean architecture principles:
OfdCodec): Exposes encode and decode endpoints, orchestrating header construction/parsing, handler lookup, and validation.OfdProtocolHandler): Plug-in modules implementing serialization, deserialization, and validation for specific OFD providers.ofd-network-client).Легковесная библиотека на Kotlin Multiplatform (KMP) для сериализации JSON-объектов в сырой формат протокола CPCR/OFD (заголовок + полезная нагрузка) и обратной десериализации байтовых массивов в структурированный JSON через provider-specific модули протокола обмена ККМ → ОФД.
Библиотека спроектирована вокруг отдельных модулей ОФД/версий протокола. На данный момент реализован только модуль kazakhtelecom/v203; новые ОФД или версии протокола должны добавляться отдельными модулями без изменения ядра кодека.
kazakhtelecom, протокол 203.RU: ... | KK: ... | EN: ...).В Maven Central библиотека не публикуется. Каждый выпуск на GitHub несёт собранную библиотеку в виде готового хранилища Maven для Gradle: ofd-proto-codec-maven-<версия>.zip. В нём метаданные модулей Gradle, все цели KMP (JVM, Android, klib для iOS) и те самые сборки библиотек протокола (ofd-kt-proto, ofd-kt-proto-v204) и клиента сети ofd-network-client, с которыми собран кодек, — в Maven Central их нет; остальные зависимости берутся из Maven Central. Сборка самого кодека берёт эти библиотеки так же — готовыми сборками из их выпусков на GitHub, а не из исходников.
ofd-proto-codec-maven-<версия>.zip из выпуска и распакуйте его в папку проекта, например libs/maven.settings.gradle.kts (или build.gradle.kts):dependencyResolutionManagement {
repositories {
maven(uri("libs/maven"))
google()
mavenCentral()
}
}commonMain в build.gradle.kts:kotlin {
sourceSets {
commonMain {
dependencies {
implementation("io.github.texport:ofd-proto-codec:<версия>")
}
}
}
}<версия> — номер выпуска без префикса v, например 1.3.0 для выпуска v1.3.0.
Вы можете подключить библиотеку непосредственно в iOS приложение с помощью Swift Package Manager в Xcode:
https://github.com/texport/ofd-proto-codec.git
1.2.1.[!IMPORTANT] Disclaimer: This is an unofficial, community-maintained library. It is not officially endorsed by, affiliated with, or sponsored by the State Revenue Committee of the Republic of Kazakhstan or any official OFD provider.
Дисклеймер: Данный проект является неофициальной библиотекой, поддерживаемой сообществом. Он не связан, не спонсируется и не утверждался Комитетом государственных доходов РК или любыми официальными провайдерами ОФД.
A lightweight, robust, and clean-architecture Kotlin Multiplatform (KMP) library for serializing JSON objects into raw CPCR/OFD protocol format (header + payload) and deserializing raw byte arrays back to structured JSON according to provider-specific KKM-to-OFD protocol modules.
The library is provider/version oriented. At the moment, the only implemented provider module is kazakhtelecom/v203; future OFD providers or protocol versions should be added as separate modules without changing the core codec facade.
kazakhtelecom protocol 203.RU: ... | KK: ... | EN: ...).The library is not published to Maven Central. Every GitHub release carries the compiled library as a ready-made Maven repository for Gradle: ofd-proto-codec-maven-<version>.zip. It contains Gradle module metadata, all KMP targets (JVM, Android, iOS klibs) and the exact builds of the protocol libraries (ofd-kt-proto, ofd-kt-proto-v204) and ofd-network-client the codec was built with, none of which is in Maven Central; the remaining dependencies resolve from Maven Central. The codec's own build takes those libraries the same way — as compiled builds from their GitHub releases, never from sources.
ofd-proto-codec-maven-<version>.zip from the release and unzip it into a folder of your project, e.g. libs/maven.settings.gradle.kts (or build.gradle.kts):dependencyResolutionManagement {
repositories {
maven(uri("libs/maven"))
google()
mavenCentral()
}
}commonMain source set inside build.gradle.kts:kotlin {
sourceSets {
commonMain {
dependencies {
implementation("io.github.texport:ofd-proto-codec:<version>")
}
}
}
}<version> is the release number without the v prefix, e.g. 1.3.0 for release v1.3.0.
You can integrate this library directly into your iOS project using Xcode's Swift Package Manager:
https://github.com/texport/ofd-proto-codec.git
1.2.1.Here is how to initialize the codec and use it to encode a JSON request or decode an OFD binary response:
import kz.mybrain.ofdcodec.application.DefaultRegistry
import kz.mybrain.ofdcodec.application.OfdCodec
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import kotlinx.serialization.json.JsonPrimitive
// 1. Initialize the registry and codec facade
val registry = DefaultRegistry.create()
val codec = OfdCodec(registry)
// 2. Encode a JSON request envelope into raw bytes
val requestEnvelope = buildJsonObject {
put("ofdId", "kazakhtelecom")
put("protocolVersion", "203")
put("messageType", "REQUEST")
put("commandType", "COMMAND_SYSTEM")
put("header", buildJsonObject {
put("appCode", 1)
put("deviceId", 12345L)
put("token", 99999L)
put("reqNum", 42)
})
put("payload", buildJsonObject {
put("service", buildJsonObject {
put("getRegInfo", true)
put("offlinePeriod", buildJsonObject {
put("beginTime", buildJsonObject {
put("date", buildJsonObject { put("year", 2026); put("month", 7); put("day", 5) })
put("time", buildJsonObject { put("hour", 22); put("minute", 0); put("second", 0) })
})
put("endTime", buildJsonObject {
put("date", buildJsonObject { put("year", 2026); put("month", 7); put("day", 5) })
put("time", buildJsonObject { put("hour", 22); put("minute", 0); put("second", 0) })
})
})
put("securityStats", buildJsonObject {
put("ticketAdSentCount", 0)
put("ticketAdFailedCount", 0)
})
put("regInfo", buildJsonObject {
put("kkm", buildJsonObject {
put("fnsKkmId", "123")
put("serialNumber", "456")
put("kkmId", "789")
})
put("org", buildJsonObject {
put("title", "My Org")
put("address", "Address")
put("inn", "123456789012")
put("addressKz", "Address KZ")
})
})
})
})
}
val encodeResult = codec.encode(requestEnvelope)
if (encodeResult.isSuccess) {
val resultJson = encodeResult.getOrThrow()
val size = resultJson["size"]
val messageBase64 = resultJson["messageBase64"]
println("Encoded size: $size")
} else {
val exception = encodeResult.exceptionOrNull()
println("Validation failed: ${exception?.message}")
}
// 3. Decode an OFD binary response packet
val rawResponseBytes: ByteArray = ByteArray(0) // received from OFD server
val decodeResult = codec.decode(rawResponseBytes)
if (decodeResult.isSuccess) {
val responseEnvelope = decodeResult.getOrThrow()
println("Decoded envelope: $responseEnvelope")
}The library follows clean architecture principles:
OfdCodec): Exposes encode and decode endpoints, orchestrating header construction/parsing, handler lookup, and validation.OfdProtocolHandler): Plug-in modules implementing serialization, deserialization, and validation for specific OFD providers.ofd-network-client).Легковесная библиотека на Kotlin Multiplatform (KMP) для сериализации JSON-объектов в сырой формат протокола CPCR/OFD (заголовок + полезная нагрузка) и обратной десериализации байтовых массивов в структурированный JSON через provider-specific модули протокола обмена ККМ → ОФД.
Библиотека спроектирована вокруг отдельных модулей ОФД/версий протокола. На данный момент реализован только модуль kazakhtelecom/v203; новые ОФД или версии протокола должны добавляться отдельными модулями без изменения ядра кодека.
kazakhtelecom, протокол 203.RU: ... | KK: ... | EN: ...).В Maven Central библиотека не публикуется. Каждый выпуск на GitHub несёт собранную библиотеку в виде готового хранилища Maven для Gradle: ofd-proto-codec-maven-<версия>.zip. В нём метаданные модулей Gradle, все цели KMP (JVM, Android, klib для iOS) и те самые сборки библиотек протокола (ofd-kt-proto, ofd-kt-proto-v204) и клиента сети ofd-network-client, с которыми собран кодек, — в Maven Central их нет; остальные зависимости берутся из Maven Central. Сборка самого кодека берёт эти библиотеки так же — готовыми сборками из их выпусков на GitHub, а не из исходников.
ofd-proto-codec-maven-<версия>.zip из выпуска и распакуйте его в папку проекта, например libs/maven.settings.gradle.kts (или build.gradle.kts):dependencyResolutionManagement {
repositories {
maven(uri("libs/maven"))
google()
mavenCentral()
}
}commonMain в build.gradle.kts:kotlin {
sourceSets {
commonMain {
dependencies {
implementation("io.github.texport:ofd-proto-codec:<версия>")
}
}
}
}<версия> — номер выпуска без префикса v, например 1.3.0 для выпуска v1.3.0.
Вы можете подключить библиотеку непосредственно в iOS приложение с помощью Swift Package Manager в Xcode:
https://github.com/texport/ofd-proto-codec.git
1.2.1.