@tonder.io/ionic-lite-sdk 0.0.58-beta.DEV-1845.1 → 0.0.58

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
@@ -25,7 +25,7 @@ You can install using NPM
25
25
  npm i @tonder.io/ionic-lite-sdk
26
26
  ```
27
27
 
28
- Add dependencies to the root of the app (index.html)
28
+ Add dependencies to the root of the app (index.html) only if you are going to use Openpay as the payment processor.
29
29
  ```html
30
30
  <script src=https://openpay.s3.amazonaws.com/openpay.v1.min.js></script>
31
31
  <script src=https://openpay.s3.amazonaws.com/openpay-data.v1.min.js></script>
@@ -297,9 +297,38 @@ if (
297
297
  - `getCustomerPaymentMethods()`: Get available payment methods
298
298
  - `payment(data)`: Process a payment
299
299
  - `verify3dsTransaction()`: Verify a 3DS transaction
300
+ - `mountCardFields({ fields, card_id })`: Mounts card input fields (e.g., CVV) for a saved card. Useful for requesting CVV when listing saved cards.
300
301
 
301
- > **Important Note about SaveCard functionality**:
302
- > To properly implement the SaveCard feature, you must use a SecureToken. For detailed implementation instructions and best practices, please refer to our official documentation on [How to use SecureToken for secure card saving](https://docs.tonder.io/integration/sdks/secure-token#how-to-use-securetoken-for-secure-card-saving).
302
+ #### mountCardFields
303
+
304
+ Mounts card input fields (currently CVV) for a saved card. When a `card_id` is provided, the CVV input will be associated with that specific card, allowing you to update its CVV. This is useful for workflows where you need to request CVV for saved cards before payment.
305
+
306
+ **Parameters:**
307
+
308
+ | Name | Type | Required | Description |
309
+ |---------|----------|----------|---------------------------------------------------------------------|
310
+ | fields | string[] | Yes | Array of fields to mount (currently supports `["cvv"]`). |
311
+ | card_id | string | No | Card ID of the saved card. Associates the CVV input with this card. |
312
+
313
+ **Important Notes:**
314
+ 1. **Single Card Selection Only:** The CVV input for a saved card must only be displayed when a specific card is selected.
315
+ 2. **One CVV Input at a Time:** You cannot display multiple CVV inputs for different cards simultaneously. Only one CVV update operation should be active at any given time.
316
+ 3. **Mutually Exclusive with Card Form:** The CVV input for a saved card cannot be shown at the same time as the full card enrollment form. These are two separate workflows:
317
+ - **Save New Card:** Use the complete card form without `card_id`.
318
+ - **Update CVV for Saved Card:** Use CVV input with `card_id` only.
319
+
320
+ **Example:**
321
+ ```tsx
322
+ // Update CVV for a saved card
323
+
324
+ // 1. Place the div in your component where the CVV field will be mounted
325
+ <div id={`collect_cvv_saved-card-id`}></div>
326
+
327
+ // 2. Call mountCardFields and pass the card_id of the selected card
328
+ liteCheckout.mountCardFields({ fields: ["cvv"], card_id: "saved-card-id" });
329
+
330
+
331
+ ```
303
332
 
304
333
 
305
334
  ## Examples
@@ -493,6 +522,176 @@ export class TonderCheckoutComponent implements OnInit, OnDestroy {
493
522
  }
494
523
  ```
495
524
 
525
+ ### React: Request CVV for saved card
526
+
527
+ ```tsx
528
+ import { LiteCheckout } from '@tonder.io/ionic-lite-sdk';
529
+ import { useEffect, useState } from 'react';
530
+
531
+ const checkoutData = {
532
+ customer: {
533
+ firstName: "Adrian",
534
+ lastName: "Martinez",
535
+ country: "Mexico",
536
+ address: "Pinos 507, Col El Tecuan",
537
+ city: "Durango",
538
+ state: "Durango",
539
+ postCode: "34105",
540
+ email: "test@example.com",
541
+ phone: "8161234567",
542
+ },
543
+ cart: {
544
+ total: 120,
545
+ items: [
546
+ {
547
+ description: "Test product description",
548
+ quantity: 1,
549
+ price_unit: 120,
550
+ discount: 25,
551
+ taxes: 12,
552
+ product_reference: 12,
553
+ name: "Test product",
554
+ amount_total: 120
555
+ }
556
+ ]
557
+ },
558
+ currency: "MXN",
559
+ // Reference from the merchant
560
+ order_reference: "ORD-123456",
561
+ metadata: {
562
+ business_user: "123456-test"
563
+ },
564
+ };
565
+
566
+ const ExploreContainer = () => {
567
+ const [liteCheckout, setLiteCheckout] = useState<any>(null);
568
+ const [cards, setCards] = useState<any[]>([]);
569
+ const [selectedCardId, setSelectedCardId] = useState<string | null>(null);
570
+ const [loading, setLoading] = useState<boolean>(false);
571
+
572
+ useEffect(() => {
573
+ if (!liteCheckout) {
574
+ setLoading(true);
575
+ initializeTonderSDK();
576
+ }
577
+ }, []);
578
+
579
+ useEffect(() => {
580
+ if (liteCheckout) {
581
+ fetchCards();
582
+ }
583
+ }, [liteCheckout]);
584
+
585
+ const initializeTonderSDK = async () => {
586
+ const sdk = new LiteCheckout({
587
+ mode: "stage",
588
+ apiKey: "YOUR_API_KEY",
589
+ returnUrl: window.location.href,
590
+ customization: { redirectOnComplete: false },
591
+ events: {
592
+ cvvEvents: {
593
+ onChange: (data) => {
594
+ console.log("CVV onChange event data:", data);
595
+ }
596
+ }
597
+ }
598
+ });
599
+ setLiteCheckout(sdk);
600
+
601
+ // Get secure token from your backend
602
+ const token = "123"
603
+
604
+ sdk.configureCheckout({ ...checkoutData, secureToken: token });
605
+ await sdk.injectCheckout();
606
+ sdk.verify3dsTransaction().then((response: any) => {
607
+ console.log('Verify 3ds response', response);
608
+ });
609
+ setLoading(false);
610
+ };
611
+
612
+ const fetchCards = async () => {
613
+ const response = await liteCheckout.getCustomerCards();
614
+ setCards(response.cards || []);
615
+ };
616
+
617
+ const handleSelectCard = (cardId: string) => {
618
+ if (cardId === selectedCardId) return;
619
+ setSelectedCardId(cardId);
620
+ liteCheckout.mountCardFields({ fields: ["cvv"], card_id: cardId });
621
+ };
622
+
623
+ const handlePayment = async () => {
624
+ if (!selectedCardId) return;
625
+ try {
626
+ const response = await liteCheckout.payment({ ...checkoutData, card: selectedCardId });
627
+ } catch (err) {
628
+ console.error("Payment error:", err);
629
+ }
630
+ };
631
+
632
+ return (
633
+ <div className="container">
634
+ <iframe className="tds-iframe" allowTransparency={true} id="tdsIframe"></iframe>
635
+ {loading ? (
636
+ <div style={{ textAlign: 'center', padding: '40px 0', color: '#007AFF' }}>
637
+ <div style={{ fontWeight: 600, fontSize: 18 }}>Loading checkout...</div>
638
+ </div>
639
+ ) : (
640
+ <>
641
+ <p>Saved cards:</p>
642
+ <div style={{ marginBottom: 24 }}>
643
+ {cards.length > 0 ? (
644
+ cards.map((card: any) => (
645
+ <div
646
+ key={card.fields.skyflow_id}
647
+ style={{
648
+ background: selectedCardId === card.fields.skyflow_id ? '#E3F2FD' : '#f9f9f9',
649
+ borderRadius: 12,
650
+ border: selectedCardId === card.fields.skyflow_id ? '2px solid #007AFF' : '2px solid transparent',
651
+ marginBottom: 12,
652
+ padding: 0,
653
+ cursor: 'pointer',
654
+ textAlign: 'left',
655
+ }}
656
+ onClick={() => handleSelectCard(card.fields.skyflow_id)}
657
+ >
658
+ <div style={{ display: 'flex', alignItems: 'center', padding: 16 }}>
659
+ {card.icon && (
660
+ <img src={card.icon} alt="card" style={{ width: 50, height: 32, marginRight: 16, objectFit: 'contain' }} />
661
+ )}
662
+ <div style={{ flex: 1, textAlign: 'left' }}>
663
+ <div style={{ fontWeight: 'bold', color: '#333', marginBottom: 4 }}>{card.fields.cardholder_name}</div>
664
+ <div style={{ color: '#666', marginBottom: 4 }}>•••• •••• •••• {card.fields.card_number.slice(-4)}</div>
665
+ <div style={{ color: '#999', fontSize: 12 }}>Expires: {card.fields.expiration_month}/{card.fields.expiration_year}</div>
666
+ </div>
667
+ {selectedCardId === card.fields.skyflow_id && (
668
+ <div
669
+ style={{ marginLeft: 12, width: 120, background: '#fff', borderRadius: 8, boxShadow: '0 2px 8px #eee', padding: 8, textAlign: 'left', display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}
670
+ onClick={e => e.stopPropagation()}
671
+ >
672
+ <div style={{ maxHeight: '90px' }} id={`collect_cvv_${card.fields.skyflow_id}`}></div>
673
+ </div>
674
+ )}
675
+ </div>
676
+ </div>
677
+ ))
678
+ ) : (
679
+ <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>
680
+ <div style={{ fontWeight: 600, fontSize: 16 }}>No saved cards</div>
681
+ <div style={{ fontSize: 14, color: '#bbb' }}>Add a card to use this method</div>
682
+ </div>
683
+ )}
684
+ </div>
685
+ <button style={{ padding: '10px', background: '#ddd' }} onClick={handlePayment}>
686
+ Pay with saved card
687
+ </button>
688
+ </>
689
+ )}
690
+ </div>
691
+ );
692
+ };
693
+ ```
694
+
496
695
  ## Request secure token
497
696
 
498
697
  ```typescript
@@ -580,14 +779,6 @@ The following functions have been deprecated and should no longer be used. Consi
580
779
  - Replace `apiKey`, `mode`, `returnUrl` with your actual values.
581
780
  - Remember to use the `configureCheckout` function after creating an instance of `LiteCheckout`. This ensures that functions such as payment processing, saving cards, deleting cards, and others work correctly.
582
781
 
583
- ### Script Dependencies
584
-
585
- For all implementations, ensure you include the necessary scripts:
586
-
587
- ```html
588
- <script src="https://openpay.s3.amazonaws.com/openpay.v1.min.js"></script>
589
- <script src="https://openpay.s3.amazonaws.com/openpay-data.v1.min.js"></script>
590
- ```
591
782
 
592
783
  ## License
593
784
 
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{get as e}from"lodash";import t from"skyflow-js";function n(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{d(o.next(e))}catch(e){i(e)}}function a(e){try{d(o.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}function o(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function r(e,t,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(e,n):r?r.value=n:t.set(e,n),n}function i(e,t,o){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:o});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor({code:e,body:t,name:n,message:o,stack:r}){this.code=e,this.body=t,this.name=n,this.message=o,this.stack=r}}const a=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),d=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},l=e=>new s({code:(null==e?void 0:e.status)?e.status:e.code,body:null==e?void 0:e.body,name:e?"string"==typeof e?"catch":e.name:"Error",message:e?"string"==typeof e?e:e.message:"Error",stack:"string"==typeof e?void 0:e.stack}),c=(e,t=void 0)=>n(void 0,void 0,void 0,(function*(){let n,o,r="Error";e&&"json"in e&&(n=yield null==e?void 0:e.json()),e&&"status"in e&&(o=e.status.toString()),!n&&e&&"text"in e&&(r=yield e.text()),(null==n?void 0:n.detail)&&(r=n.detail);return new s({code:o,body:n,name:o,message:r,stack:t})}));function u(e,t){var n,o;let r=200;try{r=Number((null==t?void 0:t.code)||200)}catch(e){}const i={status:"error",code:r,message:"",detail:(null===(n=null==t?void 0:t.body)||void 0===n?void 0:n.detail)||(null===(o=null==t?void 0:t.body)||void 0===o?void 0:o.error)||t.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),e)}class h{constructor({payload:e=null,apiKey:t,baseUrl:n,redirectOnComplete:o,tdsIframeId:r,tonderPayButtonId:i,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=n,this.apiKey=t,this.payload=e,this.tdsIframeId=r,this.tonderPayButtonId=i,this.redirectOnComplete=o,this.callBack=s}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,n,o,r,i;const s=null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(i=null===(r=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,n;if(null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((e,t)=>{var n,o,r;const i=null===(r=null===(o=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(o);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,n;return null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const e=this.getRedirectUrl();if(e)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const t=document.querySelector(`#${this.tdsIframeId}`);if(t){t.setAttribute("src",e),t.setAttribute("style","display: block");const o=this,r=e=>n(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}t&&t.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),t.removeEventListener("load",r)},i=t=>n(this,void 0,void 0,(function*(){const r=yield new Promise(((e,n)=>e(t)));if(r){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(r))return e();{const e=setTimeout((()=>n(this,void 0,void 0,(function*(){clearTimeout(e),yield i(o.requestTransactionStatus())}))),7e3)}}}));yield i(o.requestTransactionStatus())}));t.addEventListener("load",r)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return n(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration(),t=e.startsWith("https://")?e:`${this.baseUrl}${e}`,n=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==n.status)return console.error("La verificación de la transacción falló."),null;return yield n.json()}))}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[n,o]of t)e[n]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return n(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=e.creq,n.value=e.creq,t.appendChild(n);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return n(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return n(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=e.startsWith("https://")?e:`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const p=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function m(e,t,o){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/checkout-router/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(Object.assign(Object.assign({},r),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.status>=200&&i.status<=299)return yield i.json();{const e=yield i.json(),t=new Error("Failed to start checkout router");throw t.details=e,t}}catch(e){throw e}}))}function y(e,t,o=!0,r=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(e),n.setApiKey(t),n.setSandboxMode(o),yield n.deviceData.setup({signal:r})}))}const v=Object.freeze({saveCardError:"Ha ocurrido un error guardando la tarjeta. Inténtalo nuevamente.",removeCardError:"Ha ocurrido un error eliminado la tarjeta. Inténtalo nuevamente.",getCardsError:"Ha ocurrido un error obteniendo las tarjetas del customer. Inténtalo nuevamente.",cardExist:"La tarjeta fue registrada previamente.",removedCard:"Card deleted successfully",errorCheckout:"No se ha podido procesar el pago",cardSaved:"Tarjeta registrada con éxito.",getPaymentMethodsError:"Ha ocurrido un error obteniendo las métodos de pago del customer. Inténtalo nuevamente.",getBusinessError:"Ha ocurrido un error obteniendo los datos del comercio. Inténtalo nuevamente.",secureTokenError:"Ha ocurrido un error obteniendo el token de seguridad."});var f,g,_,A,b,E,T,O,C,S,I,R,j;class N{constructor({mode:e="stage",customization:t,apiKey:n,apiKeyTonder:o,returnUrl:r,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d}){f.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",g.set(this,void 0),_.set(this,void 0),this.apiKeyTonder=o||n||"",this.returnUrl=r,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||p[this.mode]||p.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new h({apiKey:n,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i}configureCheckout(e){"secureToken"in e&&o(this,f,"m",E).call(this,e.secureToken),o(this,f,"m",A).call(this,e)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield o(this,f,"m",I).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((t,r)=>n(this,void 0,void 0,(function*(){try{o(this,f,"m",A).call(this,e);const n=yield this._checkout(e);this.process3ds.setPayload(n);if(yield this._handle3dsRedirect(n)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(n),t(n)}}catch(e){r(e)}}))))}getSecureToken(e){return n(this,void 0,void 0,(function*(){try{return yield function(e,t,o=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:o});if(n.ok)return yield n.json();throw yield c(n)}catch(e){throw l(e)}}))}(this.baseUrl,e)}catch(e){throw u({message:v.secureTokenError},e)}}))}_initializeCheckout(){return n(this,void 0,void 0,(function*(){const e=yield this._fetchMerchantData();e&&e.mercado_pago&&e.mercado_pago.active&&function(){try{const e=document.createElement("script");e.src="https://www.mercadopago.com/v2/security.js",e.setAttribute("view",""),e.onload=()=>{},e.onerror=e=>{console.error("Error loading Mercado Pago script:",e)},document.head.appendChild(e)}catch(e){console.error("Error attempting to inject Mercado Pago script:",e)}}()}))}_checkout(e){return n(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(e){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(e=null){return n(this,void 0,void 0,(function*(){return o(this,_,"f")||r(this,_,yield function(e,t,o,r=null){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},signal:r,body:JSON.stringify(i)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),o(this,_,"f")}))}_handleCheckout({card:t,payment_method:r,customer:i,isSandbox:s,returnUrl:d}){return n(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:c,business:u}=this.merchantData,h=Number(this.cartTotal);try{let p;!p&&l.merchant_id&&l.public_key&&!r&&(p=yield y(l.merchant_id,l.public_key,s,this.abortController.signal));const{id:v,auth_token:f}=i,_={business:this.apiKeyTonder,client:f,billing_address_id:null,shipping_address_id:null,amount:h,status:"A",reference:c,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata},A=yield function(e,t,o){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/orders/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(r)});if(201===i.status)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,_),b=(new Date).toISOString(),E={business_pk:u.pk,client_id:v,amount:h,date:b,order_id:A.id,customer_order_reference:this.order_reference?this.order_reference:c,items:this.cartItems,currency:this.currency,metadata:this.metadata},T=yield function(e,t,o){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/business/${o.business_pk}/payments/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(r)});if(i.status>=200&&i.status<=299)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,E),O=Object.assign(Object.assign(Object.assign({name:e(this.customer,"firstName",e(this.customer,"name","")),last_name:e(this.customer,"lastName",e(this.customer,"lastname","")),email_client:e(this.customer,"email",""),phone_number:e(this.customer,"phone",""),return_url:d||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:h,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:A.id,business_id:u.pk,payment_id:T.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:a(),currency:this.currency},r?{payment_method:r}:{card:t}),{apm_config:o(this,g,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),C=yield m(this.baseUrl,this.apiKeyTonder,O);return C||!1}catch(e){throw console.log(e),e}}))}_fetchMerchantData(){return n(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){return this.merchantData}}))}_getCustomerCards(e,t){return n(this,void 0,void 0,(function*(){return yield function(e,t,o,r,i=null){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},signal:i});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield c(s)}catch(e){throw l(e)}}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,o){return n(this,void 0,void 0,(function*(){return yield function(e,t,o,r,i){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield c(s)}catch(e){throw l(e)}}))}(this.baseUrl,e,this.secureToken,t,o)}))}_removeCustomerCard(e,t,o){return n(this,void 0,void 0,(function*(){return yield function(e,t,o,r="",i){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${i}/cards/${r}`,s=yield fetch(n,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t}});if(204===s.status)return v.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield c(s)}catch(e){throw l(e)}}))}(this.baseUrl,e,this.secureToken,o,t)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(e,t,o={status:"active",pagesize:"10000"},r=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(o).toString(),i=yield fetch(`${e}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();throw yield c(i)}catch(e){throw l(e)}}))}(this.baseUrl,this.apiKeyTonder)}))}_handle3dsRedirect(e){var t,o;return n(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(t=null==e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((e=>{console.log("Error loading iframe:",e)}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function k(e,t,o=null){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${t}`},signal:o});if(n.ok){return(yield n.json()).token}throw new Error("Failed to retrieve bearer token")}))}g=new WeakMap,_=new WeakMap,f=new WeakSet,A=function(e){var t,n;!e||e&&0===Object.keys(e).length||(o(this,f,"m",b).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),o(this,f,"m",T).call(this,(null===(n=e.cart)||void 0===n?void 0:n.items)||[]),o(this,f,"m",O).call(this,e),o(this,f,"m",C).call(this,e),o(this,f,"m",S).call(this,e),o(this,f,"m",R).call(this,e))},b=function(e){e&&(this.customer=e)},E=function(e){this.secureToken=e},T=function(e){this.cartItems=e},O=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},C=function(e){this.currency=null==e?void 0:e.currency},S=function(e){this.card=null==e?void 0:e.card},I=function(e){var t,o,r;return n(this,void 0,void 0,(function*(){if("Hard"===(null===(t=null==e?void 0:e.decline)||void 0===t?void 0:t.error_type)||(null===(o=null==e?void 0:e.checkout)||void 0===o?void 0:o.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(r=e.checkout)||void 0===r?void 0:r.id)||(null==e?void 0:e.checkout_id)};try{return yield m(this.baseUrl,this.apiKeyTonder,t)}catch(e){}return e}}))},R=function(e){r(this,g,null==e?void 0:e.apm_config,"f")},function(e){e.CARD_NUMBER="card_number",e.CVV="cvv",e.EXPIRATION_MONTH="expiration_month",e.EXPIRATION_YEAR="expiration_year",e.CARDHOLDER_NAME="cardholder_name"}(j||(j={}));const M={type:t.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},w=RegExp("^(?!s*$).+"),U={type:t.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:w,error:"El campo es requerido"}},P="Titular de la tarjeta",D="Número de tarjeta",L="CVC/CVV",x="Mes",B="Año",$="Fecha de expiración",K="Nombre como aparece en la tarjeta",F="1234 1234 1234 1234",V="3-4 dígitos",z="MM",X="AA",Y={base:{border:"1px solid #e0e0e0",padding:"10px 7px",borderRadius:"5px",color:"#1d1d1d",marginTop:"2px",backgroundColor:"white",fontFamily:'"Inter", sans-serif',fontSize:"16px","&::placeholder":{color:"#ccc"}},complete:{color:"#4caf50"},invalid:{border:"1px solid #f44336"},empty:{},focus:{},global:{"@import":'url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap")'}},J={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},W={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function H({baseUrl:e,apiKey:o,vault_id:r,vault_url:i,data:s}){return n(this,void 0,void 0,(function*(){const a=t.init({vaultID:r,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield k(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}}).container(t.ContainerType.COLLECT),d=yield function(e,o){return n(this,void 0,void 0,(function*(){const r=yield function(e,o){return n(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(e).map((e=>n(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:e,type:t.ElementType.INPUT_FIELD}),key:e}})))))}))}(e,o);return r?r.map((t=>new Promise((n=>{var o;const r=document.createElement("div");r.hidden=!0,r.id=`id-${t.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(r),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const o=e[t.key];return t.element.setValue(o),n(t.element.isMounted())}}),120)}),120)})))):[]}))}(s,a);if((yield Promise.all(d)).some((e=>!e)))throw l(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield a.collect();if(e)return e.records[0].fields;throw l(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw l(e)}}))}function G(e){const{element:n,fieldMessage:o="",errorStyles:r={},requiredMessage:i="Campo requerido",invalidMessage:s="Campo no válido",events:a}=e;"on"in n&&(n.on(t.EventName.CHANGE,(e=>{Z({eventName:"onChange",data:e,events:a}),q({element:n,errorStyles:r,color:"transparent"})})),n.on(t.EventName.BLUR,(e=>{if(Z({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?i:""!=o?`El campo ${o} es inválido`:s;n.setError(t)}q({element:n,errorStyles:r})})),n.on(t.EventName.FOCUS,(e=>{Z({eventName:"onFocus",data:e,events:a}),q({element:n,errorStyles:r,color:"transparent"}),n.resetError()})))}function q(e){const{element:t,errorStyles:n={},color:o=""}=e;Object.keys(n).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},n),{base:Object.assign(Object.assign({},n.base&&Object.assign({},n.base)),""!=o&&{color:o})})})}const Z=t=>{const{eventName:n,data:o,events:r}=t;if(r&&n in r){const t=r[n];"function"==typeof t&&t({elementType:e(o,"elementType",""),isEmpty:e(o,"isEmpty",""),isFocused:e(o,"isFocused",""),isValid:e(o,"isValid","")})}},Q=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",OXXOPAY:"OXXOPAY",SPEI:"SPEI",CODI:"CODI",MERCADOPAGO:"MERCADOPAGO",PAYPAL:"PAYPAL",COMERCIALMEXICANA:"COMERCIALMEXICANA",BANCOMER:"BANCOMER",WALMART:"WALMART",BODEGA:"BODEGA",SAMSCLUB:"SAMSCLUB",SUPERAMA:"SUPERAMA",CALIMAX:"CALIMAX",EXTRA:"EXTRA",CIRCULOK:"CIRCULOK",SEVEN11:"7ELEVEN",TELECOMM:"TELECOMM",BANORTE:"BANORTE",BENAVIDES:"BENAVIDES",DELAHORRO:"DELAHORRO",ELASTURIANO:"ELASTURIANO",WALDOS:"WALDOS",ALSUPER:"ALSUPER",KIOSKO:"KIOSKO",STAMARIA:"STAMARIA",LAMASBARATA:"LAMASBARATA",FARMROMA:"FARMROMA",FARMUNION:"FARMUNION",FARMATODO:"FARMATODO",SFDEASIS:"SFDEASIS",FARM911:"FARM911",FARMECONOMICAS:"FARMECONOMICAS",FARMMEDICITY:"FARMMEDICITY",RIANXEIRA:"RIANXEIRA",WESTERNUNION:"WESTERNUNION",ZONAPAGO:"ZONAPAGO",CAJALOSANDES:"CAJALOSANDES",CAJAPAITA:"CAJAPAITA",CAJASANTA:"CAJASANTA",CAJASULLANA:"CAJASULLANA",CAJATRUJILLO:"CAJATRUJILLO",EDPYME:"EDPYME",KASNET:"KASNET",NORANDINO:"NORANDINO",QAPAQ:"QAPAQ",RAIZ:"RAIZ",PAYSER:"PAYSER",WUNION:"WUNION",BANCOCONTINENTAL:"BANCOCONTINENTAL",GMONEY:"GMONEY",GOPAY:"GOPAY",WU:"WU",PUNTOSHEY:"PUNTOSHEY",AMPM:"AMPM",JUMBOMARKET:"JUMBOMARKET",SMELPUEBLO:"SMELPUEBLO",BAM:"BAM",REFACIL:"REFACIL",ACYVALORES:"ACYVALORES"}),ee={[Q.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[Q.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[Q.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[Q.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[Q.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[Q.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[Q.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[Q.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[Q.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[Q.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[Q.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[Q.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[Q.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[Q.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[Q.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[Q.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[Q.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[Q.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[Q.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[Q.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[Q.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[Q.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[Q.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[Q.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[Q.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[Q.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[Q.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[Q.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[Q.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[Q.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[Q.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[Q.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},te=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return ee[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class ne extends N{constructor({apiKey:e,mode:t,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe"}),this.activeAPMs=[],this.collectContainer=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return n(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),t=yield this._getCustomerCards(e,this.merchantData.business.pk);return Object.assign(Object.assign({},t),{cards:t.cards.map((e=>{return Object.assign(Object.assign({},e),{icon:(t=e.fields.card_scheme,"Visa"===t?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===t?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===t?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var t}))})}catch(e){throw u({message:v.getCardsError},e)}}))}saveCustomerCard(e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{vault_id:n,vault_url:o,business:r}=this.merchantData,i=yield H({vault_id:n,vault_url:o,data:Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,""),expiration_month:e.expiration_month.replace(/\s+/g,""),expiration_year:e.expiration_year.replace(/\s+/g,""),cvv:e.cvv.replace(/\s+/g,""),cardholder_name:e.cardholder_name.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._saveCustomerCard(t,null==r?void 0:r.pk,i)}catch(e){throw u({message:v.saveCardError},e)}}))}removeCustomerCard(e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:n}=this.merchantData;return yield this._removeCustomerCard(t,null==n?void 0:n.pk,e)}catch(e){throw u({message:v.removeCardError},e)}}))}getCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){try{const e=yield this._fetchCustomerPaymentMethods();return(e&&"results"in e&&e.results.length>0?e.results:[]).filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},te(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw u({message:v.getPaymentMethodsError},e)}}))}mountCardFields(e){return n(this,void 0,void 0,(function*(){yield this.createSkyflowInstance(),this.collectContainer=yield function(e){var o,r,i,s,a,d,l,c,u,h,p,m,y,v,f,g,_;return n(this,void 0,void 0,(function*(){const{skyflowInstance:n,data:A,customization:b,events:E}=e,T=n.container(t.ContainerType.COLLECT),O=[],C={[j.CVV]:t.ElementType.CVV,[j.CARD_NUMBER]:t.ElementType.CARD_NUMBER,[j.EXPIRATION_MONTH]:t.ElementType.EXPIRATION_MONTH,[j.EXPIRATION_YEAR]:t.ElementType.EXPIRATION_YEAR,[j.CARDHOLDER_NAME]:t.ElementType.CARDHOLDER_NAME},S={[j.CVV]:[U],[j.CARD_NUMBER]:[U],[j.EXPIRATION_MONTH]:[U],[j.EXPIRATION_YEAR]:[U],[j.CARDHOLDER_NAME]:[M,U]},I={errorStyles:(null===(r=null===(o=null==b?void 0:b.styles)||void 0===o?void 0:o.cardForm)||void 0===r?void 0:r.errorStyles)||W,inputStyles:(null===(s=null===(i=null==b?void 0:b.styles)||void 0===i?void 0:i.cardForm)||void 0===s?void 0:s.inputStyles)||Y,labelStyles:(null===(d=null===(a=null==b?void 0:b.styles)||void 0===a?void 0:a.cardForm)||void 0===d?void 0:d.labelStyles)||J},R={name:(null===(l=null==b?void 0:b.labels)||void 0===l?void 0:l.name)||P,card_number:(null===(c=null==b?void 0:b.labels)||void 0===c?void 0:c.card_number)||D,cvv:(null===(u=null==b?void 0:b.labels)||void 0===u?void 0:u.cvv)||L,expiration_date:(null===(h=null==b?void 0:b.labels)||void 0===h?void 0:h.expiry_date)||$,expiration_month:(null===(p=null==b?void 0:b.labels)||void 0===p?void 0:p.expiration_month)||x,expiration_year:(null===(m=null==b?void 0:b.labels)||void 0===m?void 0:m.expiration_year)||B},N={name:(null===(y=null==b?void 0:b.placeholders)||void 0===y?void 0:y.name)||K,card_number:(null===(v=null==b?void 0:b.placeholders)||void 0===v?void 0:v.card_number)||F,cvv:(null===(f=null==b?void 0:b.placeholders)||void 0===f?void 0:f.cvv)||V,expiration_month:(null===(g=null==b?void 0:b.placeholders)||void 0===g?void 0:g.expiration_month)||z,expiration_year:(null===(_=null==b?void 0:b.placeholders)||void 0===_?void 0:_.expiration_year)||X},k={[j.CVV]:null==E?void 0:E.cvvEvents,[j.CARD_NUMBER]:null==E?void 0:E.cardNumberEvents,[j.EXPIRATION_MONTH]:null==E?void 0:E.monthEvents,[j.EXPIRATION_YEAR]:null==E?void 0:E.yearEvents,[j.CARDHOLDER_NAME]:null==E?void 0:E.cardHolderEvents};if("fields"in A&&Array.isArray(A.fields))if(A.fields.length>0&&"string"==typeof A.fields[0])for(const e of A.fields){const t=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:e,type:C[e],validations:S[e]},I),{label:R[e],placeholder:N[e]}),A.card_id?{skyflowID:A.card_id}:{}));G({element:t,errorStyles:I.errorStyles,fieldMessage:[j.CVV,j.EXPIRATION_MONTH,j.EXPIRATION_YEAR].includes(e)?"":R[e],events:k[e]});const n=`#collect_${String(e)}`+(A.card_id?`_${A.card_id}`:"");t.mount(n),O.push({element:t,containerId:n})}else for(const e of A.fields){const t=e.field,n=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:C[t],validations:S[t]},I),{label:R[t],placeholder:N[t]}),A.card_id?{skyflowID:A.card_id}:{})),o=e.container_id||`#collect_${String(t)}`+(A.card_id?`_${A.card_id}`:"");n.mount(o),O.push({element:n,containerId:o})}return{elements:O.map((e=>e.element)),container:T}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events})}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw u({message:v.getBusinessError},e)}}))}createSkyflowInstance(){return n(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:e,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({baseUrl:e,apiKey:o,vault_id:r,vault_url:i}){return n(this,void 0,void 0,(function*(){return t.init({vaultID:r,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield k(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}})}))}({vault_id:e,vault_url:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}getOpenpayDeviceSessionID(e,t,o){return n(this,void 0,void 0,(function*(){try{return yield y(e,t,o)}catch(e){throw l(e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:o}){return n(this,void 0,void 0,(function*(){return yield H({vault_id:e,vault_url:t,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:t,isSandbox:o,returnUrl:r}){var i;return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const n=yield this._getCustomer(this.abortController.signal),{vault_id:s,vault_url:a}=this.merchantData;let d;if(!t||""===t||null===t)if("string"==typeof e){const t=null===(i=this.collectContainer)||void 0===i?void 0:i.container;yield t.collect(),d={skyflow_id:e}}else d=yield H({vault_id:s,vault_url:a,data:Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._handleCheckout({card:d,payment_method:t,customer:n,isSandbox:o,returnUrl:r})}))}customerRegister(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,n={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(e){throw l(e)}}))}createOrder(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(e){throw l(e)}}))}createPayment(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(e){throw l(e)}}))}startCheckoutRouter(e){return n(this,void 0,void 0,(function*(){const t=yield m(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return n(this,void 0,void 0,(function*(){try{const{order:t,total:n,customer:o,skyflowTokens:r,return_url:i,isSandbox:d,metadata:l,currency:c,payment_method:u}=e,h=yield this._fetchMerchantData(),p=yield this.customerRegister(o.email);if(!(p&&"auth_token"in p&&h&&"reference"in h))throw new s({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const e={business:this.apiKeyTonder,client:p.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:t.items},v=yield this.createOrder(e),f=(new Date).toISOString();if(!("id"in v&&"id"in p&&"business"in h))throw new s({code:"500",body:v,name:"Keys error",message:"Order response errors"});{const e={business_pk:h.business.pk,amount:n,date:f,order_id:v.id,client_id:p.id},t=yield this.createPayment(e);let s;const{openpay_keys:g,business:_}=h;g.merchant_id&&g.public_key&&(s=yield y(g.merchant_id,g.public_key,d));const A=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:i,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:n,title_ship:"shipping",description:"transaction",device_session_id:s||null,token_id:"",order_id:"id"in v&&v.id,business_id:_.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:l,browser_info:a(),currency:c},u?{payment_method:u}:{card:r}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),b=yield m(this.baseUrl,this.apiKeyTonder,A);if(yield this.init3DSRedirect(b))return b}}}catch(e){throw l(e)}}))}registerCustomerCard(e,t,o){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${d(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":t,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(n.ok)return yield n.json();throw yield c(n)}catch(e){throw l(e)}}))}deleteCustomerCard(e,t=""){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${d(this.merchantData)}/cards/${t}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(n.ok)return!0;throw yield c(n)}catch(e){throw l(e)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const e=yield function(e,t,o="?status=active&page_size=10000&country=México",r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield c(n)}catch(e){throw l(e)}}))}(this.baseUrl,this.apiKeyTonder),t=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=t.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},te(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function oe(e){return/^\d{12,19}$/.test(e)&&de(e)}function re(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function ie(e){return/^\d{3,4}$/.test(e)}function se(e){return/^(0[1-9]|1[0-2])$/.test(e)}function ae(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const de=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),n=t.shift();let o=t.reduce(((e,t,n)=>n%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return o+=n,o%10==0};export{N as BaseInlineCheckout,ne as LiteCheckout,ie as validateCVV,oe as validateCardNumber,re as validateCardholderName,se as validateExpirationMonth,ae as validateExpirationYear};
1
+ import{get as e}from"lodash";import t from"skyflow-js";function n(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{d(o.next(e))}catch(e){i(e)}}function a(e){try{d(o.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}function o(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function r(e,t,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(e,n):r?r.value=n:t.set(e,n),n}function i(e,t,o){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:o});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor({code:e,body:t,name:n,message:o,stack:r}){this.code=e,this.body=t,this.name=n,this.message=o,this.stack=r}}const a=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),d=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},l=e=>new s({code:(null==e?void 0:e.status)?e.status:e.code,body:null==e?void 0:e.body,name:e?"string"==typeof e?"catch":e.name:"Error",message:e?"string"==typeof e?e:e.message:"Error",stack:"string"==typeof e?void 0:e.stack}),c=(e,t=void 0)=>n(void 0,void 0,void 0,(function*(){let n,o,r="Error";e&&"json"in e&&(n=yield null==e?void 0:e.json()),e&&"status"in e&&(o=e.status.toString()),!n&&e&&"text"in e&&(r=yield e.text()),(null==n?void 0:n.detail)&&(r=n.detail);return new s({code:o,body:n,name:o,message:r,stack:t})}));function u(e,t){var n,o;let r=200;try{r=Number((null==t?void 0:t.code)||200)}catch(e){}const i={status:"error",code:r,message:"",detail:(null===(n=null==t?void 0:t.body)||void 0===n?void 0:n.detail)||(null===(o=null==t?void 0:t.body)||void 0===o?void 0:o.error)||t.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),e)}class h{constructor({payload:e=null,apiKey:t,baseUrl:n,redirectOnComplete:o,tdsIframeId:r,tonderPayButtonId:i,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=n,this.apiKey=t,this.payload=e,this.tdsIframeId=r,this.tonderPayButtonId=i,this.redirectOnComplete=o,this.callBack=s}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,n,o,r,i;const s=null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(i=null===(r=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,n;if(null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((e,t)=>{var n,o,r;const i=null===(r=null===(o=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(o);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,n;return null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const e=this.getRedirectUrl();if(e)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const t=document.querySelector(`#${this.tdsIframeId}`);if(t){t.setAttribute("src",e),t.setAttribute("style","display: block");const o=this,r=e=>n(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}t&&t.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),t.removeEventListener("load",r)},i=t=>n(this,void 0,void 0,(function*(){const r=yield new Promise(((e,n)=>e(t)));if(r){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(r))return e();{const e=setTimeout((()=>n(this,void 0,void 0,(function*(){clearTimeout(e),yield i(o.requestTransactionStatus())}))),7e3)}}}));yield i(o.requestTransactionStatus())}));t.addEventListener("load",r)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return n(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration(),t=e.startsWith("https://")?e:`${this.baseUrl}${e}`,n=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==n.status)return console.error("La verificación de la transacción falló."),null;return yield n.json()}))}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[n,o]of t)e[n]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return n(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=e.creq,n.value=e.creq,t.appendChild(n);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return n(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return n(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=e.startsWith("https://")?e:`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const p=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function m(e,t,o){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/checkout-router/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(Object.assign(Object.assign({},r),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.status>=200&&i.status<=299)return yield i.json();{const e=yield i.json(),t=new Error("Failed to start checkout router");throw t.details=e,t}}catch(e){throw e}}))}function y(e,t,o=!0,r=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(e),n.setApiKey(t),n.setSandboxMode(o),yield n.deviceData.setup({signal:r})}))}const v=Object.freeze({saveCardError:"Ha ocurrido un error guardando la tarjeta. Inténtalo nuevamente.",removeCardError:"Ha ocurrido un error eliminado la tarjeta. Inténtalo nuevamente.",getCardsError:"Ha ocurrido un error obteniendo las tarjetas del customer. Inténtalo nuevamente.",cardExist:"La tarjeta fue registrada previamente.",removedCard:"Card deleted successfully",errorCheckout:"No se ha podido procesar el pago",cardSaved:"Tarjeta registrada con éxito.",getPaymentMethodsError:"Ha ocurrido un error obteniendo las métodos de pago del customer. Inténtalo nuevamente.",getBusinessError:"Ha ocurrido un error obteniendo los datos del comercio. Inténtalo nuevamente.",secureTokenError:"Ha ocurrido un error obteniendo el token de seguridad."});var f,g,_,A,b,E,T,O,C,S,I,R,j;class N{constructor({mode:e="stage",customization:t,apiKey:n,apiKeyTonder:o,returnUrl:r,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d}){f.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",g.set(this,void 0),_.set(this,void 0),this.apiKeyTonder=o||n||"",this.returnUrl=r,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||p[this.mode]||p.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new h({apiKey:n,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i}configureCheckout(e){"secureToken"in e&&o(this,f,"m",E).call(this,e.secureToken),o(this,f,"m",A).call(this,e)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield o(this,f,"m",I).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((t,r)=>n(this,void 0,void 0,(function*(){try{o(this,f,"m",A).call(this,e);const n=yield this._checkout(e);this.process3ds.setPayload(n);if(yield this._handle3dsRedirect(n)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(n),t(n)}}catch(e){r(e)}}))))}getSecureToken(e){return n(this,void 0,void 0,(function*(){try{return yield function(e,t,o=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:o});if(n.ok)return yield n.json();throw yield c(n)}catch(e){throw l(e)}}))}(this.baseUrl,e)}catch(e){throw u({message:v.secureTokenError},e)}}))}_initializeCheckout(){return n(this,void 0,void 0,(function*(){const e=yield this._fetchMerchantData();e&&e.mercado_pago&&e.mercado_pago.active&&function(){try{const e=document.createElement("script");e.src="https://www.mercadopago.com/v2/security.js",e.setAttribute("view",""),e.onload=()=>{},e.onerror=e=>{console.error("Error loading Mercado Pago script:",e)},document.head.appendChild(e)}catch(e){console.error("Error attempting to inject Mercado Pago script:",e)}}()}))}_checkout(e){return n(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(e){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(e=null){return n(this,void 0,void 0,(function*(){return o(this,_,"f")||r(this,_,yield function(e,t,o,r=null){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},signal:r,body:JSON.stringify(i)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),o(this,_,"f")}))}_handleCheckout({card:t,payment_method:r,customer:i,isSandbox:s,returnUrl:d}){return n(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:c,business:u}=this.merchantData,h=Number(this.cartTotal);try{let p;!p&&l.merchant_id&&l.public_key&&!r&&(p=yield y(l.merchant_id,l.public_key,s,this.abortController.signal));const{id:v,auth_token:f}=i,_={business:this.apiKeyTonder,client:f,billing_address_id:null,shipping_address_id:null,amount:h,status:"A",reference:c,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata},A=yield function(e,t,o){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/orders/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(r)});if(201===i.status)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,_),b=(new Date).toISOString(),E={business_pk:u.pk,client_id:v,amount:h,date:b,order_id:A.id,customer_order_reference:this.order_reference?this.order_reference:c,items:this.cartItems,currency:this.currency,metadata:this.metadata},T=yield function(e,t,o){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/business/${o.business_pk}/payments/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(r)});if(i.status>=200&&i.status<=299)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,E),O=Object.assign(Object.assign(Object.assign({name:e(this.customer,"firstName",e(this.customer,"name","")),last_name:e(this.customer,"lastName",e(this.customer,"lastname","")),email_client:e(this.customer,"email",""),phone_number:e(this.customer,"phone",""),return_url:d||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:h,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:A.id,business_id:u.pk,payment_id:T.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:a(),currency:this.currency},r?{payment_method:r}:{card:t}),{apm_config:o(this,g,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),C=yield m(this.baseUrl,this.apiKeyTonder,O);return C||!1}catch(e){throw console.log(e),e}}))}_fetchMerchantData(){return n(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){return this.merchantData}}))}_getCustomerCards(e,t){return n(this,void 0,void 0,(function*(){return yield function(e,t,o,r,i=null){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},signal:i});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield c(s)}catch(e){throw l(e)}}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,o){return n(this,void 0,void 0,(function*(){return yield function(e,t,o,r,i){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield c(s)}catch(e){throw l(e)}}))}(this.baseUrl,e,this.secureToken,t,o)}))}_removeCustomerCard(e,t,o){return n(this,void 0,void 0,(function*(){return yield function(e,t,o,r="",i){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${i}/cards/${r}`,s=yield fetch(n,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t}});if(204===s.status)return v.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield c(s)}catch(e){throw l(e)}}))}(this.baseUrl,e,this.secureToken,o,t)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(e,t,o={status:"active",pagesize:"10000"},r=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(o).toString(),i=yield fetch(`${e}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();throw yield c(i)}catch(e){throw l(e)}}))}(this.baseUrl,this.apiKeyTonder)}))}_handle3dsRedirect(e){var t,o;return n(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(t=null==e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((e=>{console.log("Error loading iframe:",e)}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function k(e,t,o=null){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${t}`},signal:o});if(n.ok){return(yield n.json()).token}throw new Error("Failed to retrieve bearer token")}))}g=new WeakMap,_=new WeakMap,f=new WeakSet,A=function(e){var t,n;!e||e&&0===Object.keys(e).length||(o(this,f,"m",b).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),o(this,f,"m",T).call(this,(null===(n=e.cart)||void 0===n?void 0:n.items)||[]),o(this,f,"m",O).call(this,e),o(this,f,"m",C).call(this,e),o(this,f,"m",S).call(this,e),o(this,f,"m",R).call(this,e))},b=function(e){e&&(this.customer=e)},E=function(e){this.secureToken=e},T=function(e){this.cartItems=e},O=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},C=function(e){this.currency=null==e?void 0:e.currency},S=function(e){this.card=null==e?void 0:e.card},I=function(e){var t,o,r;return n(this,void 0,void 0,(function*(){if("Hard"===(null===(t=null==e?void 0:e.decline)||void 0===t?void 0:t.error_type)||(null===(o=null==e?void 0:e.checkout)||void 0===o?void 0:o.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(r=e.checkout)||void 0===r?void 0:r.id)||(null==e?void 0:e.checkout_id)};try{return yield m(this.baseUrl,this.apiKeyTonder,t)}catch(e){}return e}}))},R=function(e){r(this,g,null==e?void 0:e.apm_config,"f")},function(e){e.CARD_NUMBER="card_number",e.CVV="cvv",e.EXPIRATION_MONTH="expiration_month",e.EXPIRATION_YEAR="expiration_year",e.CARDHOLDER_NAME="cardholder_name"}(j||(j={}));const M={type:t.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},w=RegExp("^(?!s*$).+"),U={type:t.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:w,error:"El campo es requerido"}},P="Titular de la tarjeta",D="Número de tarjeta",L="CVC/CVV",x="Mes",B="Año",$="Fecha de expiración",K="Nombre como aparece en la tarjeta",F="1234 1234 1234 1234",V="3-4 dígitos",z="MM",X="AA",Y={base:{border:"1px solid #e0e0e0",padding:"10px 7px",borderRadius:"5px",color:"#1d1d1d",marginTop:"2px",backgroundColor:"white",fontFamily:'"Inter", sans-serif',fontSize:"16px","&::placeholder":{color:"#ccc"}},complete:{color:"#4caf50"},invalid:{border:"1px solid #f44336"},empty:{},focus:{},global:{"@import":'url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap")'}},J={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},W={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function H({baseUrl:e,apiKey:o,vault_id:r,vault_url:i,data:s}){return n(this,void 0,void 0,(function*(){const a=t.init({vaultID:r,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield k(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}}).container(t.ContainerType.COLLECT),d=yield function(e,o){return n(this,void 0,void 0,(function*(){const r=yield function(e,o){return n(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(e).map((e=>n(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:e,type:t.ElementType.INPUT_FIELD}),key:e}})))))}))}(e,o);return r?r.map((t=>new Promise((n=>{var o;const r=document.createElement("div");r.hidden=!0,r.id=`id-${t.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(r),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const o=e[t.key];return t.element.setValue(o),n(t.element.isMounted())}}),120)}),120)})))):[]}))}(s,a);if((yield Promise.all(d)).some((e=>!e)))throw l(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield a.collect();if(e)return e.records[0].fields;throw l(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw l(e)}}))}function G(e){const{element:n,fieldMessage:o="",errorStyles:r={},requiredMessage:i="Campo requerido",invalidMessage:s="Campo no válido",events:a}=e;"on"in n&&(n.on(t.EventName.CHANGE,(e=>{Z({eventName:"onChange",data:e,events:a}),q({element:n,errorStyles:r,color:"transparent"})})),n.on(t.EventName.BLUR,(e=>{if(Z({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?i:""!=o?`El campo ${o} no es válido`:s;n.setError(t)}q({element:n,errorStyles:r})})),n.on(t.EventName.FOCUS,(e=>{Z({eventName:"onFocus",data:e,events:a}),q({element:n,errorStyles:r,color:"transparent"}),n.resetError()})))}function q(e){const{element:t,errorStyles:n={},color:o=""}=e;Object.keys(n).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},n),{base:Object.assign(Object.assign({},n.base&&Object.assign({},n.base)),""!=o&&{color:o})})})}const Z=t=>{const{eventName:n,data:o,events:r}=t;if(r&&n in r){const t=r[n];"function"==typeof t&&t({elementType:e(o,"elementType",""),isEmpty:e(o,"isEmpty",""),isFocused:e(o,"isFocused",""),isValid:e(o,"isValid","")})}},Q=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",OXXOPAY:"OXXOPAY",SPEI:"SPEI",CODI:"CODI",MERCADOPAGO:"MERCADOPAGO",PAYPAL:"PAYPAL",COMERCIALMEXICANA:"COMERCIALMEXICANA",BANCOMER:"BANCOMER",WALMART:"WALMART",BODEGA:"BODEGA",SAMSCLUB:"SAMSCLUB",SUPERAMA:"SUPERAMA",CALIMAX:"CALIMAX",EXTRA:"EXTRA",CIRCULOK:"CIRCULOK",SEVEN11:"7ELEVEN",TELECOMM:"TELECOMM",BANORTE:"BANORTE",BENAVIDES:"BENAVIDES",DELAHORRO:"DELAHORRO",ELASTURIANO:"ELASTURIANO",WALDOS:"WALDOS",ALSUPER:"ALSUPER",KIOSKO:"KIOSKO",STAMARIA:"STAMARIA",LAMASBARATA:"LAMASBARATA",FARMROMA:"FARMROMA",FARMUNION:"FARMUNION",FARMATODO:"FARMATODO",SFDEASIS:"SFDEASIS",FARM911:"FARM911",FARMECONOMICAS:"FARMECONOMICAS",FARMMEDICITY:"FARMMEDICITY",RIANXEIRA:"RIANXEIRA",WESTERNUNION:"WESTERNUNION",ZONAPAGO:"ZONAPAGO",CAJALOSANDES:"CAJALOSANDES",CAJAPAITA:"CAJAPAITA",CAJASANTA:"CAJASANTA",CAJASULLANA:"CAJASULLANA",CAJATRUJILLO:"CAJATRUJILLO",EDPYME:"EDPYME",KASNET:"KASNET",NORANDINO:"NORANDINO",QAPAQ:"QAPAQ",RAIZ:"RAIZ",PAYSER:"PAYSER",WUNION:"WUNION",BANCOCONTINENTAL:"BANCOCONTINENTAL",GMONEY:"GMONEY",GOPAY:"GOPAY",WU:"WU",PUNTOSHEY:"PUNTOSHEY",AMPM:"AMPM",JUMBOMARKET:"JUMBOMARKET",SMELPUEBLO:"SMELPUEBLO",BAM:"BAM",REFACIL:"REFACIL",ACYVALORES:"ACYVALORES"}),ee={[Q.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[Q.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[Q.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[Q.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[Q.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[Q.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[Q.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[Q.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[Q.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[Q.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[Q.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[Q.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[Q.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[Q.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[Q.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[Q.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[Q.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[Q.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[Q.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[Q.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[Q.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[Q.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[Q.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[Q.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[Q.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[Q.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[Q.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[Q.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[Q.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[Q.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[Q.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[Q.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Q.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},te=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return ee[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class ne extends N{constructor({apiKey:e,mode:t,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe"}),this.activeAPMs=[],this.collectContainer=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return n(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),t=yield this._getCustomerCards(e,this.merchantData.business.pk);return Object.assign(Object.assign({},t),{cards:t.cards.map((e=>{return Object.assign(Object.assign({},e),{icon:(t=e.fields.card_scheme,"Visa"===t?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===t?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===t?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var t}))})}catch(e){throw u({message:v.getCardsError},e)}}))}saveCustomerCard(e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{vault_id:n,vault_url:o,business:r}=this.merchantData,i=yield H({vault_id:n,vault_url:o,data:Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,""),expiration_month:e.expiration_month.replace(/\s+/g,""),expiration_year:e.expiration_year.replace(/\s+/g,""),cvv:e.cvv.replace(/\s+/g,""),cardholder_name:e.cardholder_name.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._saveCustomerCard(t,null==r?void 0:r.pk,i)}catch(e){throw u({message:v.saveCardError},e)}}))}removeCustomerCard(e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:n}=this.merchantData;return yield this._removeCustomerCard(t,null==n?void 0:n.pk,e)}catch(e){throw u({message:v.removeCardError},e)}}))}getCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){try{const e=yield this._fetchCustomerPaymentMethods();return(e&&"results"in e&&e.results.length>0?e.results:[]).filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},te(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw u({message:v.getPaymentMethodsError},e)}}))}mountCardFields(e){return n(this,void 0,void 0,(function*(){yield this.createSkyflowInstance(),this.collectContainer=yield function(e){var o,r,i,s,a,d,l,c,u,h,p,m,y,v,f,g,_;return n(this,void 0,void 0,(function*(){const{skyflowInstance:n,data:A,customization:b,events:E}=e,T=n.container(t.ContainerType.COLLECT),O=[],C={[j.CVV]:t.ElementType.CVV,[j.CARD_NUMBER]:t.ElementType.CARD_NUMBER,[j.EXPIRATION_MONTH]:t.ElementType.EXPIRATION_MONTH,[j.EXPIRATION_YEAR]:t.ElementType.EXPIRATION_YEAR,[j.CARDHOLDER_NAME]:t.ElementType.CARDHOLDER_NAME},S={[j.CVV]:[U],[j.CARD_NUMBER]:[U],[j.EXPIRATION_MONTH]:[U],[j.EXPIRATION_YEAR]:[U],[j.CARDHOLDER_NAME]:[M,U]},I={errorStyles:(null===(r=null===(o=null==b?void 0:b.styles)||void 0===o?void 0:o.cardForm)||void 0===r?void 0:r.errorStyles)||W,inputStyles:(null===(s=null===(i=null==b?void 0:b.styles)||void 0===i?void 0:i.cardForm)||void 0===s?void 0:s.inputStyles)||Y,labelStyles:(null===(d=null===(a=null==b?void 0:b.styles)||void 0===a?void 0:a.cardForm)||void 0===d?void 0:d.labelStyles)||J},R={name:(null===(l=null==b?void 0:b.labels)||void 0===l?void 0:l.name)||P,card_number:(null===(c=null==b?void 0:b.labels)||void 0===c?void 0:c.card_number)||D,cvv:(null===(u=null==b?void 0:b.labels)||void 0===u?void 0:u.cvv)||L,expiration_date:(null===(h=null==b?void 0:b.labels)||void 0===h?void 0:h.expiry_date)||$,expiration_month:(null===(p=null==b?void 0:b.labels)||void 0===p?void 0:p.expiration_month)||x,expiration_year:(null===(m=null==b?void 0:b.labels)||void 0===m?void 0:m.expiration_year)||B},N={name:(null===(y=null==b?void 0:b.placeholders)||void 0===y?void 0:y.name)||K,card_number:(null===(v=null==b?void 0:b.placeholders)||void 0===v?void 0:v.card_number)||F,cvv:(null===(f=null==b?void 0:b.placeholders)||void 0===f?void 0:f.cvv)||V,expiration_month:(null===(g=null==b?void 0:b.placeholders)||void 0===g?void 0:g.expiration_month)||z,expiration_year:(null===(_=null==b?void 0:b.placeholders)||void 0===_?void 0:_.expiration_year)||X},k={[j.CVV]:null==E?void 0:E.cvvEvents,[j.CARD_NUMBER]:null==E?void 0:E.cardNumberEvents,[j.EXPIRATION_MONTH]:null==E?void 0:E.monthEvents,[j.EXPIRATION_YEAR]:null==E?void 0:E.yearEvents,[j.CARDHOLDER_NAME]:null==E?void 0:E.cardHolderEvents};if("fields"in A&&Array.isArray(A.fields))if(A.fields.length>0&&"string"==typeof A.fields[0])for(const e of A.fields){const t=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:e,type:C[e],validations:S[e]},I),{label:R[e],placeholder:N[e]}),A.card_id?{skyflowID:A.card_id}:{}));G({element:t,errorStyles:I.errorStyles,fieldMessage:[j.CVV,j.EXPIRATION_MONTH,j.EXPIRATION_YEAR].includes(e)?"":R[e],events:k[e]});const n=`#collect_${String(e)}`+(A.card_id?`_${A.card_id}`:"");t.mount(n),O.push({element:t,containerId:n})}else for(const e of A.fields){const t=e.field,n=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:C[t],validations:S[t]},I),{label:R[t],placeholder:N[t]}),A.card_id?{skyflowID:A.card_id}:{})),o=e.container_id||`#collect_${String(t)}`+(A.card_id?`_${A.card_id}`:"");n.mount(o),O.push({element:n,containerId:o})}return{elements:O.map((e=>e.element)),container:T}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events})}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw u({message:v.getBusinessError},e)}}))}createSkyflowInstance(){return n(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:e,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({baseUrl:e,apiKey:o,vault_id:r,vault_url:i}){return n(this,void 0,void 0,(function*(){return t.init({vaultID:r,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield k(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}})}))}({vault_id:e,vault_url:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}getOpenpayDeviceSessionID(e,t,o){return n(this,void 0,void 0,(function*(){try{return yield y(e,t,o)}catch(e){throw l(e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:o}){return n(this,void 0,void 0,(function*(){return yield H({vault_id:e,vault_url:t,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:t,isSandbox:o,returnUrl:r}){var i;return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const n=yield this._getCustomer(this.abortController.signal),{vault_id:s,vault_url:a}=this.merchantData;let d;if(!t||""===t||null===t)if("string"==typeof e){const t=null===(i=this.collectContainer)||void 0===i?void 0:i.container;yield t.collect(),d={skyflow_id:e}}else d=yield H({vault_id:s,vault_url:a,data:Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._handleCheckout({card:d,payment_method:t,customer:n,isSandbox:o,returnUrl:r})}))}customerRegister(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,n={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(e){throw l(e)}}))}createOrder(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(e){throw l(e)}}))}createPayment(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(e){throw l(e)}}))}startCheckoutRouter(e){return n(this,void 0,void 0,(function*(){const t=yield m(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return n(this,void 0,void 0,(function*(){try{const{order:t,total:n,customer:o,skyflowTokens:r,return_url:i,isSandbox:d,metadata:l,currency:c,payment_method:u}=e,h=yield this._fetchMerchantData(),p=yield this.customerRegister(o.email);if(!(p&&"auth_token"in p&&h&&"reference"in h))throw new s({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const e={business:this.apiKeyTonder,client:p.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:t.items},v=yield this.createOrder(e),f=(new Date).toISOString();if(!("id"in v&&"id"in p&&"business"in h))throw new s({code:"500",body:v,name:"Keys error",message:"Order response errors"});{const e={business_pk:h.business.pk,amount:n,date:f,order_id:v.id,client_id:p.id},t=yield this.createPayment(e);let s;const{openpay_keys:g,business:_}=h;g.merchant_id&&g.public_key&&(s=yield y(g.merchant_id,g.public_key,d));const A=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:i,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:n,title_ship:"shipping",description:"transaction",device_session_id:s||null,token_id:"",order_id:"id"in v&&v.id,business_id:_.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:l,browser_info:a(),currency:c},u?{payment_method:u}:{card:r}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),b=yield m(this.baseUrl,this.apiKeyTonder,A);if(yield this.init3DSRedirect(b))return b}}}catch(e){throw l(e)}}))}registerCustomerCard(e,t,o){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${d(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":t,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(n.ok)return yield n.json();throw yield c(n)}catch(e){throw l(e)}}))}deleteCustomerCard(e,t=""){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${d(this.merchantData)}/cards/${t}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(n.ok)return!0;throw yield c(n)}catch(e){throw l(e)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const e=yield function(e,t,o="?status=active&page_size=10000&country=México",r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield c(n)}catch(e){throw l(e)}}))}(this.baseUrl,this.apiKeyTonder),t=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=t.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},te(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function oe(e){return/^\d{12,19}$/.test(e)&&de(e)}function re(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function ie(e){return/^\d{3,4}$/.test(e)}function se(e){return/^(0[1-9]|1[0-2])$/.test(e)}function ae(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const de=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),n=t.shift();let o=t.reduce(((e,t,n)=>n%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return o+=n,o%10==0};export{N as BaseInlineCheckout,ne as LiteCheckout,ie as validateCVV,oe as validateCardNumber,re as validateCardholderName,se as validateExpirationMonth,ae as validateExpirationYear};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tonder.io/ionic-lite-sdk",
3
- "version": "0.0.58-beta.DEV-1845.1",
3
+ "version": "0.0.58",
4
4
  "description": "Tonder ionic lite SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -83,7 +83,6 @@ async function getFieldsPromise(
83
83
  const fields = await getFields(data, collectContainer);
84
84
  if (!fields) return [];
85
85
 
86
- //
87
86
  return fields.map((field: { element: CollectElement; key: string }) => {
88
87
  return new Promise((resolve) => {
89
88
  const div = document.createElement("div");
@@ -302,7 +301,7 @@ function handleSkyflowElementEvents(event: {
302
301
  const msj_error = state.isEmpty
303
302
  ? requiredMessage
304
303
  : fieldMessage != ""
305
- ? `El campo ${fieldMessage} es inválido`
304
+ ? `El campo ${fieldMessage} no es válido`
306
305
  : invalidMessage;
307
306
  element.setError(msj_error);
308
307
  }
@@ -1,17 +0,0 @@
1
- import 'react';
2
-
3
- declare global {
4
- namespace JSX {
5
- interface IntrinsicElements {
6
- 'tonder-card-cvv-input': React.DetailedHTMLProps<
7
- React.HTMLAttributes<HTMLElement>,
8
- HTMLElement
9
- > & {
10
- 'skyflow-id'?: string; // lo que usas en la app
11
- skyflowid?: string; // por si cambias/compatibilidad
12
- };
13
- }
14
- }
15
- }
16
-
17
- export {};
@@ -1,19 +0,0 @@
1
- import { LiteCheckout } from '../../../classes/liteCheckout';
2
- export declare class CardCVVInput extends HTMLElement {
3
- private _skyflowId?;
4
- private _checkoutInstance?;
5
- private _cvvDiv;
6
- private _mounted;
7
- private shadow;
8
- constructor();
9
- static get observedAttributes(): string[];
10
- get skyflowId(): string | undefined;
11
- set skyflowId(val: string | undefined);
12
- get checkoutInstance(): LiteCheckout | undefined;
13
- set checkoutInstance(val: LiteCheckout | undefined);
14
- attributeChangedCallback(name: string, _old: string, value: string): void;
15
- connectedCallback(): void;
16
- disconnectedCallback(): void;
17
- private _update;
18
- private _mountCVV;
19
- }