@dropp.cc/payment-sdk 1.0.10 โ†’ 1.0.12

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.
package/README.md CHANGED
@@ -94,19 +94,81 @@ The Web SDK can also open Dropp-hosted pages inside the same modal container.
94
94
 
95
95
  ### `Dropp.dashboard(options)`
96
96
 
97
- Loads `/#/firsttimeflow` for the dashboard/home page.
97
+ Loads the dashboard/home page.
98
+
99
+ Optional for this route:
100
+
101
+ - `modules` (`string[]`): Restrict sidebar modules shown in webview.
102
+
103
+ Supported section IDs:
104
+
105
+ - `funding`
106
+ - `accounts`
107
+ - `merchants`
108
+ - `settings`
109
+ - `support`
110
+
111
+ Supported item IDs:
112
+
113
+ - `fundnow`
114
+ - `linkbank`
115
+ - `linkcard`
116
+ - `redeemnow`
117
+ - `fundcrypto`
118
+ - `transferusdc`
119
+ - `usdchistory`
120
+ - `redeemcrypto`
121
+ - `manageaccounts`
122
+ - `transactions`
123
+ - `merchantlist`
124
+ - `favorites`
125
+ - `offers`
126
+ - `profile`
127
+ - `changepin`
128
+ - `unlinkaccount`
129
+ - `accountsettings`
130
+ - `about`
131
+
132
+ The SDK passes this as a comma-separated query param in the webview URL for `#/firsttimeflow`.
133
+
134
+ ### `Dropp.load(moduleId, options)`
135
+
136
+ Loads a specific supported firsttimeflow item page directly.
137
+
138
+ Supported item IDs:
139
+
140
+ - `fundnow`
141
+ - `linkbank`
142
+ - `linkcard`
143
+ - `redeemnow`
144
+ - `fundcrypto`
145
+ - `transferusdc`
146
+ - `usdchistory`
147
+ - `redeemcrypto`
148
+ - `manageaccounts`
149
+ - `transactions`
150
+ - `merchantlist`
151
+ - `favorites`
152
+ - `offers`
153
+ - `profile`
154
+ - `changepin`
155
+ - `unlinkaccount`
156
+ - `accountsettings`
157
+ - `about`
158
+
159
+ This opens `#/firsttimeflow` and passes the selected item through the existing `modules` query param.
98
160
 
99
161
  ### `Dropp.unlinkAccount(options)`
100
162
 
101
- Loads `/#/unlink` for the account unlink page.
163
+ Loads the account unlink page.
102
164
 
103
165
  ### `Dropp.transactions(options)`
104
166
 
105
- Loads `/#/transactions` for the transactions page.
167
+ Loads the transactions page.
106
168
 
107
169
  ### `Dropp.offers(options)`
108
170
 
109
- Loads `/#/offers` for the offers page.
171
+ Loads the offers page.
110
172
 
111
173
  **Parameters:**
112
174
 
@@ -119,12 +181,20 @@ Loads `/#/offers` for the offers page.
119
181
  await Dropp.dashboard({
120
182
  onClose: () => {
121
183
  console.log('Dashboard modal closed');
122
- }
184
+ },
185
+ modules: ['funding', 'accounts', 'merchants', 'settings', 'support']
123
186
  });
124
187
 
125
188
  await Dropp.unlinkAccount();
126
189
  await Dropp.transactions();
127
190
  await Dropp.offers();
191
+
192
+ await Dropp.dashboard({
193
+ modules: ['funding', 'profile', 'about']
194
+ });
195
+
196
+ await Dropp.load('linkbank');
197
+ await Dropp.load('profile');
128
198
  ```
129
199
 
130
200
  ### SDK Instance Example:
@@ -138,6 +208,10 @@ const { sdk } = await Dropp.init({
138
208
  });
139
209
 
140
210
  await sdk.dashboard();
211
+ await sdk.dashboard({
212
+ modules: ['funding', 'accounts', 'merchants', 'settings', 'support']
213
+ });
214
+ await sdk.load('fundnow');
141
215
  await sdk.unlinkAccount();
142
216
  await sdk.transactions();
143
217
  await sdk.offers();
@@ -145,8 +219,7 @@ await sdk.offers();
145
219
 
146
220
  ## Account Status
147
221
 
148
- Use `Dropp.status()` to fetch account linkage status through a hidden iframe.
149
- The iframe loads `/#/status` with SDK context markers and auto-cleans up after the response is received.
222
+ Use `Dropp.status()` to fetch account linkage status.
150
223
 
151
224
  ### `Dropp.status()`
152
225
 
@@ -453,3 +526,7 @@ MIT License - see LICENSE file for details
453
526
  - Added Support for the Transactions.
454
527
  - Added Support for the Offers.
455
528
  - Added Support for Security before open any customized method.
