@tonder.io/ionic-lite-sdk 0.0.57 → 0.0.58-beta.DEV-1845.1
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/dist/classes/liteCheckout.d.ts +7 -2
- package/dist/helpers/skyflow.d.ts +20 -0
- package/dist/index.js +1 -1
- package/dist/shared/constants/skyflow.contants.d.ts +36 -0
- package/dist/shared/styles/skyflow.styles.d.ts +14 -0
- package/dist/types/card.d.ts +14 -0
- package/dist/types/commons.d.ts +82 -0
- package/dist/types/jsx-web-components.d.ts +17 -0
- package/dist/types/liteInlineCheckout.d.ts +8 -0
- package/dist/types/requests.d.ts +1 -1
- package/dist/ui/components/input/CardCVVInput.d.ts +19 -0
- package/package.json +2 -2
- package/src/classes/3dsHandler.ts +0 -1
- package/src/classes/liteCheckout.ts +67 -17
- package/src/helpers/mercadopago.ts +1 -3
- package/src/helpers/skyflow.ts +307 -34
- package/src/shared/constants/skyflow.contants.ts +63 -0
- package/src/shared/styles/skyflow.styles.ts +63 -0
- package/src/types/card.ts +12 -0
- package/src/types/commons.ts +95 -1
- package/src/types/liteInlineCheckout.ts +9 -1
- package/src/types/requests.ts +1 -1
- package/tests/classes/liteCheckout.test.ts +0 -57
- package/tests/methods/createOrder.test.ts +0 -142
- package/tests/methods/createPayment.test.ts +0 -122
- package/tests/methods/customerRegister.test.ts +0 -119
- package/tests/methods/getBusiness.test.ts +0 -114
- package/tests/methods/getCustomerCards.test.ts +0 -113
- package/tests/methods/registerCustomerCard.test.ts +0 -118
- package/tests/methods/startCheckoutRouter.test.ts +0 -120
- package/tests/methods/startCheckoutRouterFull.test.ts +0 -139
- package/tests/utils/defaultMock.ts +0 -22
- package/tests/utils/mockClasses.ts +0 -659
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ErrorResponse } from "./errorResponse";
|
|
2
2
|
import { BaseInlineCheckout } from "./BaseInlineCheckout";
|
|
3
3
|
import { APM, IInlineLiteCheckoutOptions } from "../types/commons";
|
|
4
|
-
import { ICustomerCardsResponse, ISaveCardRequest, ISaveCardResponse } from "../types/card";
|
|
4
|
+
import { ICustomerCardsResponse, IMountCardFieldsRequest, ISaveCardRequest, ISaveCardResponse } from "../types/card";
|
|
5
5
|
import { IPaymentMethod } from "../types/paymentMethod";
|
|
6
6
|
import { CreateOrderResponse, CreatePaymentResponse, CustomerRegisterResponse, GetBusinessResponse, RegisterCustomerCardResponse, StartCheckoutResponse } from "../types/responses";
|
|
7
7
|
import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutFullRequest, StartCheckoutIdRequest, StartCheckoutRequest, TokensRequest } from "../types/requests";
|
|
@@ -14,13 +14,18 @@ declare global {
|
|
|
14
14
|
}
|
|
15
15
|
export declare class LiteCheckout extends BaseInlineCheckout implements ILiteCheckout {
|
|
16
16
|
activeAPMs: APM[];
|
|
17
|
-
|
|
17
|
+
private collectContainer;
|
|
18
|
+
private skyflowInstance;
|
|
19
|
+
private readonly events;
|
|
20
|
+
constructor({ apiKey, mode, returnUrl, callBack, apiKeyTonder, baseUrlTonder, customization, collectorIds, events }: IInlineLiteCheckoutOptions);
|
|
18
21
|
injectCheckout(): Promise<void>;
|
|
19
22
|
getCustomerCards(): Promise<ICustomerCardsResponse>;
|
|
20
23
|
saveCustomerCard(card: ISaveCardRequest): Promise<ISaveCardResponse>;
|
|
21
24
|
removeCustomerCard(skyflowId: string): Promise<string>;
|
|
22
25
|
getCustomerPaymentMethods(): Promise<IPaymentMethod[]>;
|
|
26
|
+
mountCardFields(event: IMountCardFieldsRequest): Promise<void>;
|
|
23
27
|
getBusiness(): Promise<GetBusinessResponse>;
|
|
28
|
+
private createSkyflowInstance;
|
|
24
29
|
getOpenpayDeviceSessionID(merchant_id: string, public_key: string, is_sandbox: boolean): Promise<string | ErrorResponse>;
|
|
25
30
|
getSkyflowTokens({ vault_id, vault_url, data, }: TokensRequest): Promise<any | ErrorResponse>;
|
|
26
31
|
_setCartTotal(total: string): void;
|
|
@@ -1,3 +1,23 @@
|
|
|
1
1
|
import { ErrorResponse } from "../classes/errorResponse";
|
|
2
|
+
import Skyflow from "skyflow-js";
|
|
3
|
+
import CollectContainer from "skyflow-js/types/core/external/collect/collect-container";
|
|
4
|
+
import CollectElement from "skyflow-js/types/core/external/collect/collect-element";
|
|
2
5
|
import { TokensSkyflowRequest } from "../types/requests";
|
|
6
|
+
import { IMountCardFieldsRequest } from "../types/card";
|
|
7
|
+
import { IEvents, ILiteCustomizationOptions } from "../types/commons";
|
|
8
|
+
/**
|
|
9
|
+
* [DEPRECATION WARNING]
|
|
10
|
+
* This function should be deprecated in favor of using mountSkyflowFields for security,
|
|
11
|
+
* to prevent users from creating their own inputs.
|
|
12
|
+
*/
|
|
3
13
|
export declare function getSkyflowTokens({ baseUrl, apiKey, vault_id, vault_url, data, }: TokensSkyflowRequest): Promise<any | ErrorResponse>;
|
|
14
|
+
export declare function initSkyflowInstance({ baseUrl, apiKey, vault_id, vault_url, }: TokensSkyflowRequest): Promise<Skyflow>;
|
|
15
|
+
export declare function mountSkyflowFields(event: {
|
|
16
|
+
skyflowInstance: Skyflow;
|
|
17
|
+
data: IMountCardFieldsRequest;
|
|
18
|
+
customization?: ILiteCustomizationOptions;
|
|
19
|
+
events?: IEvents;
|
|
20
|
+
}): Promise<{
|
|
21
|
+
elements: CollectElement[];
|
|
22
|
+
container: CollectContainer;
|
|
23
|
+
}>;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{get as t}from"lodash";import e from"skyflow-js";function n(t,e,n,o){return new(n||(n=Promise))((function(r,i){function s(t){try{d(o.next(t))}catch(t){i(t)}}function a(t){try{d(o.throw(t))}catch(t){i(t)}}function d(t){var e;t.done?r(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}d((o=o.apply(t,e||[])).next())}))}function o(t,e,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!o:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(t):o?o.value:e.get(t)}function r(t,e,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 e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(t,n):r?r.value=n:e.set(t,n),n}function i(t,e,o){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${t}/api/v1/payments/business/${e}`,{headers:{Authorization:`Token ${e}`},signal:o});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor({code:t,body:e,name:n,message:o,stack:r}){this.code=t,this.body=e,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=t=>{var e;return t&&"business"in t?null===(e=null==t?void 0:t.business)||void 0===e?void 0:e.pk:""},c=t=>new s({code:(null==t?void 0:t.status)?t.status:t.code,body:null==t?void 0:t.body,name:t?"string"==typeof t?"catch":t.name:"Error",message:t?"string"==typeof t?t:t.message:"Error",stack:"string"==typeof t?void 0:t.stack}),l=(t,e=void 0)=>n(void 0,void 0,void 0,(function*(){let n,o,r="Error";t&&"json"in t&&(n=yield null==t?void 0:t.json()),t&&"status"in t&&(o=t.status.toString()),!n&&t&&"text"in t&&(r=yield t.text()),(null==n?void 0:n.detail)&&(r=n.detail);return new s({code:o,body:n,name:o,message:r,stack:e})}));function u(t,e){var n,o;let r=200;try{r=Number((null==e?void 0:e.code)||200)}catch(t){}const i={status:"error",code:r,message:"",detail:(null===(n=null==e?void 0:e.body)||void 0===n?void 0:n.detail)||(null===(o=null==e?void 0:e.body)||void 0===o?void 0:o.error)||e.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),t)}class h{constructor({payload:t=null,apiKey:e,baseUrl:n,redirectOnComplete:o,tdsIframeId:r,tonderPayButtonId:i,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=t=>{this.payload=t},this.baseUrl=n,this.apiKey=e,this.payload=t,this.tdsIframeId=r,this.tonderPayButtonId=i,this.redirectOnComplete=o,this.callBack=s}setStorageItem(t){return localStorage.setItem(this.localStorageKey,JSON.stringify(t))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var t,e,n,o,r,i;const s=null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const t=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;t?this.saveUrlWithExpiration(t):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(t){try{const e={url:t,expires:(new Date).getTime()+12e5};this.setStorageItem(e)}catch(t){console.log("error: ",t)}}getUrlWithExpiration(){const t=this.getStorageItem();if(t){const e=JSON.parse(t);if(!e)return;return(new Date).getTime()>e.expires?(this.removeVerifyTransactionUrl(),null):e.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var t,e,n;if(null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((t,e)=>{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=()=>t(!0):(console.log("No redirection found"),e(!1))}else console.log("No redirection found"),e(!1)}))}getRedirectUrl(){var t,e,n;return null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const t=this.getRedirectUrl();if(t)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=t;else{const e=document.querySelector(`#${this.tdsIframeId}`);if(e){e.setAttribute("src",t),e.setAttribute("style","display: block");const o=this,r=t=>n(this,void 0,void 0,(function*(){const t=()=>{try{const t=document.querySelector(`#${this.tonderPayButtonId}`);t&&(t.disabled=!1)}catch(t){}e&&e.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),e.removeEventListener("load",r)},i=e=>n(this,void 0,void 0,(function*(){const r=yield new Promise(((t,n)=>t(e)));if(r){if((t=>"Pending"!==(null==t?void 0:t.transaction_status))(r))return t();{const t=setTimeout((()=>n(this,void 0,void 0,(function*(){clearTimeout(t),yield i(o.requestTransactionStatus())}))),7e3)}}}));yield i(o.requestTransactionStatus())}));e.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 t=this.getUrlWithExpiration(),e=t.startsWith("https://")?t:`${this.baseUrl}${t}`,n=yield fetch(e,{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 t={},e=new URLSearchParams(window.location.search);for(const[n,o]of e)t[n]=o;return t}handleSuccessTransaction(t){return this.removeVerifyTransactionUrl(),console.log("Transacción autorizada."),t}handleDeclinedTransaction(t){return this.removeVerifyTransactionUrl(),t}handle3dsChallenge(t){return n(this,void 0,void 0,(function*(){const e=document.createElement("form");e.name="frm",e.method="POST",e.action=t.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=t.creq,n.value=t.creq,e.appendChild(n);const o=document.createElement("input");o.type="hidden",o.name=t.term_url,o.value=t.TermUrl,e.appendChild(o),document.body.appendChild(e),e.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(t){return n(this,void 0,void 0,(function*(){const e=yield t.json();return"Pending"===e.status&&e.redirect_post_url?yield this.handle3dsChallenge(e):["Success","Authorized"].includes(e.status)?this.handleSuccessTransaction(e):(this.handleDeclinedTransaction(t),e)}))}verifyTransactionStatus(){return n(this,void 0,void 0,(function*(){const t=this.getUrlWithExpiration();if(t){const e=t.startsWith("https://")?t:`${this.baseUrl}${t}`;try{const t=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==t.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),t):yield this.handleTransactionResponse(t)}catch(t){console.error("Error al verificar la transacción:",t),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(t,e,o){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/checkout-router/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},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 t=yield i.json(),e=new Error("Failed to start checkout router");throw e.details=t,e}}catch(t){throw t}}))}function y(t,e,o=!0,r=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(t),n.setApiKey(e),n.setSandboxMode(o),yield n.deviceData.setup({signal:r})}))}const f=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 v,g,_,A,b,E,T,O,C,S,j,I;class k{constructor({mode:t="stage",customization:e,apiKey:n,apiKeyTonder:o,returnUrl:r,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d}){v.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=t,this.customer={},this.baseUrl=a||p[this.mode]||p.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),e||{}),this.process3ds=new h({apiKey:n,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i}configureCheckout(t){"secureToken"in t&&o(this,v,"m",E).call(this,t.secureToken),o(this,v,"m",A).call(this,t)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const t=yield this.process3ds.verifyTransactionStatus(),e=yield o(this,v,"m",j).call(this,t);return this.process3ds.setPayload(e),this._handle3dsRedirect(e)}))}payment(t){return new Promise(((e,r)=>n(this,void 0,void 0,(function*(){try{o(this,v,"m",A).call(this,t);const n=yield this._checkout(t);this.process3ds.setPayload(n);if(yield this._handle3dsRedirect(n)){try{const t=document.querySelector(`#${this.tonderPayButtonId}`);t&&(t.disabled=!1)}catch(t){}this.callBack&&this.callBack(n),e(n)}}catch(t){r(t)}}))))}getSecureToken(t){return n(this,void 0,void 0,(function*(){try{return yield function(t,e,o=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${t}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:o});if(n.ok)return yield n.json();throw yield l(n)}catch(t){throw c(t)}}))}(this.baseUrl,t)}catch(t){throw u({message:f.secureTokenError},t)}}))}_initializeCheckout(){return n(this,void 0,void 0,(function*(){const t=yield this._fetchMerchantData();t&&t.mercado_pago&&t.mercado_pago.active&&function(){try{const t=document.createElement("script");t.src="https://www.mercadopago.com/v2/security.js",t.setAttribute("view",""),t.onload=()=>{console.log("Mercado Pago script loaded successfully.")},t.onerror=t=>{console.error("Error loading Mercado Pago script:",t)},document.head.appendChild(t)}catch(t){console.error("Error attempting to inject Mercado Pago script:",t)}}()}))}_checkout(t){return n(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(t){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(t=null){return n(this,void 0,void 0,(function*(){return o(this,_,"f")||r(this,_,yield function(t,e,o,r=null){return n(this,void 0,void 0,(function*(){const n=`${t}/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 ${e}`},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,t),"f"),o(this,_,"f")}))}_handleCheckout({card:e,payment_method:r,customer:i,isSandbox:s,returnUrl:d}){return n(this,void 0,void 0,(function*(){const{openpay_keys:c,reference:l,business:u}=this.merchantData,h=Number(this.cartTotal);try{let p;!p&&c.merchant_id&&c.public_key&&!r&&(p=yield y(c.merchant_id,c.public_key,s,this.abortController.signal));const{id:f,auth_token:v}=i,_={business:this.apiKeyTonder,client:v,billing_address_id:null,shipping_address_id:null,amount:h,status:"A",reference:l,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata},A=yield function(t,e,o){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/orders/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},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:f,amount:h,date:b,order_id:A.id,customer_order_reference:this.order_reference?this.order_reference:l,items:this.cartItems,currency:this.currency,metadata:this.metadata},T=yield function(t,e,o){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/business/${o.business_pk}/payments/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},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:t(this.customer,"firstName",t(this.customer,"name","")),last_name:t(this.customer,"lastName",t(this.customer,"lastname","")),email_client:t(this.customer,"email",""),phone_number:t(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:e}),{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(t){throw console.log(t),t}}))}_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(t){return this.merchantData}}))}_getCustomerCards(t,e){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r,i=null){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":e},signal:i});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield l(s)}catch(t){throw c(t)}}))}(this.baseUrl,t,this.secureToken,e)}))}_saveCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r,i){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":e},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield l(s)}catch(t){throw c(t)}}))}(this.baseUrl,t,this.secureToken,e,o)}))}_removeCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r="",i){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${i}/cards/${r}`,s=yield fetch(n,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":e}});if(204===s.status)return f.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield l(s)}catch(t){throw c(t)}}))}(this.baseUrl,t,this.secureToken,o,e)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(t,e,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(`${t}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();throw yield l(i)}catch(t){throw c(t)}}))}(this.baseUrl,this.apiKeyTonder)}))}_handle3dsRedirect(t){var e,o;return n(this,void 0,void 0,(function*(){if(t&&"next_action"in t?null===(o=null===(e=null==t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t)}));else{if(!this.process3ds.getRedirectUrl())return t;this.process3ds.redirectToChallenge()}}))}}function w({baseUrl:t,apiKey:o,vault_id:r,vault_url:i,data:s}){return n(this,void 0,void 0,(function*(){const a=e.init({vaultID:r,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield function(t,e,o=null){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${t}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${e}`},signal:o});if(n.ok)return(yield n.json()).token;throw new Error("Failed to retrieve bearer token")}))}(t,o)})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}),d=a.container(e.ContainerType.COLLECT),l=yield function(t,o){return n(this,void 0,void 0,(function*(){const r=yield function(t,o){return n(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(t).map((t=>n(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:t,type:e.ElementType.INPUT_FIELD}),key:t}})))))}))}(t,o);return r?r.map((e=>new Promise((n=>{var o;const r=document.createElement("div");r.hidden=!0,r.id=`id-${e.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(r),setTimeout((()=>{e.element.mount(`#id-${e.key}`),setInterval((()=>{if(e.element.isMounted()){const o=t[e.key];return e.element.update({value:o}),n(e.element.isMounted())}}),120)}),120)})))):[]}))}(s,d);if((yield Promise.all(l)).some((t=>!t)))throw c(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const t=yield d.collect();if(t)return t.records[0].fields;throw c(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(t){throw c(t)}}))}g=new WeakMap,_=new WeakMap,v=new WeakSet,A=function(t){var e,n;!t||t&&0===Object.keys(t).length||(o(this,v,"m",b).call(this,t.customer),this._setCartTotal((null===(e=t.cart)||void 0===e?void 0:e.total)||0),o(this,v,"m",T).call(this,(null===(n=t.cart)||void 0===n?void 0:n.items)||[]),o(this,v,"m",O).call(this,t),o(this,v,"m",C).call(this,t),o(this,v,"m",S).call(this,t),o(this,v,"m",I).call(this,t))},b=function(t){t&&(this.customer=t)},E=function(t){this.secureToken=t},T=function(t){this.cartItems=t},O=function(t){this.metadata=null==t?void 0:t.metadata,this.order_reference=null==t?void 0:t.order_reference},C=function(t){this.currency=null==t?void 0:t.currency},S=function(t){this.card=null==t?void 0:t.card},j=function(t){var e,o,r;return n(this,void 0,void 0,(function*(){if("Hard"===(null===(e=null==t?void 0:t.decline)||void 0===e?void 0:e.error_type)||(null===(o=null==t?void 0:t.checkout)||void 0===o?void 0:o.is_route_finished)||(null==t?void 0:t.is_route_finished)||["Pending"].includes(null==t?void 0:t.transaction_status))return t;if(["Success","Authorized"].includes(null==t?void 0:t.transaction_status))return t;if(t){const e={checkout_id:(null===(r=t.checkout)||void 0===r?void 0:r.id)||(null==t?void 0:t.checkout_id)};try{return yield m(this.baseUrl,this.apiKeyTonder,e)}catch(t){}return t}}))},I=function(t){r(this,g,null==t?void 0:t.apm_config,"f")};const M=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"}),R={[M.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[M.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[M.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[M.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[M.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[M.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[M.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[M.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[M.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[M.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[M.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[M.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[M.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[M.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[M.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[M.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[M.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[M.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[M.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[M.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[M.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[M.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[M.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[M.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[M.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[M.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[M.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[M.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[M.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[M.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[M.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[M.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},U=t=>{const e=t.toUpperCase().trim().replace(/\s+/g,"");return R[e]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class N extends k{constructor({apiKey:t,mode:e,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,collectorIds:a}){super({mode:e,apiKey:t,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe"}),this.activeAPMs=[]}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:t}=yield this._getCustomer(),e=yield this._getCustomerCards(t,this.merchantData.business.pk);return Object.assign(Object.assign({},e),{cards:e.cards.map((t=>{return Object.assign(Object.assign({},t),{icon:(e=t.fields.card_scheme,"Visa"===e?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===e?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===e?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var e}))})}catch(t){throw u({message:f.getCardsError},t)}}))}saveCustomerCard(t){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),{vault_id:n,vault_url:o,business:r}=this.merchantData,i=yield w({vault_id:n,vault_url:o,data:Object.assign(Object.assign({},t),{card_number:t.card_number.replace(/\s+/g,""),expiration_month:t.expiration_month.replace(/\s+/g,""),expiration_year:t.expiration_year.replace(/\s+/g,""),cvv:t.cvv.replace(/\s+/g,""),cardholder_name:t.cardholder_name.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._saveCustomerCard(e,null==r?void 0:r.pk,i)}catch(t){throw u({message:f.saveCardError},t)}}))}removeCustomerCard(t){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),{business:n}=this.merchantData;return yield this._removeCustomerCard(e,null==n?void 0:n.pk,t)}catch(t){throw u({message:f.removeCardError},t)}}))}getCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){try{const t=yield this._fetchCustomerPaymentMethods();return(t&&"results"in t&&t.results.length>0?t.results:[]).filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},U(t.payment_method)))).sort(((t,e)=>t.priority-e.priority))}catch(t){throw u({message:f.getPaymentMethodsError},t)}}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(t){throw u({message:f.getBusinessError},t)}}))}getOpenpayDeviceSessionID(t,e,o){return n(this,void 0,void 0,(function*(){try{return yield y(t,e,o)}catch(t){throw c(t)}}))}getSkyflowTokens({vault_id:t,vault_url:e,data:o}){return n(this,void 0,void 0,(function*(){return yield w({vault_id:t,vault_url:e,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(t){this.cartTotal=t}_checkout({card:t,payment_method:e,isSandbox:o,returnUrl:r}){return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const n=yield this._getCustomer(this.abortController.signal),{vault_id:i,vault_url:s}=this.merchantData;let a;return e&&""!==e&&null!==e||(a="string"==typeof t?{skyflow_id:t}:yield w({vault_id:i,vault_url:s,data:Object.assign(Object.assign({},t),{card_number:t.card_number.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})),yield this._handleCheckout({card:a,payment_method:e,customer:n,isSandbox:o,returnUrl:r})}))}customerRegister(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/customer/`,n={email:t},o=yield fetch(e,{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 l(o)}catch(t){throw c(t)}}))}createOrder(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/orders/`,n=t,o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield l(o)}catch(t){throw c(t)}}))}createPayment(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/business/${t.business_pk}/payments/`,n=t,o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield l(o)}catch(t){throw c(t)}}))}startCheckoutRouter(t){return n(this,void 0,void 0,(function*(){const e=yield m(this.baseUrl,this.apiKeyTonder,t);if(yield this.init3DSRedirect(e))return e}))}init3DSRedirect(t){return n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(t),yield this._handle3dsRedirect(t)}))}startCheckoutRouterFull(t){return n(this,void 0,void 0,(function*(){try{const{order:e,total:n,customer:o,skyflowTokens:r,return_url:i,isSandbox:d,metadata:c,currency:l,payment_method:u}=t,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 t={business:this.apiKeyTonder,client:p.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:e.items},f=yield this.createOrder(t),v=(new Date).toISOString();if(!("id"in f&&"id"in p&&"business"in h))throw new s({code:"500",body:f,name:"Keys error",message:"Order response errors"});{const t={business_pk:h.business.pk,amount:n,date:v,order_id:f.id,client_id:p.id},e=yield this.createPayment(t);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 f&&f.id,business_id:_.pk,payment_id:"pk"in e&&e.pk,source:"sdk",metadata:c,browser_info:a(),currency:l},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(t){throw c(t)}}))}registerCustomerCard(t,e,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 ${t}`,"User-token":e,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(n.ok)return yield n.json();throw yield l(n)}catch(t){throw c(t)}}))}deleteCustomerCard(t,e=""){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/${e}`,{method:"DELETE",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(n.ok)return!0;throw yield l(n)}catch(t){throw c(t)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const t=yield function(t,e,o="?status=active&page_size=10000&country=México",r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${t}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield l(n)}catch(t){throw c(t)}}))}(this.baseUrl,this.apiKeyTonder),e=t&&t.results&&t.results.length>0?t.results:[];return this.activeAPMs=e.filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},U(t.payment_method)))).sort(((t,e)=>t.priority-e.priority)),this.activeAPMs}catch(t){return console.error("Error getting APMS",t),[]}}))}}function P(t){return/^\d{12,19}$/.test(t)&&K(t)}function L(t){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(t)}function D(t){return/^\d{3,4}$/.test(t)}function $(t){return/^(0[1-9]|1[0-2])$/.test(t)}function B(t){if(!/^\d{2}$/.test(t))return!1;const e=(new Date).getFullYear()%100;return parseInt(t,10)>=e}const K=t=>{const e=`${t}`.split("").reverse().map((t=>Number.parseInt(t))),n=e.shift();let o=e.reduce(((t,e,n)=>n%2!=0?t+e:t+((e*=2)>9?e-9:e)),0);return o+=n,o%10==0};export{k as BaseInlineCheckout,N as LiteCheckout,D as validateCVV,P as validateCardNumber,L as validateCardholderName,$ as validateExpirationMonth,B 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} 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};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
declare const lengthMatchRule: {
|
|
2
|
+
type: import("skyflow-js").ValidationRuleType;
|
|
3
|
+
params: {
|
|
4
|
+
max: number;
|
|
5
|
+
};
|
|
6
|
+
};
|
|
7
|
+
declare const regexMatchRule: {
|
|
8
|
+
type: import("skyflow-js").ValidationRuleType;
|
|
9
|
+
params: {
|
|
10
|
+
regex: RegExp;
|
|
11
|
+
error: string;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
declare const getErrorField: (event: {
|
|
15
|
+
elementType?: string;
|
|
16
|
+
isEmpty?: boolean;
|
|
17
|
+
isFocused?: boolean;
|
|
18
|
+
isValid?: boolean;
|
|
19
|
+
value?: string;
|
|
20
|
+
}, field: string) => string;
|
|
21
|
+
declare const DEFAULT_SKYFLOW_lABELS: {
|
|
22
|
+
name: string;
|
|
23
|
+
card_number: string;
|
|
24
|
+
cvv: string;
|
|
25
|
+
expiration_month: string;
|
|
26
|
+
expiration_year: string;
|
|
27
|
+
expiration_date: string;
|
|
28
|
+
};
|
|
29
|
+
declare const DEFAULT_SKYFLOW_PLACEHOLDERS: {
|
|
30
|
+
name: string;
|
|
31
|
+
card_number: string;
|
|
32
|
+
cvv: string;
|
|
33
|
+
expiration_month: string;
|
|
34
|
+
expiration_year: string;
|
|
35
|
+
};
|
|
36
|
+
export { lengthMatchRule, regexMatchRule, getErrorField, DEFAULT_SKYFLOW_lABELS, DEFAULT_SKYFLOW_PLACEHOLDERS, };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { CollectInputStylesVariant, CollectLabelStylesVariant } from "../../types/commons";
|
|
2
|
+
import { LabelStyles } from "skyflow-js/types/utils/common";
|
|
3
|
+
declare const DEFAULT_SKYFLOW_INPUT_STYLES: CollectInputStylesVariant;
|
|
4
|
+
declare const DEFAULT_SKYFLOW_lABEL_STYLES: LabelStyles;
|
|
5
|
+
declare const DEFAULT_SKYFLOW_ERROR_TEXT_STYLES: CollectLabelStylesVariant;
|
|
6
|
+
declare const SKYFLOW_HIDDEN_ERROR_TEXT_STYLES: {
|
|
7
|
+
base: {
|
|
8
|
+
fontSize: string;
|
|
9
|
+
fontWeight: string;
|
|
10
|
+
color: string;
|
|
11
|
+
fontFamily: string;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
export { DEFAULT_SKYFLOW_INPUT_STYLES, DEFAULT_SKYFLOW_lABEL_STYLES, DEFAULT_SKYFLOW_ERROR_TEXT_STYLES, SKYFLOW_HIDDEN_ERROR_TEXT_STYLES, };
|
package/dist/types/card.d.ts
CHANGED
|
@@ -28,3 +28,17 @@ export interface ISaveCardRequest {
|
|
|
28
28
|
expiration_year: string;
|
|
29
29
|
cardholder_name: string;
|
|
30
30
|
}
|
|
31
|
+
export declare enum CardFieldEnum {
|
|
32
|
+
CARD_NUMBER = "card_number",
|
|
33
|
+
CVV = "cvv",
|
|
34
|
+
EXPIRATION_MONTH = "expiration_month",
|
|
35
|
+
EXPIRATION_YEAR = "expiration_year",
|
|
36
|
+
CARDHOLDER_NAME = "cardholder_name"
|
|
37
|
+
}
|
|
38
|
+
export interface IMountCardFieldsRequest {
|
|
39
|
+
fields: CardFieldEnum[] | {
|
|
40
|
+
container_id?: string;
|
|
41
|
+
field: CardFieldEnum;
|
|
42
|
+
}[];
|
|
43
|
+
card_id?: string;
|
|
44
|
+
}
|
package/dist/types/commons.d.ts
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import { ICustomer } from "./customer";
|
|
2
2
|
import { IProcessPaymentRequest, IStartCheckoutResponse } from "./checkout";
|
|
3
|
+
import CollectorContainer from "skyflow-js/types/core/external/collect/collect-container";
|
|
4
|
+
import ComposableContainer from "skyflow-js/types/core/external/collect/compose-collect-container";
|
|
5
|
+
import RevealContainer from "skyflow-js/types/core/external/reveal/reveal-container";
|
|
6
|
+
import CollectElement from "skyflow-js/types/core/external/collect/collect-element";
|
|
7
|
+
import ComposableElement from "skyflow-js/types/core/external/collect/compose-collect-element";
|
|
8
|
+
import RevealElement from "skyflow-js/types/core/external/reveal/reveal-element";
|
|
9
|
+
import { LabelStyles } from "skyflow-js/types/utils/common";
|
|
3
10
|
export type Business = {
|
|
4
11
|
business: {
|
|
5
12
|
pk: number;
|
|
@@ -112,6 +119,28 @@ export interface IInlineLiteCheckoutOptions extends IInlineCheckoutBaseOptions {
|
|
|
112
119
|
collectorIds?: {
|
|
113
120
|
tdsIframe?: string;
|
|
114
121
|
};
|
|
122
|
+
customization?: ILiteCustomizationOptions;
|
|
123
|
+
events?: IEvents;
|
|
124
|
+
}
|
|
125
|
+
export interface ICardFormEvents {
|
|
126
|
+
cardHolderEvents?: IInputEvents;
|
|
127
|
+
cardNumberEvents?: IInputEvents;
|
|
128
|
+
cvvEvents?: IInputEvents;
|
|
129
|
+
monthEvents?: IInputEvents;
|
|
130
|
+
yearEvents?: IInputEvents;
|
|
131
|
+
}
|
|
132
|
+
export interface IInputEvents {
|
|
133
|
+
onChange?: (event: IEventSecureInput) => void;
|
|
134
|
+
onFocus?: (event: IEventSecureInput) => void;
|
|
135
|
+
onBlur?: (event: IEventSecureInput) => void;
|
|
136
|
+
}
|
|
137
|
+
export interface IEventSecureInput {
|
|
138
|
+
elementType: string;
|
|
139
|
+
isEmpty: boolean;
|
|
140
|
+
isFocused: boolean;
|
|
141
|
+
isValid: boolean;
|
|
142
|
+
}
|
|
143
|
+
export interface IEvents extends ICardFormEvents {
|
|
115
144
|
}
|
|
116
145
|
export interface IApiError {
|
|
117
146
|
code: string;
|
|
@@ -128,3 +157,56 @@ export interface IPublicError {
|
|
|
128
157
|
export type CustomizationOptions = {
|
|
129
158
|
redirectOnComplete?: boolean;
|
|
130
159
|
};
|
|
160
|
+
export interface InCollectorContainer {
|
|
161
|
+
container: CollectorContainer | ComposableContainer | RevealContainer;
|
|
162
|
+
elements: (CollectElement | ComposableElement | RevealElement)[];
|
|
163
|
+
}
|
|
164
|
+
export interface ILiteCustomizationOptions extends CustomizationOptions {
|
|
165
|
+
styles?: IStyles;
|
|
166
|
+
labels?: IFormLabels;
|
|
167
|
+
placeholders?: IFormPlaceholder;
|
|
168
|
+
}
|
|
169
|
+
export interface IFormLabels {
|
|
170
|
+
name?: string;
|
|
171
|
+
card_number?: string;
|
|
172
|
+
cvv?: string;
|
|
173
|
+
expiry_date?: string;
|
|
174
|
+
expiration_year?: string;
|
|
175
|
+
expiration_month?: string;
|
|
176
|
+
}
|
|
177
|
+
export interface IFormPlaceholder {
|
|
178
|
+
name?: string;
|
|
179
|
+
card_number?: string;
|
|
180
|
+
cvv?: string;
|
|
181
|
+
expiration_month?: string;
|
|
182
|
+
expiration_year?: string;
|
|
183
|
+
}
|
|
184
|
+
export interface IStyles {
|
|
185
|
+
cardForm?: ILiteCardFormStyles;
|
|
186
|
+
}
|
|
187
|
+
export interface ILiteCardFormStyles extends StylesBaseVariant, IElementStyle {
|
|
188
|
+
}
|
|
189
|
+
export interface StylesBaseVariant {
|
|
190
|
+
base?: Record<string, any>;
|
|
191
|
+
}
|
|
192
|
+
export interface IElementStyle {
|
|
193
|
+
inputStyles?: CollectInputStylesVariant;
|
|
194
|
+
labelStyles?: LabelStyles;
|
|
195
|
+
errorStyles?: StylesBaseVariant;
|
|
196
|
+
}
|
|
197
|
+
export interface StylesFocusVariant {
|
|
198
|
+
focus?: Record<string, any>;
|
|
199
|
+
}
|
|
200
|
+
export interface CollectInputStylesVariant extends StylesBaseVariant, StylesFocusVariant {
|
|
201
|
+
complete?: Record<string, any>;
|
|
202
|
+
invalid?: Record<string, any>;
|
|
203
|
+
empty?: Record<string, any>;
|
|
204
|
+
cardIcon?: Record<string, any>;
|
|
205
|
+
dropdownIcon?: Record<string, any>;
|
|
206
|
+
dropdown?: Record<string, any>;
|
|
207
|
+
dropdownListItem?: Record<string, any>;
|
|
208
|
+
global: Record<string, any>;
|
|
209
|
+
}
|
|
210
|
+
export interface CollectLabelStylesVariant extends StylesBaseVariant, StylesFocusVariant {
|
|
211
|
+
requiredAsterisk?: Record<string, any>;
|
|
212
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
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 {};
|
|
@@ -158,4 +158,12 @@ export interface ILiteCheckout {
|
|
|
158
158
|
* during the payment process.
|
|
159
159
|
*/
|
|
160
160
|
getOpenpayDeviceSessionID(merchant_id: string, public_key: string, is_sandbox: boolean): Promise<string | ErrorResponse>;
|
|
161
|
+
/**
|
|
162
|
+
* Displays and renders card input fields in the checkout.
|
|
163
|
+
* Uses the provided configuration to show the required fields in the payment form.
|
|
164
|
+
* @param {import("./card").IMountCardFieldsRequest} event - Configuration for the card fields to render.
|
|
165
|
+
* @returns {Promise<void>} Resolves when the fields have been successfully rendered.
|
|
166
|
+
* @public
|
|
167
|
+
*/
|
|
168
|
+
mountCardFields(event: import("./card").IMountCardFieldsRequest): Promise<void>;
|
|
161
169
|
}
|
package/dist/types/requests.d.ts
CHANGED
|
@@ -0,0 +1,19 @@
|
|
|
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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tonder.io/ionic-lite-sdk",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.58-beta.DEV-1845.1",
|
|
4
4
|
"description": "Tonder ionic lite SDK",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"license": "ISC",
|
|
14
14
|
"dependencies": {
|
|
15
15
|
"lodash.get": "^4.4.2",
|
|
16
|
-
"skyflow-js": "
|
|
16
|
+
"skyflow-js": "2.4.4",
|
|
17
17
|
"ts-node": "^10.9.2"
|
|
18
18
|
},
|
|
19
19
|
"publishConfig": {
|