@fire-spark/payments-transbank-client 0.0.0-stage → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ plugins {
2
+ id 'com.android.library'
3
+ id 'expo-module-gradle-plugin'
4
+ }
5
+
6
+ group = 'dev.firespark.payments.transbank'
7
+ version = '0.1.0'
8
+
9
+ android {
10
+ namespace "dev.firespark.payments.transbank"
11
+ defaultConfig {
12
+ versionCode 1
13
+ versionName "0.1.0"
14
+ }
15
+ }
16
+
17
+ dependencies {
18
+ // The app module ships the JARs (copied by the config plugin).
19
+ compileOnly files("${rootProject.projectDir}/app/libs/cyc-h2hpos-client-2.6.jar")
20
+ compileOnly files("${rootProject.projectDir}/app/libs/cyc-h2hpos-caller-eculink-2.5.jar")
21
+ compileOnly files("${rootProject.projectDir}/app/libs/EcuLink-1.0-SNAPSHOT.jar")
22
+ compileOnly files("${rootProject.projectDir}/app/libs/jSerialComm-2.11.0.jar")
23
+ }
@@ -0,0 +1,5 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.INTERNET" />
3
+ <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
4
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
5
+ </manifest>
@@ -0,0 +1,16 @@
1
+ package dev.firespark.payments.transbank
2
+
3
+ import android.util.Log
4
+
5
+ /** Process-wide gate for `TRANSBANK_DEBUG` logcat lines. Off until `setLogs`. */
6
+ internal object TransbankDebug {
7
+ const val TAG = "TRANSBANK_DEBUG"
8
+
9
+ @Volatile
10
+ var enabled: Boolean = false
11
+
12
+ fun log(message: String) {
13
+ if (!enabled) return
14
+ Log.d(TAG, message)
15
+ }
16
+ }
@@ -0,0 +1,144 @@
1
+ package dev.firespark.payments.transbank
2
+
3
+ import android.content.Context
4
+ import android.os.Environment
5
+ import cl.cyc.h2hpos.api.Invocador
6
+ import com.fazecast.jSerialComm.SerialPort
7
+ import expo.modules.kotlin.Promise
8
+ import expo.modules.kotlin.modules.Module
9
+ import expo.modules.kotlin.modules.ModuleDefinition
10
+ import java.io.File
11
+ import java.io.IOException
12
+ import java.util.concurrent.Executors
13
+
14
+ /**
15
+ * Same directory KIOSCOS uses: public Download/SDKChile.
16
+ * Keep it in sync with REQUIREMENT_PATH in the pinpad package.
17
+ */
18
+ class TransbankModule : Module() {
19
+ private val executor = Executors.newSingleThreadExecutor()
20
+
21
+ @Volatile
22
+ private var loaded = false
23
+
24
+ private fun context(): Context {
25
+ val react = appContext.reactContext
26
+ return react?.applicationContext
27
+ ?: throw IllegalStateException("React context lost")
28
+ }
29
+
30
+ private fun loadSerial() {
31
+ if (loaded) return
32
+ synchronized(this) {
33
+ if (loaded) return
34
+ System.loadLibrary("jSerialComm")
35
+ SerialPort.setAndroidContext(context())
36
+ loaded = true
37
+ }
38
+ }
39
+
40
+ private fun directory(): File {
41
+ val dir = Environment.getExternalStoragePublicDirectory("Download/SDKChile/")
42
+ if (dir == null || (!dir.exists() && !dir.mkdirs())) {
43
+ throw IOException("Could not create the Transbank directory")
44
+ }
45
+ return dir
46
+ }
47
+
48
+ private fun writeFile(contents: String) {
49
+ File(directory(), "spdh40.properties").writeText(contents)
50
+ }
51
+
52
+ private fun invoke(call: (Invocador) -> String): String {
53
+ loadSerial()
54
+ return call(Invocador(directory()))
55
+ }
56
+
57
+ /** `TXCRET` and `AUTRET` only. The raw pair string stays off logcat. */
58
+ private fun field(raw: String, name: String): String? {
59
+ for (pair in raw.split('&')) {
60
+ val index = pair.indexOf('=')
61
+ if (index <= 0) continue
62
+ if (pair.substring(0, index) != name) continue
63
+ return pair.substring(index + 1)
64
+ }
65
+ return null
66
+ }
67
+
68
+ private fun codes(raw: String): String {
69
+ val txcret = field(raw, "TXCRET")
70
+ val autret = field(raw, "AUTRET")
71
+ val parts = ArrayList<String>()
72
+ if (txcret != null) parts.add("TXCRET=$txcret")
73
+ if (autret != null) parts.add("AUTRET=$autret")
74
+ return parts.joinToString(" ")
75
+ }
76
+
77
+ private fun timed(name: String, block: () -> Any?): Any? {
78
+ TransbankDebug.log("$name › start")
79
+ val started = System.currentTimeMillis()
80
+ try {
81
+ val value = block()
82
+ val ms = System.currentTimeMillis() - started
83
+ val extra = if (value is String) codes(value) else ""
84
+ val suffix = if (extra.isEmpty()) "" else " $extra"
85
+ TransbankDebug.log("$name › ok ms=$ms$suffix")
86
+ return value
87
+ } catch (error: Throwable) {
88
+ val ms = System.currentTimeMillis() - started
89
+ val message = error.message ?: error.javaClass.simpleName
90
+ TransbankDebug.log("$name › error ms=$ms message=$message")
91
+ throw error
92
+ }
93
+ }
94
+
95
+ private fun run(name: String, promise: Promise, block: () -> Any?) {
96
+ executor.execute {
97
+ try {
98
+ promise.resolve(timed(name, block))
99
+ } catch (error: Throwable) {
100
+ val message = error.message ?: "Transbank failed"
101
+ val cause = error as? Exception ?: Exception(message, error)
102
+ promise.reject("TRANSBANK_ERROR", message, cause)
103
+ }
104
+ }
105
+ }
106
+
107
+ override fun definition() = ModuleDefinition {
108
+ Name("Transbank")
109
+
110
+ Function("setLogs") { enabled: Boolean ->
111
+ TransbankDebug.enabled = enabled
112
+ }
113
+
114
+ AsyncFunction("writeProperties") { contents: String, promise: Promise ->
115
+ run("writeProperties", promise) { writeFile(contents) }
116
+ }
117
+
118
+ AsyncFunction("creditPurchase") { body: String, promise: Promise ->
119
+ run("ventaCredito", promise) { invoke { it.ventaCredito(body) } }
120
+ }
121
+
122
+ AsyncFunction("debitPurchase") { body: String, promise: Promise ->
123
+ run("ventaDebito", promise) { invoke { it.ventaDebito(body) } }
124
+ }
125
+
126
+ AsyncFunction("confirm") { promise: Promise ->
127
+ run("confirmacion", promise) { invoke { it.confirmacion() } }
128
+ }
129
+
130
+ AsyncFunction("reverse") { promise: Promise ->
131
+ run("procesaReversa", promise) { invoke { it.procesaReversa() } }
132
+ }
133
+
134
+ AsyncFunction("refund") { body: String, promise: Promise ->
135
+ run("devolucion", promise) { invoke { it.devolucion(body) } }
136
+ }
137
+
138
+ AsyncFunction("close") { body: String, promise: Promise ->
139
+ run("cierre", promise) { invoke { it.cierre(body) } }
140
+ }
141
+
142
+ OnDestroy { executor.shutdownNow() }
143
+ }
144
+ }
package/app.plugin.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require("./plugin/withTransbank.cjs");
@@ -0,0 +1,47 @@
1
+ //#region src/types.d.ts
2
+ /** Raw `key=value` pairs joined by `&`, as `Invocador` returns them. */
3
+ type TransbankNativeModule = {
4
+ setLogs(enabled: boolean): void;
5
+ writeProperties(contents: string): Promise<void>;
6
+ creditPurchase(requerimiento: string): Promise<string>;
7
+ debitPurchase(requerimiento: string): Promise<string>;
8
+ confirm(): Promise<string>;
9
+ reverse(): Promise<string>;
10
+ refund(requerimiento: string): Promise<string>;
11
+ close(requerimiento: string): Promise<string>;
12
+ };
13
+ //#endregion
14
+ //#region src/client.d.ts
15
+ declare class TransbankUnavailableError extends Error {
16
+ constructor();
17
+ }
18
+ type TransbankClient = {
19
+ readonly available: boolean;
20
+ writeProperties: (contents: string) => Promise<void>;
21
+ creditPurchase: (requerimiento: string) => Promise<string>;
22
+ debitPurchase: (requerimiento: string) => Promise<string>;
23
+ confirm: () => Promise<string>;
24
+ reverse: () => Promise<string>;
25
+ refund: (requerimiento: string) => Promise<string>;
26
+ close: (requerimiento: string) => Promise<string>;
27
+ };
28
+ /** A missing module fails each call. This factory does not throw. */
29
+ declare const createTransbankClient: (native: TransbankNativeModule | null) => TransbankClient;
30
+ //#endregion
31
+ //#region src/debug.d.ts
32
+ /** Turns console and Android logcat traces on or off. Default is off. */
33
+ declare const setTransbankLogs: (value: boolean) => void;
34
+ /** Logs one step: `[TRANSBANK_DEBUG] scope › event { data }`. */
35
+ declare const transbankDebug: (scope: string, event: string, data?: unknown) => void;
36
+ /** Logs the input, the output or the error, and the duration of a call. */
37
+ declare const transbankDebugCall: <T>(scope: string, input: unknown, call: () => Promise<T>) => Promise<T>;
38
+ //#endregion
39
+ //#region src/native.d.ts
40
+ /** `null` on iOS, web, or an Android build without this plugin. */
41
+ declare const transbankNative: TransbankNativeModule | null;
42
+ //#endregion
43
+ //#region src/index.d.ts
44
+ /** Client bound to the device module. `available` is false without it. */
45
+ declare const transbank: TransbankClient;
46
+ //#endregion
47
+ export { type TransbankClient, type TransbankNativeModule, TransbankUnavailableError, createTransbankClient, setTransbankLogs, transbank, transbankDebug, transbankDebugCall, transbankNative };
package/dist/index.mjs ADDED
@@ -0,0 +1,116 @@
1
+ import { requireOptionalNativeModule } from "expo";
2
+ //#region src/client.ts
3
+ var TransbankUnavailableError = class extends Error {
4
+ constructor() {
5
+ super("Transbank pinpad is not available on this device");
6
+ this.name = "TransbankUnavailableError";
7
+ }
8
+ };
9
+ /** A missing module fails each call. This factory does not throw. */
10
+ const createTransbankClient = (native) => {
11
+ const call = async (run) => {
12
+ if (!native) throw new TransbankUnavailableError();
13
+ return run(native);
14
+ };
15
+ return {
16
+ available: !!native,
17
+ writeProperties: (contents) => call((mod) => mod.writeProperties(contents)),
18
+ creditPurchase: (body) => call((mod) => mod.creditPurchase(body)),
19
+ debitPurchase: (body) => call((mod) => mod.debitPurchase(body)),
20
+ confirm: () => call((mod) => mod.confirm()),
21
+ reverse: () => call((mod) => mod.reverse()),
22
+ refund: (body) => call((mod) => mod.refund(body)),
23
+ close: (body) => call((mod) => mod.close(body))
24
+ };
25
+ };
26
+ //#endregion
27
+ //#region src/native.ts
28
+ /** `null` on iOS, web, or an Android build without this plugin. */
29
+ const transbankNative = requireOptionalNativeModule("Transbank");
30
+ //#endregion
31
+ //#region src/debug.ts
32
+ const TAG = "[TRANSBANK_DEBUG]";
33
+ /** 14–19 digits. Amounts, dates and short ids stay as-is. */
34
+ const PAN = /\d{14,19}/g;
35
+ /** Track 1/2 sentinels. The payload is not a field we record on purpose. */
36
+ const TRACK = /[%;][\dA-Za-z=^]{12,}/g;
37
+ const HIDDEN = /* @__PURE__ */ new Set(["VOUCHER", "voucher"]);
38
+ let enabled = false;
39
+ const elapsed = (startedAt) => Date.now() - startedAt;
40
+ /** Drops the voucher pair. Its text can carry the PAN. */
41
+ const dropVoucher = (value) => {
42
+ return value.split("&").filter((pair) => {
43
+ const index = pair.indexOf("=");
44
+ if (index <= 0) return true;
45
+ return pair.slice(0, index) !== "VOUCHER";
46
+ }).join("&");
47
+ };
48
+ const mask = (value) => {
49
+ return dropVoucher(value).replace(TRACK, "<track>").replace(PAN, (digits) => {
50
+ return `************${digits.slice(-4)}`;
51
+ });
52
+ };
53
+ const safe = (value) => {
54
+ if (typeof value === "string") return mask(value);
55
+ if (value instanceof Map) return safe(Object.fromEntries(value));
56
+ if (value instanceof Error) {
57
+ const code = value.code;
58
+ const message = mask(value.message);
59
+ return {
60
+ name: value.name,
61
+ message,
62
+ code
63
+ };
64
+ }
65
+ if (Array.isArray(value)) return value.map((item) => safe(item));
66
+ if (!value || typeof value !== "object") return value;
67
+ const out = {};
68
+ for (const [name, item] of Object.entries(value)) {
69
+ if (HIDDEN.has(name)) continue;
70
+ out[name] = safe(item);
71
+ }
72
+ return out;
73
+ };
74
+ /** Turns console and Android logcat traces on or off. Default is off. */
75
+ const setTransbankLogs = (value) => {
76
+ enabled = value;
77
+ transbankNative?.setLogs(value);
78
+ };
79
+ /** Logs one step: `[TRANSBANK_DEBUG] scope › event { data }`. */
80
+ const transbankDebug = (scope, event, data) => {
81
+ if (!enabled) return;
82
+ const time = (/* @__PURE__ */ new Date()).toISOString();
83
+ const line = `${scope} › ${event}`;
84
+ if (data === void 0) {
85
+ console.log(TAG, time, line);
86
+ return;
87
+ }
88
+ console.log(TAG, time, line, safe(data));
89
+ };
90
+ /** Logs the input, the output or the error, and the duration of a call. */
91
+ const transbankDebugCall = async (scope, input, call) => {
92
+ const startedAt = Date.now();
93
+ transbankDebug(scope, "→ in", input);
94
+ try {
95
+ const output = await call();
96
+ const ms = elapsed(startedAt);
97
+ transbankDebug(scope, "← out", {
98
+ output,
99
+ ms
100
+ });
101
+ return output;
102
+ } catch (error) {
103
+ const ms = elapsed(startedAt);
104
+ transbankDebug(scope, "✕ error", {
105
+ error,
106
+ ms
107
+ });
108
+ throw error;
109
+ }
110
+ };
111
+ //#endregion
112
+ //#region src/index.ts
113
+ /** Client bound to the device module. `available` is false without it. */
114
+ const transbank = createTransbankClient(transbankNative);
115
+ //#endregion
116
+ export { TransbankUnavailableError, createTransbankClient, setTransbankLogs, transbank, transbankDebug, transbankDebugCall, transbankNative };
@@ -0,0 +1,6 @@
1
+ {
2
+ "platforms": ["android"],
3
+ "android": {
4
+ "modules": ["dev.firespark.payments.transbank.TransbankModule"]
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@fire-spark/payments-transbank-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.18.0",
4
+ "description": "Fire Spark native client for Transbank Hasar H2H on Android. Writes spdh40.properties and calls cl.cyc.h2hpos.api.Invocador.",
5
+ "sideEffects": false,
6
+ "files": [
7
+ "dist",
8
+ "android/build.gradle",
9
+ "android/src",
10
+ "plugin",
11
+ "app.plugin.js",
12
+ "expo-module.config.json"
13
+ ],
14
+ "main": "./dist/index.mjs",
15
+ "types": "./dist/index.d.mts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.mts",
19
+ "import": "./dist/index.mjs",
20
+ "default": "./dist/index.mjs"
21
+ },
22
+ "./app.plugin": "./app.plugin.js",
23
+ "./package.json": "./package.json"
24
+ },
25
+ "peerDependencies": {
26
+ "expo": ">=57"
27
+ },
28
+ "devDependencies": {
29
+ "expo": "~57.0.25",
30
+ "tsdown": "^0.22.14",
31
+ "typescript": "^7.0.2",
32
+ "vitest": "^2.1.8"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "tsdown": {
38
+ "entry": [
39
+ "src/index.ts"
40
+ ],
41
+ "format": [
42
+ "esm"
43
+ ],
44
+ "platform": "neutral",
45
+ "dts": {
46
+ "tsconfig": "tsconfig.build.json"
47
+ },
48
+ "clean": true,
49
+ "deps": {
50
+ "neverBundle": [
51
+ "expo"
52
+ ]
53
+ }
54
+ },
55
+ "scripts": {
56
+ "build": "tsdown",
57
+ "dev": "tsdown --watch",
58
+ "check-types": "tsc --noEmit",
59
+ "test:utils": "vitest run",
60
+ "lint": "oxlint ./src --max-warnings=0",
61
+ "format": "oxfmt ./src",
62
+ "check-format": "oxfmt --check ./src"
63
+ }
6
64
  }