529
+
530
+ ### v1.0.10 (2026-07-10)
531
+ - Added Support for the 404 methods.
532
+ - Added Support for the status check.
@@ -1,2 +1,2 @@
1
- const e={READY:"DROPP_SDK_READY",PAYMENT_SUCCESS:"PAYMENT_SUCCESS",PAYMENT_FAILED:"PAYMENT_FAILED",PAYMENT_CANCELLED:"PAYMENT_CANCELLED",ACCOUNT_STATUS:"ACCOUNT_STATUS",CLOSE_WEBVIEW:"CLOSE_WEBVIEW",AUTO_CLOSE_WEBVIEW:"AUTO_CLOSE_WEBVIEW",PAYMENT_PAGE_LOADED:"PAYMENT_PAGE_LOADED",PAGE_LOADED:"PAGE_LOADED"},t="DROPP_SDK_INIT",s="DROPP_SDK_CLOSE",n={PRODUCTION:"production",QA:"qa",SANDBOX:"sandbox"},i={[n.PRODUCTION]:"https://wv.dropp.cc",[n.QA]:"https://wv.qa.dropp.cc",[n.SANDBOX]:"https://wv.sandbox.dropp.cc"},r={[n.PRODUCTION]:["https://wv.dropp.cc"],[n.QA]:["https://wv.qa.dropp.cc"],[n.SANDBOX]:["https://wv.sandbox.dropp.cc"]},o=3e4,a=6e5,l={STANDARD:"standard",PREAUTH:"preauth",RECURRING:"recurring"},c="INIT_TIMEOUT",d="PAYMENT_TIMEOUT",u="INVALID_CONFIG",h="ALREADY_OPEN",p="UNKNOWN_ERROR",m="1.0.2";const g=new class{constructor(e,t={}){this.environment=e,this.forceEnabled=!!t.enabled,this.enabled=this._shouldEnableLogging()}_shouldEnableLogging(){return this.forceEnabled}setEnvironment(e,t={}){this.environment=e,"boolean"==typeof t.enabled&&(this.forceEnabled=t.enabled),this.enabled=this._shouldEnableLogging()}setEnabled(e){this.forceEnabled=!!e,this.enabled=this._shouldEnableLogging()}log(...e){this.enabled&&console.log(...e)}warn(...e){this.enabled&&console.warn(...e)}error(...e){this.enabled&&console.error(...e)}debug(...e){this.enabled&&console.debug(...e)}info(...e){this.enabled&&console.info(...e)}}("qa",{enabled:!1}),y=["USD","HBAR","USDC"],f=["NONE","HALF_HOURLY","HOURLY","DAILY","WEEKLY","MONTHLY","YEARLY"],S=[l.STANDARD,l.PREAUTH,l.RECURRING];function D(e,t={}){const{isProduction:s=!1,allowLocalCallbacksInNonProd:n=!1}=t;if("string"!=typeof e||!e.trim())return!1;try{const t=new URL(e.trim()),i="https:"===t.protocol;if(!("http:"===t.protocol)&&!i)return!1;return function(e){if(!e)return!1;const t=e.trim().toLowerCase();if("localhost"===t||"127.0.0.1"===t||"::1"===t||t.endsWith(".local"))return!0;if(!/^(\d{1,3}\.){3}\d{1,3}$/.test(t))return!1;const s=t.split(".").map(e=>Number(e));if(s.some(e=>Number.isNaN(e)||e<0||e>255))return!1;const[n,i]=s;return 10===n||127===n||172===n&&i>=16&&i<=31||192===n&&168===i||169===n&&254===i}(t.hostname)?!s&&n:!s||i}catch{return!1}}function b(e={},t={}){const s=[],n=e.paymentType||l.STANDARD,i="production"===(t.environment||"").toLowerCase(),r=!!t.allowLocalCallbacksInNonProd,o="string"==typeof e.currency?e.currency.trim().toUpperCase():"";if(S.includes(n)||s.push(`paymentType must be one of: ${S.join(", ")}`),void 0===e.amount||null===e.amount||""===e.amount?s.push("amount is required"):function(e){const t="number"==typeof e?e:parseFloat(e);return"number"==typeof t&&!Number.isNaN(t)&&t>0}(e.amount)||s.push("amount must be a positive number"),e.currency&&"string"==typeof e.currency&&e.currency.trim()?y.includes(o)||s.push(`currency must be one of: ${y.join(", ")}`):s.push("currency is required"),e.itemName&&"string"==typeof e.itemName&&e.itemName.trim()||s.push("itemName is required"),n===l.PREAUTH&&(o&&"USD"!==o&&s.push("currency must be USD for preauth payments"),e.callbackUrl&&String(e.callbackUrl).trim()?D(e.callbackUrl,{isProduction:i,allowLocalCallbacksInNonProd:r})||s.push(i?"callbackUrl must be HTTPS in production and cannot target loopback/private hosts":"callbackUrl must be a valid HTTP/HTTPS URL and cannot target loopback/private hosts unless explicitly enabled"):s.push("callbackUrl (signing URL) is required for preauth payments"),void 0===e.authHoldTimeInSeconds||null===e.authHoldTimeInSeconds||""===e.authHoldTimeInSeconds?s.push("authHoldTimeInSeconds is required for preauth payments"):function(e){const t="number"==typeof e?e:parseInt(e,10);return Number.isInteger(t)&&t>0}(e.authHoldTimeInSeconds)||s.push("authHoldTimeInSeconds must be a positive integer (seconds)")),n===l.RECURRING){e.callbackUrl&&String(e.callbackUrl).trim()?D(e.callbackUrl,{isProduction:i,allowLocalCallbacksInNonProd:r})||s.push(i?"callbackUrl must be HTTPS in production and cannot target loopback/private hosts":"callbackUrl must be a valid HTTP/HTTPS URL and cannot target loopback/private hosts unless explicitly enabled"):s.push("callbackUrl (signing URL) is required for recurring payments");const t=(e.frequency||e.recurringInterval||"").toString().trim().toUpperCase();t?f.includes(t)||s.push(`frequency must be one of: ${f.join(", ")}`):s.push("frequency is required for recurring payments"),e.recurringEndDate&&String(e.recurringEndDate).trim()?!function(e){if("string"!=typeof e||!e.trim())return!1;const t=new Date(e.trim());return!Number.isNaN(t.getTime())}(e.recurringEndDate)?s.push("recurringEndDate must be a valid ISO date-time string"):new Date(e.recurringEndDate.trim())<=new Date&&s.push("recurringEndDate must be in the future"):s.push("recurringEndDate (expiry) is required for recurring payments")}return{valid:0===s.length,errors:s}}function w(e,t,s={}){return{code:e,message:t,details:s,timestamp:(new Date).toISOString(),toString(){return this.message||"Dropp SDK error"}}}class T{constructor(e,t,s=null){this.environment=e,this.onMessage=t,this.sessionId=`dropp-sdk-${Date.now()}-${Math.random().toString(36).substring(2,15)}`,g.log("[MessageHandler] Session initialized"),this.iframe=null,this.allowedOrigins=s?.length>0?s:r[e]||[],this.messageListener=null,this.pendingMessages=new Map}init(e){this.iframe=e,this.messageListener=this._handleMessage.bind(this),window.addEventListener("message",this.messageListener)}destroy(){this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.iframe=null,this.pendingMessages.clear()}_handleMessage(e){if(g.log("[MessageHandler] Received postMessage event"),e.source===window)return void g.log("[MessageHandler] Ignoring message from self");if(!this._validateOrigin(e.origin))return void g.warn("[Dropp SDK] Rejected message from untrusted origin:",e.origin);if(!this.iframe||e.source!==this.iframe.contentWindow)return void g.warn("[Dropp SDK] Rejected message from unexpected source",{eventOrigin:e.origin});const t=e.data;this._validateMessageStructure(t)?t.sessionId&&t.sessionId!==this.sessionId?g.warn("[Dropp SDK] Rejected message with invalid session ID"):(g.log("[MessageHandler] Message passed validation"),this._processMessage(t)):g.warn("[Dropp SDK] Rejected message with invalid structure")}_validateOrigin(e){return!(!e.startsWith("http://localhost:")&&!e.startsWith("http://127.0.0.1:"))||this.allowedOrigins.includes(e)}_validateMessageStructure(t){if(!t||"object"!=typeof t)return!1;if(!t.type||"string"!=typeof t.type)return!1;return!!Object.values(e).includes(t.type)&&!(t.type!==e.ACCOUNT_STATUS&&!t.timestamp)}_processMessage(e){g.log("[Dropp SDK] Received message:",e.type),this.onMessage&&this.onMessage(e)}sendToPaymentApp(e,t={}){if(!this.iframe||!this.iframe.contentWindow)return g.error("[Dropp SDK] Cannot send message: iframe not ready"),!1;const s={type:e,data:t,sessionId:this.sessionId,timestamp:(new Date).toISOString(),sdkVersion:"1.0.0"},n=this.allowedOrigins[0]||"*";try{return this.iframe.contentWindow.postMessage(s,n),g.log("[Dropp SDK] Sent message:",e),!0}catch(e){return g.error("[Dropp SDK] Error sending message:",e),!1}}sendInit(e){return this.sendToPaymentApp(t,{mode:"sdk",config:e})}sendClose(){return this.sendToPaymentApp(s,{})}getSessionId(){return this.sessionId}}class v{constructor(e){this.onClose=e,this.overlay=null,this.container=null,this.iframe=null,this.closeButton=null,this.isOpen=!1,this.escapeListener=null}open(){return this.isOpen?(g.warn("[Dropp SDK] Modal is already open"),null):(this._createModal(),this._attachEventListeners(),this._show(),this.isOpen=!0,this.iframe)}close(){g.log("[ModalManager] ๐Ÿšฆ close() called, isOpen:",this.isOpen),this.isOpen?(g.log("[ModalManager] ๐Ÿšฆ Hiding modal..."),this._hide(),g.log("[ModalManager] ๐Ÿšฆ Removing event listeners..."),this._removeEventListeners(),g.log("[ModalManager] ๐Ÿšฆ Destroying modal..."),this._destroyModal(),this.isOpen=!1,g.log("[ModalManager] โœ… Modal close sequence initiated")):g.log("[ModalManager] โš ๏ธ Modal is not open, skipping close")}_createModal(){this.overlay=document.createElement("div"),this.overlay.id="dropp-payment-overlay",this._applyOverlayStyles(this.overlay),this.container=document.createElement("div"),this.container.id="dropp-payment-container",this._applyContainerStyles(this.container),this.iframe=document.createElement("iframe"),this.iframe.id="dropp-payment-iframe",this.iframe.setAttribute("allow","payment"),this.iframe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),this.iframe.setAttribute("referrerpolicy","no-referrer"),this.iframe.setAttribute("title","Dropp Payment"),this._applyIframeStyles(this.iframe),this.container.appendChild(this.iframe),this.overlay.appendChild(this.container),document.body.appendChild(this.overlay)}_applyOverlayStyles(e){Object.assign(e.style,{position:"fixed",inset:"0",width:"100vw",height:"100vh",margin:"0",padding:"20px",boxSizing:"border-box",backgroundColor:"rgba(0, 0, 0, 0.6)",zIndex:999999..toString(),display:"flex",alignItems:"center",justifyContent:"center",opacity:"0",transition:"opacity 0.3s ease",backdropFilter:"blur(4px)",overflow:"auto"})}_applyContainerStyles(e){const t=window.innerWidth<768;this._isMobile=t,Object.assign(e.style,{position:"relative",flex:"0 0 auto",alignSelf:"center",margin:"auto",width:"100%",maxWidth:t?"100%":"400px",height:t?"100%":"auto",minHeight:t?"100%":"800px",maxHeight:t?"100%":"min(1000px, calc(100vh - 40px))",backgroundColor:"#ffffff",borderRadius:t?"0":"16px",boxShadow:"0 20px 60px rgba(0, 0, 0, 0.3)",overflow:"hidden",transform:"scale(0.95)",transition:"transform 0.3s ease, opacity 0.3s ease",display:"flex",flexDirection:"column"})}_getContainerTransform(e){return`scale(${e})`}_applyCloseButtonStyles(e){Object.assign(e.style,{position:"absolute",top:"16px",right:"16px",zIndex:"10",width:"40px",height:"40px",border:"none",borderRadius:"50%",backgroundColor:"rgba(255, 255, 255, 0.9)",color:"#333",fontSize:"28px",lineHeight:"1",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.15)",transition:"all 0.2s ease",fontFamily:"Arial, sans-serif",padding:"0"}),e.addEventListener("mouseenter",()=>{Object.assign(e.style,{backgroundColor:"#f5f5f5",transform:"scale(1.1)"})}),e.addEventListener("mouseleave",()=>{Object.assign(e.style,{backgroundColor:"rgba(255, 255, 255, 0.9)",transform:"scale(1)"})})}_applyIframeStyles(e){const t=this._isMobile;Object.assign(e.style,{width:"100%",flex:"1 1 auto",minHeight:t?"100%":"min(520px, calc(90vh - 40px))",height:t?"100%":"min(520px, calc(90vh - 40px))",border:"none",display:"block"})}_show(){document.body.style.overflow="hidden",requestAnimationFrame(()=>{this.overlay&&(this.overlay.style.opacity="1"),this.container&&(this.container.style.transform=this._getContainerTransform(1))})}_hide(){g.log("[ModalManager] ๐ŸŽญ _hide() called"),this.overlay&&(this.overlay.style.opacity="0",g.log("[ModalManager] ๐ŸŽญ Overlay opacity set to 0")),this.container&&(this.container.style.transform=this._getContainerTransform(.95),g.log("[ModalManager] ๐ŸŽญ Container transform set to scale(0.95)")),document.body.style.overflow="",g.log("[ModalManager] ๐ŸŽญ Body scroll restored")}_destroyModal(){g.log("[ModalManager] ๐Ÿ—‘๏ธ _destroyModal() called, waiting 300ms for animation"),setTimeout(()=>{g.log("[ModalManager] ๐Ÿ—‘๏ธ Animation complete, removing from DOM"),this.overlay&&this.overlay.parentNode&&(this.overlay.parentNode.removeChild(this.overlay),g.log("[ModalManager] ๐Ÿ—‘๏ธ Overlay removed from DOM")),this.overlay=null,this.container=null,this.iframe=null,this.closeButton=null,g.log("[ModalManager] โœ… Modal destroyed")},300)}_attachEventListeners(){}_removeEventListeners(){this.escapeListener&&(document.removeEventListener("keydown",this.escapeListener),this.escapeListener=null)}_handleCloseClick(e){e.stopPropagation(),this.onClose&&this.onClose("user_closed")}_handleOverlayClick(e){e.target===this.overlay&&this.onClose&&this.onClose("user_closed")}_handleEscapeKey(e){"Escape"===e.key&&this.isOpen&&this.onClose&&this.onClose("user_closed")}getIframe(){return this.iframe}getIsOpen(){return this.isOpen}}class E{constructor(e={}){if("undefined"==typeof window||"undefined"==typeof document)throw new Error("Dropp Payment SDK can only be used in a browser environment");if(!e.merchantId||!e.apiKey||!e.packageName)throw new Error("merchantId, apiKey, and packageName are required to initialize SDK");if(this.merchantId=e.merchantId,this.apiKey=e.apiKey,this.packageName=e.packageName,this.environment=e.environment||n.QA,this.baseUrl=e.paymentAppUrl||e.baseUrl||i[this.environment],this.isInitialized=!1,this.initializationPromise=null,this.getServerAuthToken="function"==typeof e.getServerAuthToken?e.getServerAuthToken:null,this.requireServerAuthToken="boolean"==typeof e.requireServerAuthToken?e.requireServerAuthToken:this.environment===n.PRODUCTION,this.allowLocalCallbacksInNonProd=!!e.allowLocalCallbacksInNonProd,e.allowedOrigins?.length)this.allowedOrigins=e.allowedOrigins;else try{this.allowedOrigins=[new URL(this.baseUrl).origin]}catch{this.allowedOrigins=r[this.environment]||[]}this.isOpen=!1,this.currentSession=null,this.currentFlowType=null,this.statusSession=null,this.hiddenIframe=null,this.statusTimeout=null,this.initTimeout=null,this.paymentTimeout=null,this.messageHandler=null,this.modalManager=null,g.setEnvironment(this.environment,{enabled:!!e.debugLogging}),g.log(`[Dropp SDK] Initialized v${m} - Environment: ${this.environment}`)}pay(e={}){return new Promise((t,s)=>{if(this.isOpen){const e=w(h,"A payment session is already in progress",{currentSession:this.currentSession});return void s(e)}(async()=>{try{await this.initialize();const n=b(e,{environment:this.environment,allowLocalCallbacksInNonProd:this.allowLocalCallbacksInNonProd});if(!n.valid){const e=w(u,"Invalid payment configuration",{errors:n.errors});return void s(e)}this.onSuccess=e.onSuccess||null,this.onFailure=e.onFailure||null,this.onCancel=e.onCancel||null,this.onClose=e.onClose||null,this.currentSession={resolve:t,reject:s,options:e,startTime:Date.now()},await this._initializePayment(e)}catch(e){const t=e&&e.code===u?e:w(p,"Failed to initialize payment",{originalError:e?.message||String(e)});s(t),this._cleanup()}})()})}async initialize(){return this.initializationPromise||(this.initializationPromise=(async()=>(await this._validateInitializationCredentials(),this.isInitialized=!0,{status:"success",code:"INITIALIZED",message:"Dropp SDK initialized successfully"}))().catch(e=>{throw this.isInitialized=!1,this.initializationPromise=null,e})),this.initializationPromise}_getValidationUrl(){const e={[n.QA]:"https://main.qa.dropp.cc/payer/webview/validate",[n.SANDBOX]:"https://sandbox.api.dropp.cc/payer/webview/validate",[n.PRODUCTION]:"https://api.dropp.cc/payer/webview/validate"};return e[this.environment]||e[n.QA]}async _validateInitializationCredentials(){const e=this._getValidationUrl();let t,s=null;try{t=await fetch(e,{method:"POST",headers:{accept:"application/json, text/plain, */*","content-type":"application/json","x-api-key":this.apiKey,"x-app-package":this.packageName},body:JSON.stringify({id:this.merchantId})})}catch(t){throw w(u,"Unable to validate merchant credentials",{endpoint:e,originalError:t?.message||String(t)})}try{s=await t.json()}catch{s=null}if(!t.ok)throw w(u,"Merchant validation failed for merchantId/apiKey/packageName",{endpoint:e,status:t.status,response:s});const n=Number(s?.responseCode),i=s?.errors,r=!Array.isArray(i)||0===i.length;if(!(s&&0===n&&r))throw w(u,"Merchant validation returned an unsuccessful response",{endpoint:e,status:t.status,response:s});g.log("[Dropp SDK] Merchant credentials validated successfully")}closePayment(){if(this.isOpen){if("page"===this.currentFlowType)return void this._cleanup();this._handleCancel("sdk_close")}}dashboard(e={}){return this._openHostedPage("/firsttimeflow",e)}unlinkAccount(e={}){return this._openHostedPage("/unlink",e)}transactions(e={}){return this._openHostedPage("/transactions",e)}offers(e={}){return this._openHostedPage("/offers",e)}status(){return new Promise((e,t)=>{this.isOpen||"status"===this.currentFlowType?t(w(h,"A Dropp session is already in progress",{currentSession:this.currentSession,currentFlowType:this.currentFlowType})):(async()=>{try{await this.initialize(),this.currentFlowType="status",this.currentSession=null,this.onSuccess=null,this.onFailure=null,this.onCancel=null,this.onClose=null,this.messageHandler=new T(this.environment,this._handleMessage.bind(this),this.allowedOrigins);const s=document.createElement("iframe");s.id="dropp-status-iframe",s.setAttribute("allow","payment"),s.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),s.setAttribute("referrerpolicy","no-referrer"),s.setAttribute("title","Dropp Account Status"),Object.assign(s.style,{position:"absolute",width:"1px",height:"1px",border:"0",opacity:"0",pointerEvents:"none",visibility:"hidden"}),document.body.appendChild(s),this.hiddenIframe=s,this.messageHandler.init(s);const n=new URLSearchParams({sdkMode:"true",sessionId:this.messageHandler.getSessionId(),sdkVersion:m,platform:"web"}),i=this.baseUrl.replace(/\/+$/,"");s.src=`${i}/#/status?${n.toString()}`,this.statusSession={resolve:e,reject:t,startTime:Date.now()},this.statusTimeout=setTimeout(()=>{const e=w(c,"Account status request timed out",{type:"status",sessionDuration:this.statusSession?Date.now()-this.statusSession.startTime:0});this.statusSession&&this.statusSession.reject(e),this._cleanup()},o)}catch(e){t(w(p,"Failed to get account status",{originalError:e?.message||String(e)})),this._cleanup()}})()})}async _initializePayment(e){g.log("[Dropp SDK] Initializing payment session"),this.currentFlowType="payment",this.messageHandler=new T(this.environment,this._handleMessage.bind(this),this.allowedOrigins),this.modalManager=new v(this._handleModalClose.bind(this));const t=this.modalManager.open();if(!t)throw new Error("Failed to create modal iframe");this.messageHandler.init(t);const s=e.paymentType||l.STANDARD;let n="/payViaUrl";s===l.PREAUTH?n="/preAuthPayment":s===l.RECURRING&&(n="/recurringPayment");const i=s===l.RECURRING?(e.frequency||e.recurringInterval||"").toString().trim().toUpperCase():"",r=s===l.RECURRING&&"NONE"===i,c=e.appUrl||("undefined"!=typeof window&&window.location?window.location.href:void 0),d={merchantAccount:this.merchantId,amount:s===l.PREAUTH?void 0:e.amount,maxAmount:s===l.PREAUTH||r?e.amount:void 0,fixAmount:s!==l.RECURRING||r?void 0:e.amount,acceptPaymentDelay:s===l.STANDARD&&!0===e.acceptPaymentDelay||void 0,currency:e.currency,itemName:e.itemName,description:e.description,invoiceId:e.invoiceId||`INV-${Date.now()}`,invoiceType:s===l.PREAUTH?"PREAUTH":void 0,apiKey:this.apiKey,packageName:this.packageName,sdkVersion:m,platform:"web",appUrl:c,sessionId:this.messageHandler.getSessionId()};if(g.log("[Dropp SDK] Including SDK session context in payment params"),e.successURL&&(d.successURL=e.successURL),e.failureURL&&(d.failureURL=e.failureURL),s===l.RECURRING){const t=e.frequency||e.recurringInterval;t&&(d.frequency=t),e.recurringEndDate&&(d.expiry=e.recurringEndDate)}s===l.PREAUTH&&e.authHoldTimeInSeconds&&(d.authHoldTimeInSeconds=e.authHoldTimeInSeconds),e.callbackUrl&&(d.url=e.callbackUrl,d.submitToCallBack="post");const h={sessionId:d.sessionId,merchantAccount:this.merchantId,amount:e.amount,paymentType:s,invoiceId:d.invoiceId,expiry:e.recurringEndDate||null,issuedAt:Date.now()};let p="string"==typeof e.serverAuthToken?e.serverAuthToken.trim():"";if(!p&&this.getServerAuthToken)try{const e=await this.getServerAuthToken(h);p="string"==typeof e?e.trim():""}catch(e){throw w(u,"Failed to obtain server auth token",{originalError:e?.message||String(e)})}if(this.requireServerAuthToken&&!p)throw w(u,"serverAuthToken is required. Provide options.serverAuthToken or config.getServerAuthToken.",{environment:this.environment,paymentType:s,invoiceId:d.invoiceId});const y=await async function(e,t,s,n,i={}){try{const{serverAuthToken:r=""}=i,o={};Object.keys(s).forEach(e=>{const t=s[e];null!=t&&(o[e]=t)}),g.log("[buildPaymentUrl] Building payment URL payload");const a=JSON.stringify(o),l=btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),c=Date.now().toString(),d=new URLSearchParams({pay:l,sdkTs:c,sdkVersion:n,platform:"web"});return r&&d.set("authToken",r),`${e}/#${t}?${d.toString()}`}catch(e){throw g.error("Error building payment URL:",e),e}}(this.baseUrl,n,d,m,{serverAuthToken:p});g.log("[Dropp SDK] Loading payment flow iframe"),t.src=y,this.isOpen=!0,this.initTimeout=setTimeout(()=>{this._handleTimeout("init")},o),this.paymentTimeout=setTimeout(()=>{this._handleTimeout("payment")},a)}async _openHostedPage(e,t={}){if(this.isOpen)throw w(h,"A Dropp session is already in progress",{currentSession:this.currentSession,route:e});await this.initialize(),this.currentFlowType="page",this.currentSession=null,this.onSuccess=null,this.onFailure=null,this.onCancel=null,this.onClose="function"==typeof t.onClose?t.onClose:null,this.messageHandler=new T(this.environment,this._handleMessage.bind(this),this.allowedOrigins),this.modalManager=new v(this._handleModalClose.bind(this));const s=this.modalManager.open();if(!s)throw new Error("Failed to create modal iframe");this.messageHandler.init(s);const n=new URLSearchParams({sdkMode:"true",sessionId:this.messageHandler.getSessionId(),sdkVersion:m,platform:"web"}),i=this.baseUrl.replace(/\/+$/,"");return s.src=`${i}/#${e}?${n.toString()}`,this.isOpen=!0,g.log("[Dropp SDK] Hosted page opened",{route:e}),{status:"opened",route:e}}_handleMessage(t){const{type:s,data:n}=t;switch(s){case e.READY:this._handleReady(n);break;case e.PAGE_LOADED:case e.PAYMENT_PAGE_LOADED:this._handlePageLoaded(n);break;case e.PAYMENT_SUCCESS:this._handleSuccess(n);break;case e.PAYMENT_FAILED:this._handleFailure(n);break;case e.PAYMENT_CANCELLED:this._handleCancel("user_cancelled");break;case e.ACCOUNT_STATUS:this._handleAccountStatus(n);break;case e.AUTO_CLOSE_WEBVIEW:g.log("[Dropp SDK] AUTO_CLOSE_WEBVIEW received - closing modal"),this._cleanup(),g.log("[Dropp SDK] Cleanup completed");break;case e.CLOSE_WEBVIEW:if(g.log("[Dropp SDK] CLOSE_WEBVIEW received from app - closing modal"),"status"===this.currentFlowType&&this.statusSession){const e=w(p,"Account status request was closed before response was received",{type:"status",sessionDuration:Date.now()-this.statusSession.startTime});this.statusSession.reject(e),this._cleanup();break}this._handleCancel("app_close");break;default:g.warn("[Dropp SDK] Unknown message type:",s)}}_handleReady(e){if(g.log("[Dropp SDK] Payment app ready"),this.initTimeout&&(clearTimeout(this.initTimeout),this.initTimeout=null),this.messageHandler&&this.currentSession){const e={};Object.keys(this.currentSession.options).forEach(t=>{const s=this.currentSession.options[t];"function"!=typeof s&&(e[t]=s)}),g.log("[Dropp SDK] Sending init config to payment app"),this.messageHandler.sendInit(e)}}_handlePageLoaded(e){g.log("[Dropp SDK] Payment page loaded")}_handleAccountStatus(t){g.log("[Dropp SDK] Account status received"),this.statusSession?(this.statusSession.resolve({type:e.ACCOUNT_STATUS,data:t}),this._cleanup()):g.warn("[Dropp SDK] ACCOUNT_STATUS received without active status session")}_handleSuccess(e){g.log("[Dropp SDK] Payment successful");const t={status:"success",...e,sessionDuration:Date.now()-this.currentSession.startTime};this.currentSession&&this.currentSession.resolve(t),this.onSuccess&&this.onSuccess(t)}_handleFailure(e){g.log("[Dropp SDK] Payment failed");const t={status:"failed",...e,sessionDuration:Date.now()-this.currentSession.startTime};this.currentSession&&this.currentSession.resolve(t),this.onFailure&&this.onFailure(t)}_handleCancel(e){g.log("[Dropp SDK] Payment cancelled");const t={status:"cancelled",reason:e,sessionDuration:this.currentSession?Date.now()-this.currentSession.startTime:0};this.currentSession&&this.currentSession.resolve(t),this.onCancel&&this.onCancel(t),this._cleanup()}_handleModalClose(e){g.log("[Dropp SDK] Modal closed by user"),"page"!==this.currentFlowType?this._handleCancel(e):this._cleanup()}_handleTimeout(e){g.error("[Dropp SDK] Timeout:",e);const t=w("init"===e?c:d,"init"===e?"Payment app failed to load within timeout period":"Payment session timed out",{type:e,sessionDuration:this.currentSession?Date.now()-this.currentSession.startTime:0});this.currentSession&&this.currentSession.reject(t),this.onFailure&&this.onFailure({status:"failed",error:t}),this._cleanup()}_cleanup(){g.log("[Dropp SDK] ๐Ÿงน Cleaning up session - starting cleanup"),this.initTimeout&&(clearTimeout(this.initTimeout),this.initTimeout=null),this.paymentTimeout&&(clearTimeout(this.paymentTimeout),this.paymentTimeout=null),this.statusTimeout&&(clearTimeout(this.statusTimeout),this.statusTimeout=null),this.messageHandler&&(g.log("[Dropp SDK] ๐Ÿงน Destroying message handler"),this.messageHandler.destroy(),this.messageHandler=null),this.modalManager&&(g.log("[Dropp SDK] ๐Ÿงน Closing modal manager"),this.modalManager.close(),g.log("[Dropp SDK] ๐Ÿงน Modal manager closed"),this.modalManager=null),this.hiddenIframe&&this.hiddenIframe.parentNode&&this.hiddenIframe.parentNode.removeChild(this.hiddenIframe),this.hiddenIframe=null,this.currentSession=null,this.statusSession=null,this.currentFlowType=null,this.isOpen=!1,this.onClose&&this.onClose()}static getVersion(){return m}static getEnvironments(){return{...n}}static getPaymentTypes(){return{...l}}}let _=null;async function I(e){_=new E(e);return{...await _.initialize(),sdk:_}}function A(){return _}const C={init:e=>I(e),pay(e){if(!_){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.pay(options).");throw e.code="SDK_NOT_INITIALIZED",e}return _.pay(e)},dashboard(e){if(!_){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.dashboard(options).");throw e.code="SDK_NOT_INITIALIZED",e}return _.dashboard(e)},unlinkAccount(e){if(!_){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.unlinkAccount(options).");throw e.code="SDK_NOT_INITIALIZED",e}return _.unlinkAccount(e)},transactions(e){if(!_){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.transactions(options).");throw e.code="SDK_NOT_INITIALIZED",e}return _.transactions(e)},offers(e){if(!_){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.offers(options).");throw e.code="SDK_NOT_INITIALIZED",e}return _.offers(e)},status(){if(!_){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.status().");throw e.code="SDK_NOT_INITIALIZED",e}return _.status()},getInstance:()=>_};var N={DroppPaymentSDK:E,createPaymentSDK:I,Dropp:C,ENVIRONMENTS:n,PAYMENT_TYPES:l};export{C as Dropp,E as DroppPaymentSDK,n as ENVIRONMENTS,l as PAYMENT_TYPES,I as createPaymentSDK,N as default,A as getDroppInstance};
1
+ const e={READY:"DROPP_SDK_READY",PAYMENT_SUCCESS:"PAYMENT_SUCCESS",PAYMENT_FAILED:"PAYMENT_FAILED",PAYMENT_CANCELLED:"PAYMENT_CANCELLED",ACCOUNT_STATUS:"ACCOUNT_STATUS",CLOSE_WEBVIEW:"CLOSE_WEBVIEW",AUTO_CLOSE_WEBVIEW:"AUTO_CLOSE_WEBVIEW",PAYMENT_PAGE_LOADED:"PAYMENT_PAGE_LOADED",PAGE_LOADED:"PAGE_LOADED"},t="DROPP_SDK_INIT",s="DROPP_SDK_CLOSE",n={PRODUCTION:"production",QA:"qa",SANDBOX:"sandbox"},i={[n.PRODUCTION]:"https://wv.dropp.cc",[n.QA]:"https://wv.qa.dropp.cc",[n.SANDBOX]:"https://wv.sandbox.dropp.cc"},o={[n.PRODUCTION]:["https://wv.dropp.cc"],[n.QA]:["https://wv.qa.dropp.cc"],[n.SANDBOX]:["https://wv.sandbox.dropp.cc"]},r=3e4,a=6e5,l={STANDARD:"standard",PREAUTH:"preauth",RECURRING:"recurring"},c="INIT_TIMEOUT",d="PAYMENT_TIMEOUT",u="INVALID_CONFIG",h="ALREADY_OPEN",p="UNKNOWN_ERROR",m="1.0.2";const g=new class{constructor(e,t={}){this.environment=e,this.forceEnabled=!!t.enabled,this.enabled=this._shouldEnableLogging()}_shouldEnableLogging(){return this.forceEnabled}setEnvironment(e,t={}){this.environment=e,"boolean"==typeof t.enabled&&(this.forceEnabled=t.enabled),this.enabled=this._shouldEnableLogging()}setEnabled(e){this.forceEnabled=!!e,this.enabled=this._shouldEnableLogging()}log(...e){this.enabled&&console.log(...e)}warn(...e){this.enabled&&console.warn(...e)}error(...e){this.enabled&&console.error(...e)}debug(...e){this.enabled&&console.debug(...e)}info(...e){this.enabled&&console.info(...e)}}("qa",{enabled:!1}),y=["USD","HBAR","USDC"],f=["NONE","HALF_HOURLY","HOURLY","DAILY","WEEKLY","MONTHLY","YEARLY"],S=[l.STANDARD,l.PREAUTH,l.RECURRING];function D(e,t={}){const{isProduction:s=!1,allowLocalCallbacksInNonProd:n=!1}=t;if("string"!=typeof e||!e.trim())return!1;try{const t=new URL(e.trim()),i="https:"===t.protocol;if(!("http:"===t.protocol)&&!i)return!1;return function(e){if(!e)return!1;const t=e.trim().toLowerCase();if("localhost"===t||"127.0.0.1"===t||"::1"===t||t.endsWith(".local"))return!0;if(!/^(\d{1,3}\.){3}\d{1,3}$/.test(t))return!1;const s=t.split(".").map(e=>Number(e));if(s.some(e=>Number.isNaN(e)||e<0||e>255))return!1;const[n,i]=s;return 10===n||127===n||172===n&&i>=16&&i<=31||192===n&&168===i||169===n&&254===i}(t.hostname)?!s&&n:!s||i}catch{return!1}}function w(e={},t={}){const s=[],n=e.paymentType||l.STANDARD,i="production"===(t.environment||"").toLowerCase(),o=!!t.allowLocalCallbacksInNonProd,r="string"==typeof e.currency?e.currency.trim().toUpperCase():"";if(S.includes(n)||s.push(`paymentType must be one of: ${S.join(", ")}`),void 0===e.amount||null===e.amount||""===e.amount?s.push("amount is required"):function(e){const t="number"==typeof e?e:parseFloat(e);return"number"==typeof t&&!Number.isNaN(t)&&t>0}(e.amount)||s.push("amount must be a positive number"),e.currency&&"string"==typeof e.currency&&e.currency.trim()?y.includes(r)||s.push(`currency must be one of: ${y.join(", ")}`):s.push("currency is required"),e.itemName&&"string"==typeof e.itemName&&e.itemName.trim()||s.push("itemName is required"),n===l.PREAUTH&&(r&&"USD"!==r&&s.push("currency must be USD for preauth payments"),e.callbackUrl&&String(e.callbackUrl).trim()?D(e.callbackUrl,{isProduction:i,allowLocalCallbacksInNonProd:o})||s.push(i?"callbackUrl must be HTTPS in production and cannot target loopback/private hosts":"callbackUrl must be a valid HTTP/HTTPS URL and cannot target loopback/private hosts unless explicitly enabled"):s.push("callbackUrl (signing URL) is required for preauth payments"),void 0===e.authHoldTimeInSeconds||null===e.authHoldTimeInSeconds||""===e.authHoldTimeInSeconds?s.push("authHoldTimeInSeconds is required for preauth payments"):function(e){const t="number"==typeof e?e:parseInt(e,10);return Number.isInteger(t)&&t>0}(e.authHoldTimeInSeconds)||s.push("authHoldTimeInSeconds must be a positive integer (seconds)")),n===l.RECURRING){e.callbackUrl&&String(e.callbackUrl).trim()?D(e.callbackUrl,{isProduction:i,allowLocalCallbacksInNonProd:o})||s.push(i?"callbackUrl must be HTTPS in production and cannot target loopback/private hosts":"callbackUrl must be a valid HTTP/HTTPS URL and cannot target loopback/private hosts unless explicitly enabled"):s.push("callbackUrl (signing URL) is required for recurring payments");const t=(e.frequency||e.recurringInterval||"").toString().trim().toUpperCase();t?f.includes(t)||s.push(`frequency must be one of: ${f.join(", ")}`):s.push("frequency is required for recurring payments"),e.recurringEndDate&&String(e.recurringEndDate).trim()?!function(e){if("string"!=typeof e||!e.trim())return!1;const t=new Date(e.trim());return!Number.isNaN(t.getTime())}(e.recurringEndDate)?s.push("recurringEndDate must be a valid ISO date-time string"):new Date(e.recurringEndDate.trim())<=new Date&&s.push("recurringEndDate must be in the future"):s.push("recurringEndDate (expiry) is required for recurring payments")}return{valid:0===s.length,errors:s}}function b(e,t,s={}){return{code:e,message:t,details:s,timestamp:(new Date).toISOString(),toString(){return this.message||"Dropp SDK error"}}}class T{constructor(e,t,s=null){this.environment=e,this.onMessage=t,this.sessionId=`dropp-sdk-${Date.now()}-${Math.random().toString(36).substring(2,15)}`,g.log("[MessageHandler] Session initialized"),this.iframe=null,this.allowedOrigins=s?.length>0?s:o[e]||[],this.messageListener=null,this.pendingMessages=new Map}init(e){this.iframe=e,this.messageListener=this._handleMessage.bind(this),window.addEventListener("message",this.messageListener)}destroy(){this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.iframe=null,this.pendingMessages.clear()}_handleMessage(e){if(g.log("[MessageHandler] Received postMessage event"),e.source===window)return void g.log("[MessageHandler] Ignoring message from self");if(!this._validateOrigin(e.origin))return void g.warn("[Dropp SDK] Rejected message from untrusted origin:",e.origin);if(!this.iframe||e.source!==this.iframe.contentWindow)return void g.warn("[Dropp SDK] Rejected message from unexpected source",{eventOrigin:e.origin});const t=e.data;this._validateMessageStructure(t)?t.sessionId&&t.sessionId!==this.sessionId?g.warn("[Dropp SDK] Rejected message with invalid session ID"):(g.log("[MessageHandler] Message passed validation"),this._processMessage(t)):g.warn("[Dropp SDK] Rejected message with invalid structure")}_validateOrigin(e){return!(!e.startsWith("http://localhost:")&&!e.startsWith("http://127.0.0.1:"))||this.allowedOrigins.includes(e)}_validateMessageStructure(t){if(!t||"object"!=typeof t)return!1;if(!t.type||"string"!=typeof t.type)return!1;return!!Object.values(e).includes(t.type)&&!(t.type!==e.ACCOUNT_STATUS&&!t.timestamp)}_processMessage(e){g.log("[Dropp SDK] Received message:",e.type),this.onMessage&&this.onMessage(e)}sendToPaymentApp(e,t={}){if(!this.iframe||!this.iframe.contentWindow)return g.error("[Dropp SDK] Cannot send message: iframe not ready"),!1;const s={type:e,data:t,sessionId:this.sessionId,timestamp:(new Date).toISOString(),sdkVersion:"1.0.0"},n=this.allowedOrigins[0]||"*";try{return this.iframe.contentWindow.postMessage(s,n),g.log("[Dropp SDK] Sent message:",e),!0}catch(e){return g.error("[Dropp SDK] Error sending message:",e),!1}}sendInit(e){return this.sendToPaymentApp(t,{mode:"sdk",config:e})}sendClose(){return this.sendToPaymentApp(s,{})}getSessionId(){return this.sessionId}}class v{constructor(e){this.onClose=e,this.overlay=null,this.container=null,this.iframe=null,this.closeButton=null,this.isOpen=!1,this.escapeListener=null}open(){return this.isOpen?(g.warn("[Dropp SDK] Modal is already open"),null):(this._createModal(),this._attachEventListeners(),this._show(),this.isOpen=!0,this.iframe)}close(){g.log("[ModalManager] ๐Ÿšฆ close() called, isOpen:",this.isOpen),this.isOpen?(g.log("[ModalManager] ๐Ÿšฆ Hiding modal..."),this._hide(),g.log("[ModalManager] ๐Ÿšฆ Removing event listeners..."),this._removeEventListeners(),g.log("[ModalManager] ๐Ÿšฆ Destroying modal..."),this._destroyModal(),this.isOpen=!1,g.log("[ModalManager] โœ… Modal close sequence initiated")):g.log("[ModalManager] โš ๏ธ Modal is not open, skipping close")}_createModal(){this.overlay=document.createElement("div"),this.overlay.id="dropp-payment-overlay",this._applyOverlayStyles(this.overlay),this.container=document.createElement("div"),this.container.id="dropp-payment-container",this._applyContainerStyles(this.container),this.iframe=document.createElement("iframe"),this.iframe.id="dropp-payment-iframe",this.iframe.setAttribute("allow","payment"),this.iframe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),this.iframe.setAttribute("referrerpolicy","no-referrer"),this.iframe.setAttribute("title","Dropp Payment"),this._applyIframeStyles(this.iframe),this.container.appendChild(this.iframe),this.overlay.appendChild(this.container),document.body.appendChild(this.overlay)}_applyOverlayStyles(e){Object.assign(e.style,{position:"fixed",inset:"0",width:"100vw",height:"100vh",margin:"0",padding:"20px",boxSizing:"border-box",backgroundColor:"rgba(0, 0, 0, 0.6)",zIndex:999999..toString(),display:"flex",alignItems:"center",justifyContent:"center",opacity:"0",transition:"opacity 0.3s ease",backdropFilter:"blur(4px)",overflow:"auto"})}_applyContainerStyles(e){const t=window.innerWidth<768;this._isMobile=t,Object.assign(e.style,{position:"relative",flex:"0 0 auto",alignSelf:"center",margin:"auto",width:"100%",maxWidth:t?"100%":"400px",height:t?"100%":"auto",minHeight:t?"100%":"800px",maxHeight:t?"100%":"min(1000px, calc(100vh - 40px))",backgroundColor:"#ffffff",borderRadius:t?"0":"16px",boxShadow:"0 20px 60px rgba(0, 0, 0, 0.3)",overflow:"hidden",transform:"scale(0.95)",transition:"transform 0.3s ease, opacity 0.3s ease",display:"flex",flexDirection:"column"})}_getContainerTransform(e){return`scale(${e})`}_applyCloseButtonStyles(e){Object.assign(e.style,{position:"absolute",top:"16px",right:"16px",zIndex:"10",width:"40px",height:"40px",border:"none",borderRadius:"50%",backgroundColor:"rgba(255, 255, 255, 0.9)",color:"#333",fontSize:"28px",lineHeight:"1",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.15)",transition:"all 0.2s ease",fontFamily:"Arial, sans-serif",padding:"0"}),e.addEventListener("mouseenter",()=>{Object.assign(e.style,{backgroundColor:"#f5f5f5",transform:"scale(1.1)"})}),e.addEventListener("mouseleave",()=>{Object.assign(e.style,{backgroundColor:"rgba(255, 255, 255, 0.9)",transform:"scale(1)"})})}_applyIframeStyles(e){const t=this._isMobile;Object.assign(e.style,{width:"100%",flex:"1 1 auto",minHeight:t?"100%":"min(520px, calc(90vh - 40px))",height:t?"100%":"min(520px, calc(90vh - 40px))",border:"none",display:"block"})}_show(){document.body.style.overflow="hidden",requestAnimationFrame(()=>{this.overlay&&(this.overlay.style.opacity="1"),this.container&&(this.container.style.transform=this._getContainerTransform(1))})}_hide(){g.log("[ModalManager] ๐ŸŽญ _hide() called"),this.overlay&&(this.overlay.style.opacity="0",g.log("[ModalManager] ๐ŸŽญ Overlay opacity set to 0")),this.container&&(this.container.style.transform=this._getContainerTransform(.95),g.log("[ModalManager] ๐ŸŽญ Container transform set to scale(0.95)")),document.body.style.overflow="",g.log("[ModalManager] ๐ŸŽญ Body scroll restored")}_destroyModal(){g.log("[ModalManager] ๐Ÿ—‘๏ธ _destroyModal() called, waiting 300ms for animation"),setTimeout(()=>{g.log("[ModalManager] ๐Ÿ—‘๏ธ Animation complete, removing from DOM"),this.overlay&&this.overlay.parentNode&&(this.overlay.parentNode.removeChild(this.overlay),g.log("[ModalManager] ๐Ÿ—‘๏ธ Overlay removed from DOM")),this.overlay=null,this.container=null,this.iframe=null,this.closeButton=null,g.log("[ModalManager] โœ… Modal destroyed")},300)}_attachEventListeners(){}_removeEventListeners(){this.escapeListener&&(document.removeEventListener("keydown",this.escapeListener),this.escapeListener=null)}_handleCloseClick(e){e.stopPropagation(),this.onClose&&this.onClose("user_closed")}_handleOverlayClick(e){e.target===this.overlay&&this.onClose&&this.onClose("user_closed")}_handleEscapeKey(e){"Escape"===e.key&&this.isOpen&&this.onClose&&this.onClose("user_closed")}getIframe(){return this.iframe}getIsOpen(){return this.isOpen}}const E=["fundnow","linkbank","linkcard","redeemnow","fundcrypto","transferusdc","usdchistory","redeemcrypto","manageaccounts","transactions","merchantlist","favorites","offers","profile","changepin","unlinkaccount","accountsettings","about"];class I{constructor(e={}){if("undefined"==typeof window||"undefined"==typeof document)throw new Error("Dropp Payment SDK can only be used in a browser environment");if(!e.merchantId||!e.apiKey||!e.packageName)throw new Error("merchantId, apiKey, and packageName are required to initialize SDK");if(this.merchantId=e.merchantId,this.apiKey=e.apiKey,this.packageName=e.packageName,this.environment=e.environment||n.QA,this.baseUrl=e.paymentAppUrl||e.baseUrl||i[this.environment],this.isInitialized=!1,this.initializationPromise=null,this.getServerAuthToken="function"==typeof e.getServerAuthToken?e.getServerAuthToken:null,this.requireServerAuthToken="boolean"==typeof e.requireServerAuthToken?e.requireServerAuthToken:this.environment===n.PRODUCTION,this.allowLocalCallbacksInNonProd=!!e.allowLocalCallbacksInNonProd,e.allowedOrigins?.length)this.allowedOrigins=e.allowedOrigins;else try{this.allowedOrigins=[new URL(this.baseUrl).origin]}catch{this.allowedOrigins=o[this.environment]||[]}this.isOpen=!1,this.currentSession=null,this.currentFlowType=null,this.statusSession=null,this.hiddenIframe=null,this.statusTimeout=null,this.initTimeout=null,this.paymentTimeout=null,this.messageHandler=null,this.modalManager=null,g.setEnvironment(this.environment,{enabled:!!e.debugLogging}),g.log(`[Dropp SDK] Initialized v${m} - Environment: ${this.environment}`)}pay(e={}){return new Promise((t,s)=>{if(this.isOpen){const e=b(h,"A payment session is already in progress",{currentSession:this.currentSession});return void s(e)}(async()=>{try{await this.initialize();const n=w(e,{environment:this.environment,allowLocalCallbacksInNonProd:this.allowLocalCallbacksInNonProd});if(!n.valid){const e=b(u,"Invalid payment configuration",{errors:n.errors});return void s(e)}this.onSuccess=e.onSuccess||null,this.onFailure=e.onFailure||null,this.onCancel=e.onCancel||null,this.onClose=e.onClose||null,this.currentSession={resolve:t,reject:s,options:e,startTime:Date.now()},await this._initializePayment(e)}catch(e){const t=e&&e.code===u?e:b(p,"Failed to initialize payment",{originalError:e?.message||String(e)});s(t),this._cleanup()}})()})}async initialize(){return this.initializationPromise||(this.initializationPromise=(async()=>(await this._validateInitializationCredentials(),this.isInitialized=!0,{status:"success",code:"INITIALIZED",message:"Dropp SDK initialized successfully"}))().catch(e=>{throw this.isInitialized=!1,this.initializationPromise=null,e})),this.initializationPromise}_getValidationUrl(){const e={[n.QA]:"https://main.qa.dropp.cc/payer/webview/validate",[n.SANDBOX]:"https://sandbox.api.dropp.cc/payer/webview/validate",[n.PRODUCTION]:"https://api.dropp.cc/payer/webview/validate"};return e[this.environment]||e[n.QA]}async _validateInitializationCredentials(){const e=this._getValidationUrl();let t,s=null;try{t=await fetch(e,{method:"POST",headers:{accept:"application/json, text/plain, */*","content-type":"application/json","x-api-key":this.apiKey,"x-app-package":this.packageName},body:JSON.stringify({id:this.merchantId})})}catch(t){throw b(u,"Unable to validate merchant credentials",{endpoint:e,originalError:t?.message||String(t)})}try{s=await t.json()}catch{s=null}if(!t.ok)throw b(u,"Merchant validation failed for merchantId/apiKey/packageName",{endpoint:e,status:t.status,response:s});const n=Number(s?.responseCode),i=s?.errors,o=!Array.isArray(i)||0===i.length;if(!(s&&0===n&&o))throw b(u,"Merchant validation returned an unsuccessful response",{endpoint:e,status:t.status,response:s});g.log("[Dropp SDK] Merchant credentials validated successfully")}closePayment(){if(this.isOpen){if("page"===this.currentFlowType)return void this._cleanup();this._handleCancel("sdk_close")}}dashboard(e={}){return this._openHostedPage("/firsttimeflow",e)}load(e,t={}){const s="string"==typeof e?e.trim():"";if(!s)throw b(u,"moduleId is required for Dropp.load(moduleId)",{moduleId:e});if(!E.includes(s))throw b(u,"Unsupported moduleId passed to Dropp.load(moduleId)",{moduleId:s,supportedModuleIds:[...E]});return this._openHostedPage("/firsttimeflow",{...t,modules:[s]})}unlinkAccount(e={}){return this._openHostedPage("/unlink",e)}transactions(e={}){return this._openHostedPage("/transactions",e)}offers(e={}){return this._openHostedPage("/offers",e)}status(){return new Promise((e,t)=>{this.isOpen||"status"===this.currentFlowType?t(b(h,"A Dropp session is already in progress",{currentSession:this.currentSession,currentFlowType:this.currentFlowType})):(async()=>{try{await this.initialize(),this.currentFlowType="status",this.currentSession=null,this.onSuccess=null,this.onFailure=null,this.onCancel=null,this.onClose=null,this.messageHandler=new T(this.environment,this._handleMessage.bind(this),this.allowedOrigins);const s=document.createElement("iframe");s.id="dropp-status-iframe",s.setAttribute("allow","payment"),s.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),s.setAttribute("referrerpolicy","no-referrer"),s.setAttribute("title","Dropp Account Status"),Object.assign(s.style,{position:"absolute",width:"1px",height:"1px",border:"0",opacity:"0",pointerEvents:"none",visibility:"hidden"}),document.body.appendChild(s),this.hiddenIframe=s,this.messageHandler.init(s);const n=new URLSearchParams({sdkMode:"true",sessionId:this.messageHandler.getSessionId(),sdkVersion:m,platform:"web"}),i=this.baseUrl.replace(/\/+$/,"");s.src=`${i}/#/status?${n.toString()}`,this.statusSession={resolve:e,reject:t,startTime:Date.now()},this.statusTimeout=setTimeout(()=>{const e=b(c,"Account status request timed out",{type:"status",sessionDuration:this.statusSession?Date.now()-this.statusSession.startTime:0});this.statusSession&&this.statusSession.reject(e),this._cleanup()},r)}catch(e){t(b(p,"Failed to get account status",{originalError:e?.message||String(e)})),this._cleanup()}})()})}async _initializePayment(e){g.log("[Dropp SDK] Initializing payment session"),this.currentFlowType="payment",this.messageHandler=new T(this.environment,this._handleMessage.bind(this),this.allowedOrigins),this.modalManager=new v(this._handleModalClose.bind(this));const t=this.modalManager.open();if(!t)throw new Error("Failed to create modal iframe");this.messageHandler.init(t);const s=e.paymentType||l.STANDARD;let n="/payViaUrl";s===l.PREAUTH?n="/preAuthPayment":s===l.RECURRING&&(n="/recurringPayment");const i=s===l.RECURRING?(e.frequency||e.recurringInterval||"").toString().trim().toUpperCase():"",o=s===l.RECURRING&&"NONE"===i,c=e.appUrl||("undefined"!=typeof window&&window.location?window.location.href:void 0),d={merchantAccount:this.merchantId,amount:s===l.PREAUTH?void 0:e.amount,maxAmount:s===l.PREAUTH||o?e.amount:void 0,fixAmount:s!==l.RECURRING||o?void 0:e.amount,acceptPaymentDelay:s===l.STANDARD&&!0===e.acceptPaymentDelay||void 0,currency:e.currency,itemName:e.itemName,description:e.description,invoiceId:e.invoiceId||`INV-${Date.now()}`,invoiceType:s===l.PREAUTH?"PREAUTH":void 0,apiKey:this.apiKey,packageName:this.packageName,sdkVersion:m,platform:"web",appUrl:c,sessionId:this.messageHandler.getSessionId()};if(g.log("[Dropp SDK] Including SDK session context in payment params"),e.successURL&&(d.successURL=e.successURL),e.failureURL&&(d.failureURL=e.failureURL),s===l.RECURRING){const t=e.frequency||e.recurringInterval;t&&(d.frequency=t),e.recurringEndDate&&(d.expiry=e.recurringEndDate)}s===l.PREAUTH&&e.authHoldTimeInSeconds&&(d.authHoldTimeInSeconds=e.authHoldTimeInSeconds),e.callbackUrl&&(d.url=e.callbackUrl,d.submitToCallBack="post");const h={sessionId:d.sessionId,merchantAccount:this.merchantId,amount:e.amount,paymentType:s,invoiceId:d.invoiceId,expiry:e.recurringEndDate||null,issuedAt:Date.now()};let p="string"==typeof e.serverAuthToken?e.serverAuthToken.trim():"";if(!p&&this.getServerAuthToken)try{const e=await this.getServerAuthToken(h);p="string"==typeof e?e.trim():""}catch(e){throw b(u,"Failed to obtain server auth token",{originalError:e?.message||String(e)})}if(this.requireServerAuthToken&&!p)throw b(u,"serverAuthToken is required. Provide options.serverAuthToken or config.getServerAuthToken.",{environment:this.environment,paymentType:s,invoiceId:d.invoiceId});const y=await async function(e,t,s,n,i={}){try{const{serverAuthToken:o=""}=i,r={};Object.keys(s).forEach(e=>{const t=s[e];null!=t&&(r[e]=t)}),g.log("[buildPaymentUrl] Building payment URL payload");const a=JSON.stringify(r),l=btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),c=Date.now().toString(),d=new URLSearchParams({pay:l,sdkTs:c,sdkVersion:n,platform:"web"});return o&&d.set("authToken",o),`${e}/#${t}?${d.toString()}`}catch(e){throw g.error("Error building payment URL:",e),e}}(this.baseUrl,n,d,m,{serverAuthToken:p});g.log("[Dropp SDK] Loading payment flow iframe"),t.src=y,this.isOpen=!0,this.initTimeout=setTimeout(()=>{this._handleTimeout("init")},r),this.paymentTimeout=setTimeout(()=>{this._handleTimeout("payment")},a)}async _openHostedPage(e,t={}){if(this.isOpen)throw b(h,"A Dropp session is already in progress",{currentSession:this.currentSession,route:e});await this.initialize(),this.currentFlowType="page",this.currentSession=null,this.onSuccess=null,this.onFailure=null,this.onCancel=null,this.onClose="function"==typeof t.onClose?t.onClose:null,this.messageHandler=new T(this.environment,this._handleMessage.bind(this),this.allowedOrigins),this.modalManager=new v(this._handleModalClose.bind(this));const s=this.modalManager.open();if(!s)throw new Error("Failed to create modal iframe");this.messageHandler.init(s);const n=new URLSearchParams({sdkMode:"true",sessionId:this.messageHandler.getSessionId(),sdkVersion:m,platform:"web"});if("/firsttimeflow"===e&&Array.isArray(t.modules)){const e=t.modules.map(e=>"string"==typeof e?e.trim():"").filter(Boolean);e.length>0&&n.set("modules",e.join(","))}const i=this.baseUrl.replace(/\/+$/,"");return s.src=`${i}/#${e}?${n.toString()}`,this.isOpen=!0,g.log("[Dropp SDK] Hosted page opened",{route:e}),{status:"opened",route:e}}_handleMessage(t){const{type:s,data:n}=t;switch(s){case e.READY:this._handleReady(n);break;case e.PAGE_LOADED:case e.PAYMENT_PAGE_LOADED:this._handlePageLoaded(n);break;case e.PAYMENT_SUCCESS:this._handleSuccess(n);break;case e.PAYMENT_FAILED:this._handleFailure(n);break;case e.PAYMENT_CANCELLED:this._handleCancel("user_cancelled");break;case e.ACCOUNT_STATUS:this._handleAccountStatus(n);break;case e.AUTO_CLOSE_WEBVIEW:g.log("[Dropp SDK] AUTO_CLOSE_WEBVIEW received - closing modal"),this._cleanup(),g.log("[Dropp SDK] Cleanup completed");break;case e.CLOSE_WEBVIEW:if(g.log("[Dropp SDK] CLOSE_WEBVIEW received from app - closing modal"),"status"===this.currentFlowType&&this.statusSession){const e=b(p,"Account status request was closed before response was received",{type:"status",sessionDuration:Date.now()-this.statusSession.startTime});this.statusSession.reject(e),this._cleanup();break}this._handleCancel("app_close");break;default:g.warn("[Dropp SDK] Unknown message type:",s)}}_handleReady(e){if(g.log("[Dropp SDK] Payment app ready"),this.initTimeout&&(clearTimeout(this.initTimeout),this.initTimeout=null),this.messageHandler&&this.currentSession){const e={};Object.keys(this.currentSession.options).forEach(t=>{const s=this.currentSession.options[t];"function"!=typeof s&&(e[t]=s)}),g.log("[Dropp SDK] Sending init config to payment app"),this.messageHandler.sendInit(e)}}_handlePageLoaded(e){g.log("[Dropp SDK] Payment page loaded")}_handleAccountStatus(t){g.log("[Dropp SDK] Account status received"),this.statusSession?(this.statusSession.resolve({type:e.ACCOUNT_STATUS,data:t}),this._cleanup()):g.warn("[Dropp SDK] ACCOUNT_STATUS received without active status session")}_handleSuccess(e){g.log("[Dropp SDK] Payment successful");const t={status:"success",...e,sessionDuration:Date.now()-this.currentSession.startTime};this.currentSession&&this.currentSession.resolve(t),this.onSuccess&&this.onSuccess(t)}_handleFailure(e){g.log("[Dropp SDK] Payment failed");const t={status:"failed",...e,sessionDuration:Date.now()-this.currentSession.startTime};this.currentSession&&this.currentSession.resolve(t),this.onFailure&&this.onFailure(t)}_handleCancel(e){g.log("[Dropp SDK] Payment cancelled");const t={status:"cancelled",reason:e,sessionDuration:this.currentSession?Date.now()-this.currentSession.startTime:0};this.currentSession&&this.currentSession.resolve(t),this.onCancel&&this.onCancel(t),this._cleanup()}_handleModalClose(e){g.log("[Dropp SDK] Modal closed by user"),"page"!==this.currentFlowType?this._handleCancel(e):this._cleanup()}_handleTimeout(e){g.error("[Dropp SDK] Timeout:",e);const t=b("init"===e?c:d,"init"===e?"Payment app failed to load within timeout period":"Payment session timed out",{type:e,sessionDuration:this.currentSession?Date.now()-this.currentSession.startTime:0});this.currentSession&&this.currentSession.reject(t),this.onFailure&&this.onFailure({status:"failed",error:t}),this._cleanup()}_cleanup(){g.log("[Dropp SDK] ๐Ÿงน Cleaning up session - starting cleanup"),this.initTimeout&&(clearTimeout(this.initTimeout),this.initTimeout=null),this.paymentTimeout&&(clearTimeout(this.paymentTimeout),this.paymentTimeout=null),this.statusTimeout&&(clearTimeout(this.statusTimeout),this.statusTimeout=null),this.messageHandler&&(g.log("[Dropp SDK] ๐Ÿงน Destroying message handler"),this.messageHandler.destroy(),this.messageHandler=null),this.modalManager&&(g.log("[Dropp SDK] ๐Ÿงน Closing modal manager"),this.modalManager.close(),g.log("[Dropp SDK] ๐Ÿงน Modal manager closed"),this.modalManager=null),this.hiddenIframe&&this.hiddenIframe.parentNode&&this.hiddenIframe.parentNode.removeChild(this.hiddenIframe),this.hiddenIframe=null,this.currentSession=null,this.statusSession=null,this.currentFlowType=null,this.isOpen=!1,this.onClose&&this.onClose()}static getVersion(){return m}static getEnvironments(){return{...n}}static getPaymentTypes(){return{...l}}}let _=null;async function A(e){_=new I(e);return{...await _.initialize(),sdk:_}}function C(){return _}const N={init:e=>A(e),pay(e){if(!_){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.pay(options).");throw e.code="SDK_NOT_INITIALIZED",e}return _.pay(e)},dashboard(e){if(!_){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.dashboard(options).");throw e.code="SDK_NOT_INITIALIZED",e}return _.dashboard(e)},load(e,t){if(!_){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.load(moduleId, options).");throw e.code="SDK_NOT_INITIALIZED",e}return _.load(e,t)},unlinkAccount(e){if(!_){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.unlinkAccount(options).");throw e.code="SDK_NOT_INITIALIZED",e}return _.unlinkAccount(e)},transactions(e){if(!_){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.transactions(options).");throw e.code="SDK_NOT_INITIALIZED",e}return _.transactions(e)},offers(e){if(!_){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.offers(options).");throw e.code="SDK_NOT_INITIALIZED",e}return _.offers(e)},status(){if(!_){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.status().");throw e.code="SDK_NOT_INITIALIZED",e}return _.status()},getInstance:()=>_};var O={DroppPaymentSDK:I,createPaymentSDK:A,Dropp:N,ENVIRONMENTS:n,PAYMENT_TYPES:l};export{N as Dropp,I as DroppPaymentSDK,n as ENVIRONMENTS,l as PAYMENT_TYPES,A as createPaymentSDK,O as default,C as getDroppInstance};
2
2
  //# sourceMappingURL=dropp-payment-sdk.esm.js.map