@tonder.io/ionic-lite-sdk 0.0.39-beta.1 → 0.0.41-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/classes/3dsHandler.d.ts +9 -1
- package/dist/classes/BaseInlineCheckout.d.ts +5 -3
- package/dist/index.js +1 -1
- package/dist/types/commons.d.ts +10 -0
- package/package.json +1 -1
- package/src/classes/3dsHandler.ts +102 -2
- package/src/classes/BaseInlineCheckout.ts +27 -4
- package/src/types/commons.ts +11 -0
package/README.md
CHANGED
|
@@ -43,7 +43,7 @@ import { LiteCheckout } from "@tonder.io/ionic-lite-sdk"
|
|
|
43
43
|
const liteCheckout = new LiteCheckout({
|
|
44
44
|
signal,
|
|
45
45
|
baseUrlTonder,
|
|
46
|
-
|
|
46
|
+
apiKeyTonder
|
|
47
47
|
})
|
|
48
48
|
|
|
49
49
|
// The configureCheckout function allows you to set initial information,
|
|
@@ -93,7 +93,7 @@ const paymentResponse = await liteCheckout.payment(paymentData);
|
|
|
93
93
|
| Property | Type | Description |
|
|
94
94
|
|:---------:|:--------:|:--------------------------------------------------------------------------------------------:|
|
|
95
95
|
| mode | string | Environment mode. Options: 'stage', 'production', 'sandbox', 'development'. Default: 'stage' |
|
|
96
|
-
|
|
|
96
|
+
| apiKey | string | Your API key from the Tonder Dashboard |
|
|
97
97
|
| returnrl | string | URL where the checkout form is mounted (used for 3DS) |
|
|
98
98
|
| callBack | function | Callback function to be invoked after the payment process ends successfully. |
|
|
99
99
|
|
|
@@ -1,14 +1,21 @@
|
|
|
1
|
+
import { CustomizationOptions } from "../types/commons";
|
|
1
2
|
type ThreeDSHandlerContructor = {
|
|
2
3
|
payload?: any;
|
|
3
4
|
apiKey?: string;
|
|
4
5
|
baseUrl?: string;
|
|
6
|
+
customization?: CustomizationOptions;
|
|
7
|
+
tdsIframeId?: string;
|
|
8
|
+
callBack?: (params: any) => any;
|
|
5
9
|
};
|
|
6
10
|
export declare class ThreeDSHandler {
|
|
11
|
+
callBack?: (params: any) => any;
|
|
7
12
|
baseUrl?: string;
|
|
8
13
|
apiKey?: string;
|
|
9
14
|
payload?: any;
|
|
10
15
|
localStorageKey: string;
|
|
11
|
-
|
|
16
|
+
customization: CustomizationOptions;
|
|
17
|
+
tdsIframeId?: string;
|
|
18
|
+
constructor({ payload, apiKey, baseUrl, customization, tdsIframeId, callBack }: ThreeDSHandlerContructor);
|
|
12
19
|
setStorageItem(data: any): void;
|
|
13
20
|
getStorageItem(): string | null;
|
|
14
21
|
removeStorageItem(): void;
|
|
@@ -20,6 +27,7 @@ export declare class ThreeDSHandler {
|
|
|
20
27
|
loadIframe(): Promise<unknown> | undefined;
|
|
21
28
|
getRedirectUrl(): any;
|
|
22
29
|
redirectToChallenge(): void;
|
|
30
|
+
requestTransactionStatus(): Promise<any>;
|
|
23
31
|
getURLParameters(): any;
|
|
24
32
|
handleSuccessTransaction(response: any): any;
|
|
25
33
|
handleDeclinedTransaction(response: any): any;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ThreeDSHandler } from "./3dsHandler";
|
|
2
|
-
import { Business, IConfigureCheckout, IInlineCheckoutBaseOptions } from "../types/commons";
|
|
2
|
+
import { Business, IConfigureCheckout, IInlineCheckoutBaseOptions, CustomizationOptions } from "../types/commons";
|
|
3
3
|
import { ICustomer } from "../types/customer";
|
|
4
4
|
import { IItem, IProcessPaymentRequest, IStartCheckoutResponse } from "../types/checkout";
|
|
5
5
|
import { ICustomerCardsResponse, ISaveCardResponse, ISaveCardSkyflowRequest } from "../types/card";
|
|
@@ -13,18 +13,20 @@ export declare class BaseInlineCheckout {
|
|
|
13
13
|
mode?: "production" | "sandbox" | "stage" | "development" | undefined;
|
|
14
14
|
apiKeyTonder: string;
|
|
15
15
|
returnUrl?: string;
|
|
16
|
+
tdsIframeId?: string;
|
|
16
17
|
callBack?: ((response: IStartCheckoutResponse | Record<string, any>) => void) | undefined;
|
|
17
18
|
merchantData?: Business;
|
|
18
19
|
abortController: AbortController;
|
|
19
|
-
secureToken: string
|
|
20
|
+
secureToken: string;
|
|
20
21
|
customer?: ICustomer | {
|
|
21
22
|
email: string;
|
|
22
23
|
};
|
|
24
|
+
customization: CustomizationOptions;
|
|
23
25
|
cartItems?: IItem[];
|
|
24
26
|
metadata: {};
|
|
25
27
|
card?: {} | undefined;
|
|
26
28
|
currency?: string;
|
|
27
|
-
constructor({ mode, apiKey, apiKeyTonder, returnUrl, callBack, baseUrlTonder }: IInlineCheckoutBaseOptions);
|
|
29
|
+
constructor({ mode, customization, apiKey, apiKeyTonder, returnUrl, tdsIframeId, callBack, baseUrlTonder }: IInlineCheckoutBaseOptions);
|
|
28
30
|
configureCheckout(data: IConfigureCheckout): void;
|
|
29
31
|
verify3dsTransaction(): Promise<ITransaction | IStartCheckoutResponse | void>;
|
|
30
32
|
payment(data: IProcessPaymentRequest): Promise<IStartCheckoutResponse>;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{get as t}from"lodash";import e from"skyflow-js";function n(t,e,n,o){return new(n||(n=Promise))((function(r,i){function s(t){try{d(o.next(t))}catch(t){i(t)}}function a(t){try{d(o.throw(t))}catch(t){i(t)}}function d(t){var e;t.done?r(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}d((o=o.apply(t,e||[])).next())}))}function o(t,e,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!o:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(t):o?o.value:e.get(t)}function r(t,e,o){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${t}/api/v1/payments/business/${e}`,{headers:{Authorization:`Token ${e}`},signal:o});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class i{constructor({code:t,body:e,name:n,message:o,stack:r}){this.code=t,this.body=e,this.name=n,this.message=o,this.stack=r}}const s=()=>({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}),a=t=>{var e;return t&&"business"in t?null===(e=null==t?void 0:t.business)||void 0===e?void 0:e.pk:""},d=t=>new i({code:(null==t?void 0:t.status)?t.status:t.code,body:null==t?void 0:t.body,name:t?"string"==typeof t?"catch":t.name:"Error",message:t?"string"==typeof t?t:t.message:"Error",stack:"string"==typeof t?void 0:t.stack}),l=(t,e=void 0)=>n(void 0,void 0,void 0,(function*(){let n,o,r="Error";t&&"json"in t&&(n=yield null==t?void 0:t.json()),t&&"status"in t&&(o=t.status.toString()),!n&&t&&"text"in t&&(r=yield t.text()),(null==n?void 0:n.detail)&&(r=n.detail);return new i({code:o,body:n,name:o,message:r,stack:e})}));function c(t,e){var n,o;let r=200;try{r=Number((null==e?void 0:e.code)||200)}catch(t){}const i={status:"error",code:r,message:"",detail:(null===(n=null==e?void 0:e.body)||void 0===n?void 0:n.detail)||(null===(o=null==e?void 0:e.body)||void 0===o?void 0:o.error)||e.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),t)}class u{constructor({payload:t=null,apiKey:e,baseUrl:n}){this.localStorageKey="verify_transaction_status_url",this.setPayload=t=>{this.payload=t},this.baseUrl=n,this.apiKey=e,this.payload=t}setStorageItem(t){return localStorage.setItem(this.localStorageKey,JSON.stringify(t))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var t,e,n,o,r,i;const s=null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const t=null===(i=null===(r=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;t?this.saveUrlWithExpiration(t):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(t){try{const e={url:t,expires:(new Date).getTime()+12e5};this.setStorageItem(e)}catch(t){console.log("error: ",t)}}getUrlWithExpiration(){const t=this.getStorageItem();if(t){const e=JSON.parse(t);if(!e)return;return(new Date).getTime()>e.expires?(this.removeVerifyTransactionUrl(),null):e.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var t,e,n;if(null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((t,e)=>{var n,o,r;const i=null===(r=null===(o=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(o);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>t(!0):(console.log("No redirection found"),e(!1))}else console.log("No redirection found"),e(!1)}))}getRedirectUrl(){var t,e,n;return null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const t=this.getRedirectUrl();t?(this.saveVerifyTransactionUrl(),window.location=t):console.log("No redirection found")}getURLParameters(){const t={},e=new URLSearchParams(window.location.search);for(const[n,o]of e)t[n]=o;return t}handleSuccessTransaction(t){return this.removeVerifyTransactionUrl(),console.log("Transacción autorizada."),t}handleDeclinedTransaction(t){return this.removeVerifyTransactionUrl(),t}handle3dsChallenge(t){return n(this,void 0,void 0,(function*(){const e=document.createElement("form");e.name="frm",e.method="POST",e.action=t.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=t.creq,n.value=t.creq,e.appendChild(n);const o=document.createElement("input");o.type="hidden",o.name=t.term_url,o.value=t.TermUrl,e.appendChild(o),document.body.appendChild(e),e.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(t){return n(this,void 0,void 0,(function*(){const e=yield t.json();return"Pending"===e.status&&e.redirect_post_url?yield this.handle3dsChallenge(e):["Success","Authorized"].includes(e.status)?this.handleSuccessTransaction(e):(this.handleDeclinedTransaction(t),e)}))}verifyTransactionStatus(){return n(this,void 0,void 0,(function*(){const t=this.getUrlWithExpiration();if(t){const e=`${this.baseUrl}${t}`;try{const t=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==t.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),t):yield this.handleTransactionResponse(t)}catch(t){console.error("Error al verificar la transacción:",t),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const h=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function p(t,e,o){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/checkout-router/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(Object.assign(Object.assign({},r),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.status>=200&&i.status<=299)return yield i.json();{const t=yield i.json(),e=new Error("Failed to start checkout router");throw e.details=t,e}}catch(t){throw t}}))}function m(t,e,o=!0,r=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(t),n.setApiKey(e),n.setSandboxMode(o),yield n.deviceData.setup({signal:r})}))}const y=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."});var f,g,v,_,A,b,E,T,C;class O{constructor({mode:t="stage",apiKey:e,apiKeyTonder:n,returnUrl:o,callBack:r=(()=>{}),baseUrlTonder:i}){f.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken=null,this.metadata={},this.card={},this.currency="",g.set(this,void 0),this.apiKeyTonder=n||e||"",this.returnUrl=o,this.callBack=r,this.mode=t,this.customer={},this.baseUrl=i||h[this.mode]||h.stage,this.abortController=new AbortController,this.process3ds=new u({apiKey:e,baseUrl:this.baseUrl})}configureCheckout(t){"customer"in t&&o(this,f,"m",v).call(this,t.customer),"secureToken"in t&&o(this,f,"m",_).call(this,t.secureToken)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const t=yield this.process3ds.verifyTransactionStatus(),e=yield o(this,f,"m",C).call(this,t);return this.process3ds.setPayload(e),this._handle3dsRedirect(e)}))}payment(t){return new Promise(((e,r)=>n(this,void 0,void 0,(function*(){var n,i;try{o(this,f,"m",v).call(this,t.customer),this._setCartTotal(null===(n=t.cart)||void 0===n?void 0:n.total),o(this,f,"m",A).call(this,null===(i=t.cart)||void 0===i?void 0:i.items),o(this,f,"m",b).call(this,t),o(this,f,"m",E).call(this,t),o(this,f,"m",T).call(this,t);const r=yield this._checkout(t);this.process3ds.setPayload(r),this.callBack&&this.callBack(r);(yield this._handle3dsRedirect(r))&&e(r)}catch(t){r(t)}}))))}_initializeCheckout(){return n(this,void 0,void 0,(function*(){const t=yield this._fetchMerchantData();t&&t.mercado_pago&&t.mercado_pago.active&&function(){try{const t=document.createElement("script");t.src="https://www.mercadopago.com/v2/security.js",t.setAttribute("view",""),t.onload=()=>{console.log("Mercado Pago script loaded successfully.")},t.onerror=t=>{console.error("Error loading Mercado Pago script:",t)},document.head.appendChild(t)}catch(t){console.error("Error attempting to inject Mercado Pago script:",t)}}()}))}_checkout(t){return n(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(t){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(t=null){return n(this,void 0,void 0,(function*(){return o(this,g,"f")||function(t,e,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===o?r.call(t,n):r?r.value=n:e.set(t,n)}(this,g,yield function(t,e,o,r=null){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},signal:r,body:JSON.stringify(i)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,t),"f"),o(this,g,"f")}))}_handleCheckout({card:e,payment_method:o,customer:r,isSandbox:i,returnUrl:a}){return n(this,void 0,void 0,(function*(){const{openpay_keys:d,reference:l,business:c}=this.merchantData,u=Number(this.cartTotal);try{let h;!h&&d.merchant_id&&d.public_key&&(h=yield m(d.merchant_id,d.public_key,i,this.abortController.signal));const{id:y,auth_token:f}=r,g={business:this.apiKeyTonder,client:f,billing_address_id:null,shipping_address_id:null,amount:u,status:"A",reference:l,is_oneclick:!0,items:this.cartItems},v=yield function(t,e,o){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/orders/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(r)});if(201===i.status)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,g),_=(new Date).toISOString(),A={business_pk:c.pk,client_id:y,amount:u,date:_,order_id:v.id},b=yield function(t,e,o){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/business/${o.business_pk}/payments/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(r)});if(i.status>=200&&i.status<=299)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,A),E=Object.assign({name:t(this.customer,"firstName",t(this.customer,"name","")),last_name:t(this.customer,"lastName",t(this.customer,"lastname","")),email_client:t(this.customer,"email",""),phone_number:t(this.customer,"phone",""),return_url:a||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:u,title_ship:"shipping",description:"transaction",device_session_id:h||null,token_id:"",order_id:v.id,business_id:c.pk,payment_id:b.pk,source:"sdk",metadata:this.metadata,browser_info:s(),currency:this.currency},o?{payment_method:o}:{card:e}),T=yield p(this.baseUrl,this.apiKeyTonder,E);return T||!1}catch(t){throw console.log(t),t}}))}_fetchMerchantData(){return n(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield r(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(t){return this.merchantData}}))}_getCustomerCards(t,e){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r=null){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${o}/cards/`,i=yield fetch(n,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();const s=yield i.json();throw yield l(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,t,e)}))}_saveCustomerCard(t,e,o,r){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r,i){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","User-token":o},body:JSON.stringify(i)});if(s.ok)return yield s.json();const a=yield s.json();throw yield l(s,a)}catch(t){throw d(t)}}))}(this.baseUrl,e,t,o,r)}))}_removeCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){return yield function(t,e,o="",r){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${r}/cards/${o}`,i=yield fetch(n,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"}});if(204===i.status)return y.cardSaved;if(i.ok&&"json"in i)return yield i.json();const s=yield i.json();throw yield l(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,t,o,e)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(t,e,o={status:"active",pagesize:"10000"},r=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(o).toString(),i=yield fetch(`${t}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();const s=yield i.json();throw yield l(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,this.apiKeyTonder)}))}_handle3dsRedirect(t){var e,o;return n(this,void 0,void 0,(function*(){if(t&&"next_action"in t?null===(o=null===(e=null==t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t)}));else{if(!this.process3ds.getRedirectUrl())return t;this.process3ds.redirectToChallenge()}}))}}function S({baseUrl:t,apiKey:o,vault_id:r,vault_url:i,data:s}){return n(this,void 0,void 0,(function*(){const a=e.init({vaultID:r,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield function(t,e,o=null){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${t}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${e}`},signal:o});if(n.ok)return(yield n.json()).token;throw new Error("Failed to retrieve bearer token")}))}(t,o)})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}),l=a.container(e.ContainerType.COLLECT),c=yield function(t,o){return n(this,void 0,void 0,(function*(){const r=yield function(t,o){return n(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(t).map((t=>n(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:t,type:e.ElementType.INPUT_FIELD}),key:t}})))))}))}(t,o);return r?r.map((e=>new Promise((n=>{var o;const r=document.createElement("div");r.hidden=!0,r.id=`id-${e.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(r),setTimeout((()=>{e.element.mount(`#id-${e.key}`),setInterval((()=>{if(e.element.isMounted()){const o=t[e.key];return e.element.update({value:o}),n(e.element.isMounted())}}),120)}),120)})))):[]}))}(s,l);if((yield Promise.all(c)).some((t=>!t)))throw d(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const t=yield l.collect();if(t)return t.records[0].fields;throw d(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(t){throw d(t)}}))}g=new WeakMap,f=new WeakSet,v=function(t){t&&(this.customer=t)},_=function(t){this.secureToken=t},A=function(t){this.cartItems=t},b=function(t){this.metadata=null==t?void 0:t.metadata},E=function(t){this.currency=null==t?void 0:t.currency},T=function(t){this.card=null==t?void 0:t.card},C=function(t){var e,o;return n(this,void 0,void 0,(function*(){if("Hard"===(null===(e=null==t?void 0:t.decline)||void 0===e?void 0:e.error_type))return t;if(["Success","Authorized"].includes(null==t?void 0:t.transaction_status))return t;if(t){const e={checkout_id:null===(o=t.checkout)||void 0===o?void 0:o.id};try{return yield p(this.baseUrl,this.apiKeyTonder,e)}catch(t){}return t}}))};const j=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",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"}),w={[j.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[j.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[j.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[j.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[j.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[j.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[j.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[j.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[j.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[j.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[j.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[j.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[j.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[j.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[j.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[j.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[j.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[j.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[j.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[j.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[j.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[j.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[j.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[j.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[j.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[j.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[j.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[j.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[j.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[j.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},M=t=>{const e=t.toUpperCase().trim().replace(/\s+/g,"");return w[e]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class R extends O{constructor({apiKey:t,mode:e,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i}){super({mode:e,apiKey:t,returnUrl:n,callBack:o,apiKeyTonder:r,baseUrlTonder:i}),this.activeAPMs=[]}injectCheckout(){return n(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),e=yield this._getCustomerCards(t,this.merchantData.business.pk);return Object.assign(Object.assign({},e),{cards:e.cards.map((t=>{return Object.assign(Object.assign({},t),{icon:(e=t.fields.card_scheme,"Visa"===e?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===e?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===e?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var e}))})}catch(t){throw c({message:y.getCardsError},t)}}))}saveCustomerCard(t,e){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:n}=yield this._getCustomer(),{vault_id:o,vault_url:r,business:i}=this.merchantData,s=yield S({vault_id:o,vault_url:r,data:e,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._saveCustomerCard(t,n,null==i?void 0:i.pk,s)}catch(t){throw c({message:y.saveCardError},t)}}))}removeCustomerCard(t){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),{business:n}=this.merchantData;return yield this._removeCustomerCard(e,null==n?void 0:n.pk,t)}catch(t){throw c({message:y.removeCardError},t)}}))}getCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){try{const t=yield this._fetchCustomerPaymentMethods();return(t&&"results"in t&&t.results.length>0?t.results:[]).filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},M(t.payment_method)))).sort(((t,e)=>t.priority-e.priority))}catch(t){throw c({message:y.getPaymentMethodsError},t)}}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield r(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(t){throw c({message:y.getBusinessError},t)}}))}getOpenpayDeviceSessionID(t,e,o){return n(this,void 0,void 0,(function*(){try{return yield m(t,e,o)}catch(t){throw d(t)}}))}getSkyflowTokens({vault_id:t,vault_url:e,data:o}){return n(this,void 0,void 0,(function*(){return yield S({vault_id:t,vault_url:e,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(t){this.cartTotal=t}_checkout({card:t,payment_method:e,isSandbox:o,returnUrl:r}){return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const n=yield this._getCustomer(this.abortController.signal),{vault_id:i,vault_url:s}=this.merchantData;let a;return e&&""===e&&null!==e||(a="string"==typeof t?{skyflow_id:t}:yield S({vault_id:i,vault_url:s,data:Object.assign(Object.assign({},t),{card_number:t.card_number.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})),yield this._handleCheckout({card:a,payment_method:e,customer:n,isSandbox:o,returnUrl:r})}))}customerRegister(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/customer/`,n={email:t},o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield l(o)}catch(t){throw d(t)}}))}createOrder(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/orders/`,n=t,o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield l(o)}catch(t){throw d(t)}}))}createPayment(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/business/${t.business_pk}/payments/`,n=t,o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield l(o)}catch(t){throw d(t)}}))}startCheckoutRouter(t){return n(this,void 0,void 0,(function*(){const e=yield p(this.baseUrl,this.apiKeyTonder,t);if(yield this.init3DSRedirect(e))return e}))}init3DSRedirect(t){return n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(t),yield this._handle3dsRedirect(t)}))}startCheckoutRouterFull(t){return n(this,void 0,void 0,(function*(){try{const{order:e,total:n,customer:o,skyflowTokens:r,return_url:a,isSandbox:d,metadata:l,currency:c,payment_method:u}=t,h=yield this._fetchMerchantData(),y=yield this.customerRegister(o.email);if(!(y&&"auth_token"in y&&h&&"reference"in h))throw new i({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const t={business:this.apiKeyTonder,client:y.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:e.items},f=yield this.createOrder(t),g=(new Date).toISOString();if(!("id"in f&&"id"in y&&"business"in h))throw new i({code:"500",body:f,name:"Keys error",message:"Order response errors"});{const t={business_pk:h.business.pk,amount:n,date:g,order_id:f.id,client_id:y.id},e=yield this.createPayment(t);let i;const{openpay_keys:v,business:_}=h;v.merchant_id&&v.public_key&&(i=yield m(v.merchant_id,v.public_key,d));const A=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:a,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:n,title_ship:"shipping",description:"transaction",device_session_id:i||null,token_id:"",order_id:"id"in f&&f.id,business_id:_.pk,payment_id:"pk"in e&&e.pk,source:"sdk",metadata:l,browser_info:s(),currency:c},u?{payment_method:u}:{card:r}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),b=yield p(this.baseUrl,this.apiKeyTonder,A);if(yield this.init3DSRedirect(b))return b}}}catch(t){throw d(t)}}))}registerCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${a(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"User-token":e,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(n.ok)return yield n.json();throw yield l(n)}catch(t){throw d(t)}}))}deleteCustomerCard(t,e=""){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${a(this.merchantData)}/cards/${e}`,{method:"DELETE",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(n.ok)return!0;throw yield l(n)}catch(t){throw d(t)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const t=yield function(t,e,o="?status=active&page_size=10000&country=México",r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${t}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield l(n)}catch(t){throw d(t)}}))}(this.baseUrl,this.apiKeyTonder),e=t&&t.results&&t.results.length>0?t.results:[];return this.activeAPMs=e.filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},M(t.payment_method)))).sort(((t,e)=>t.priority-e.priority)),this.activeAPMs}catch(t){return console.error("Error getting APMS",t),[]}}))}getSecureToken(t){return n(this,void 0,void 0,(function*(){try{const e=yield fetch(`${this.baseUrl}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(e.ok)return yield e.json();throw yield l(e)}catch(t){throw d(t)}}))}}function I(t){return/^\d{12,19}$/.test(t)&&L(t)}function k(t){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(t)}function N(t){return/^\d{3,4}$/.test(t)}function U(t){return/^(0[1-9]|1[0-2])$/.test(t)}function P(t){if(!/^\d{2}$/.test(t))return!1;const e=(new Date).getFullYear()%100;return parseInt(t,10)>=e}const L=t=>{const e=`${t}`.split("").reverse().map((t=>Number.parseInt(t))),n=e.shift();let o=e.reduce(((t,e,n)=>n%2!=0?t+e:t+((e*=2)>9?e-9:e)),0);return o+=n,o%10==0};export{O as BaseInlineCheckout,R as LiteCheckout,N as validateCVV,I as validateCardNumber,k as validateCardholderName,U as validateExpirationMonth,P as validateExpirationYear};
|
|
1
|
+
import{get as t}from"lodash";import e from"skyflow-js";function o(t,e,o,n){return new(o||(o=Promise))((function(r,i){function s(t){try{d(n.next(t))}catch(t){i(t)}}function a(t){try{d(n.throw(t))}catch(t){i(t)}}function d(t){var e;t.done?r(t.value):(e=t.value,e instanceof o?e:new o((function(t){t(e)}))).then(s,a)}d((n=n.apply(t,e||[])).next())}))}function n(t,e,o,n){if("a"===o&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===o?n:"a"===o?n.call(t):n?n.value:e.get(t)}function r(t,e,n){return o(this,void 0,void 0,(function*(){const o=yield fetch(`${t}/api/v1/payments/business/${e}`,{headers:{Authorization:`Token ${e}`},signal:n});return yield o.json()}))}"function"==typeof SuppressedError&&SuppressedError;class i{constructor({code:t,body:e,name:o,message:n,stack:r}){this.code=t,this.body=e,this.name=o,this.message=n,this.stack=r}}const s=()=>({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}),a=t=>{var e;return t&&"business"in t?null===(e=null==t?void 0:t.business)||void 0===e?void 0:e.pk:""},d=t=>new i({code:(null==t?void 0:t.status)?t.status:t.code,body:null==t?void 0:t.body,name:t?"string"==typeof t?"catch":t.name:"Error",message:t?"string"==typeof t?t:t.message:"Error",stack:"string"==typeof t?void 0:t.stack}),c=(t,e=void 0)=>o(void 0,void 0,void 0,(function*(){let o,n,r="Error";t&&"json"in t&&(o=yield null==t?void 0:t.json()),t&&"status"in t&&(n=t.status.toString()),!o&&t&&"text"in t&&(r=yield t.text()),(null==o?void 0:o.detail)&&(r=o.detail);return new i({code:n,body:o,name:n,message:r,stack:e})}));function l(t,e){var o,n;let r=200;try{r=Number((null==e?void 0:e.code)||200)}catch(t){}const i={status:"error",code:r,message:"",detail:(null===(o=null==e?void 0:e.body)||void 0===o?void 0:o.detail)||(null===(n=null==e?void 0:e.body)||void 0===n?void 0:n.error)||e.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),t)}class u{constructor({payload:t=null,apiKey:e,baseUrl:o,customization:n,tdsIframeId:r,callBack:i}){this.localStorageKey="verify_transaction_status_url",this.customization={saveCards:{showSaveCardOption:!0,showSaved:!0,autoSave:!1},redirectOnComplete:!0},this.setPayload=t=>{this.payload=t},this.baseUrl=o,this.apiKey=e,this.payload=t,this.tdsIframeId=r,this.customization=Object.assign(Object.assign(Object.assign({},this.customization),n||{}),{saveCards:Object.assign(Object.assign({},this.customization.saveCards),(null==n?void 0:n.saveCards)||{})}),this.callBack=i}setStorageItem(t){return localStorage.setItem(this.localStorageKey,JSON.stringify(t))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var t,e,o,n,r,i;const s=null===(o=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===o?void 0:o.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const t=null===(i=null===(r=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;t?this.saveUrlWithExpiration(t):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(t){try{const e={url:t,expires:(new Date).getTime()+12e5};this.setStorageItem(e)}catch(t){console.log("error: ",t)}}getUrlWithExpiration(){const t=this.getStorageItem();if(t){const e=JSON.parse(t);if(!e)return;return(new Date).getTime()>e.expires?(this.removeVerifyTransactionUrl(),null):e.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var t,e,o;if(null===(o=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===o?void 0:o.iframe)return new Promise(((t,e)=>{var o,n,r;const i=null===(r=null===(n=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===n?void 0:n.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const o=document.createElement("div");o.innerHTML=i,document.body.appendChild(o);const n=document.createElement("script");n.textContent='document.getElementById("tdsMmethodForm").submit();',o.appendChild(n);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>t(!0):(console.log("No redirection found"),e(!1))}else console.log("No redirection found"),e(!1)}))}getRedirectUrl(){var t,e,o;return null===(o=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===o?void 0:o.url}redirectToChallenge(){var t;const e=this.getRedirectUrl();if(e)if(this.saveVerifyTransactionUrl(),this.customization)if(null===(t=this.customization)||void 0===t?void 0:t.redirectOnComplete)window.location=e;else{const t=document.querySelector(`#${this.tdsIframeId}`);if(t){t.setAttribute("src",e),t.setAttribute("style","display: block");const n=this,r=e=>o(this,void 0,void 0,(function*(){const e=i=>o(this,void 0,void 0,(function*(){const s=yield new Promise(((t,e)=>t(i)));if(s){if((t=>"Pending"!==(null==t?void 0:t.transaction_status))(s))return t&&t.setAttribute("style","display: none"),n.callBack&&n.callBack(n.payload),void t.removeEventListener("load",r);{const t=setTimeout((()=>o(this,void 0,void 0,(function*(){clearTimeout(t),yield e(n.requestTransactionStatus())}))),15e3)}}}));yield e(n.requestTransactionStatus())}));t.addEventListener("load",r)}else console.log("No iframe found")}else window.location=e;else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return o(this,void 0,void 0,(function*(){const t=this.getUrlWithExpiration(),e=`${this.baseUrl}${t}`,o=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==o.status)return console.error("La verificación de la transacción falló."),null;return yield o.json()}))}getURLParameters(){const t={},e=new URLSearchParams(window.location.search);for(const[o,n]of e)t[o]=n;return t}handleSuccessTransaction(t){return this.removeVerifyTransactionUrl(),console.log("Transacción autorizada."),t}handleDeclinedTransaction(t){return this.removeVerifyTransactionUrl(),t}handle3dsChallenge(t){return o(this,void 0,void 0,(function*(){const e=document.createElement("form");e.name="frm",e.method="POST",e.action=t.redirect_post_url;const o=document.createElement("input");o.type="hidden",o.name=t.creq,o.value=t.creq,e.appendChild(o);const n=document.createElement("input");n.type="hidden",n.name=t.term_url,n.value=t.TermUrl,e.appendChild(n),document.body.appendChild(e),e.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(t){return o(this,void 0,void 0,(function*(){const e=yield t.json();return"Pending"===e.status&&e.redirect_post_url?yield this.handle3dsChallenge(e):["Success","Authorized"].includes(e.status)?this.handleSuccessTransaction(e):(this.handleDeclinedTransaction(t),e)}))}verifyTransactionStatus(){return o(this,void 0,void 0,(function*(){const t=this.getUrlWithExpiration();if(t){const e=`${this.baseUrl}${t}`;try{const t=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==t.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),t):yield this.handleTransactionResponse(t)}catch(t){console.error("Error al verificar la transacción:",t),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const h=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function p(t,e,n){return o(this,void 0,void 0,(function*(){try{const o=`${t}/api/v1/checkout-router/`,r=n,i=yield fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(Object.assign(Object.assign({},r),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.status>=200&&i.status<=299)return yield i.json();{const t=yield i.json(),e=new Error("Failed to start checkout router");throw e.details=t,e}}catch(t){throw t}}))}function m(t,e,n=!0,r=null){return o(this,void 0,void 0,(function*(){let o=yield window.OpenPay;return o.setId(t),o.setApiKey(e),o.setSandboxMode(n),yield o.deviceData.setup({signal:r})}))}const y=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."});var f,v,g,_,A,b,E,T,C;class O{constructor({mode:t="stage",customization:e,apiKey:o,apiKeyTonder:n,returnUrl:r,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a}){f.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={saveCards:{showSaveCardOption:!0,showSaved:!0,autoSave:!1},redirectOnComplete:!0},this.metadata={},this.card={},this.currency="",v.set(this,void 0),this.apiKeyTonder=n||o||"",this.returnUrl=r,this.callBack=s,this.mode=t,this.customer={},this.baseUrl=a||h[this.mode]||h.stage,this.abortController=new AbortController,this.process3ds=new u({apiKey:o,baseUrl:this.baseUrl,customization:e,tdsIframeId:i,callBack:s}),this.tdsIframeId=i,this.customization=Object.assign(Object.assign(Object.assign({},this.customization),e||{}),{saveCards:Object.assign(Object.assign({},this.customization.saveCards),(null==e?void 0:e.saveCards)||{})})}configureCheckout(t){"customer"in t&&n(this,f,"m",g).call(this,t.customer),"secureToken"in t&&n(this,f,"m",_).call(this,t.secureToken)}verify3dsTransaction(){return o(this,void 0,void 0,(function*(){const t=yield this.process3ds.verifyTransactionStatus(),e=yield n(this,f,"m",C).call(this,t);return this.process3ds.setPayload(e),this._handle3dsRedirect(e)}))}payment(t){return new Promise(((e,r)=>o(this,void 0,void 0,(function*(){var o,i;try{n(this,f,"m",g).call(this,t.customer),this._setCartTotal(null===(o=t.cart)||void 0===o?void 0:o.total),n(this,f,"m",A).call(this,null===(i=t.cart)||void 0===i?void 0:i.items),n(this,f,"m",b).call(this,t),n(this,f,"m",E).call(this,t),n(this,f,"m",T).call(this,t);const r=yield this._checkout(t);this.process3ds.setPayload(r);(yield this._handle3dsRedirect(r))&&(this.callBack&&this.callBack(r),e(r))}catch(t){r(t)}}))))}_initializeCheckout(){return o(this,void 0,void 0,(function*(){const t=yield this._fetchMerchantData();t&&t.mercado_pago&&t.mercado_pago.active&&function(){try{const t=document.createElement("script");t.src="https://www.mercadopago.com/v2/security.js",t.setAttribute("view",""),t.onload=()=>{console.log("Mercado Pago script loaded successfully.")},t.onerror=t=>{console.error("Error loading Mercado Pago script:",t)},document.head.appendChild(t)}catch(t){console.error("Error attempting to inject Mercado Pago script:",t)}}()}))}_checkout(t){return o(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(t){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(t=null){return o(this,void 0,void 0,(function*(){return n(this,v,"f")||function(t,e,o,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===n?r.call(t,o):r?r.value=o:e.set(t,o)}(this,v,yield function(t,e,n,r=null){return o(this,void 0,void 0,(function*(){const o=`${t}/api/v1/customer/`,i={email:n.email,first_name:null==n?void 0:n.firstName,last_name:null==n?void 0:n.lastName,phone:null==n?void 0:n.phone},s=yield fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},signal:r,body:JSON.stringify(i)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,t),"f"),n(this,v,"f")}))}_handleCheckout({card:e,payment_method:n,customer:r,isSandbox:i,returnUrl:a}){return o(this,void 0,void 0,(function*(){const{openpay_keys:d,reference:c,business:l}=this.merchantData,u=Number(this.cartTotal);try{let h;!h&&d.merchant_id&&d.public_key&&(h=yield m(d.merchant_id,d.public_key,i,this.abortController.signal));const{id:y,auth_token:f}=r,v={business:this.apiKeyTonder,client:f,billing_address_id:null,shipping_address_id:null,amount:u,status:"A",reference:c,is_oneclick:!0,items:this.cartItems},g=yield function(t,e,n){return o(this,void 0,void 0,(function*(){const o=`${t}/api/v1/orders/`,r=n,i=yield fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(r)});if(201===i.status)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,v),_=(new Date).toISOString(),A={business_pk:l.pk,client_id:y,amount:u,date:_,order_id:g.id},b=yield function(t,e,n){return o(this,void 0,void 0,(function*(){const o=`${t}/api/v1/business/${n.business_pk}/payments/`,r=n,i=yield fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(r)});if(i.status>=200&&i.status<=299)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,A),E=Object.assign({name:t(this.customer,"firstName",t(this.customer,"name","")),last_name:t(this.customer,"lastName",t(this.customer,"lastname","")),email_client:t(this.customer,"email",""),phone_number:t(this.customer,"phone",""),return_url:a||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:u,title_ship:"shipping",description:"transaction",device_session_id:h||null,token_id:"",order_id:g.id,business_id:l.pk,payment_id:b.pk,source:"sdk",metadata:this.metadata,browser_info:s(),currency:this.currency},n?{payment_method:n}:{card:e}),T=yield p(this.baseUrl,this.apiKeyTonder,E);return T||!1}catch(t){throw console.log(t),t}}))}_fetchMerchantData(){return o(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield r(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(t){return this.merchantData}}))}_getCustomerCards(t,e){return o(this,void 0,void 0,(function*(){return yield function(t,e,n,r=null){return o(this,void 0,void 0,(function*(){try{const o=`${t}/api/v1/business/${n}/cards/`,i=yield fetch(o,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();const s=yield i.json();throw yield c(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,t,e)}))}_saveCustomerCard(t,e,n,r){return o(this,void 0,void 0,(function*(){return yield function(t,e,n,r,i){return o(this,void 0,void 0,(function*(){try{const o=`${t}/api/v1/business/${r}/cards/`,s=yield fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","User-token":n},body:JSON.stringify(i)});if(s.ok)return yield s.json();const a=yield s.json();throw yield c(s,a)}catch(t){throw d(t)}}))}(this.baseUrl,this.secureToken,t,n,r)}))}_removeCustomerCard(t,e,n){return o(this,void 0,void 0,(function*(){return yield function(t,e,n="",r){return o(this,void 0,void 0,(function*(){try{const o=`${t}/api/v1/business/${r}/cards/${n}`,i=yield fetch(o,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"}});if(204===i.status)return y.cardSaved;if(i.ok&&"json"in i)return yield i.json();const s=yield i.json();throw yield c(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,t,n,e)}))}_fetchCustomerPaymentMethods(){return o(this,void 0,void 0,(function*(){return yield function(t,e,n={status:"active",pagesize:"10000"},r=null){return o(this,void 0,void 0,(function*(){try{const o=new URLSearchParams(n).toString(),i=yield fetch(`${t}/api/v1/payment_methods?${o}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();const s=yield i.json();throw yield c(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,this.apiKeyTonder)}))}_handle3dsRedirect(t){var e,n;return o(this,void 0,void 0,(function*(){if(t&&"next_action"in t?null===(n=null===(e=null==t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===n?void 0:n.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t)}));else{if(!this.process3ds.getRedirectUrl())return t;this.process3ds.redirectToChallenge()}}))}}function S({baseUrl:t,apiKey:n,vault_id:r,vault_url:i,data:s}){return o(this,void 0,void 0,(function*(){const a=e.init({vaultID:r,vaultURL:i,getBearerToken:()=>o(this,void 0,void 0,(function*(){return yield function(t,e,n=null){return o(this,void 0,void 0,(function*(){const o=yield fetch(`${t}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${e}`},signal:n});if(o.ok)return(yield o.json()).token;throw new Error("Failed to retrieve bearer token")}))}(t,n)})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}),c=a.container(e.ContainerType.COLLECT),l=yield function(t,n){return o(this,void 0,void 0,(function*(){const r=yield function(t,n){return o(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(t).map((t=>o(this,void 0,void 0,(function*(){return{element:yield n.create({table:"cards",column:t,type:e.ElementType.INPUT_FIELD}),key:t}})))))}))}(t,n);return r?r.map((e=>new Promise((o=>{var n;const r=document.createElement("div");r.hidden=!0,r.id=`id-${e.key}`,null===(n=document.querySelector("body"))||void 0===n||n.appendChild(r),setTimeout((()=>{e.element.mount(`#id-${e.key}`),setInterval((()=>{if(e.element.isMounted()){const n=t[e.key];return e.element.update({value:n}),o(e.element.isMounted())}}),120)}),120)})))):[]}))}(s,c);if((yield Promise.all(l)).some((t=>!t)))throw d(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const t=yield c.collect();if(t)return t.records[0].fields;throw d(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(t){throw d(t)}}))}v=new WeakMap,f=new WeakSet,g=function(t){t&&(this.customer=t)},_=function(t){this.secureToken=t},A=function(t){this.cartItems=t},b=function(t){this.metadata=null==t?void 0:t.metadata},E=function(t){this.currency=null==t?void 0:t.currency},T=function(t){this.card=null==t?void 0:t.card},C=function(t){var e,n;return o(this,void 0,void 0,(function*(){if("Hard"===(null===(e=null==t?void 0:t.decline)||void 0===e?void 0:e.error_type))return t;if(["Success","Authorized"].includes(null==t?void 0:t.transaction_status))return t;if(t){const e={checkout_id:null===(n=t.checkout)||void 0===n?void 0:n.id};try{return yield p(this.baseUrl,this.apiKeyTonder,e)}catch(t){}return t}}))};const j=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",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"}),w={[j.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[j.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[j.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[j.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[j.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[j.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[j.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[j.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[j.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[j.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[j.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[j.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[j.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[j.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[j.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[j.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[j.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[j.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[j.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[j.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[j.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[j.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[j.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[j.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[j.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[j.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[j.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[j.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[j.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[j.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[j.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},I=t=>{const e=t.toUpperCase().trim().replace(/\s+/g,"");return w[e]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class k extends O{constructor({apiKey:t,mode:e,returnUrl:o,callBack:n,apiKeyTonder:r,baseUrlTonder:i}){super({mode:e,apiKey:t,returnUrl:o,callBack:n,apiKeyTonder:r,baseUrlTonder:i}),this.activeAPMs=[]}injectCheckout(){return o(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return o(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),e=yield this._getCustomerCards(t,this.merchantData.business.pk);return Object.assign(Object.assign({},e),{cards:e.cards.map((t=>{return Object.assign(Object.assign({},t),{icon:(e=t.fields.card_scheme,"Visa"===e?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===e?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===e?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var e}))})}catch(t){throw l({message:y.getCardsError},t)}}))}saveCustomerCard(t,e){return o(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:o}=yield this._getCustomer(),{vault_id:n,vault_url:r,business:i}=this.merchantData,s=yield S({vault_id:n,vault_url:r,data:e,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._saveCustomerCard(t,o,null==i?void 0:i.pk,s)}catch(t){throw l({message:y.saveCardError},t)}}))}removeCustomerCard(t){return o(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),{business:o}=this.merchantData;return yield this._removeCustomerCard(e,null==o?void 0:o.pk,t)}catch(t){throw l({message:y.removeCardError},t)}}))}getCustomerPaymentMethods(){return o(this,void 0,void 0,(function*(){try{const t=yield this._fetchCustomerPaymentMethods();return(t&&"results"in t&&t.results.length>0?t.results:[]).filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},I(t.payment_method)))).sort(((t,e)=>t.priority-e.priority))}catch(t){throw l({message:y.getPaymentMethodsError},t)}}))}getBusiness(){return o(this,void 0,void 0,(function*(){try{return yield r(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(t){throw l({message:y.getBusinessError},t)}}))}getOpenpayDeviceSessionID(t,e,n){return o(this,void 0,void 0,(function*(){try{return yield m(t,e,n)}catch(t){throw d(t)}}))}getSkyflowTokens({vault_id:t,vault_url:e,data:n}){return o(this,void 0,void 0,(function*(){return yield S({vault_id:t,vault_url:e,data:n,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(t){this.cartTotal=t}_checkout({card:t,payment_method:e,isSandbox:n,returnUrl:r}){return o(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const o=yield this._getCustomer(this.abortController.signal),{vault_id:i,vault_url:s}=this.merchantData;let a;return e&&""===e&&null!==e||(a="string"==typeof t?{skyflow_id:t}:yield S({vault_id:i,vault_url:s,data:Object.assign(Object.assign({},t),{card_number:t.card_number.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})),yield this._handleCheckout({card:a,payment_method:e,customer:o,isSandbox:n,returnUrl:r})}))}customerRegister(t){return o(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/customer/`,o={email:t},n=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(o)});if(n.ok)return yield n.json();throw yield c(n)}catch(t){throw d(t)}}))}createOrder(t){return o(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/orders/`,o=t,n=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(o)});if(n.ok)return yield n.json();throw yield c(n)}catch(t){throw d(t)}}))}createPayment(t){return o(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/business/${t.business_pk}/payments/`,o=t,n=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(o)});if(n.ok)return yield n.json();throw yield c(n)}catch(t){throw d(t)}}))}startCheckoutRouter(t){return o(this,void 0,void 0,(function*(){const e=yield p(this.baseUrl,this.apiKeyTonder,t);if(yield this.init3DSRedirect(e))return e}))}init3DSRedirect(t){return o(this,void 0,void 0,(function*(){return this.process3ds.setPayload(t),yield this._handle3dsRedirect(t)}))}startCheckoutRouterFull(t){return o(this,void 0,void 0,(function*(){try{const{order:e,total:o,customer:n,skyflowTokens:r,return_url:a,isSandbox:d,metadata:c,currency:l,payment_method:u}=t,h=yield this._fetchMerchantData(),y=yield this.customerRegister(n.email);if(!(y&&"auth_token"in y&&h&&"reference"in h))throw new i({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const t={business:this.apiKeyTonder,client:y.auth_token,billing_address_id:null,shipping_address_id:null,amount:o,reference:h.reference,is_oneclick:!0,items:e.items},f=yield this.createOrder(t),v=(new Date).toISOString();if(!("id"in f&&"id"in y&&"business"in h))throw new i({code:"500",body:f,name:"Keys error",message:"Order response errors"});{const t={business_pk:h.business.pk,amount:o,date:v,order_id:f.id,client_id:y.id},e=yield this.createPayment(t);let i;const{openpay_keys:g,business:_}=h;g.merchant_id&&g.public_key&&(i=yield m(g.merchant_id,g.public_key,d));const A=Object.assign(Object.assign({name:n.name,last_name:n.lastname,email_client:n.email,phone_number:n.phone,return_url:a,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:o,title_ship:"shipping",description:"transaction",device_session_id:i||null,token_id:"",order_id:"id"in f&&f.id,business_id:_.pk,payment_id:"pk"in e&&e.pk,source:"sdk",metadata:c,browser_info:s(),currency:l},u?{payment_method:u}:{card:r}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),b=yield p(this.baseUrl,this.apiKeyTonder,A);if(yield this.init3DSRedirect(b))return b}}}catch(t){throw d(t)}}))}registerCustomerCard(t,e,n){return o(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const o=yield fetch(`${this.baseUrl}/api/v1/business/${a(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"User-token":e,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},n))});if(o.ok)return yield o.json();throw yield c(o)}catch(t){throw d(t)}}))}deleteCustomerCard(t,e=""){return o(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const o=yield fetch(`${this.baseUrl}/api/v1/business/${a(this.merchantData)}/cards/${e}`,{method:"DELETE",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(o.ok)return!0;throw yield c(o)}catch(t){throw d(t)}}))}getActiveAPMs(){return o(this,void 0,void 0,(function*(){try{const t=yield function(t,e,n="?status=active&page_size=10000&country=México",r=null){return o(this,void 0,void 0,(function*(){try{const o=yield fetch(`${t}/api/v1/payment_methods${n}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(o.ok)return yield o.json();throw yield c(o)}catch(t){throw d(t)}}))}(this.baseUrl,this.apiKeyTonder),e=t&&t.results&&t.results.length>0?t.results:[];return this.activeAPMs=e.filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},I(t.payment_method)))).sort(((t,e)=>t.priority-e.priority)),this.activeAPMs}catch(t){return console.error("Error getting APMS",t),[]}}))}getSecureToken(t){return o(this,void 0,void 0,(function*(){try{const e=yield fetch(`${this.baseUrl}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(e.ok)return yield e.json();throw yield c(e)}catch(t){throw d(t)}}))}}function M(t){return/^\d{12,19}$/.test(t)&&L(t)}function R(t){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(t)}function N(t){return/^\d{3,4}$/.test(t)}function U(t){return/^(0[1-9]|1[0-2])$/.test(t)}function P(t){if(!/^\d{2}$/.test(t))return!1;const e=(new Date).getFullYear()%100;return parseInt(t,10)>=e}const L=t=>{const e=`${t}`.split("").reverse().map((t=>Number.parseInt(t))),o=e.shift();let n=e.reduce(((t,e,o)=>o%2!=0?t+e:t+((e*=2)>9?e-9:e)),0);return n+=o,n%10==0};export{O as BaseInlineCheckout,k as LiteCheckout,N as validateCVV,M as validateCardNumber,R as validateCardholderName,U as validateExpirationMonth,P as validateExpirationYear};
|
package/dist/types/commons.d.ts
CHANGED
|
@@ -104,6 +104,8 @@ export interface IInlineCheckoutBaseOptions {
|
|
|
104
104
|
apiKey: string;
|
|
105
105
|
returnUrl?: string;
|
|
106
106
|
callBack?: (response: IStartCheckoutResponse | Record<string, any>) => void;
|
|
107
|
+
customization?: CustomizationOptions;
|
|
108
|
+
tdsIframeId?: string;
|
|
107
109
|
}
|
|
108
110
|
export interface IInlineLiteCheckoutOptions extends IInlineCheckoutBaseOptions {
|
|
109
111
|
}
|
|
@@ -119,3 +121,11 @@ export interface IPublicError {
|
|
|
119
121
|
message: string;
|
|
120
122
|
detail: Record<string, any> | string;
|
|
121
123
|
}
|
|
124
|
+
export type CustomizationOptions = {
|
|
125
|
+
saveCards?: {
|
|
126
|
+
showSaveCardOption?: boolean;
|
|
127
|
+
showSaved?: boolean;
|
|
128
|
+
autoSave?: boolean;
|
|
129
|
+
};
|
|
130
|
+
redirectOnComplete?: boolean;
|
|
131
|
+
};
|
package/package.json
CHANGED
|
@@ -1,24 +1,52 @@
|
|
|
1
|
+
import { CustomizationOptions } from "../types/commons"
|
|
2
|
+
|
|
1
3
|
type ThreeDSHandlerContructor = {
|
|
2
4
|
payload?: any,
|
|
3
5
|
apiKey?: string,
|
|
4
6
|
baseUrl?: string,
|
|
7
|
+
customization?: CustomizationOptions,
|
|
8
|
+
tdsIframeId?: string,
|
|
9
|
+
callBack?: (params: any) => any
|
|
5
10
|
}
|
|
6
11
|
|
|
7
12
|
export class ThreeDSHandler {
|
|
8
13
|
|
|
14
|
+
callBack?: (params: any) => any
|
|
9
15
|
baseUrl?: string
|
|
10
16
|
apiKey?: string
|
|
11
17
|
payload?: any
|
|
12
18
|
localStorageKey: string = "verify_transaction_status_url"
|
|
19
|
+
customization: CustomizationOptions = {
|
|
20
|
+
saveCards: {
|
|
21
|
+
showSaveCardOption: true,
|
|
22
|
+
showSaved: true,
|
|
23
|
+
autoSave: false
|
|
24
|
+
},
|
|
25
|
+
redirectOnComplete: true
|
|
26
|
+
}
|
|
27
|
+
tdsIframeId?: string
|
|
13
28
|
|
|
14
29
|
constructor({
|
|
15
30
|
payload = null,
|
|
16
31
|
apiKey,
|
|
17
32
|
baseUrl,
|
|
33
|
+
customization,
|
|
34
|
+
tdsIframeId,
|
|
35
|
+
callBack
|
|
18
36
|
}: ThreeDSHandlerContructor) {
|
|
19
37
|
this.baseUrl = baseUrl,
|
|
20
38
|
this.apiKey = apiKey,
|
|
21
39
|
this.payload = payload
|
|
40
|
+
this.tdsIframeId = tdsIframeId
|
|
41
|
+
this.customization = {
|
|
42
|
+
...this.customization,
|
|
43
|
+
...(customization || {}),
|
|
44
|
+
saveCards: {
|
|
45
|
+
...this.customization.saveCards,
|
|
46
|
+
...(customization?.saveCards || {}),
|
|
47
|
+
},
|
|
48
|
+
}
|
|
49
|
+
this.callBack = callBack
|
|
22
50
|
}
|
|
23
51
|
|
|
24
52
|
setStorageItem (data: any) {
|
|
@@ -128,10 +156,82 @@ export class ThreeDSHandler {
|
|
|
128
156
|
const url = this.getRedirectUrl()
|
|
129
157
|
if (url) {
|
|
130
158
|
this.saveVerifyTransactionUrl()
|
|
131
|
-
|
|
159
|
+
if(this.customization) {
|
|
160
|
+
if(this.customization?.redirectOnComplete) {
|
|
161
|
+
window.location = url;
|
|
162
|
+
} else {
|
|
163
|
+
const iframe = document.querySelector(`#${this.tdsIframeId}`)
|
|
164
|
+
if(iframe) {
|
|
165
|
+
|
|
166
|
+
iframe.setAttribute("src", url);
|
|
167
|
+
iframe.setAttribute("style", "display: block");
|
|
168
|
+
|
|
169
|
+
const self = this;
|
|
170
|
+
|
|
171
|
+
const listenerHandler = async (event: any) => {
|
|
172
|
+
|
|
173
|
+
const checkStatus = (result: any) => result?.transaction_status !== "Pending";
|
|
174
|
+
|
|
175
|
+
const executeAction = () => {
|
|
176
|
+
if(iframe) {
|
|
177
|
+
iframe.setAttribute("style", "display: none");
|
|
178
|
+
}
|
|
179
|
+
if(self.callBack) self.callBack(self.payload);
|
|
180
|
+
iframe.removeEventListener("load", listenerHandler);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const chainPromises = async (promise: Promise<any>) => {
|
|
184
|
+
const result = await new Promise((resolve, reject) => resolve(promise))
|
|
185
|
+
if(result) {
|
|
186
|
+
if(checkStatus(result)) {
|
|
187
|
+
return executeAction()
|
|
188
|
+
} else {
|
|
189
|
+
const timer = setTimeout(async () => {
|
|
190
|
+
clearTimeout(timer);
|
|
191
|
+
await chainPromises(self.requestTransactionStatus());
|
|
192
|
+
}, 15000)
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
await chainPromises(self.requestTransactionStatus())
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
iframe.addEventListener("load", listenerHandler)
|
|
201
|
+
|
|
202
|
+
} else {
|
|
203
|
+
console.log('No iframe found');
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
} else {
|
|
207
|
+
window.location = url;
|
|
208
|
+
}
|
|
209
|
+
} else {
|
|
210
|
+
if (this.callBack) this.callBack!(this.payload);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async requestTransactionStatus() {
|
|
215
|
+
|
|
216
|
+
const verifyUrl = this.getUrlWithExpiration();
|
|
217
|
+
const url = `${this.baseUrl}${verifyUrl}`;
|
|
218
|
+
const response = await fetch(url, {
|
|
219
|
+
method: "GET",
|
|
220
|
+
headers: {
|
|
221
|
+
"Content-Type": "application/json",
|
|
222
|
+
Authorization: `Token ${this.apiKey}`,
|
|
223
|
+
},
|
|
224
|
+
// body: JSON.stringify(data),
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
if (response.status !== 200) {
|
|
228
|
+
console.error('La verificación de la transacción falló.');
|
|
229
|
+
return null;
|
|
132
230
|
} else {
|
|
133
|
-
|
|
231
|
+
const response_json = await response.json();
|
|
232
|
+
return response_json;
|
|
134
233
|
}
|
|
234
|
+
|
|
135
235
|
}
|
|
136
236
|
|
|
137
237
|
// Returns an object
|
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
saveCustomerCard,
|
|
19
19
|
} from "../data/cardApi";
|
|
20
20
|
import { fetchCustomerPaymentMethods } from "../data/paymentMethodApi";
|
|
21
|
-
import {Business, IConfigureCheckout, IInlineCheckoutBaseOptions} from "../types/commons";
|
|
21
|
+
import {Business, IConfigureCheckout, IInlineCheckoutBaseOptions, CustomizationOptions} from "../types/commons";
|
|
22
22
|
import {ICustomer} from "../types/customer";
|
|
23
23
|
import {ICardFields, IItem, IProcessPaymentRequest, IStartCheckoutResponse} from "../types/checkout";
|
|
24
24
|
import {ICustomerCardsResponse, ISaveCardResponse, ISaveCardSkyflowRequest} from "../types/card";
|
|
@@ -31,11 +31,20 @@ export class BaseInlineCheckout {
|
|
|
31
31
|
mode?: "production" | "sandbox" | "stage" | "development" | undefined;
|
|
32
32
|
apiKeyTonder: string;
|
|
33
33
|
returnUrl?: string;
|
|
34
|
+
tdsIframeId?: string;
|
|
34
35
|
callBack?: ((response: IStartCheckoutResponse | Record<string, any>) => void) | undefined;
|
|
35
36
|
merchantData?: Business;
|
|
36
37
|
abortController: AbortController;
|
|
37
|
-
secureToken: string
|
|
38
|
+
secureToken: string = "";
|
|
38
39
|
customer?: ICustomer | { email: string };
|
|
40
|
+
customization: CustomizationOptions = {
|
|
41
|
+
saveCards: {
|
|
42
|
+
showSaveCardOption: true,
|
|
43
|
+
showSaved: true,
|
|
44
|
+
autoSave: false
|
|
45
|
+
},
|
|
46
|
+
redirectOnComplete: true
|
|
47
|
+
}
|
|
39
48
|
|
|
40
49
|
cartItems?: IItem[];
|
|
41
50
|
metadata = {};
|
|
@@ -46,9 +55,11 @@ export class BaseInlineCheckout {
|
|
|
46
55
|
|
|
47
56
|
constructor({
|
|
48
57
|
mode = "stage",
|
|
58
|
+
customization,
|
|
49
59
|
apiKey,
|
|
50
60
|
apiKeyTonder,
|
|
51
61
|
returnUrl,
|
|
62
|
+
tdsIframeId,
|
|
52
63
|
callBack = () => {},
|
|
53
64
|
baseUrlTonder
|
|
54
65
|
}: IInlineCheckoutBaseOptions) {
|
|
@@ -62,7 +73,19 @@ export class BaseInlineCheckout {
|
|
|
62
73
|
this.process3ds = new ThreeDSHandler({
|
|
63
74
|
apiKey: apiKey,
|
|
64
75
|
baseUrl: this.baseUrl,
|
|
76
|
+
customization: customization,
|
|
77
|
+
tdsIframeId: tdsIframeId,
|
|
78
|
+
callBack: callBack
|
|
65
79
|
});
|
|
80
|
+
this.tdsIframeId = tdsIframeId;
|
|
81
|
+
this.customization = {
|
|
82
|
+
...this.customization,
|
|
83
|
+
...(customization || {}),
|
|
84
|
+
saveCards: {
|
|
85
|
+
...this.customization.saveCards,
|
|
86
|
+
...(customization?.saveCards || {})
|
|
87
|
+
}
|
|
88
|
+
}
|
|
66
89
|
}
|
|
67
90
|
|
|
68
91
|
configureCheckout(data: IConfigureCheckout) {
|
|
@@ -88,9 +111,9 @@ export class BaseInlineCheckout {
|
|
|
88
111
|
this.#handleCard(data);
|
|
89
112
|
const response = await this._checkout(data);
|
|
90
113
|
this.process3ds.setPayload(response);
|
|
91
|
-
if (this.callBack) this.callBack!(response);
|
|
92
114
|
const payload = await this._handle3dsRedirect(response);
|
|
93
115
|
if (payload) {
|
|
116
|
+
if (this.callBack) this.callBack!(response);
|
|
94
117
|
resolve(response);
|
|
95
118
|
}
|
|
96
119
|
} catch (error) {
|
|
@@ -279,7 +302,7 @@ export class BaseInlineCheckout {
|
|
|
279
302
|
): Promise<ISaveCardResponse> {
|
|
280
303
|
return await saveCustomerCard(
|
|
281
304
|
this.baseUrl,
|
|
282
|
-
secureToken,
|
|
305
|
+
this.secureToken,
|
|
283
306
|
authToken,
|
|
284
307
|
businessId,
|
|
285
308
|
skyflowTokens,
|
package/src/types/commons.ts
CHANGED
|
@@ -110,6 +110,8 @@ export interface IInlineCheckoutBaseOptions {
|
|
|
110
110
|
apiKey: string;
|
|
111
111
|
returnUrl?: string;
|
|
112
112
|
callBack?: (response: IStartCheckoutResponse | Record<string, any>) => void;
|
|
113
|
+
customization?: CustomizationOptions;
|
|
114
|
+
tdsIframeId?: string
|
|
113
115
|
}
|
|
114
116
|
|
|
115
117
|
export interface IInlineLiteCheckoutOptions
|
|
@@ -129,3 +131,12 @@ export interface IPublicError {
|
|
|
129
131
|
message: string;
|
|
130
132
|
detail: Record<string, any> | string;
|
|
131
133
|
}
|
|
134
|
+
|
|
135
|
+
export type CustomizationOptions = {
|
|
136
|
+
saveCards?: {
|
|
137
|
+
showSaveCardOption?: boolean;
|
|
138
|
+
showSaved?: boolean;
|
|
139
|
+
autoSave?: boolean;
|
|
140
|
+
},
|
|
141
|
+
redirectOnComplete?: boolean
|
|
142
|
+
}
|