@tonder.io/ionic-lite-sdk 0.0.63-beta.DEV-1975.2 → 0.0.63-beta.DEV-1975.4
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/BaseInlineCheckout.d.ts +7 -3
- package/dist/helpers/card_on_file.d.ts +45 -0
- package/dist/index.js +1 -1
- package/dist/types/cardOnFile.d.ts +133 -0
- package/dist/types/commons.d.ts +5 -0
- package/package.json +1 -1
- package/src/classes/BaseInlineCheckout.ts +27 -4
- package/src/helpers/card_on_file.ts +267 -0
- package/src/types/cardOnFile.ts +155 -0
- package/src/types/commons.ts +5 -0
|
@@ -6,6 +6,7 @@ import { ICustomerCardsResponse, ISaveCardInternalResponse, ISaveCardSkyflowRequ
|
|
|
6
6
|
import { IPaymentMethodResponse } from "../types/paymentMethod";
|
|
7
7
|
import { ITransaction } from "../types/transaction";
|
|
8
8
|
import { GetSecureTokenResponse } from "../types/responses";
|
|
9
|
+
import { CardOnFile } from "../helpers/card_on_file";
|
|
9
10
|
export declare class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOptions> {
|
|
10
11
|
#private;
|
|
11
12
|
baseUrl: string;
|
|
@@ -29,6 +30,7 @@ export declare class BaseInlineCheckout<T extends CustomizationOptions = Customi
|
|
|
29
30
|
order_reference?: string | null;
|
|
30
31
|
card?: {} | undefined;
|
|
31
32
|
currency?: string;
|
|
33
|
+
protected cardOnFileInstance: CardOnFile | null;
|
|
32
34
|
constructor({ mode, customization, apiKey, apiKeyTonder, returnUrl, tdsIframeId, callBack, baseUrlTonder, tonderPayButtonId }: IInlineCheckoutBaseOptions);
|
|
33
35
|
configureCheckout(data: IConfigureCheckout): void;
|
|
34
36
|
verify3dsTransaction(): Promise<ITransaction | IStartCheckoutResponse | void>;
|
|
@@ -38,18 +40,20 @@ export declare class BaseInlineCheckout<T extends CustomizationOptions = Customi
|
|
|
38
40
|
_checkout(data: any): Promise<any>;
|
|
39
41
|
_setCartTotal(total: string | number): void;
|
|
40
42
|
_getCustomer(signal?: AbortSignal | null): Promise<Record<string, any>>;
|
|
41
|
-
_handleCheckout({ card, payment_method, customer, isSandbox,
|
|
42
|
-
card?: string
|
|
43
|
+
_handleCheckout({ card, payment_method, customer, isSandbox, enable_card_on_file, returnUrl: returnUrlData }: {
|
|
44
|
+
card?: Record<string, any>;
|
|
43
45
|
payment_method?: string;
|
|
44
46
|
customer: Record<string, any>;
|
|
45
47
|
isSandbox?: boolean;
|
|
46
48
|
returnUrl?: string;
|
|
47
|
-
|
|
49
|
+
enable_card_on_file?: boolean;
|
|
48
50
|
}): Promise<any>;
|
|
49
51
|
_fetchMerchantData(): Promise<Business | undefined>;
|
|
50
52
|
_getCustomerCards(authToken: string, businessId: string | number): Promise<ICustomerCardsResponse>;
|
|
51
53
|
_saveCustomerCard(authToken: string, businessId: string | number, skyflowTokens: ISaveCardSkyflowRequest, appOrigin?: boolean): Promise<ISaveCardInternalResponse>;
|
|
52
54
|
_removeCustomerCard(authToken: string, businessId: string | number, skyflowId: string): Promise<string>;
|
|
53
55
|
_fetchCustomerPaymentMethods(): Promise<IPaymentMethodResponse>;
|
|
56
|
+
protected _hasCardOnFileKeys(): boolean;
|
|
57
|
+
protected _initializeCardOnFile(): Promise<CardOnFile>;
|
|
54
58
|
_handle3dsRedirect(response: ITransaction | IStartCheckoutResponse | void): Promise<void | IStartCheckoutResponse | ITransaction>;
|
|
55
59
|
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { AcquirerInstance, CardOnFileSubscriptionRequest, CardOnFileSubscriptionResponse, CardOnFileTokenRequest, CardOnFileTokenResponse, ProcessParams, SecurityInfo } from "../types/cardOnFile";
|
|
2
|
+
declare global {
|
|
3
|
+
interface Window {
|
|
4
|
+
Kushki: new (config: {
|
|
5
|
+
merchantId: string;
|
|
6
|
+
inTestEnvironment: boolean;
|
|
7
|
+
}) => AcquirerInstance;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export declare class CardOnFile {
|
|
11
|
+
private readonly apiUrl;
|
|
12
|
+
private readonly merchantId;
|
|
13
|
+
private readonly apiKey;
|
|
14
|
+
private readonly isTestEnvironment;
|
|
15
|
+
private acquirerInstance;
|
|
16
|
+
constructor(config: {
|
|
17
|
+
merchantId: string;
|
|
18
|
+
apiKey: string;
|
|
19
|
+
isTestEnvironment?: boolean;
|
|
20
|
+
});
|
|
21
|
+
initialize(): Promise<void>;
|
|
22
|
+
private getAcquirerInstance;
|
|
23
|
+
/**
|
|
24
|
+
* Get JWT for 3DS authentication
|
|
25
|
+
* @param cardBin - First 8 digits of the card number
|
|
26
|
+
*/
|
|
27
|
+
getJwt(cardBin: string): Promise<string>;
|
|
28
|
+
/**
|
|
29
|
+
* Generate a recurring charge token
|
|
30
|
+
*/
|
|
31
|
+
generateToken(request: CardOnFileTokenRequest): Promise<CardOnFileTokenResponse>;
|
|
32
|
+
/**
|
|
33
|
+
* Create a subscription with the generated token
|
|
34
|
+
*/
|
|
35
|
+
createSubscription(request: CardOnFileSubscriptionRequest): Promise<CardOnFileSubscriptionResponse>;
|
|
36
|
+
/**
|
|
37
|
+
* Validate 3DS challenge
|
|
38
|
+
* @returns true if validation passed, throws error otherwise
|
|
39
|
+
*/
|
|
40
|
+
validate3DS(secureId: string, security: SecurityInfo): Promise<boolean>;
|
|
41
|
+
/**
|
|
42
|
+
* Complete flow: JWT → Token → 3DS validation → Subscription
|
|
43
|
+
*/
|
|
44
|
+
process(params: ProcessParams): Promise<CardOnFileSubscriptionResponse>;
|
|
45
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{get as e}from"lodash";import t from"skyflow-js";function n(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{d(o.next(e))}catch(e){i(e)}}function a(e){try{d(o.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}function o(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function r(e,t,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(e,n):r?r.value=n:t.set(e,n),n}function i(e,t,o){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:o});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor({code:e,body:t,name:n,message:o,stack:r}){this.code=e,this.body=t,this.name=n,this.message=o,this.stack=r}}var a;!function(e){e.INIT_ERROR="INIT_ERROR",e.CREATE_ERROR="CREATE_ERROR",e.REMOVE_SDK_ERROR="REMOVE_SDK_ERROR",e.INVALID_TYPE="INVALID_TYPE",e.STATE_ERROR="STATE_ERROR",e.FETCH_BUSINESS_ERROR="FETCH_BUSINESS_ERROR",e.INVALID_CONFIG="INVALID_CONFIG",e.MERCHANT_CREDENTIAL_REQUIRED="MERCHANT_CREDENTIAL_REQUIRED",e.INVALID_PAYMENT_REQUEST="INVALID_PAYMENT_REQUEST",e.INVALID_PAYMENT_REQUEST_CARD_PM="INVALID_PAYMENT_REQUEST_CARD_PM",e.TYPE_SDK_REQUIRED="TYPE_SDK_REQUIRED",e.ENVIRONMENT_REQUIRED="ENVIRONMENT_REQUIRED",e.FETCH_CARDS_ERROR="FETCH_CARDS_ERROR",e.FETCH_TRANSACTION_ERROR="FETCH_TRANSACTION_ERROR",e.CUSTOMER_AUTH_TOKEN_NOT_VALID="CUSTOMER_AUTH_TOKEN_NOT_VALID",e.SAVE_CARD_ERROR="SAVE_CARD_ERROR",e.REMOVE_CARD_ERROR="REMOVE_CARD_ERROR",e.SUMMARY_CARD_ERROR="SUMMARY_CARD_ERROR",e.CREATE_PAYMENT_ERROR="CREATE_PAYMENT_ERROR",e.PAYMENT_PROCESS_ERROR="PAYMENT_PROCESS_ERROR",e.INVALID_CARD_DATA="INVALID_CARD_DATA",e.SAVE_CARD_PROCESS_ERROR="SAVE_CARD_PROCESS_ERROR",e.START_CHECKOUT_ERROR="START_CHECKOUT_ERROR",e.CREATE_ORDER_ERROR="CREATE_ORDER_ERROR",e.BUSINESS_ID_REQUIRED="BUSINESS_ID_REQUIRED",e.CLIENT_ID_REQUIRED="CLIENT_ID_REQUIRED",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INVALID_ITEMS="INVALID_ITEMS",e.CUSTOMER_OPERATION_ERROR="CUSTOMER_OPERATION_ERROR",e.INVALID_EMAIL="INVALID_EMAIL",e.FETCH_PAYMENT_METHODS_ERROR="FETCH_PAYMENT_METHODS_ERROR",e.INVALID_VAULT_TOKEN="INVALID_VAULT_TOKEN",e.VAULT_TOKEN_ERROR="VAULT_TOKEN_ERROR",e.SECURE_TOKEN_ERROR="SECURE_TOKEN_ERROR",e.SECURE_TOKEN_INVALID="SECURE_TOKEN_INVALID",e.INVALID_SECRET_API_KEY="INVALID_SECRET_API_KEY",e.REMOVE_CARD="REMOVE_CARD",e.SKYFLOW_NOT_INITIALIZED="SKYFLOW_NOT_INITIALIZED",e.ERROR_LOAD_PAYMENT_FORM="ERROR_LOAD_PAYMENT_FORM",e.ERROR_LOAD_ENROLLMENT_FORM="ERROR_LOAD_ENROLLMENT_FORM",e.MOUNT_COLLECT_ERROR="MOUNT_COLLECT_ERROR",e.CARD_SAVED_SUCCESSFULLY="CARD_SAVED_SUCCESSFULLY",e.CARD_REMOVED_SUCCESSFULLY="CARD_REMOVED_SUCCESSFULLY",e.REQUEST_ABORTED="REQUEST_ABORTED",e.REQUEST_FAILED="REQUEST_FAILED",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.THREEDS_REDIRECTION_ERROR="THREEDS_REDIRECTION_ERROR"}(a||(a={}));const d=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."}),l={[a.INIT_ERROR]:"Error initializing the SDK.",[a.INVALID_TYPE]:"SDK Type invalid.",[a.STATE_ERROR]:"Error updating SDK state.",[a.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[a.INVALID_CONFIG]:"Required configuration options.",[a.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[a.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[a.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[a.TYPE_SDK_REQUIRED]:"SDK type required.",[a.ENVIRONMENT_REQUIRED]:"Environment required.",[a.FETCH_CARDS_ERROR]:"Error retrieving cards.",[a.CUSTOMER_AUTH_TOKEN_NOT_VALID]:"The customer's auth token is invalid. Please verify that the customer's data was provided when creating the SDK (sdk.create) and try again.",[a.SAVE_CARD_ERROR]:"Error saving the card.",[a.REMOVE_CARD_ERROR]:"Error deleting the card.",[a.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[a.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[a.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[a.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[a.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[a.START_CHECKOUT_ERROR]:"Error processing the payment.",[a.CREATE_ORDER_ERROR]:"Error creating the order.",[a.BUSINESS_ID_REQUIRED]:"Business ID is required.",[a.CLIENT_ID_REQUIRED]:"Client ID is required.",[a.INVALID_AMOUNT]:"Invalid amount.",[a.INVALID_ITEMS]:"Invalid items.",[a.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[a.INVALID_EMAIL]:"Invalid email.",[a.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[a.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[a.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[a.SECURE_TOKEN_ERROR]:"Error getting secure token.",[a.SECURE_TOKEN_INVALID]:"Invalid secure token.",[a.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[a.REMOVE_CARD]:"Card deleted successfully",[a.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[a.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[a.INVALID_CARD_DATA]:"Invalid card data.",[a.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[a.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[a.REQUEST_ABORTED]:"Requests canceled.",[a.REQUEST_FAILED]:"Request failed.",[a.UNKNOWN_ERROR]:"An unexpected error occurred.",[a.CREATE_ERROR]:"Error creating the SDK.",[a.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[a.THREEDS_REDIRECTION_ERROR]:"Ocurrió un error durante la redirección de 3DS.",[a.REMOVE_SDK_ERROR]:"Ocurrió un error removiendo la instancia del SDK."};a.INIT_ERROR,a.STATE_ERROR,a.FETCH_BUSINESS_ERROR,a.INVALID_CONFIG,a.TYPE_SDK_REQUIRED,a.ENVIRONMENT_REQUIRED,a.FETCH_CARDS_ERROR,a.SAVE_CARD_ERROR,a.REMOVE_CARD_ERROR,a.CREATE_PAYMENT_ERROR,a.START_CHECKOUT_ERROR,a.CREATE_ORDER_ERROR,a.BUSINESS_ID_REQUIRED,a.CLIENT_ID_REQUIRED,a.INVALID_AMOUNT,a.INVALID_ITEMS,a.CUSTOMER_OPERATION_ERROR,a.INVALID_EMAIL,a.FETCH_PAYMENT_METHODS_ERROR,a.INVALID_VAULT_TOKEN,a.VAULT_TOKEN_ERROR,a.SECURE_TOKEN_ERROR,a.INVALID_SECRET_API_KEY,a.CUSTOMER_AUTH_TOKEN_NOT_VALID,a.SECURE_TOKEN_INVALID,a.REMOVE_CARD,a.SKYFLOW_NOT_INITIALIZED,a.INVALID_TYPE,a.PAYMENT_PROCESS_ERROR,a.INVALID_PAYMENT_REQUEST,a.INVALID_PAYMENT_REQUEST_CARD_PM,a.SAVE_CARD_PROCESS_ERROR,a.ERROR_LOAD_PAYMENT_FORM,a.INVALID_CARD_DATA,a.ERROR_LOAD_ENROLLMENT_FORM,a.MOUNT_COLLECT_ERROR,a.CARD_SAVED_SUCCESSFULLY,a.CARD_REMOVED_SUCCESSFULLY,a.REQUEST_ABORTED,a.REQUEST_FAILED,a.UNKNOWN_ERROR,a.CREATE_ERROR,a.FETCH_TRANSACTION_ERROR,a.THREEDS_REDIRECTION_ERROR,a.REMOVE_SDK_ERROR;class c extends Error{constructor(e){var t,n;const o=e.message||l[e.code]||"Unknown error";super(o),this.name="TonderError",this.code=e.code,this.details={code:(null===(t=e.details)||void 0===t?void 0:t.code)||e.code,message:(null===(n=e.details)||void 0===n?void 0:n.message)||o}}}const u=()=>({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}),h=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},E=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}),_=(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 p(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 m{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 R=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function y(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 A(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})}))}var v,f,O,T,g,I,C,S,N,D,b,M,U;class L{constructor({mode:e="stage",customization:t,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="",f.set(this,void 0),O.set(this,void 0),this.apiKeyTonder=o||n||"",this.returnUrl=r,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||R[this.mode]||R.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new m({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,v,"m",I).call(this,e.secureToken),o(this,v,"m",T).call(this,e)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield o(this,v,"m",b).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,v,"m",T).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 _(n)}catch(e){throw E(e)}}))}(this.baseUrl,e)}catch(e){throw p({message:d.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,O,"f")||r(this,O,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,O,"f")}))}_handleCheckout({card:t,payment_method:r,customer:i,isSandbox:s,card_on_file_id:a,returnUrl:d}){return n(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:c,business:h}=this.merchantData,E=Number(this.cartTotal);try{let _;!_&&l.merchant_id&&l.public_key&&!r&&(_=yield A(l.merchant_id,l.public_key,s,this.abortController.signal));const{id:p,auth_token:m}=i,R={business:this.apiKeyTonder,client:m,billing_address_id:null,shipping_address_id:null,amount:E,status:"A",reference:c,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata},v=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,R),O=(new Date).toISOString(),T={business_pk:h.pk,client_id:p,amount:E,date:O,order_id:v.id,customer_order_reference:this.order_reference?this.order_reference:c,items:this.cartItems,currency:this.currency,metadata:this.metadata},g=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,T),I=Object.assign(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:E,title_ship:"shipping",description:"transaction",device_session_id:_||null,token_id:"",order_id:v.id,business_id:h.pk,payment_id:g.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:u(),currency:this.currency},r?{payment_method:r}:{card:t}),{apm_config:o(this,f,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),a?{card_on_file_id:a}:{}),C=yield y(this.baseUrl,this.apiKeyTonder,I);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 _(s)}catch(e){throw E(e)}}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,o,r=!1){return n(this,void 0,void 0,(function*(){return yield function(e,t,o,r,i,s=!1){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${r}/cards/`,a=yield fetch(n,{method:"POST",headers:Object.assign({Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},s?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(i)});if(a.ok)return yield a.json();throw yield _(a)}catch(e){throw E(e)}}))}(this.baseUrl,e,this.secureToken,t,o,r)}))}_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 d.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield _(s)}catch(e){throw E(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 _(i)}catch(e){throw E(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 P(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")}))}f=new WeakMap,O=new WeakMap,v=new WeakSet,T=function(e){var t,n;!e||e&&0===Object.keys(e).length||(o(this,v,"m",g).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),o(this,v,"m",C).call(this,(null===(n=e.cart)||void 0===n?void 0:n.items)||[]),o(this,v,"m",S).call(this,e),o(this,v,"m",N).call(this,e),o(this,v,"m",D).call(this,e),o(this,v,"m",M).call(this,e))},g=function(e){e&&(this.customer=e)},I=function(e){this.secureToken=e},C=function(e){this.cartItems=e},S=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},N=function(e){this.currency=null==e?void 0:e.currency},D=function(e){this.card=null==e?void 0:e.card},b=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 y(this.baseUrl,this.apiKeyTonder,t)}catch(e){}return e}}))},M=function(e){r(this,f,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"}(U||(U={}));const j={type:t.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},w=RegExp("^(?!s*$).+"),k={type:t.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:w,error:"El campo es requerido"}},V="Titular de la tarjeta",K="Número de tarjeta",F="CVC/CVV",x="Mes",B="Año",Y="Fecha de expiración",$="Nombre como aparece en la tarjeta",H="1234 1234 1234 1234",z="3-4 dígitos",Q="MM",W="AA",X={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'}},G={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function q({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 P(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 E(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 E(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw E(e)}}))}function Z(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=>{te({eventName:"onChange",data:e,events:a}),ee({element:n,errorStyles:r,color:"transparent"})})),n.on(t.EventName.BLUR,(e=>{if(te({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?i:""!=o?`El campo ${o} no es válido`:s;n.setError(t)}ee({element:n,errorStyles:r})})),n.on(t.EventName.FOCUS,(e=>{te({eventName:"onFocus",data:e,events:a}),ee({element:n,errorStyles:r,color:"transparent"}),n.resetError()})))}function ee(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 te=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","")})}};function ne(e){return n(this,void 0,void 0,(function*(){const{element:t,containerId:n,retries:o=2,delay:r=30}=e;for(let e=0;e<=o;e++){if(document.querySelector(n))return void t.mount(n);e<o&&(yield new Promise((e=>setTimeout(e,r))))}console.warn(`[mountCardFields] Container ${n} was not found after ${o+1} attempts`)}))}const oe=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"}),re={[oe.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[oe.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[oe.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[oe.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[oe.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[oe.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[oe.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[oe.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[oe.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[oe.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[oe.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[oe.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[oe.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[oe.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[oe.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[oe.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[oe.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[oe.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[oe.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[oe.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[oe.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[oe.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[oe.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[oe.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[oe.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[oe.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[oe.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[oe.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[oe.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[oe.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[oe.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[oe.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[oe.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},ie=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return re[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class se extends L{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.mountedElementsByContext=new Map,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 p({message:d.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 q({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 p({message:d.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 p({message:d.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},ie(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw p({message:d.getPaymentMethodsError},e)}}))}mountCardFields(e){var o;return n(this,void 0,void 0,(function*(){const r=e.card_id?`update:${e.card_id}`:"create",i=null!==(o=e.unmount_context)&&void 0!==o?o:"all";"none"!==i&&("current"===i?this.unmountCardFields(r):this.unmountCardFields(i)),yield this.createSkyflowInstance();const s=yield function(e){var o,r,i,s,a,d,l,c,u,h,E,_,p,m,R,y,A;return n(this,void 0,void 0,(function*(){const{skyflowInstance:n,data:v,customization:f,events:O}=e,T=n.container(t.ContainerType.COLLECT),g=[],I={[U.CVV]:t.ElementType.CVV,[U.CARD_NUMBER]:t.ElementType.CARD_NUMBER,[U.EXPIRATION_MONTH]:t.ElementType.EXPIRATION_MONTH,[U.EXPIRATION_YEAR]:t.ElementType.EXPIRATION_YEAR,[U.CARDHOLDER_NAME]:t.ElementType.CARDHOLDER_NAME},C={[U.CVV]:[k],[U.CARD_NUMBER]:[k],[U.EXPIRATION_MONTH]:[k],[U.EXPIRATION_YEAR]:[k],[U.CARDHOLDER_NAME]:[j,k]},S={errorStyles:(null===(r=null===(o=null==f?void 0:f.styles)||void 0===o?void 0:o.cardForm)||void 0===r?void 0:r.errorStyles)||G,inputStyles:(null===(s=null===(i=null==f?void 0:f.styles)||void 0===i?void 0:i.cardForm)||void 0===s?void 0:s.inputStyles)||X,labelStyles:(null===(d=null===(a=null==f?void 0:f.styles)||void 0===a?void 0:a.cardForm)||void 0===d?void 0:d.labelStyles)||J},N={name:(null===(l=null==f?void 0:f.labels)||void 0===l?void 0:l.name)||V,card_number:(null===(c=null==f?void 0:f.labels)||void 0===c?void 0:c.card_number)||K,cvv:(null===(u=null==f?void 0:f.labels)||void 0===u?void 0:u.cvv)||F,expiration_date:(null===(h=null==f?void 0:f.labels)||void 0===h?void 0:h.expiry_date)||Y,expiration_month:(null===(E=null==f?void 0:f.labels)||void 0===E?void 0:E.expiration_month)||x,expiration_year:(null===(_=null==f?void 0:f.labels)||void 0===_?void 0:_.expiration_year)||B},D={name:(null===(p=null==f?void 0:f.placeholders)||void 0===p?void 0:p.name)||$,card_number:(null===(m=null==f?void 0:f.placeholders)||void 0===m?void 0:m.card_number)||H,cvv:(null===(R=null==f?void 0:f.placeholders)||void 0===R?void 0:R.cvv)||z,expiration_month:(null===(y=null==f?void 0:f.placeholders)||void 0===y?void 0:y.expiration_month)||Q,expiration_year:(null===(A=null==f?void 0:f.placeholders)||void 0===A?void 0:A.expiration_year)||W},b={[U.CVV]:null==O?void 0:O.cvvEvents,[U.CARD_NUMBER]:null==O?void 0:O.cardNumberEvents,[U.EXPIRATION_MONTH]:null==O?void 0:O.monthEvents,[U.EXPIRATION_YEAR]:null==O?void 0:O.yearEvents,[U.CARDHOLDER_NAME]:null==O?void 0:O.cardHolderEvents};if("fields"in v&&Array.isArray(v.fields))if(v.fields.length>0&&"string"==typeof v.fields[0])for(const e of v.fields){const t=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:e,type:I[e],validations:C[e]},S),{label:N[e],placeholder:D[e]}),v.card_id?{skyflowID:v.card_id}:{}));Z({element:t,errorStyles:S.errorStyles,fieldMessage:[U.CVV,U.EXPIRATION_MONTH,U.EXPIRATION_YEAR].includes(e)?"":N[e],events:b[e]});const n=`#collect_${String(e)}`+(v.card_id?`_${v.card_id}`:"");yield ne({element:t,containerId:n}),g.push({element:t,containerId:n})}else for(const e of v.fields){const t=e.field,n=T.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:I[t],validations:C[t]},S),{label:N[t],placeholder:D[t]}),v.card_id?{skyflowID:v.card_id}:{})),o=e.container_id||`#collect_${String(t)}`+(v.card_id?`_${v.card_id}`:"");yield ne({element:n,containerId:o}),g.push({element:n,containerId:o})}return{elements:g.map((e=>e.element)),container:T}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events});this.mountedElementsByContext.set(r,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const n=`update:${e}`,o=this.mountedElementsByContext.get(n);return(null===(t=null==o?void 0:o.container)||void 0===t?void 0:t.container)||null}unmountCardFields(e="all"){"all"===e?(this.mountedElementsByContext.forEach(((e,t)=>{this.unmountContext(t)})),this.mountedElementsByContext.clear()):(this.unmountContext(e),this.mountedElementsByContext.delete(e))}unmountContext(e){const t=this.mountedElementsByContext.get(e);if(!t)return;const{elements:n}=t;n&&n.length>0&&n.forEach((t=>{try{t&&"function"==typeof t.unmount&&t.unmount()}catch(t){console.warn(`Error unmounting Skyflow element from context '${e}':`,t)}}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw p({message:d.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 P(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 A(e,t,o)}catch(e){throw E(e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:o}){return n(this,void 0,void 0,(function*(){return yield q({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:d}=this.merchantData;let l;if(!t)if("string"==typeof e){const t=this.getContainerByCardId(e);try{t&&(yield t.collect())}catch(e){if(t){const t=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.description;throw new c({code:a.MOUNT_COLLECT_ERROR,details:{message:t}})}}l={skyflow_id:e}}else l=yield q({vault_id:s,vault_url:d,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:l,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 _(o)}catch(e){throw E(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 _(o)}catch(e){throw E(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 _(o)}catch(e){throw E(e)}}))}startCheckoutRouter(e){return n(this,void 0,void 0,(function*(){const t=yield y(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:a,metadata:d,currency:l,payment_method:c}=e,h=yield this._fetchMerchantData(),E=yield this.customerRegister(o.email);if(!(E&&"auth_token"in E&&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:E.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:t.items},_=yield this.createOrder(e),p=(new Date).toISOString();if(!("id"in _&&"id"in E&&"business"in h))throw new s({code:"500",body:_,name:"Keys error",message:"Order response errors"});{const e={business_pk:h.business.pk,amount:n,date:p,order_id:_.id,client_id:E.id},t=yield this.createPayment(e);let s;const{openpay_keys:m,business:R}=h;m.merchant_id&&m.public_key&&(s=yield A(m.merchant_id,m.public_key,a));const v=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 _&&_.id,business_id:R.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:u(),currency:l},c?{payment_method:c}:{card:r}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),f=yield y(this.baseUrl,this.apiKeyTonder,v);if(yield this.init3DSRedirect(f))return f}}}catch(e){throw E(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/${h(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 _(n)}catch(e){throw E(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/${h(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 _(n)}catch(e){throw E(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 _(n)}catch(e){throw E(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},ie(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function ae(e){return/^\d{12,19}$/.test(e)&&he(e)}function de(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function le(e){return/^\d{3,4}$/.test(e)}function ce(e){return/^(0[1-9]|1[0-2])$/.test(e)}function ue(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const he=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{L as BaseInlineCheckout,se as LiteCheckout,le as validateCVV,ae as validateCardNumber,de as validateCardholderName,ce as validateExpirationMonth,ue as validateExpirationYear};
|
|
1
|
+
import{get as e}from"lodash";import t from"skyflow-js";function n(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{d(r.next(e))}catch(e){i(e)}}function a(e){try{d(r.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}d((r=r.apply(e,t||[])).next())}))}function r(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}function o(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n}function i(e,t,r){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:r});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor({code:e,body:t,name:n,message:r,stack:o}){this.code=e,this.body=t,this.name=n,this.message=r,this.stack=o}}var a;!function(e){e.INIT_ERROR="INIT_ERROR",e.CREATE_ERROR="CREATE_ERROR",e.REMOVE_SDK_ERROR="REMOVE_SDK_ERROR",e.INVALID_TYPE="INVALID_TYPE",e.STATE_ERROR="STATE_ERROR",e.FETCH_BUSINESS_ERROR="FETCH_BUSINESS_ERROR",e.INVALID_CONFIG="INVALID_CONFIG",e.MERCHANT_CREDENTIAL_REQUIRED="MERCHANT_CREDENTIAL_REQUIRED",e.INVALID_PAYMENT_REQUEST="INVALID_PAYMENT_REQUEST",e.INVALID_PAYMENT_REQUEST_CARD_PM="INVALID_PAYMENT_REQUEST_CARD_PM",e.TYPE_SDK_REQUIRED="TYPE_SDK_REQUIRED",e.ENVIRONMENT_REQUIRED="ENVIRONMENT_REQUIRED",e.FETCH_CARDS_ERROR="FETCH_CARDS_ERROR",e.FETCH_TRANSACTION_ERROR="FETCH_TRANSACTION_ERROR",e.CUSTOMER_AUTH_TOKEN_NOT_VALID="CUSTOMER_AUTH_TOKEN_NOT_VALID",e.SAVE_CARD_ERROR="SAVE_CARD_ERROR",e.REMOVE_CARD_ERROR="REMOVE_CARD_ERROR",e.SUMMARY_CARD_ERROR="SUMMARY_CARD_ERROR",e.CREATE_PAYMENT_ERROR="CREATE_PAYMENT_ERROR",e.PAYMENT_PROCESS_ERROR="PAYMENT_PROCESS_ERROR",e.INVALID_CARD_DATA="INVALID_CARD_DATA",e.SAVE_CARD_PROCESS_ERROR="SAVE_CARD_PROCESS_ERROR",e.START_CHECKOUT_ERROR="START_CHECKOUT_ERROR",e.CREATE_ORDER_ERROR="CREATE_ORDER_ERROR",e.BUSINESS_ID_REQUIRED="BUSINESS_ID_REQUIRED",e.CLIENT_ID_REQUIRED="CLIENT_ID_REQUIRED",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INVALID_ITEMS="INVALID_ITEMS",e.CUSTOMER_OPERATION_ERROR="CUSTOMER_OPERATION_ERROR",e.INVALID_EMAIL="INVALID_EMAIL",e.FETCH_PAYMENT_METHODS_ERROR="FETCH_PAYMENT_METHODS_ERROR",e.INVALID_VAULT_TOKEN="INVALID_VAULT_TOKEN",e.VAULT_TOKEN_ERROR="VAULT_TOKEN_ERROR",e.SECURE_TOKEN_ERROR="SECURE_TOKEN_ERROR",e.SECURE_TOKEN_INVALID="SECURE_TOKEN_INVALID",e.INVALID_SECRET_API_KEY="INVALID_SECRET_API_KEY",e.REMOVE_CARD="REMOVE_CARD",e.SKYFLOW_NOT_INITIALIZED="SKYFLOW_NOT_INITIALIZED",e.ERROR_LOAD_PAYMENT_FORM="ERROR_LOAD_PAYMENT_FORM",e.ERROR_LOAD_ENROLLMENT_FORM="ERROR_LOAD_ENROLLMENT_FORM",e.MOUNT_COLLECT_ERROR="MOUNT_COLLECT_ERROR",e.CARD_SAVED_SUCCESSFULLY="CARD_SAVED_SUCCESSFULLY",e.CARD_REMOVED_SUCCESSFULLY="CARD_REMOVED_SUCCESSFULLY",e.REQUEST_ABORTED="REQUEST_ABORTED",e.REQUEST_FAILED="REQUEST_FAILED",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.THREEDS_REDIRECTION_ERROR="THREEDS_REDIRECTION_ERROR"}(a||(a={}));const d=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."}),l={[a.INIT_ERROR]:"Error initializing the SDK.",[a.INVALID_TYPE]:"SDK Type invalid.",[a.STATE_ERROR]:"Error updating SDK state.",[a.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[a.INVALID_CONFIG]:"Required configuration options.",[a.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[a.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[a.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[a.TYPE_SDK_REQUIRED]:"SDK type required.",[a.ENVIRONMENT_REQUIRED]:"Environment required.",[a.FETCH_CARDS_ERROR]:"Error retrieving cards.",[a.CUSTOMER_AUTH_TOKEN_NOT_VALID]:"The customer's auth token is invalid. Please verify that the customer's data was provided when creating the SDK (sdk.create) and try again.",[a.SAVE_CARD_ERROR]:"Error saving the card.",[a.REMOVE_CARD_ERROR]:"Error deleting the card.",[a.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[a.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[a.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[a.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[a.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[a.START_CHECKOUT_ERROR]:"Error processing the payment.",[a.CREATE_ORDER_ERROR]:"Error creating the order.",[a.BUSINESS_ID_REQUIRED]:"Business ID is required.",[a.CLIENT_ID_REQUIRED]:"Client ID is required.",[a.INVALID_AMOUNT]:"Invalid amount.",[a.INVALID_ITEMS]:"Invalid items.",[a.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[a.INVALID_EMAIL]:"Invalid email.",[a.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[a.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[a.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[a.SECURE_TOKEN_ERROR]:"Error getting secure token.",[a.SECURE_TOKEN_INVALID]:"Invalid secure token.",[a.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[a.REMOVE_CARD]:"Card deleted successfully",[a.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[a.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[a.INVALID_CARD_DATA]:"Invalid card data.",[a.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[a.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[a.REQUEST_ABORTED]:"Requests canceled.",[a.REQUEST_FAILED]:"Request failed.",[a.UNKNOWN_ERROR]:"An unexpected error occurred.",[a.CREATE_ERROR]:"Error creating the SDK.",[a.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[a.THREEDS_REDIRECTION_ERROR]:"Ocurrió un error durante la redirección de 3DS.",[a.REMOVE_SDK_ERROR]:"Ocurrió un error removiendo la instancia del SDK."};a.INIT_ERROR,a.STATE_ERROR,a.FETCH_BUSINESS_ERROR,a.INVALID_CONFIG,a.TYPE_SDK_REQUIRED,a.ENVIRONMENT_REQUIRED,a.FETCH_CARDS_ERROR,a.SAVE_CARD_ERROR,a.REMOVE_CARD_ERROR,a.CREATE_PAYMENT_ERROR,a.START_CHECKOUT_ERROR,a.CREATE_ORDER_ERROR,a.BUSINESS_ID_REQUIRED,a.CLIENT_ID_REQUIRED,a.INVALID_AMOUNT,a.INVALID_ITEMS,a.CUSTOMER_OPERATION_ERROR,a.INVALID_EMAIL,a.FETCH_PAYMENT_METHODS_ERROR,a.INVALID_VAULT_TOKEN,a.VAULT_TOKEN_ERROR,a.SECURE_TOKEN_ERROR,a.INVALID_SECRET_API_KEY,a.CUSTOMER_AUTH_TOKEN_NOT_VALID,a.SECURE_TOKEN_INVALID,a.REMOVE_CARD,a.SKYFLOW_NOT_INITIALIZED,a.INVALID_TYPE,a.PAYMENT_PROCESS_ERROR,a.INVALID_PAYMENT_REQUEST,a.INVALID_PAYMENT_REQUEST_CARD_PM,a.SAVE_CARD_PROCESS_ERROR,a.ERROR_LOAD_PAYMENT_FORM,a.INVALID_CARD_DATA,a.ERROR_LOAD_ENROLLMENT_FORM,a.MOUNT_COLLECT_ERROR,a.CARD_SAVED_SUCCESSFULLY,a.CARD_REMOVED_SUCCESSFULLY,a.REQUEST_ABORTED,a.REQUEST_FAILED,a.UNKNOWN_ERROR,a.CREATE_ERROR,a.FETCH_TRANSACTION_ERROR,a.THREEDS_REDIRECTION_ERROR,a.REMOVE_SDK_ERROR;class c extends Error{constructor(e){var t,n;const r=e.message||l[e.code]||"Unknown error";super(r),this.name="TonderError",this.code=e.code,this.details={code:(null===(t=e.details)||void 0===t?void 0:t.code)||e.code,message:(null===(n=e.details)||void 0===n?void 0:n.message)||r}}}const u=()=>({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}),h=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},E=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}),p=(e,t=void 0)=>n(void 0,void 0,void 0,(function*(){let n,r,o="Error";e&&"json"in e&&(n=yield null==e?void 0:e.json()),e&&"status"in e&&(r=e.status.toString()),!n&&e&&"text"in e&&(o=yield e.text()),(null==n?void 0:n.detail)&&(o=n.detail);return new s({code:r,body:n,name:r,message:o,stack:t})}));function _(e,t){var n,r;let o=200;try{o=Number((null==t?void 0:t.code)||200)}catch(e){}const i={status:"error",code:o,message:"",detail:(null===(n=null==t?void 0:t.body)||void 0===n?void 0:n.detail)||(null===(r=null==t?void 0:t.body)||void 0===r?void 0:r.error)||t.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),e)}class m{constructor({payload:e=null,apiKey:t,baseUrl:n,redirectOnComplete:r,tdsIframeId:o,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=o,this.tonderPayButtonId=i,this.redirectOnComplete=r,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,r,o,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===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.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,r,o;const i=null===(o=null===(r=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===o?void 0:o.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const r=document.createElement("script");r.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(r);const o=document.getElementById("tdsMmethodTgtFrame");o?o.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 r=this,o=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"),r.callBack&&r.callBack(r.payload),t.removeEventListener("load",o)},i=t=>n(this,void 0,void 0,(function*(){const o=yield new Promise(((e,n)=>e(t)));if(o){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(o))return e();{const e=setTimeout((()=>n(this,void 0,void 0,(function*(){clearTimeout(e),yield i(r.requestTransactionStatus())}))),7e3)}}}));yield i(r.requestTransactionStatus())}));t.addEventListener("load",o)}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,r]of t)e[n]=r;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 r=document.createElement("input");r.type="hidden",r.name=e.term_url,r.value=e.TermUrl,t.appendChild(r),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 R=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function y(e,t,r){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/checkout-router/`,o=r,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(Object.assign(Object.assign({},o),"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 v(e,t,r=!0,o=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(e),n.setApiKey(t),n.setSandboxMode(r),yield n.deviceData.setup({signal:o})}))}const A="https://cdn.kushkipagos.com/kushki.min.js";let f=!1,O=null;class T{constructor(e){var t;this.acquirerInstance=null,this.isTestEnvironment=null===(t=e.isTestEnvironment)||void 0===t||t,this.apiUrl=this.isTestEnvironment?"https://api-stage.tonder.io":"https://api.tonder.io",this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return n(this,void 0,void 0,(function*(){yield function(){return n(this,void 0,void 0,(function*(){return f?Promise.resolve():O||(O=new Promise(((e,t)=>{if(document.querySelector(`script[src="${A}"]`))return f=!0,void e();const n=document.createElement("script");n.src=A,n.async=!0,n.onload=()=>{f=!0,e()},n.onerror=()=>{O=null,t(new Error("Failed to load acquirer script"))},document.head.appendChild(n)})),O)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw new Error("Acquirer script not loaded. Call initialize() first.");return new window.Kushki({merchantId:e,inTestEnvironment:t})}(this.merchantId,this.isTestEnvironment)}))}getAcquirerInstance(){if(!this.acquirerInstance)throw new Error("CardOnFile not initialized. Call initialize() first.");return this.acquirerInstance}getJwt(e){return n(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((n,r)=>{t.requestSecureInit({card:{number:e}},(e=>{if("code"in e&&e.code)return void r(new Error(`Error getting JWT: ${e.message}`));const t=e;t.jwt?n(t.jwt):r(new Error("No JWT returned from acquirer"))}))}))}))}generateToken(e){return n(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}/acq-kushki/subscription/token`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok){const e=yield t.text();throw new Error(`Failed to generate token: ${t.status} - ${e}`)}return t.json()}))}createSubscription(e){return n(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}/acq-kushki/subscription/create`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok){const e=yield t.text();throw new Error(`Failed to create subscription: ${t.status} - ${e}`)}return t.json()}))}validate3DS(e,t){return n(this,void 0,void 0,(function*(){const n=this.getAcquirerInstance();return new Promise(((r,o)=>{n.requestValidate3DS({secureId:e,security:t},(e=>{const t=e;t.code&&"3DS000"!==t.code?o(new Error("3DS validation failed}")):!1!==t.isValid?r(!0):o(new Error("3DS validation failed"))}))}))}))}process(e){var t,r;return n(this,void 0,void 0,(function*(){const n=yield this.getJwt(e.cardBin),o=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:n}),i=o.secureId||(null===(t=o.details)||void 0===t?void 0:t.secureId),s=o.security||(null===(r=o.details)||void 0===r?void 0:r.security);if(!i||!s)throw new Error("Missing secureId or security in token response");return yield this.validate3DS(i,s),this.createSubscription({token:o.token,contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}var g,I,C,S,N,b,D,M,U,L,w,P,k;class j{constructor({mode:e="stage",customization:t,apiKey:n,apiKeyTonder:r,returnUrl:o,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d}){g.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",this.cardOnFileInstance=null,I.set(this,void 0),C.set(this,void 0),this.apiKeyTonder=r||n||"",this.returnUrl=o,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||R[this.mode]||R.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new m({apiKey:n,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i}configureCheckout(e){"secureToken"in e&&r(this,g,"m",b).call(this,e.secureToken),r(this,g,"m",S).call(this,e)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield r(this,g,"m",w).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((t,o)=>n(this,void 0,void 0,(function*(){try{r(this,g,"m",S).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){o(e)}}))))}getSecureToken(e){return n(this,void 0,void 0,(function*(){try{return yield function(e,t,r=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:r});if(n.ok)return yield n.json();throw yield p(n)}catch(e){throw E(e)}}))}(this.baseUrl,e)}catch(e){throw _({message:d.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)}}(),this._hasCardOnFileKeys()&&(yield this._initializeCardOnFile())}))}_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 r(this,C,"f")||o(this,C,yield function(e,t,r,o=null){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/customer/`,i={email:r.email,first_name:null==r?void 0:r.firstName,last_name:null==r?void 0:r.lastName,phone:null==r?void 0:r.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},signal:o,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"),r(this,C,"f")}))}_handleCheckout({card:t,payment_method:o,customer:i,isSandbox:s,enable_card_on_file:a,returnUrl:d}){return n(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:c,business:h}=this.merchantData,E=Number(this.cartTotal);try{let p;!p&&l.merchant_id&&l.public_key&&!o&&(p=yield v(l.merchant_id,l.public_key,s,this.abortController.signal));const{id:_,auth_token:m}=i,R={business:this.apiKeyTonder,client:m,billing_address_id:null,shipping_address_id:null,amount:E,status:"A",reference:c,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata},A=yield function(e,t,r){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/orders/`,o=r,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(o)});if(201===i.status)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,R),f=(new Date).toISOString(),O={business_pk:h.pk,client_id:_,amount:E,date:f,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,r){return n(this,void 0,void 0,(function*(){const n=`${e}/api/v1/business/${r.business_pk}/payments/`,o=r,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(o)});if(i.status>=200&&i.status<=299)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,O),g=Object.assign(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:E,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:A.id,business_id:h.pk,payment_id:T.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:u(),currency:this.currency},o?{payment_method:o}:{card:t}),{apm_config:r(this,I,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),a?{enable_card_on_file:a}:{}),C=yield y(this.baseUrl,this.apiKeyTonder,g);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,r,o,i=null){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${o}/cards/`,s=yield fetch(n,{method:"GET",headers:{Authorization:`Bearer ${r}`,"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 p(s)}catch(e){throw E(e)}}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,r,o=!1){return n(this,void 0,void 0,(function*(){return yield function(e,t,r,o,i,s=!1){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${o}/cards/`,a=yield fetch(n,{method:"POST",headers:Object.assign({Authorization:`Bearer ${r}`,"Content-Type":"application/json","User-token":t},s?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(i)});if(a.ok)return yield a.json();throw yield p(a)}catch(e){throw E(e)}}))}(this.baseUrl,e,this.secureToken,t,r,o)}))}_removeCustomerCard(e,t,r){return n(this,void 0,void 0,(function*(){return yield function(e,t,r,o="",i){return n(this,void 0,void 0,(function*(){try{const n=`${e}/api/v1/business/${i}/cards/${o}`,s=yield fetch(n,{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","User-token":t}});if(204===s.status)return d.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield p(s)}catch(e){throw E(e)}}))}(this.baseUrl,e,this.secureToken,r,t)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(e,t,r={status:"active",pagesize:"10000"},o=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(r).toString(),i=yield fetch(`${e}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:o});if(i.ok)return yield i.json();throw yield p(i)}catch(e){throw E(e)}}))}(this.baseUrl,this.apiKeyTonder)}))}_hasCardOnFileKeys(){var e,t;return!!(null===(t=null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys)||void 0===t?void 0:t.public_key)}_initializeCardOnFile(){var e;return n(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new T({merchantId:null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys.public_key,apiKey:this.apiKeyTonder,isTestEnvironment:"production"!==this.mode}),yield this.cardOnFileInstance.initialize()),this.cardOnFileInstance}))}_handle3dsRedirect(e){var t,r;return n(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(r=null===(t=null==e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===r?void 0:r.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 V(e,t,r=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:r});if(n.ok){return(yield n.json()).token}throw new Error("Failed to retrieve bearer token")}))}I=new WeakMap,C=new WeakMap,g=new WeakSet,S=function(e){var t,n;!e||e&&0===Object.keys(e).length||(r(this,g,"m",N).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),r(this,g,"m",D).call(this,(null===(n=e.cart)||void 0===n?void 0:n.items)||[]),r(this,g,"m",M).call(this,e),r(this,g,"m",U).call(this,e),r(this,g,"m",L).call(this,e),r(this,g,"m",P).call(this,e))},N=function(e){e&&(this.customer=e)},b=function(e){this.secureToken=e},D=function(e){this.cartItems=e},M=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},U=function(e){this.currency=null==e?void 0:e.currency},L=function(e){this.card=null==e?void 0:e.card},w=function(e){var t,r,o;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===(r=null==e?void 0:e.checkout)||void 0===r?void 0:r.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===(o=e.checkout)||void 0===o?void 0:o.id)||(null==e?void 0:e.checkout_id)};try{return yield y(this.baseUrl,this.apiKeyTonder,t)}catch(e){}return e}}))},P=function(e){o(this,I,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"}(k||(k={}));const K={type:t.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},F=RegExp("^(?!s*$).+"),x={type:t.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:F,error:"El campo es requerido"}},B="Titular de la tarjeta",$="Número de tarjeta",Y="CVC/CVV",H="Mes",z="Año",W="Fecha de expiración",Q="Nombre como aparece en la tarjeta",q="1234 1234 1234 1234",J="3-4 dígitos",X="MM",G="AA",Z={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")'}},ee={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},te={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function ne({baseUrl:e,apiKey:r,vault_id:o,vault_url:i,data:s}){return n(this,void 0,void 0,(function*(){const a=t.init({vaultID:o,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield V(e,r)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}}).container(t.ContainerType.COLLECT),d=yield function(e,r){return n(this,void 0,void 0,(function*(){const o=yield function(e,r){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 r.create({table:"cards",column:e,type:t.ElementType.INPUT_FIELD}),key:e}})))))}))}(e,r);return o?o.map((t=>new Promise((n=>{var r;const o=document.createElement("div");o.hidden=!0,o.id=`id-${t.key}`,null===(r=document.querySelector("body"))||void 0===r||r.appendChild(o),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const r=e[t.key];return t.element.setValue(r),n(t.element.isMounted())}}),120)}),120)})))):[]}))}(s,a);if((yield Promise.all(d)).some((e=>!e)))throw E(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 E(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw E(e)}}))}function re(e){const{element:n,fieldMessage:r="",errorStyles:o={},requiredMessage:i="Campo requerido",invalidMessage:s="Campo no válido",events:a}=e;"on"in n&&(n.on(t.EventName.CHANGE,(e=>{ie({eventName:"onChange",data:e,events:a}),oe({element:n,errorStyles:o,color:"transparent"})})),n.on(t.EventName.BLUR,(e=>{if(ie({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?i:""!=r?`El campo ${r} no es válido`:s;n.setError(t)}oe({element:n,errorStyles:o})})),n.on(t.EventName.FOCUS,(e=>{ie({eventName:"onFocus",data:e,events:a}),oe({element:n,errorStyles:o,color:"transparent"}),n.resetError()})))}function oe(e){const{element:t,errorStyles:n={},color:r=""}=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)),""!=r&&{color:r})})})}const ie=t=>{const{eventName:n,data:r,events:o}=t;if(o&&n in o){const t=o[n];"function"==typeof t&&t({elementType:e(r,"elementType",""),isEmpty:e(r,"isEmpty",""),isFocused:e(r,"isFocused",""),isValid:e(r,"isValid","")})}};function se(e){return n(this,void 0,void 0,(function*(){const{element:t,containerId:n,retries:r=2,delay:o=30}=e;for(let e=0;e<=r;e++){if(document.querySelector(n))return void t.mount(n);e<r&&(yield new Promise((e=>setTimeout(e,o))))}console.warn(`[mountCardFields] Container ${n} was not found after ${r+1} attempts`)}))}const ae=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"}),de={[ae.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[ae.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[ae.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[ae.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[ae.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[ae.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[ae.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[ae.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[ae.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[ae.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[ae.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[ae.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[ae.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[ae.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[ae.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[ae.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[ae.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[ae.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[ae.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[ae.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[ae.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[ae.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[ae.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[ae.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[ae.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[ae.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[ae.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[ae.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[ae.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[ae.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[ae.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[ae.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[ae.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},le=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return de[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class ce extends j{constructor({apiKey:e,mode:t,returnUrl:n,callBack:r,apiKeyTonder:o,baseUrlTonder:i,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:n,callBack:r,apiKeyTonder:o,baseUrlTonder:i,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe"}),this.activeAPMs=[],this.mountedElementsByContext=new Map,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 _({message:d.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:r,business:o}=this.merchantData,i=yield ne({vault_id:n,vault_url:r,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==o?void 0:o.pk,i)}catch(e){throw _({message:d.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 _({message:d.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},le(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw _({message:d.getPaymentMethodsError},e)}}))}mountCardFields(e){var r;return n(this,void 0,void 0,(function*(){const o=e.card_id?`update:${e.card_id}`:"create",i=null!==(r=e.unmount_context)&&void 0!==r?r:"all";"none"!==i&&("current"===i?this.unmountCardFields(o):this.unmountCardFields(i)),yield this.createSkyflowInstance();const s=yield function(e){var r,o,i,s,a,d,l,c,u,h,E,p,_,m,R,y,v;return n(this,void 0,void 0,(function*(){const{skyflowInstance:n,data:A,customization:f,events:O}=e,T=n.container(t.ContainerType.COLLECT),g=[],I={[k.CVV]:t.ElementType.CVV,[k.CARD_NUMBER]:t.ElementType.CARD_NUMBER,[k.EXPIRATION_MONTH]:t.ElementType.EXPIRATION_MONTH,[k.EXPIRATION_YEAR]:t.ElementType.EXPIRATION_YEAR,[k.CARDHOLDER_NAME]:t.ElementType.CARDHOLDER_NAME},C={[k.CVV]:[x],[k.CARD_NUMBER]:[x],[k.EXPIRATION_MONTH]:[x],[k.EXPIRATION_YEAR]:[x],[k.CARDHOLDER_NAME]:[K,x]},S={errorStyles:(null===(o=null===(r=null==f?void 0:f.styles)||void 0===r?void 0:r.cardForm)||void 0===o?void 0:o.errorStyles)||te,inputStyles:(null===(s=null===(i=null==f?void 0:f.styles)||void 0===i?void 0:i.cardForm)||void 0===s?void 0:s.inputStyles)||Z,labelStyles:(null===(d=null===(a=null==f?void 0:f.styles)||void 0===a?void 0:a.cardForm)||void 0===d?void 0:d.labelStyles)||ee},N={name:(null===(l=null==f?void 0:f.labels)||void 0===l?void 0:l.name)||B,card_number:(null===(c=null==f?void 0:f.labels)||void 0===c?void 0:c.card_number)||$,cvv:(null===(u=null==f?void 0:f.labels)||void 0===u?void 0:u.cvv)||Y,expiration_date:(null===(h=null==f?void 0:f.labels)||void 0===h?void 0:h.expiry_date)||W,expiration_month:(null===(E=null==f?void 0:f.labels)||void 0===E?void 0:E.expiration_month)||H,expiration_year:(null===(p=null==f?void 0:f.labels)||void 0===p?void 0:p.expiration_year)||z},b={name:(null===(_=null==f?void 0:f.placeholders)||void 0===_?void 0:_.name)||Q,card_number:(null===(m=null==f?void 0:f.placeholders)||void 0===m?void 0:m.card_number)||q,cvv:(null===(R=null==f?void 0:f.placeholders)||void 0===R?void 0:R.cvv)||J,expiration_month:(null===(y=null==f?void 0:f.placeholders)||void 0===y?void 0:y.expiration_month)||X,expiration_year:(null===(v=null==f?void 0:f.placeholders)||void 0===v?void 0:v.expiration_year)||G},D={[k.CVV]:null==O?void 0:O.cvvEvents,[k.CARD_NUMBER]:null==O?void 0:O.cardNumberEvents,[k.EXPIRATION_MONTH]:null==O?void 0:O.monthEvents,[k.EXPIRATION_YEAR]:null==O?void 0:O.yearEvents,[k.CARDHOLDER_NAME]:null==O?void 0:O.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:I[e],validations:C[e]},S),{label:N[e],placeholder:b[e]}),A.card_id?{skyflowID:A.card_id}:{}));re({element:t,errorStyles:S.errorStyles,fieldMessage:[k.CVV,k.EXPIRATION_MONTH,k.EXPIRATION_YEAR].includes(e)?"":N[e],events:D[e]});const n=`#collect_${String(e)}`+(A.card_id?`_${A.card_id}`:"");yield se({element:t,containerId:n}),g.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:I[t],validations:C[t]},S),{label:N[t],placeholder:b[t]}),A.card_id?{skyflowID:A.card_id}:{})),r=e.container_id||`#collect_${String(t)}`+(A.card_id?`_${A.card_id}`:"");yield se({element:n,containerId:r}),g.push({element:n,containerId:r})}return{elements:g.map((e=>e.element)),container:T}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events});this.mountedElementsByContext.set(o,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const n=`update:${e}`,r=this.mountedElementsByContext.get(n);return(null===(t=null==r?void 0:r.container)||void 0===t?void 0:t.container)||null}unmountCardFields(e="all"){"all"===e?(this.mountedElementsByContext.forEach(((e,t)=>{this.unmountContext(t)})),this.mountedElementsByContext.clear()):(this.unmountContext(e),this.mountedElementsByContext.delete(e))}unmountContext(e){const t=this.mountedElementsByContext.get(e);if(!t)return;const{elements:n}=t;n&&n.length>0&&n.forEach((t=>{try{t&&"function"==typeof t.unmount&&t.unmount()}catch(t){console.warn(`Error unmounting Skyflow element from context '${e}':`,t)}}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw _({message:d.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:r}=this.merchantData;this.skyflowInstance=yield function({baseUrl:e,apiKey:r,vault_id:o,vault_url:i}){return n(this,void 0,void 0,(function*(){return t.init({vaultID:o,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield V(e,r)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}})}))}({vault_id:e,vault_url:r,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}getOpenpayDeviceSessionID(e,t,r){return n(this,void 0,void 0,(function*(){try{return yield v(e,t,r)}catch(e){throw E(e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:r}){return n(this,void 0,void 0,(function*(){return yield ne({vault_id:e,vault_url:t,data:r,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:t,isSandbox:r,returnUrl:o}){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:d}=this.merchantData;let l;if(!t)if("string"==typeof e){const t=this.getContainerByCardId(e);try{t&&(yield t.collect())}catch(e){if(t){const t=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.description;throw new c({code:a.MOUNT_COLLECT_ERROR,details:{message:t}})}}l={skyflow_id:e}}else l=yield ne({vault_id:s,vault_url:d,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:l,payment_method:t,customer:n,isSandbox:r,returnUrl:o})}))}customerRegister(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,n={email:e},r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(n)});if(r.ok)return yield r.json();throw yield p(r)}catch(e){throw E(e)}}))}createOrder(e){return n(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,n=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(r.ok)return yield r.json();throw yield p(r)}catch(e){throw E(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,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(r.ok)return yield r.json();throw yield p(r)}catch(e){throw E(e)}}))}startCheckoutRouter(e){return n(this,void 0,void 0,(function*(){const t=yield y(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:r,skyflowTokens:o,return_url:i,isSandbox:a,metadata:d,currency:l,payment_method:c}=e,h=yield this._fetchMerchantData(),E=yield this.customerRegister(r.email);if(!(E&&"auth_token"in E&&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:E.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:t.items},p=yield this.createOrder(e),_=(new Date).toISOString();if(!("id"in p&&"id"in E&&"business"in h))throw new s({code:"500",body:p,name:"Keys error",message:"Order response errors"});{const e={business_pk:h.business.pk,amount:n,date:_,order_id:p.id,client_id:E.id},t=yield this.createPayment(e);let s;const{openpay_keys:m,business:R}=h;m.merchant_id&&m.public_key&&(s=yield v(m.merchant_id,m.public_key,a));const A=Object.assign(Object.assign({name:r.name,last_name:r.lastname,email_client:r.email,phone_number:r.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 p&&p.id,business_id:R.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:u(),currency:l},c?{payment_method:c}:{card:o}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),f=yield y(this.baseUrl,this.apiKeyTonder,A);if(yield this.init3DSRedirect(f))return f}}}catch(e){throw E(e)}}))}registerCustomerCard(e,t,r){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${h(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":t,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},r))});if(n.ok)return yield n.json();throw yield p(n)}catch(e){throw E(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/${h(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 p(n)}catch(e){throw E(e)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const e=yield function(e,t,r="?status=active&page_size=10000&country=México",o=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${e}/api/v1/payment_methods${r}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:o});if(n.ok)return yield n.json();throw yield p(n)}catch(e){throw E(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},le(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function ue(e){return/^\d{12,19}$/.test(e)&&me(e)}function he(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function Ee(e){return/^\d{3,4}$/.test(e)}function pe(e){return/^(0[1-9]|1[0-2])$/.test(e)}function _e(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const me=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),n=t.shift();let r=t.reduce(((e,t,n)=>n%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return r+=n,r%10==0};export{j as BaseInlineCheckout,ce as LiteCheckout,Ee as validateCVV,ue as validateCardNumber,he as validateCardholderName,pe as validateExpirationMonth,_e as validateExpirationYear};
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
export interface AcquirerInstance {
|
|
2
|
+
requestSecureInit: (params: SecureInitParams, callback: (response: SecureInitResponse | AcquirerErrorResponse) => void) => void;
|
|
3
|
+
requestValidate3DS: (params: Validate3DSParams, callback: (response: Validate3DSResponse | AcquirerErrorResponse) => void) => void;
|
|
4
|
+
}
|
|
5
|
+
export interface SecureInitParams {
|
|
6
|
+
card: {
|
|
7
|
+
number: string;
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
export interface SecureInitResponse {
|
|
11
|
+
jwt: string;
|
|
12
|
+
}
|
|
13
|
+
export interface Validate3DSParams {
|
|
14
|
+
secureId: string;
|
|
15
|
+
security: SecurityInfo;
|
|
16
|
+
}
|
|
17
|
+
export interface Validate3DSResponse {
|
|
18
|
+
code?: string;
|
|
19
|
+
message?: string;
|
|
20
|
+
isValid?: boolean;
|
|
21
|
+
}
|
|
22
|
+
export interface AcquirerErrorResponse {
|
|
23
|
+
code: string;
|
|
24
|
+
message: string;
|
|
25
|
+
}
|
|
26
|
+
export interface SecurityInfo {
|
|
27
|
+
acsURL: string;
|
|
28
|
+
authenticationTransactionId: string;
|
|
29
|
+
authRequired: boolean;
|
|
30
|
+
paReq: string;
|
|
31
|
+
specificationVersion: string;
|
|
32
|
+
}
|
|
33
|
+
export interface CardOnFileTokenRequest {
|
|
34
|
+
card: {
|
|
35
|
+
name: string;
|
|
36
|
+
number: string;
|
|
37
|
+
expiryMonth: string;
|
|
38
|
+
expiryYear: string;
|
|
39
|
+
cvv: string;
|
|
40
|
+
};
|
|
41
|
+
currency: string;
|
|
42
|
+
jwt: string;
|
|
43
|
+
}
|
|
44
|
+
export interface CardOnFileTokenResponse {
|
|
45
|
+
token: string;
|
|
46
|
+
secureId?: string;
|
|
47
|
+
secureService?: string;
|
|
48
|
+
security?: SecurityInfo;
|
|
49
|
+
details?: {
|
|
50
|
+
secureId?: string;
|
|
51
|
+
security?: SecurityInfo;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
export interface CardOnFileSubscriptionRequest {
|
|
55
|
+
token: string;
|
|
56
|
+
contactDetails: {
|
|
57
|
+
firstName: string;
|
|
58
|
+
lastName: string;
|
|
59
|
+
email: string;
|
|
60
|
+
};
|
|
61
|
+
metadata: {
|
|
62
|
+
customerId: string;
|
|
63
|
+
notes?: string;
|
|
64
|
+
};
|
|
65
|
+
currency: string;
|
|
66
|
+
}
|
|
67
|
+
export interface CardOnFileSubscriptionResponse {
|
|
68
|
+
details: {
|
|
69
|
+
amount: {
|
|
70
|
+
subtotalIva: number;
|
|
71
|
+
subtotalIva0: number;
|
|
72
|
+
ice: number;
|
|
73
|
+
iva: number;
|
|
74
|
+
currency: string;
|
|
75
|
+
};
|
|
76
|
+
binCard: string;
|
|
77
|
+
binInfo: {
|
|
78
|
+
bank: string;
|
|
79
|
+
type: string;
|
|
80
|
+
};
|
|
81
|
+
cardHolderName: string;
|
|
82
|
+
contactDetails: {
|
|
83
|
+
firstName: string;
|
|
84
|
+
lastName: string;
|
|
85
|
+
email: string;
|
|
86
|
+
};
|
|
87
|
+
created: string;
|
|
88
|
+
lastFourDigits: string;
|
|
89
|
+
maskedCreditCard: string;
|
|
90
|
+
merchantId: string;
|
|
91
|
+
merchantName: string;
|
|
92
|
+
paymentBrand: string;
|
|
93
|
+
periodicity: string;
|
|
94
|
+
planName: string;
|
|
95
|
+
processorBankName: string;
|
|
96
|
+
startDate: string;
|
|
97
|
+
};
|
|
98
|
+
subscriptionId: string;
|
|
99
|
+
}
|
|
100
|
+
export interface SkyflowCollectFields {
|
|
101
|
+
card_number: string;
|
|
102
|
+
cvv: string;
|
|
103
|
+
expiration_month: string;
|
|
104
|
+
expiration_year: string;
|
|
105
|
+
cardholder_name: string;
|
|
106
|
+
skyflow_id: string;
|
|
107
|
+
[key: string]: string;
|
|
108
|
+
}
|
|
109
|
+
export interface SkyflowCollectRecord {
|
|
110
|
+
fields: SkyflowCollectFields;
|
|
111
|
+
}
|
|
112
|
+
export interface SkyflowCollectResponse {
|
|
113
|
+
records?: SkyflowCollectRecord[];
|
|
114
|
+
}
|
|
115
|
+
export interface CardTokens {
|
|
116
|
+
name: string;
|
|
117
|
+
number: string;
|
|
118
|
+
expiryMonth: string;
|
|
119
|
+
expiryYear: string;
|
|
120
|
+
cvv: string;
|
|
121
|
+
}
|
|
122
|
+
export interface ContactDetails {
|
|
123
|
+
firstName: string;
|
|
124
|
+
lastName: string;
|
|
125
|
+
email: string;
|
|
126
|
+
}
|
|
127
|
+
export interface ProcessParams {
|
|
128
|
+
cardTokens: CardTokens;
|
|
129
|
+
cardBin: string;
|
|
130
|
+
contactDetails: ContactDetails;
|
|
131
|
+
customerId: string;
|
|
132
|
+
currency: string;
|
|
133
|
+
}
|
package/dist/types/commons.d.ts
CHANGED
|
@@ -7,6 +7,10 @@ import CollectElement from "skyflow-js/types/core/external/collect/collect-eleme
|
|
|
7
7
|
import ComposableElement from "skyflow-js/types/core/external/collect/compose-collect-element";
|
|
8
8
|
import RevealElement from "skyflow-js/types/core/external/reveal/reveal-element";
|
|
9
9
|
import { LabelStyles } from "skyflow-js/types/utils/common";
|
|
10
|
+
export type CardOnFileKeys = {
|
|
11
|
+
merchant_id: string;
|
|
12
|
+
public_key: string;
|
|
13
|
+
};
|
|
10
14
|
export type Business = {
|
|
11
15
|
business: {
|
|
12
16
|
pk: number;
|
|
@@ -39,6 +43,7 @@ export type Business = {
|
|
|
39
43
|
vault_url: string;
|
|
40
44
|
reference: number;
|
|
41
45
|
is_installments_available: boolean;
|
|
46
|
+
cardonfile_keys?: CardOnFileKeys;
|
|
42
47
|
};
|
|
43
48
|
export type Customer = {
|
|
44
49
|
firstName: string;
|
package/package.json
CHANGED
|
@@ -35,6 +35,7 @@ import {GetSecureTokenResponse} from "../types/responses";
|
|
|
35
35
|
import {getSecureToken} from "../data/tokenApi";
|
|
36
36
|
import {MESSAGES} from "../shared/constants/messages";
|
|
37
37
|
import { IMPConfigRequest } from "../types/mercadoPago";
|
|
38
|
+
import { CardOnFile } from "../helpers/card_on_file";
|
|
38
39
|
export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOptions> {
|
|
39
40
|
baseUrl = "";
|
|
40
41
|
cartTotal: string | number = "0";
|
|
@@ -58,6 +59,7 @@ export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOp
|
|
|
58
59
|
order_reference?: string | null = null;
|
|
59
60
|
card? = {};
|
|
60
61
|
currency?: string = "";
|
|
62
|
+
protected cardOnFileInstance: CardOnFile | null = null;
|
|
61
63
|
#apm_config?:IMPConfigRequest | Record<string, any>
|
|
62
64
|
#customerData?: Record<string, any>;
|
|
63
65
|
|
|
@@ -153,6 +155,10 @@ export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOp
|
|
|
153
155
|
) {
|
|
154
156
|
injectMercadoPagoSecurity();
|
|
155
157
|
}
|
|
158
|
+
|
|
159
|
+
if (this._hasCardOnFileKeys()) {
|
|
160
|
+
await this._initializeCardOnFile();
|
|
161
|
+
}
|
|
156
162
|
}
|
|
157
163
|
|
|
158
164
|
async _checkout(data: any): Promise<any> {
|
|
@@ -184,16 +190,16 @@ export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOp
|
|
|
184
190
|
payment_method,
|
|
185
191
|
customer,
|
|
186
192
|
isSandbox,
|
|
187
|
-
|
|
193
|
+
enable_card_on_file,
|
|
188
194
|
// TODO: DEPRECATED
|
|
189
195
|
returnUrl: returnUrlData
|
|
190
196
|
}: {
|
|
191
|
-
card?: string
|
|
197
|
+
card?: Record<string, any>;
|
|
192
198
|
payment_method?: string;
|
|
193
199
|
customer: Record<string, any>;
|
|
194
200
|
isSandbox?: boolean;
|
|
195
201
|
returnUrl?: string;
|
|
196
|
-
|
|
202
|
+
enable_card_on_file?: boolean;
|
|
197
203
|
}) {
|
|
198
204
|
const { openpay_keys, reference, business } = this.merchantData!;
|
|
199
205
|
const total = Number(this.cartTotal);
|
|
@@ -286,7 +292,7 @@ export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOp
|
|
|
286
292
|
...(!!payment_method ? { payment_method } : { card }),
|
|
287
293
|
apm_config: this.#apm_config,
|
|
288
294
|
...(this.customer && "identification" in this.customer ? { identification: this.customer.identification } : {}),
|
|
289
|
-
...(!!
|
|
295
|
+
...(!!enable_card_on_file ? { enable_card_on_file } : {}),
|
|
290
296
|
};
|
|
291
297
|
|
|
292
298
|
const jsonResponseRouter = await startCheckoutRouter(
|
|
@@ -372,6 +378,23 @@ export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOp
|
|
|
372
378
|
return await fetchCustomerPaymentMethods(this.baseUrl, this.apiKeyTonder);
|
|
373
379
|
}
|
|
374
380
|
|
|
381
|
+
protected _hasCardOnFileKeys(): boolean {
|
|
382
|
+
return !!this.merchantData?.cardonfile_keys?.public_key;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
protected async _initializeCardOnFile(): Promise<CardOnFile> {
|
|
386
|
+
if (!this.cardOnFileInstance) {
|
|
387
|
+
this.cardOnFileInstance = new CardOnFile({
|
|
388
|
+
merchantId: this.merchantData?.cardonfile_keys!.public_key!,
|
|
389
|
+
apiKey: this.apiKeyTonder,
|
|
390
|
+
isTestEnvironment: this.mode !== "production",
|
|
391
|
+
});
|
|
392
|
+
await this.cardOnFileInstance.initialize();
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
return this.cardOnFileInstance;
|
|
396
|
+
}
|
|
397
|
+
|
|
375
398
|
#handleCustomer(customer: ICustomer | { email: string }) {
|
|
376
399
|
if (!customer) return;
|
|
377
400
|
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AcquirerInstance,
|
|
3
|
+
CardOnFileSubscriptionRequest,
|
|
4
|
+
CardOnFileSubscriptionResponse,
|
|
5
|
+
CardOnFileTokenRequest,
|
|
6
|
+
CardOnFileTokenResponse,
|
|
7
|
+
ProcessParams,
|
|
8
|
+
SecureInitResponse,
|
|
9
|
+
SecurityInfo,
|
|
10
|
+
Validate3DSResponse,
|
|
11
|
+
} from "../types/cardOnFile";
|
|
12
|
+
|
|
13
|
+
declare global {
|
|
14
|
+
interface Window {
|
|
15
|
+
// External acquirer SDK (Kushki)
|
|
16
|
+
Kushki: new (config: { merchantId: string; inTestEnvironment: boolean }) => AcquirerInstance;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// ============ Helper Functions ============
|
|
21
|
+
|
|
22
|
+
const ACQUIRER_SCRIPT_URL = "https://cdn.kushkipagos.com/kushki.min.js";
|
|
23
|
+
|
|
24
|
+
let acquirerScriptLoaded = false;
|
|
25
|
+
let acquirerScriptPromise: Promise<void> | null = null;
|
|
26
|
+
|
|
27
|
+
async function loadAcquirerScript(): Promise<void> {
|
|
28
|
+
if (acquirerScriptLoaded) {
|
|
29
|
+
return Promise.resolve();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (acquirerScriptPromise) {
|
|
33
|
+
return acquirerScriptPromise;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
acquirerScriptPromise = new Promise((resolve, reject) => {
|
|
37
|
+
const existingScript = document.querySelector(`script[src="${ACQUIRER_SCRIPT_URL}"]`);
|
|
38
|
+
|
|
39
|
+
if (existingScript) {
|
|
40
|
+
acquirerScriptLoaded = true;
|
|
41
|
+
resolve();
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const script = document.createElement("script");
|
|
46
|
+
script.src = ACQUIRER_SCRIPT_URL;
|
|
47
|
+
script.async = true;
|
|
48
|
+
|
|
49
|
+
script.onload = () => {
|
|
50
|
+
acquirerScriptLoaded = true;
|
|
51
|
+
resolve();
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
script.onerror = () => {
|
|
55
|
+
acquirerScriptPromise = null;
|
|
56
|
+
reject(new Error("Failed to load acquirer script"));
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
document.head.appendChild(script);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
return acquirerScriptPromise;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function createAcquirerInstance(
|
|
66
|
+
merchantId: string,
|
|
67
|
+
isTestEnvironment: boolean
|
|
68
|
+
): AcquirerInstance {
|
|
69
|
+
if (!window.Kushki) {
|
|
70
|
+
throw new Error("Acquirer script not loaded. Call initialize() first.");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return new window.Kushki({
|
|
74
|
+
merchantId,
|
|
75
|
+
inTestEnvironment: isTestEnvironment,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ============ Constants ============
|
|
80
|
+
|
|
81
|
+
const ACQ_API_URL_STAGE = "https://api-stage.tonder.io";
|
|
82
|
+
const ACQ_API_URL_PROD = "https://api.tonder.io";
|
|
83
|
+
|
|
84
|
+
// ============ CardOnFile Class ============
|
|
85
|
+
|
|
86
|
+
export class CardOnFile {
|
|
87
|
+
private readonly apiUrl: string;
|
|
88
|
+
private readonly merchantId: string;
|
|
89
|
+
private readonly apiKey: string;
|
|
90
|
+
private readonly isTestEnvironment: boolean;
|
|
91
|
+
private acquirerInstance: AcquirerInstance | null = null;
|
|
92
|
+
|
|
93
|
+
constructor(config: {
|
|
94
|
+
merchantId: string;
|
|
95
|
+
apiKey: string;
|
|
96
|
+
isTestEnvironment?: boolean;
|
|
97
|
+
}) {
|
|
98
|
+
this.isTestEnvironment = config.isTestEnvironment ?? true;
|
|
99
|
+
this.apiUrl = this.isTestEnvironment ? ACQ_API_URL_STAGE : ACQ_API_URL_PROD;
|
|
100
|
+
this.merchantId = config.merchantId;
|
|
101
|
+
this.apiKey = config.apiKey;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async initialize(): Promise<void> {
|
|
105
|
+
await loadAcquirerScript();
|
|
106
|
+
this.acquirerInstance = createAcquirerInstance(
|
|
107
|
+
this.merchantId,
|
|
108
|
+
this.isTestEnvironment
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private getAcquirerInstance(): AcquirerInstance {
|
|
113
|
+
if (!this.acquirerInstance) {
|
|
114
|
+
throw new Error("CardOnFile not initialized. Call initialize() first.");
|
|
115
|
+
}
|
|
116
|
+
return this.acquirerInstance;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Get JWT for 3DS authentication
|
|
121
|
+
* @param cardBin - First 8 digits of the card number
|
|
122
|
+
*/
|
|
123
|
+
async getJwt(cardBin: string): Promise<string> {
|
|
124
|
+
const acquirer = this.getAcquirerInstance();
|
|
125
|
+
|
|
126
|
+
return new Promise<string>((resolve, reject) => {
|
|
127
|
+
acquirer.requestSecureInit(
|
|
128
|
+
{
|
|
129
|
+
card: {
|
|
130
|
+
number: cardBin,
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
(response) => {
|
|
134
|
+
if ("code" in response && response.code) {
|
|
135
|
+
reject(new Error(`Error getting JWT: ${response.message}`));
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const successResponse = response as SecureInitResponse;
|
|
140
|
+
if (!successResponse.jwt) {
|
|
141
|
+
reject(new Error("No JWT returned from acquirer"));
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
resolve(successResponse.jwt);
|
|
146
|
+
}
|
|
147
|
+
);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Generate a recurring charge token
|
|
153
|
+
*/
|
|
154
|
+
async generateToken(request: CardOnFileTokenRequest): Promise<CardOnFileTokenResponse> {
|
|
155
|
+
const response = await fetch(
|
|
156
|
+
`${this.apiUrl}/acq-kushki/subscription/token`,
|
|
157
|
+
{
|
|
158
|
+
method: "POST",
|
|
159
|
+
headers: {
|
|
160
|
+
"Content-Type": "application/json",
|
|
161
|
+
Authorization: `Token ${this.apiKey}`,
|
|
162
|
+
},
|
|
163
|
+
body: JSON.stringify(request),
|
|
164
|
+
}
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
if (!response.ok) {
|
|
168
|
+
const errorText = await response.text();
|
|
169
|
+
throw new Error(`Failed to generate token: ${response.status} - ${errorText}`);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return response.json() as Promise<CardOnFileTokenResponse>;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Create a subscription with the generated token
|
|
177
|
+
*/
|
|
178
|
+
async createSubscription(request: CardOnFileSubscriptionRequest): Promise<CardOnFileSubscriptionResponse> {
|
|
179
|
+
const response = await fetch(
|
|
180
|
+
`${this.apiUrl}/acq-kushki/subscription/create`,
|
|
181
|
+
{
|
|
182
|
+
method: "POST",
|
|
183
|
+
headers: {
|
|
184
|
+
"Content-Type": "application/json",
|
|
185
|
+
Authorization: `Token ${this.apiKey}`,
|
|
186
|
+
},
|
|
187
|
+
body: JSON.stringify(request),
|
|
188
|
+
}
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
if (!response.ok) {
|
|
192
|
+
const errorText = await response.text();
|
|
193
|
+
throw new Error(`Failed to create subscription: ${response.status} - ${errorText}`);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return response.json() as Promise<CardOnFileSubscriptionResponse>;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Validate 3DS challenge
|
|
201
|
+
* @returns true if validation passed, throws error otherwise
|
|
202
|
+
*/
|
|
203
|
+
async validate3DS(
|
|
204
|
+
secureId: string,
|
|
205
|
+
security: SecurityInfo
|
|
206
|
+
): Promise<boolean> {
|
|
207
|
+
const acquirer = this.getAcquirerInstance();
|
|
208
|
+
|
|
209
|
+
return new Promise<boolean>((resolve, reject) => {
|
|
210
|
+
acquirer.requestValidate3DS(
|
|
211
|
+
{
|
|
212
|
+
secureId,
|
|
213
|
+
security,
|
|
214
|
+
},
|
|
215
|
+
(response) => {
|
|
216
|
+
const validResponse = response as Validate3DSResponse;
|
|
217
|
+
// Check for error code
|
|
218
|
+
if (validResponse.code && validResponse.code !== "3DS000") {
|
|
219
|
+
reject(new Error(`3DS validation failed}`));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Check isValid flag if present
|
|
224
|
+
if (validResponse.isValid === false) {
|
|
225
|
+
reject(new Error("3DS validation failed"));
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
resolve(true);
|
|
230
|
+
}
|
|
231
|
+
);
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Complete flow: JWT → Token → 3DS validation → Subscription
|
|
237
|
+
*/
|
|
238
|
+
async process(params: ProcessParams): Promise<CardOnFileSubscriptionResponse> {
|
|
239
|
+
const jwt = await this.getJwt(params.cardBin);
|
|
240
|
+
const tokenResponse = await this.generateToken({
|
|
241
|
+
card: params.cardTokens,
|
|
242
|
+
currency: params.currency,
|
|
243
|
+
jwt,
|
|
244
|
+
});
|
|
245
|
+
// Handle both response structures: root level or nested in details
|
|
246
|
+
const secureId = tokenResponse.secureId || tokenResponse.details?.secureId;
|
|
247
|
+
const security = tokenResponse.security || tokenResponse.details?.security;
|
|
248
|
+
|
|
249
|
+
// Validate 3DS is required
|
|
250
|
+
if (!secureId || !security) {
|
|
251
|
+
throw new Error("Missing secureId or security in token response");
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Validate 3DS - throws error if validation fails
|
|
255
|
+
await this.validate3DS(secureId, security);
|
|
256
|
+
|
|
257
|
+
// Only continue to subscription if 3DS validation passed
|
|
258
|
+
return this.createSubscription({
|
|
259
|
+
token: tokenResponse.token,
|
|
260
|
+
contactDetails: params.contactDetails,
|
|
261
|
+
metadata: {
|
|
262
|
+
customerId: params.customerId,
|
|
263
|
+
},
|
|
264
|
+
currency: params.currency,
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
export interface AcquirerInstance {
|
|
2
|
+
requestSecureInit: (
|
|
3
|
+
params: SecureInitParams,
|
|
4
|
+
callback: (response: SecureInitResponse | AcquirerErrorResponse) => void
|
|
5
|
+
) => void;
|
|
6
|
+
requestValidate3DS: (
|
|
7
|
+
params: Validate3DSParams,
|
|
8
|
+
callback: (response: Validate3DSResponse | AcquirerErrorResponse) => void
|
|
9
|
+
) => void;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface SecureInitParams {
|
|
13
|
+
card: {
|
|
14
|
+
number: string;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface SecureInitResponse {
|
|
19
|
+
jwt: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface Validate3DSParams {
|
|
23
|
+
secureId: string;
|
|
24
|
+
security: SecurityInfo;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface Validate3DSResponse {
|
|
28
|
+
code?: string;
|
|
29
|
+
message?: string;
|
|
30
|
+
isValid?: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface AcquirerErrorResponse {
|
|
34
|
+
code: string;
|
|
35
|
+
message: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface SecurityInfo {
|
|
39
|
+
acsURL: string;
|
|
40
|
+
authenticationTransactionId: string;
|
|
41
|
+
authRequired: boolean;
|
|
42
|
+
paReq: string;
|
|
43
|
+
specificationVersion: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface CardOnFileTokenRequest {
|
|
47
|
+
card: {
|
|
48
|
+
name: string;
|
|
49
|
+
number: string;
|
|
50
|
+
expiryMonth: string;
|
|
51
|
+
expiryYear: string;
|
|
52
|
+
cvv: string;
|
|
53
|
+
};
|
|
54
|
+
currency: string;
|
|
55
|
+
jwt: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface CardOnFileTokenResponse {
|
|
59
|
+
token: string;
|
|
60
|
+
secureId?: string;
|
|
61
|
+
secureService?: string;
|
|
62
|
+
security?: SecurityInfo;
|
|
63
|
+
details?: {
|
|
64
|
+
secureId?: string;
|
|
65
|
+
security?: SecurityInfo;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface CardOnFileSubscriptionRequest {
|
|
70
|
+
token: string;
|
|
71
|
+
contactDetails: {
|
|
72
|
+
firstName: string;
|
|
73
|
+
lastName: string;
|
|
74
|
+
email: string;
|
|
75
|
+
};
|
|
76
|
+
metadata: {
|
|
77
|
+
customerId: string;
|
|
78
|
+
notes?: string;
|
|
79
|
+
};
|
|
80
|
+
currency: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface CardOnFileSubscriptionResponse {
|
|
84
|
+
details: {
|
|
85
|
+
amount: {
|
|
86
|
+
subtotalIva: number;
|
|
87
|
+
subtotalIva0: number;
|
|
88
|
+
ice: number;
|
|
89
|
+
iva: number;
|
|
90
|
+
currency: string;
|
|
91
|
+
};
|
|
92
|
+
binCard: string;
|
|
93
|
+
binInfo: {
|
|
94
|
+
bank: string;
|
|
95
|
+
type: string;
|
|
96
|
+
};
|
|
97
|
+
cardHolderName: string;
|
|
98
|
+
contactDetails: {
|
|
99
|
+
firstName: string;
|
|
100
|
+
lastName: string;
|
|
101
|
+
email: string;
|
|
102
|
+
};
|
|
103
|
+
created: string;
|
|
104
|
+
lastFourDigits: string;
|
|
105
|
+
maskedCreditCard: string;
|
|
106
|
+
merchantId: string;
|
|
107
|
+
merchantName: string;
|
|
108
|
+
paymentBrand: string;
|
|
109
|
+
periodicity: string;
|
|
110
|
+
planName: string;
|
|
111
|
+
processorBankName: string;
|
|
112
|
+
startDate: string;
|
|
113
|
+
};
|
|
114
|
+
subscriptionId: string;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface SkyflowCollectFields {
|
|
118
|
+
card_number: string;
|
|
119
|
+
cvv: string;
|
|
120
|
+
expiration_month: string;
|
|
121
|
+
expiration_year: string;
|
|
122
|
+
cardholder_name: string;
|
|
123
|
+
skyflow_id: string;
|
|
124
|
+
[key: string]: string;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface SkyflowCollectRecord {
|
|
128
|
+
fields: SkyflowCollectFields;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export interface SkyflowCollectResponse {
|
|
132
|
+
records?: SkyflowCollectRecord[];
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export interface CardTokens {
|
|
136
|
+
name: string;
|
|
137
|
+
number: string;
|
|
138
|
+
expiryMonth: string;
|
|
139
|
+
expiryYear: string;
|
|
140
|
+
cvv: string;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export interface ContactDetails {
|
|
144
|
+
firstName: string;
|
|
145
|
+
lastName: string;
|
|
146
|
+
email: string;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface ProcessParams {
|
|
150
|
+
cardTokens: CardTokens;
|
|
151
|
+
cardBin: string;
|
|
152
|
+
contactDetails: ContactDetails;
|
|
153
|
+
customerId: string;
|
|
154
|
+
currency: string;
|
|
155
|
+
}
|
package/src/types/commons.ts
CHANGED
|
@@ -8,6 +8,10 @@ import ComposableElement from "skyflow-js/types/core/external/collect/compose-co
|
|
|
8
8
|
import RevealElement from "skyflow-js/types/core/external/reveal/reveal-element";
|
|
9
9
|
import {LabelStyles} from "skyflow-js/types/utils/common";
|
|
10
10
|
|
|
11
|
+
export type CardOnFileKeys = {
|
|
12
|
+
merchant_id: string;
|
|
13
|
+
public_key: string;
|
|
14
|
+
}
|
|
11
15
|
|
|
12
16
|
export type Business = {
|
|
13
17
|
business: {
|
|
@@ -41,6 +45,7 @@ export type Business = {
|
|
|
41
45
|
vault_url: string;
|
|
42
46
|
reference: number;
|
|
43
47
|
is_installments_available: boolean;
|
|
48
|
+
cardonfile_keys?: CardOnFileKeys;
|
|
44
49
|
};
|
|
45
50
|
|
|
46
51
|
export type Customer = {
|