UNPKG

@onepaynpm/onepay-sdk

Version:

Official OnePay payment gateway SDK for JavaScript applications

764 lines (755 loc) 25.5 kB
/*! * @onepaynpm/onepay-sdk v1.0.2 * Official OnePay payment gateway SDK for JavaScript applications * https://github.com/onepay-lk/onepay-sdk#readme * * Copyright (c) 2025 OnePay Team * Released under the MIT License */ function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function (t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () { return this; }), _regeneratorDefine(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function () { return { w: i, m: f }; })(); } function _regeneratorDefine(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine = function (e, r, n, t) { if (r) i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n;else { function o(r, n) { _regeneratorDefine(e, r, function (e) { return this._invoke(r, n, e); }); } o("next", 0), o("throw", 1), o("return", 2); } }, _regeneratorDefine(e, r, n, t); } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } /** * Loads a given script by appending it to <head> */ function loadScript(src) { return new Promise(function (resolve, reject) { var script = document.createElement("script"); script.src = src; script.async = true; script.onload = function () { return resolve(); }; script.onerror = function () { return reject(new Error("Script load error: ".concat(src))); }; document.head.appendChild(script); }); } /** * Loads Firebase scripts in sequence */ function loadFirebaseScripts() { return _loadFirebaseScripts.apply(this, arguments); } /** * Initialize Firebase with provided configuration */ function _loadFirebaseScripts() { _loadFirebaseScripts = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() { return _regenerator().w(function (_context) { while (1) switch (_context.n) { case 0: _context.n = 1; return loadScript("https://www.gstatic.com/firebasejs/9.17.2/firebase-app-compat.js"); case 1: _context.n = 2; return loadScript("https://www.gstatic.com/firebasejs/9.17.2/firebase-firestore-compat.js"); case 2: return _context.a(2); } }, _callee); })); return _loadFirebaseScripts.apply(this, arguments); } function initializeFirebase(config) { if (typeof window === 'undefined') { throw new Error('Firebase can only be initialized in browser environment'); } // @ts-ignore if (!window.firebase) { throw new Error('Firebase scripts not loaded. Call loadFirebaseScripts() first.'); } // @ts-ignore if (!window.firebase.apps.length) { // @ts-ignore window.firebase.initializeApp(config); } // @ts-ignore return window.firebase.firestore(); } /** * Utility to generate a SHA256 hash from the OnePay data + hashsalt */ function generateSHA256Hash(_x, _x2) { return _generateSHA256Hash.apply(this, arguments); } function _generateSHA256Hash() { _generateSHA256Hash = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(data, hashsalt) { var payloadString, encoder, dataBuffer, hashBuffer; return _regenerator().w(function (_context) { while (1) switch (_context.n) { case 0: payloadString = "".concat(data.app_id).concat(data.currency).concat(data.amount.toFixed(2)).concat(hashsalt); encoder = new TextEncoder(); dataBuffer = encoder.encode(payloadString); _context.n = 1; return crypto.subtle.digest("SHA-256", dataBuffer); case 1: hashBuffer = _context.v; return _context.a(2, Array.from(new Uint8Array(hashBuffer)).map(function (b) { return b.toString(16).padStart(2, "0"); }).join("")); } }, _callee); })); return _generateSHA256Hash.apply(this, arguments); } var backdrop = null; /** * Creates and displays the payment iframe with backdrop */ function openPaymentIframe(redirectURL, transactionId) { // Create a backdrop backdrop = document.createElement("div"); backdrop.style.position = "fixed"; backdrop.style.top = "0"; backdrop.style.left = "0"; backdrop.style.width = "100%"; backdrop.style.height = "100%"; backdrop.style.backgroundColor = "rgba(0, 0, 0, 0.5)"; backdrop.style.zIndex = "9998"; backdrop.style.display = "flex"; backdrop.style.alignItems = "center"; backdrop.style.justifyContent = "center"; // Create a container to center the iFrame var container = document.createElement("div"); container.style.position = "relative"; container.style.zIndex = "9999"; container.style.backgroundColor = "#fff"; container.style.borderRadius = "8px"; container.style.overflow = "hidden"; container.style.boxShadow = "0 4px 6px rgba(0, 0, 0, 0.1)"; // Add a close button var closeButton = document.createElement("button"); closeButton.innerHTML = "×"; closeButton.style.position = "absolute"; closeButton.style.right = "10px"; closeButton.style.top = "30px"; closeButton.style.zIndex = "10000"; closeButton.style.backgroundColor = "#fff"; closeButton.style.border = "none"; closeButton.style.borderRadius = "50%"; closeButton.style.width = "30px"; closeButton.style.height = "30px"; closeButton.style.fontSize = "20px"; closeButton.style.cursor = "pointer"; closeButton.style.display = "flex"; closeButton.style.alignItems = "center"; closeButton.style.justifyContent = "center"; closeButton.style.boxShadow = "0 2px 4px rgba(0,0,0,0.2)"; closeButton.onmouseover = function () { closeButton.style.backgroundColor = "#f0f0f0"; }; closeButton.onmouseout = function () { closeButton.style.backgroundColor = "#fff"; }; // Set up close button click handler closeButton.addEventListener("click", function () { console.log("Close button clicked"); // Remove the backdrop if (backdrop && backdrop.parentNode) { backdrop.parentNode.removeChild(backdrop); } // Create and dispatch the close event var closeEvent = new CustomEvent("onePayClose", { detail: { transaction_id: transactionId, status: "CLOSED" }, bubbles: true }); // Dispatch the event document.dispatchEvent(closeEvent); console.log("Close event dispatched"); }); // Create the iFrame var iframe = document.createElement("iframe"); iframe.src = redirectURL; iframe.style.width = window.innerWidth <= 1300 ? "430px" : "430px"; iframe.style.height = "600px"; iframe.style.border = "none"; iframe.style.display = "block"; // Put the close button and iframe into the container container.appendChild(closeButton); container.appendChild(iframe); // Put the container into the backdrop backdrop.appendChild(container); // Finally, add the backdrop to the document body document.body.appendChild(backdrop); } /** * Closes the payment gateway */ function closePaymentGateway() { try { if (backdrop && backdrop.parentNode) { backdrop.parentNode.removeChild(backdrop); backdrop = null; console.log("Payment gateway closed successfully"); return true; } else { console.log("No payment gateway found to close"); return false; } } catch (error) { console.error("Error closing payment gateway:", error); return false; } } /** * Listens to the transaction data in Firestore by transactionId */ function listenToTransaction(db, transactionId) { if (!db) { console.error("Firestore (db) is not initialized!"); return function () {}; } // Example: docRef = db.collection("onepay").doc("transaction") var docRef = db.collection("onepay").doc("transaction"); var unsubscribe = docRef.onSnapshot(function (doc) { console.log("Transaction document updated:", doc); if (doc.exists) { console.log("Document data:", doc.data()); var data = doc.data(); var transactionData = data[transactionId]; console.log("Transaction data:", transactionData); if (transactionData) { if (transactionData.is_pay) { // Payment success closePaymentGateway(); var successResult = { code: "201", transaction_id: transactionId, status: "SUCCESS" }; document.dispatchEvent(new CustomEvent("onePaySuccess", { detail: successResult })); unsubscribe(); } else { // Payment fail or not completed closePaymentGateway(); var failResult = { code: "400", transaction_id: transactionId, status: "FAIL" }; document.dispatchEvent(new CustomEvent("onePayFail", { detail: failResult })); unsubscribe(); } } } else { console.error("Firestore document not found!"); } }); return unsubscribe; } var DEFAULT_API_BASE_URL = 'https://api.onepay.lk'; /** * Calls the OnePay payment API */ function triggerPaymentAPI(payload, token) { var apiBaseUrl = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_API_BASE_URL; var db = arguments.length > 3 ? arguments[3] : undefined; return fetch("".concat(apiBaseUrl, "/v3/checkout/link/"), { method: "POST", headers: { "Content-Type": "application/json", Authorization: token }, body: JSON.stringify(payload) }).then(function (response) { if (!response.ok) { throw new Error("HTTP error! status: ".concat(response.status)); } return response.json(); }).then(function (data) { var _a, _b, _c; var redirectURL = (_b = (_a = data === null || data === void 0 ? void 0 : data.data) === null || _a === void 0 ? void 0 : _a.gateway) === null || _b === void 0 ? void 0 : _b.redirect_url; var transactionId = (_c = data === null || data === void 0 ? void 0 : data.data) === null || _c === void 0 ? void 0 : _c.ipg_transaction_id; if (redirectURL && transactionId) { openPaymentIframe(redirectURL, transactionId); if (db) { listenToTransaction(db, transactionId); } } else { throw new Error("Failed to retrieve redirect URL/transaction ID from API response."); } }).catch(function (error) { console.error("Error in triggerPaymentAPI:", error); throw error; }); } /** * Calls the OnePay subscription API */ function triggerSubscriptionAPI(payload, token) { var apiBaseUrl = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_API_BASE_URL; var db = arguments.length > 3 ? arguments[3] : undefined; return fetch("".concat(apiBaseUrl, "/v3/subscription/"), { method: "POST", headers: { "Content-Type": "application/json", Authorization: token }, body: JSON.stringify(payload) }).then(function (res) { if (!res.ok) throw new Error("HTTP ".concat(res.status)); return res.json(); }).then(function (json) { var _a, _b; var redirectURL = (_a = json === null || json === void 0 ? void 0 : json.data) === null || _a === void 0 ? void 0 : _a.url; var subscriptionId = (_b = json === null || json === void 0 ? void 0 : json.data) === null || _b === void 0 ? void 0 : _b.subscription_id; if (redirectURL && subscriptionId) { openPaymentIframe(redirectURL, subscriptionId); if (db) { listenToTransaction(db, subscriptionId); } } else { throw new Error("Subscription API did not return URL / ID."); } }).catch(function (err) { console.error("Subscription API error:", err); throw err; }); } var OnePaySDK = /*#__PURE__*/function () { function OnePaySDK() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, OnePaySDK); this.db = null; this.initialized = false; this.firebaseConfig = options.firebaseConfig || { apiKey: "AIzaSyDGxd3PoP01JN25cPXfgRsVoc-C6XE2FTk", authDomain: "spemai-global.firebaseapp.com", projectId: "spemai-global", storageBucket: "spemai-global.appspot.com", messagingSenderId: "864345120875", appId: "1:864345120875:web:d33dbc1b2b02f8098dd12e" }; this.apiBaseUrl = options.apiBaseUrl || 'https://api.onepay.lk'; this.debug = options.debug || false; } /** * Initialize the SDK */ return _createClass(OnePaySDK, [{ key: "initialize", value: (function () { var _initialize = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() { var _t; return _regenerator().w(function (_context) { while (1) switch (_context.n) { case 0: if (!this.initialized) { _context.n = 1; break; } if (this.debug) console.log('OnePay SDK already initialized'); return _context.a(2); case 1: _context.p = 1; _context.n = 2; return loadFirebaseScripts(); case 2: this.db = initializeFirebase(this.firebaseConfig); this.initialized = true; if (this.debug) console.log('OnePay SDK initialized successfully'); _context.n = 4; break; case 3: _context.p = 3; _t = _context.v; console.error('Failed to initialize OnePay SDK:', _t); throw _t; case 4: return _context.a(2); } }, _callee, this, [[1, 3]]); })); function initialize() { return _initialize.apply(this, arguments); } return initialize; }() /** * Process a direct payment with existing gateway URL */ ) }, { key: "processDirectPayment", value: (function () { var _processDirectPayment = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(data) { return _regenerator().w(function (_context2) { while (1) switch (_context2.n) { case 0: _context2.n = 1; return this.ensureInitialized(); case 1: openPaymentIframe(data.directGatewayURL, data.directTransactionId); this.startListening(data.directTransactionId); case 2: return _context2.a(2); } }, _callee2, this); })); function processDirectPayment(_x) { return _processDirectPayment.apply(this, arguments); } return processDirectPayment; }() /** * Process a standard payment */ ) }, { key: "processPayment", value: (function () { var _processPayment = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(data) { var payload, hash, _t2; return _regenerator().w(function (_context3) { while (1) switch (_context3.n) { case 0: _context3.n = 1; return this.ensureInitialized(); case 1: _context3.p = 1; payload = { currency: data.currency, amount: data.amount, app_id: data.appid, reference: data.orderReference, customer_first_name: data.customerFirstName, customer_last_name: data.customerLastName, customer_phone_number: data.customerPhoneNumber, customer_email: data.customerEmail, transaction_redirect_url: data.transactionRedirectUrl, additional_data: data.additionalData }; _context3.n = 2; return generateSHA256Hash(payload, data.hashToken); case 2: hash = _context3.v; payload.hash = hash; _context3.n = 3; return triggerPaymentAPI(payload, data.apptoken, this.apiBaseUrl, this.db); case 3: _context3.n = 5; break; case 4: _context3.p = 4; _t2 = _context3.v; console.error('Error processing payment:', _t2); throw _t2; case 5: return _context3.a(2); } }, _callee3, this, [[1, 4]]); })); function processPayment(_x2) { return _processPayment.apply(this, arguments); } return processPayment; }() /** * Process a subscription */ ) }, { key: "processSubscription", value: (function () { var _processSubscription = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(data) { var payload, hash, _t3; return _regenerator().w(function (_context4) { while (1) switch (_context4.n) { case 0: _context4.n = 1; return this.ensureInitialized(); case 1: _context4.p = 1; payload = { app_id: data.appid, name: data.name, amount: data.amount, currency: data.currency, interval: data.interval, interval_count: data.interval_count, days_until_due: data.days_until_due, trial_period_days: data.trial_period_days, customer_details: data.customer_details }; _context4.n = 2; return generateSHA256Hash(payload, data.apptoken); case 2: hash = _context4.v; payload.hash = hash; _context4.n = 3; return triggerSubscriptionAPI(payload, data.apptoken, this.apiBaseUrl, this.db); case 3: _context4.n = 5; break; case 4: _context4.p = 4; _t3 = _context4.v; console.error('Error processing subscription:', _t3); throw _t3; case 5: return _context4.a(2); } }, _callee4, this, [[1, 4]]); })); function processSubscription(_x3) { return _processSubscription.apply(this, arguments); } return processSubscription; }() /** * Add event listeners for payment events */ ) }, { key: "addEventListener", value: function addEventListener(listeners) { if (listeners.onSuccess) { document.addEventListener('onePaySuccess', function (event) { listeners.onSuccess(event.detail); }); } if (listeners.onFail) { document.addEventListener('onePayFail', function (event) { listeners.onFail(event.detail); }); } if (listeners.onClose) { document.addEventListener('onePayClose', function (event) { listeners.onClose(event.detail); }); } } /** * Remove event listeners */ }, { key: "removeEventListener", value: function removeEventListener(type, listener) { document.removeEventListener(type, listener); } /** * Close the payment gateway */ }, { key: "closePaymentGateway", value: function closePaymentGateway$1() { return closePaymentGateway(); } /** * Check if SDK is initialized */ }, { key: "isInitialized", value: function isInitialized() { return this.initialized; } /** * Ensure SDK is initialized before operations */ }, { key: "ensureInitialized", value: (function () { var _ensureInitialized = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() { return _regenerator().w(function (_context5) { while (1) switch (_context5.n) { case 0: if (this.initialized) { _context5.n = 1; break; } _context5.n = 1; return this.initialize(); case 1: return _context5.a(2); } }, _callee5, this); })); function ensureInitialized() { return _ensureInitialized.apply(this, arguments); } return ensureInitialized; }() /** * Start listening to transaction updates */ ) }, { key: "startListening", value: function startListening(transactionId) { return listenToTransaction(this.db, transactionId); } }]); }(); // Main SDK export export { OnePaySDK, closePaymentGateway, OnePaySDK as default, generateSHA256Hash, initializeFirebase, loadFirebaseScripts, openPaymentIframe }; //# sourceMappingURL=index.esm.js.map