UNPKG

quivio-transaction-processor

Version:

React Native hook for Card payment integration with DataCap

365 lines 19.3 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PaymentContext = exports.PaymentProvider = void 0; var react_1 = __importStar(require("react")); var react_native_1 = require("react-native"); var types_1 = require("./types"); var react_2 = require("react"); var PaymentContext = (0, react_1.createContext)(undefined); exports.PaymentContext = PaymentContext; function PaymentProvider(_a) { var children = _a.children, config = _a.config, _b = _a.disabled, disabled = _b === void 0 ? false : _b; var DsiEMVManagerBridge = react_native_1.NativeModules.DsiEMVManagerBridge; var _c = (0, react_2.useState)([]), logs = _c[0], setLogs = _c[1]; var _d = (0, react_2.useState)(false), isDeviceConnected = _d[0], setIsDeviceConnected = _d[1]; var _e = (0, react_2.useState)(false), loading = _e[0], setLoading = _e[1]; var _f = (0, react_2.useState)(false), isInitialized = _f[0], setIsInitialized = _f[1]; var eventEmitterRef = (0, react_2.useRef)(null); var listenersRef = (0, react_2.useRef)({}); // Now it's an array of listeners for each event var waitingForEvent = (0, react_2.useRef)(false); var appendLog = (0, react_2.useCallback)(function (type, payload) { setLogs(function (prev) { return __spreadArray([ { type: type, payload: payload, timestamp: Date.now(), } ], prev, true); }); }, []); // Initialize the EMV manager with configuration data (called only once) var initializeEMV = (0, react_2.useCallback)(function (config) { if (isInitialized) { appendLog('initialize', 'EMV already initialized'); setIsInitialized(true); setLoading(false); return; } try { setLoading(true); waitingForEvent.current = true; console.log('Initializing EMV with config:', config); DsiEMVManagerBridge.initialize(config); appendLog('Initialization', "EMV initialized with config: ".concat(JSON.stringify(config))); setIsInitialized(true); } catch (e) { setLoading(false); waitingForEvent.current = false; appendLog('error', "initialize failed: ".concat(e.message)); } }, [isInitialized, appendLog, config]); // Event subscription functions var subscribeToEvent = (0, react_2.useCallback)(function (eventName, callback) { if (eventEmitterRef.current) { var listener = eventEmitterRef.current.addListener(eventName, callback); // Store listener in the ref object if (!listenersRef.current[eventName]) { listenersRef.current[eventName] = []; } listenersRef.current[eventName].push(listener); return listener; // Return listener for potential removal later } }, []); var unsubscribeFromEvent = (0, react_2.useCallback)(function (eventName, callback) { var listeners = listenersRef.current[eventName]; if (listeners) { var listener_1 = listeners.find(function (listener) { return listener.listener === callback; }); if (listener_1) { listener_1.remove(); // Remove the listener from the stored list listenersRef.current[eventName] = listeners.filter(function (l) { return l !== listener_1; }); } } }, []); (0, react_2.useEffect)(function () { if (!DsiEMVManagerBridge) { console.error('Native module DsiEMVManagerBridge not found'); return; } if (disabled) { return; } var emitter = eventEmitterRef.current || new react_native_1.NativeEventEmitter(react_native_1.Platform.OS === 'android' ? DsiEMVManagerBridge : undefined); eventEmitterRef.current = emitter; // Subscribe to all events initially types_1.EVENT_NAMES.forEach(function (event) { var listener = emitter.addListener(event, function (payload) { console.log("React Native received event: ".concat(event), payload); // Handle ping config responses if (event === 'onConfigPingSuccess') { console.log('Setting device connected to TRUE'); appendLog('onConfigPingSuccess', 'Configuration ping successful'); setIsDeviceConnected(true); setLoading(false); waitingForEvent.current = false; } else if (event === 'onConfigPingFailed') { appendLog('onConfigPingFailed', 'Configuration ping failed'); setIsDeviceConnected(false); setLoading(false); waitingForEvent.current = false; } // Handle setup config responses else if (event === 'onConfigCompleted') { appendLog('setupConfigResponse', 'Setup Configured Successfully'); setIsDeviceConnected(true); setLoading(false); waitingForEvent.current = false; } else if (event === 'onConfigError') { appendLog('setupConfigResponse', 'Setup config failed'); setIsDeviceConnected(false); setLoading(false); waitingForEvent.current = false; } // Handle other events else if (event === 'onSaleTransactionCompleted') { var _a = payload || {}, cmdStatus = _a.cmdStatus, textResponse = _a.textResponse, sequenceNo = _a.sequenceNo, userTrace = _a.userTrace, acctNo = _a.acctNo, cardType = _a.cardType, authCode = _a.authCode, captureStatus = _a.captureStatus, refNo = _a.refNo, invoiceNo = _a.invoiceNo, amount = _a.amount, acqRefData = _a.acqRefData, entryMethod = _a.entryMethod, date = _a.date, time = _a.time; appendLog('Single time sale transaction completed', "TransactionStatus: ".concat(cmdStatus, "\nText: ").concat(textResponse, "\nSequenceNo: ").concat(sequenceNo, "\nUserTrace: ").concat(userTrace, "\nAcctNo: ").concat(acctNo, "\ncardType: ").concat(cardType, "\nauthCode: ").concat(authCode, "\nCaptureStatus: ").concat(captureStatus, "\nRefNo: ").concat(refNo, "\nInvoiceNo: ").concat(invoiceNo, "\nAmount: ").concat(amount === null || amount === void 0 ? void 0 : amount.purchase, "\nAcqRefData: ").concat(acqRefData, "\nEntryMethod: ").concat(entryMethod, "\nDate: ").concat(date, "\nTime: ").concat(time)); setLoading(false); waitingForEvent.current = false; } else if (event === 'onRecurringSaleCompleted') { var _b = payload || {}, cmdStatus = _b.cmdStatus, textResponse = _b.textResponse, sequenceNo = _b.sequenceNo, userTrace = _b.userTrace, captureStatus = _b.captureStatus, refNo = _b.refNo, invoiceNo = _b.invoiceNo, amount = _b.amount, cardholderName = _b.cardholderName, acctNo = _b.acctNo, cardType = _b.cardType, authCode = _b.authCode, entryMethod = _b.entryMethod, recordNo = _b.recordNo, recurringData = _b.recurringData, acqRefData = _b.acqRefData, date = _b.date, time = _b.time, payAPIId = _b.payAPIId; appendLog('Sale transaction with recurring data completed', "TransactionStatus: ".concat(cmdStatus, "\nText: ").concat(textResponse, "\nSequenceNo: ").concat(sequenceNo, "\nUserTrace: ").concat(userTrace, "\nCaptureStatus: ").concat(captureStatus, "\nRefNo: ").concat(refNo, "\nInvoiceNo: ").concat(invoiceNo, "\nAmount: ").concat(amount === null || amount === void 0 ? void 0 : amount.purchase, "\n\nCardHolderName: ").concat(cardholderName, "\nAcctNo: ").concat(acctNo, "\ncardType: ").concat(cardType, "\nauthCode: ").concat(authCode, "\nEntryMethod: ").concat(entryMethod, "\n\nRecordNo: ").concat(recordNo, "\nRecurringData: ").concat(recurringData, "\n\nAcqRefData: ").concat(acqRefData, "\nDate: ").concat(date, "\nTime: ").concat(time, "\nPayAPIID: ").concat(payAPIId)); setLoading(false); waitingForEvent.current = false; } else if (event === 'onReplaceCardCompleted') { var _c = payload || {}, cmdStatus = _c.cmdStatus, textResponse = _c.textResponse, sequenceNo = _c.sequenceNo, userTrace = _c.userTrace, captureStatus = _c.captureStatus, refNo = _c.refNo, invoiceNo = _c.invoiceNo, amount = _c.amount, cardholderName = _c.cardholderName, acctNo = _c.acctNo, cardType = _c.cardType, authCode = _c.authCode, entryMethod = _c.entryMethod, recordNo = _c.recordNo, acqRefData = _c.acqRefData, date = _c.date, time = _c.time, payAPIId = _c.payAPIId; appendLog('Replace card in recurring transaction completed', "Status: ".concat(cmdStatus, "\nResponse: ").concat(textResponse, "\nSequenceNo: ").concat(sequenceNo, "\nUserTrace: ").concat(userTrace, "\nCaptureStatus: ").concat(captureStatus, "\nRefNo: ").concat(refNo, "\nInvoiceNo: ").concat(invoiceNo, "\nAmount: ").concat(amount === null || amount === void 0 ? void 0 : amount.purchase, "\n\nCardHolderName: ").concat(cardholderName, "\nAcctNo: ").concat(acctNo, "\ncardType: ").concat(cardType, "\nauthCode: ").concat(authCode, "\nEntryMethod: ").concat(entryMethod, "\n\nRecordNo: ").concat(recordNo, "\n\nAcqRefData: ").concat(acqRefData, "\nDate: ").concat(date, "\nTime: ").concat(time, "\nPayAPIID: ").concat(payAPIId)); setLoading(false); waitingForEvent.current = false; } else if (event === 'onCardReadSuccessfully') { var binNumber = payload === null || payload === void 0 ? void 0 : payload.binNumber; appendLog('Card successfully read', 'Card read successfully And BIN: ' + binNumber); setLoading(false); waitingForEvent.current = false; } else if (event === 'onError') { appendLog('Error:', payload); setLoading(false); waitingForEvent.current = false; } else { // For other events, clear loading state setLoading(false); waitingForEvent.current = false; } }); // Store the listener in the ref if (!listenersRef.current[event]) { listenersRef.current[event] = []; } listenersRef.current[event].push(listener); }); // Initialize EMV manager first (only once) if (config) initializeEMV(config); else console.error("MISSING CONFIGURATION for INITIALIZATION"); // After initialization, call pingConfig to check connection setTimeout(function () { pingConfig(); }, 1000); // Clean up listeners when the component is unmounted return function () { Object.values(listenersRef.current).forEach(function (eventListeners) { eventListeners.forEach(function (listener) { return listener.remove(); }); }); listenersRef.current = {}; if (DsiEMVManagerBridge && typeof DsiEMVManagerBridge.clearTransactionListener === 'function') { DsiEMVManagerBridge.clearTransactionListener(); } }; }, [appendLog, disabled]); // Export the specific functions from DsiEMVManagerBridge var runSaleTransaction = (0, react_2.useCallback)(function (amount) { try { setLoading(true); waitingForEvent.current = true; DsiEMVManagerBridge.runSaleTransaction(amount); appendLog('Running Single time sale transaction', "Amount: ".concat(amount)); } catch (e) { setLoading(false); waitingForEvent.current = false; appendLog('error', "runSaleTransaction failed: ".concat(e.message)); } }, [appendLog]); var collectCardDetails = (0, react_2.useCallback)(function () { try { setLoading(true); waitingForEvent.current = true; DsiEMVManagerBridge.collectCardDetails(); appendLog('Running Card Details Collection', 'Requested card details'); } catch (e) { setLoading(false); waitingForEvent.current = false; appendLog('error', "collectCardDetails failed: ".concat(e.message)); } }, [appendLog]); var runRecurringTransaction = (0, react_2.useCallback)(function (amount) { try { setLoading(true); waitingForEvent.current = true; DsiEMVManagerBridge.runRecurringTransaction(amount); appendLog('Running a sale transaction with recurring data', "Amount: ".concat(amount)); } catch (e) { setLoading(false); waitingForEvent.current = false; appendLog('error', "runRecurringTransaction failed: ".concat(e.message)); } }, [appendLog]); var replaceCardInRecurring = (0, react_2.useCallback)(function () { try { setLoading(true); waitingForEvent.current = true; DsiEMVManagerBridge.replaceCardInRecurring(); appendLog('Running replace card in recurring', 'Replacing card in recurring transaction'); } catch (e) { setLoading(false); waitingForEvent.current = false; appendLog('error', "replaceCardInRecurring failed: ".concat(e.message)); } }, [appendLog]); var setupConfig = (0, react_2.useCallback)(function () { try { if (!isInitialized) { appendLog('setupConfig', 'EMV not initialized. Initializing first...'); initializeEMV(config); return; } setLoading(true); waitingForEvent.current = true; DsiEMVManagerBridge.setupConfig(); appendLog('setupConfig', 'Setting up configurations....'); } catch (e) { setLoading(false); waitingForEvent.current = false; appendLog('error', "setupConfig failed: ".concat(e.message)); } }, [appendLog, isInitialized, initializeEMV]); var pingConfig = (0, react_2.useCallback)(function () { try { setLoading(true); waitingForEvent.current = true; DsiEMVManagerBridge.pingConfig(); appendLog('Ping Device', 'Checking Device Status'); } catch (e) { setLoading(false); waitingForEvent.current = false; appendLog('error', "Pinging Device failed: ".concat(e.message)); } }, [appendLog]); var clearTransactionListener = (0, react_2.useCallback)(function () { try { DsiEMVManagerBridge.clearTransactionListener(); appendLog('clearTransactionListener', 'Cleared transaction listener'); } catch (e) { appendLog('error', "clearTransactionListener failed: ".concat(e.message)); } }, [appendLog]); // Clear all logs only var clearAllTransactions = (0, react_2.useCallback)(function () { try { // Clear logs only setLogs([]); appendLog('Clearing All Logs', 'All logs cleared'); } catch (e) { appendLog('error', "Clearing All Transactions failed: ".concat(e.message)); } }, [appendLog]); // Cancel current operation var cancelOperation = (0, react_2.useCallback)(function () { try { DsiEMVManagerBridge.cancelTransaction(); setLoading(false); waitingForEvent.current = false; } catch (e) { setLoading(false); waitingForEvent.current = false; appendLog('error', "cancelOperation failed: ".concat(e.message)); } }, [appendLog]); var getClientVersion = (0, react_2.useCallback)(function () { try { setLoading(true); waitingForEvent.current = true; appendLog('getClientVersion', 'Getting client version information...'); DsiEMVManagerBridge.getClientVersion(); } catch (e) { setLoading(false); waitingForEvent.current = false; appendLog('error', "getClientVersion failed: ".concat(e.message)); } }, [appendLog]); return (react_1.default.createElement(PaymentContext.Provider, { value: { logs: logs, isDeviceConnected: isDeviceConnected, loading: loading, isInitialized: isInitialized, handleCardPayment: runSaleTransaction, handleInHousePayment: collectCardDetails, runRecurringTransaction: runRecurringTransaction, replaceCardInRecurring: replaceCardInRecurring, getClientVersion: getClientVersion, setupConfig: setupConfig, pingConfig: pingConfig, clearTransactionListener: clearTransactionListener, clearAllTransactions: clearAllTransactions, cancelOperation: cancelOperation, initializeEMV: initializeEMV, subscribeToEvent: subscribeToEvent, unsubscribeFromEvent: unsubscribeFromEvent, EVENTS: Object.freeze(types_1.EVENT_NAMES.reduce(function (acc, name) { acc[name] = name; return acc; }, {})) } }, children)); } exports.PaymentProvider = PaymentProvider; //# sourceMappingURL=PaymentProvider.js.map