@@ -0,0 +1,115 @@
1
+ const {
2
+ AndroidConfig,
3
+ withAndroidManifest,
4
+ withAppBuildGradle,
5
+ withDangerousMod
6
+ } = require("expo/config-plugins");
7
+ const fs = require("fs");
8
+ const path = require("path");
9
+
10
+ const JARS = [
11
+ "cyc-h2hpos-client-2.6.jar",
12
+ "cyc-h2hpos-caller-eculink-2.5.jar",
13
+ "EcuLink-1.0-SNAPSHOT.jar",
14
+ "jSerialComm-2.11.0.jar"
15
+ ];
16
+ const SERIAL_LIB = "libjSerialComm.so";
17
+ const MARKER = "// @fire-spark/payments-transbank-client";
18
+
19
+ const copy = (from, to) => {
20
+ fs.mkdirSync(path.dirname(to), { recursive: true });
21
+ fs.copyFileSync(from, to);
22
+ };
23
+
24
+ /**
25
+ * Expected layout of `binariesDir` (never committed):
26
+ * cyc-h2hpos-client-2.6.jar
27
+ * cyc-h2hpos-caller-eculink-2.5.jar
28
+ * EcuLink-1.0-SNAPSHOT.jar
29
+ * jSerialComm-2.11.0.jar
30
+ * jniLibs/<abi>/libjSerialComm.so
31
+ */
32
+ const withTransbankBinaries = (config, { binariesDir }) =>
33
+ withDangerousMod(config, [
34
+ "android",
35
+ async cfg => {
36
+ const source = path.resolve(cfg.modRequest.projectRoot, binariesDir);
37
+ const app = path.join(cfg.modRequest.platformProjectRoot, "app");
38
+ for (const jar of JARS) {
39
+ const from = path.join(source, jar);
40
+ if (!fs.existsSync(from)) {
41
+ throw new Error(
42
+ `[transbank] missing ${from}; set binariesDir to the Hasar H2H files`
43
+ );
44
+ }
45
+ copy(from, path.join(app, "libs", jar));
46
+ }
47
+ const jniLibs = path.join(source, "jniLibs");
48
+ const libs = fs.existsSync(jniLibs)
49
+ ? fs.readdirSync(jniLibs, { recursive: true })
50
+ : [];
51
+ const so = libs.filter(file => String(file).endsWith(".so"));
52
+ const serial = so.some(file => path.basename(String(file)) === SERIAL_LIB);
53
+ if (!serial) {
54
+ throw new Error(`[transbank] no ${SERIAL_LIB} found under ${jniLibs}/<abi>/`);
55
+ }
56
+ for (const file of so) {
57
+ const from = path.join(jniLibs, String(file));
58
+ const to = path.join(app, "src/main/jniLibs", String(file));
59
+ copy(from, to);
60
+ }
61
+ return cfg;
62
+ }
63
+ ]);
64
+
65
+ const gradleDeps = JARS.map(jar => {
66
+ return ` implementation files("libs/${jar}")`;
67
+ }).join("\n");
68
+
69
+ const gradleBlock = `
70
+ ${MARKER}
71
+ android {
72
+ packagingOptions {
73
+ jniLibs {
74
+ useLegacyPackaging true
75
+ }
76
+ }
77
+ }
78
+ dependencies {
79
+ ${gradleDeps}
80
+ }
81
+ `;
82
+
83
+ const withTransbankGradle = config =>
84
+ withAppBuildGradle(config, cfg => {
85
+ if (!cfg.modResults.contents.includes(MARKER)) {
86
+ cfg.modResults.contents += gradleBlock;
87
+ }
88
+ return cfg;
89
+ });
90
+
91
+ const withLegacyStorage = config =>
92
+ withAndroidManifest(config, cfg => {
93
+ const app = AndroidConfig.Manifest.getMainApplicationOrThrow(cfg.modResults);
94
+ app.$["android:requestLegacyExternalStorage"] = "true";
95
+ return cfg;
96
+ });
97
+
98
+ const PERMISSIONS = [
99
+ "android.permission.INTERNET",
100
+ "android.permission.READ_EXTERNAL_STORAGE",
101
+ "android.permission.WRITE_EXTERNAL_STORAGE"
102
+ ];
103
+
104
+ /** @param {{ binariesDir: string }} options */
105
+ const withTransbank = (config, options = {}) => {
106
+ if (!options.binariesDir) {
107
+ throw new Error("[transbank] the plugin needs { binariesDir }");
108
+ }
109
+ config = AndroidConfig.Permissions.withPermissions(config, PERMISSIONS);
110
+ config = withLegacyStorage(config);
111
+ config = withTransbankBinaries(config, options);
112
+ return withTransbankGradle(config);
113
+ };
114
+
115
+ module.exports = withTransbank;
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.