@tonder.io/ionic-lite-sdk 0.0.51 → 0.0.52-beta.DEV-1610.2
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/3dsHandler.d.ts +3 -4
- package/dist/classes/BaseInlineCheckout.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/shared/constants/paymentMethodAPM.d.ts +1 -0
- package/dist/types/checkout.d.ts +2 -0
- package/dist/types/commons.d.ts +2 -7
- package/dist/types/customer.d.ts +4 -0
- package/dist/types/mercadoPago.d.ts +62 -0
- package/package.json +1 -1
- package/src/classes/3dsHandler.ts +6 -26
- package/src/classes/BaseInlineCheckout.ts +24 -24
- package/src/classes/liteCheckout.ts +1 -1
- package/src/shared/catalog/paymentMethodsCatalog.ts +8 -0
- package/src/shared/constants/paymentMethodAPM.ts +1 -0
- package/src/types/checkout.ts +2 -0
- package/src/types/commons.ts +2 -7
- package/src/types/customer.ts +4 -0
- package/src/types/liteInlineCheckout.ts +1 -1
- package/src/types/mercadoPago.ts +62 -0
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { CustomizationOptions } from "../types/commons";
|
|
2
1
|
type ThreeDSHandlerContructor = {
|
|
3
2
|
payload?: any;
|
|
4
3
|
apiKey?: string;
|
|
5
4
|
baseUrl?: string;
|
|
6
|
-
|
|
5
|
+
redirectOnComplete?: boolean;
|
|
7
6
|
tdsIframeId?: string;
|
|
8
7
|
tonderPayButtonId?: string;
|
|
9
8
|
callBack?: (params: any) => any;
|
|
@@ -14,10 +13,10 @@ export declare class ThreeDSHandler {
|
|
|
14
13
|
apiKey?: string;
|
|
15
14
|
payload?: any;
|
|
16
15
|
localStorageKey: string;
|
|
17
|
-
|
|
16
|
+
redirectOnComplete?: boolean;
|
|
18
17
|
tdsIframeId?: string;
|
|
19
18
|
tonderPayButtonId?: string;
|
|
20
|
-
constructor({ payload, apiKey, baseUrl,
|
|
19
|
+
constructor({ payload, apiKey, baseUrl, redirectOnComplete, tdsIframeId, tonderPayButtonId, callBack }: ThreeDSHandlerContructor);
|
|
21
20
|
setStorageItem(data: any): void;
|
|
22
21
|
getStorageItem(): string | null;
|
|
23
22
|
removeStorageItem(): void;
|
|
@@ -6,7 +6,7 @@ import { ICustomerCardsResponse, ISaveCardResponse, ISaveCardSkyflowRequest } fr
|
|
|
6
6
|
import { IPaymentMethodResponse } from "../types/paymentMethod";
|
|
7
7
|
import { ITransaction } from "../types/transaction";
|
|
8
8
|
import { GetSecureTokenResponse } from "../types/responses";
|
|
9
|
-
export declare class BaseInlineCheckout {
|
|
9
|
+
export declare class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOptions> {
|
|
10
10
|
#private;
|
|
11
11
|
baseUrl: string;
|
|
12
12
|
cartTotal: string | number;
|
|
@@ -23,7 +23,7 @@ export declare class BaseInlineCheckout {
|
|
|
23
23
|
customer?: ICustomer | {
|
|
24
24
|
email: string;
|
|
25
25
|
};
|
|
26
|
-
customization:
|
|
26
|
+
customization: T;
|
|
27
27
|
cartItems?: IItem[];
|
|
28
28
|
metadata: {};
|
|
29
29
|
card?: {} | undefined;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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,tonderPayButtonId:i,callBack:s}){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.tonderPayButtonId=i,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=s}setStorageItem(t){return localStorage.setItem(this.localStorageKey,JSON.stringify(t))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var t,e,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=()=>{try{const t=document.querySelector(`#${this.tonderPayButtonId}`);t&&(t.disabled=!1)}catch(t){}t&&t.setAttribute("style","display: none"),n.callBack&&n.callBack(n.payload),t.removeEventListener("load",r)},i=t=>o(this,void 0,void 0,(function*(){const r=yield new Promise(((e,o)=>e(t)));if(r){if((t=>"Pending"!==(null==t?void 0:t.transaction_status))(r))return e();{const t=setTimeout((()=>o(this,void 0,void 0,(function*(){clearTimeout(t),yield i(n.requestTransactionStatus())}))),7e3)}}}));yield i(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.",secureTokenError:"Ha ocurrido un error obteniendo el token de seguridad."});var f,v,g,_,A,b,E,T,C,O;class S{constructor({mode:t="stage",customization:e,apiKey:o,apiKeyTonder:n,returnUrl:r,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d}){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,tonderPayButtonId:d,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){"secureToken"in t&&n(this,f,"m",A).call(this,t.secureToken),n(this,f,"m",g).call(this,t)}verify3dsTransaction(){return o(this,void 0,void 0,(function*(){const t=yield this.process3ds.verifyTransactionStatus(),e=yield n(this,f,"m",O).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*(){try{n(this,f,"m",g).call(this,t);const o=yield this._checkout(t);this.process3ds.setPayload(o);if(yield this._handle3dsRedirect(o)){try{const t=document.querySelector(`#${this.tonderPayButtonId}`);t&&(t.disabled=!1)}catch(t){}this.callBack&&this.callBack(o),e(o)}}catch(t){r(t)}}))))}getSecureToken(t){return o(this,void 0,void 0,(function*(){try{return yield function(t,e,n=null){return o(this,void 0,void 0,(function*(){try{const o=yield fetch(`${t}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:n});if(o.ok)return yield o.json();throw yield c(o)}catch(t){throw d(t)}}))}(this.baseUrl,t)}catch(t){throw l({message:y.secureTokenError},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,i=null){return o(this,void 0,void 0,(function*(){try{const o=`${t}/api/v1/business/${r}/cards/`,s=yield fetch(o,{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","User-token":e},signal:i});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield c(s)}catch(t){throw d(t)}}))}(this.baseUrl,t,this.secureToken,e)}))}_saveCustomerCard(t,e,n){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 ${n}`,"Content-Type":"application/json","User-token":e},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield c(s)}catch(t){throw d(t)}}))}(this.baseUrl,t,this.secureToken,e,n)}))}_removeCustomerCard(t,e,n){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/${i}/cards/${r}`,s=yield fetch(o,{method:"DELETE",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","User-token":e}});if(204===s.status)return y.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield c(s)}catch(t){throw d(t)}}))}(this.baseUrl,t,this.secureToken,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();throw yield c(i)}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 j({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){var e,o;!t||t&&0===Object.keys(t).length||(n(this,f,"m",_).call(this,t.customer),this._setCartTotal((null===(e=t.cart)||void 0===e?void 0:e.total)||0),n(this,f,"m",b).call(this,(null===(o=t.cart)||void 0===o?void 0:o.items)||[]),n(this,f,"m",E).call(this,t),n(this,f,"m",T).call(this,t),n(this,f,"m",C).call(this,t))},_=function(t){t&&(this.customer=t)},A=function(t){this.secureToken=t},b=function(t){this.cartItems=t},E=function(t){this.metadata=null==t?void 0:t.metadata},T=function(t){this.currency=null==t?void 0:t.currency},C=function(t){this.card=null==t?void 0:t.card},O=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 w=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"}),I={[w.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[w.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[w.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[w.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[w.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[w.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[w.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[w.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[w.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[w.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[w.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[w.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[w.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[w.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[w.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[w.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[w.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[w.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[w.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[w.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[w.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[w.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[w.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[w.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[w.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[w.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[w.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[w.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[w.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[w.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[w.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},k=t=>{const e=t.toUpperCase().trim().replace(/\s+/g,"");return I[e]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class M extends S{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){return o(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),{vault_id:o,vault_url:n,business:r}=this.merchantData,i=yield j({vault_id:o,vault_url:n,data:t,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._saveCustomerCard(e,null==r?void 0:r.pk,i)}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},k(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 j({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 j({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},k(t.payment_method)))).sort(((t,e)=>t.priority-e.priority)),this.activeAPMs}catch(t){return console.error("Error getting APMS",t),[]}}))}}function R(t){return/^\d{12,19}$/.test(t)&&D(t)}function U(t){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(t)}function N(t){return/^\d{3,4}$/.test(t)}function P(t){return/^(0[1-9]|1[0-2])$/.test(t)}function L(t){if(!/^\d{2}$/.test(t))return!1;const e=(new Date).getFullYear()%100;return parseInt(t,10)>=e}const D=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{S as BaseInlineCheckout,M as LiteCheckout,N as validateCVV,R as validateCardNumber,U as validateCardholderName,P as validateExpirationMonth,L as validateExpirationYear};
|
|
1
|
+
import{get as t}from"lodash";import e from"skyflow-js";function n(t,e,n,o){return new(n||(n=Promise))((function(r,i){function s(t){try{d(o.next(t))}catch(t){i(t)}}function a(t){try{d(o.throw(t))}catch(t){i(t)}}function d(t){var e;t.done?r(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}d((o=o.apply(t,e||[])).next())}))}function o(t,e,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!o:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(t):o?o.value:e.get(t)}function r(t,e,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(t,n):r?r.value=n:e.set(t,n),n}function i(t,e,o){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${t}/api/v1/payments/business/${e}`,{headers:{Authorization:`Token ${e}`},signal:o});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor({code:t,body:e,name:n,message:o,stack:r}){this.code=t,this.body=e,this.name=n,this.message=o,this.stack=r}}const a=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),d=t=>{var e;return t&&"business"in t?null===(e=null==t?void 0:t.business)||void 0===e?void 0:e.pk:""},c=t=>new s({code:(null==t?void 0:t.status)?t.status:t.code,body:null==t?void 0:t.body,name:t?"string"==typeof t?"catch":t.name:"Error",message:t?"string"==typeof t?t:t.message:"Error",stack:"string"==typeof t?void 0:t.stack}),l=(t,e=void 0)=>n(void 0,void 0,void 0,(function*(){let n,o,r="Error";t&&"json"in t&&(n=yield null==t?void 0:t.json()),t&&"status"in t&&(o=t.status.toString()),!n&&t&&"text"in t&&(r=yield t.text()),(null==n?void 0:n.detail)&&(r=n.detail);return new s({code:o,body:n,name:o,message:r,stack:e})}));function u(t,e){var n,o;let r=200;try{r=Number((null==e?void 0:e.code)||200)}catch(t){}const i={status:"error",code:r,message:"",detail:(null===(n=null==e?void 0:e.body)||void 0===n?void 0:n.detail)||(null===(o=null==e?void 0:e.body)||void 0===o?void 0:o.error)||e.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),t)}class h{constructor({payload:t=null,apiKey:e,baseUrl:n,redirectOnComplete:o,tdsIframeId:r,tonderPayButtonId:i,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=t=>{this.payload=t},this.baseUrl=n,this.apiKey=e,this.payload=t,this.tdsIframeId=r,this.tonderPayButtonId=i,this.redirectOnComplete=o,this.callBack=s}setStorageItem(t){return localStorage.setItem(this.localStorageKey,JSON.stringify(t))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var t,e,n,o,r,i;const s=null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const t=null===(i=null===(r=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;t?this.saveUrlWithExpiration(t):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(t){try{const e={url:t,expires:(new Date).getTime()+12e5};this.setStorageItem(e)}catch(t){console.log("error: ",t)}}getUrlWithExpiration(){const t=this.getStorageItem();if(t){const e=JSON.parse(t);if(!e)return;return(new Date).getTime()>e.expires?(this.removeVerifyTransactionUrl(),null):e.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var t,e,n;if(null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((t,e)=>{var n,o,r;const i=null===(r=null===(o=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(o);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>t(!0):(console.log("No redirection found"),e(!1))}else console.log("No redirection found"),e(!1)}))}getRedirectUrl(){var t,e,n;return null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const t=this.getRedirectUrl();if(t)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=t;else{const e=document.querySelector(`#${this.tdsIframeId}`);if(e){e.setAttribute("src",t),e.setAttribute("style","display: block");const o=this,r=t=>n(this,void 0,void 0,(function*(){const t=()=>{try{const t=document.querySelector(`#${this.tonderPayButtonId}`);t&&(t.disabled=!1)}catch(t){}e&&e.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),e.removeEventListener("load",r)},i=e=>n(this,void 0,void 0,(function*(){const r=yield new Promise(((t,n)=>t(e)));if(r){if((t=>"Pending"!==(null==t?void 0:t.transaction_status))(r))return t();{const t=setTimeout((()=>n(this,void 0,void 0,(function*(){clearTimeout(t),yield i(o.requestTransactionStatus())}))),7e3)}}}));yield i(o.requestTransactionStatus())}));e.addEventListener("load",r)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return n(this,void 0,void 0,(function*(){const t=this.getUrlWithExpiration(),e=`${this.baseUrl}${t}`,n=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==n.status)return console.error("La verificación de la transacción falló."),null;return yield n.json()}))}getURLParameters(){const t={},e=new URLSearchParams(window.location.search);for(const[n,o]of e)t[n]=o;return t}handleSuccessTransaction(t){return this.removeVerifyTransactionUrl(),console.log("Transacción autorizada."),t}handleDeclinedTransaction(t){return this.removeVerifyTransactionUrl(),t}handle3dsChallenge(t){return n(this,void 0,void 0,(function*(){const e=document.createElement("form");e.name="frm",e.method="POST",e.action=t.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=t.creq,n.value=t.creq,e.appendChild(n);const o=document.createElement("input");o.type="hidden",o.name=t.term_url,o.value=t.TermUrl,e.appendChild(o),document.body.appendChild(e),e.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(t){return n(this,void 0,void 0,(function*(){const e=yield t.json();return"Pending"===e.status&&e.redirect_post_url?yield this.handle3dsChallenge(e):["Success","Authorized"].includes(e.status)?this.handleSuccessTransaction(e):(this.handleDeclinedTransaction(t),e)}))}verifyTransactionStatus(){return n(this,void 0,void 0,(function*(){const t=this.getUrlWithExpiration();if(t){const e=t.startsWith("https://")?t:`${this.baseUrl}${t}`;try{const t=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==t.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),t):yield this.handleTransactionResponse(t)}catch(t){console.error("Error al verificar la transacción:",t),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const p=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function m(t,e,o){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/checkout-router/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(Object.assign(Object.assign({},r),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.status>=200&&i.status<=299)return yield i.json();{const t=yield i.json(),e=new Error("Failed to start checkout router");throw e.details=t,e}}catch(t){throw t}}))}function y(t,e,o=!0,r=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(t),n.setApiKey(e),n.setSandboxMode(o),yield n.deviceData.setup({signal:r})}))}const f=Object.freeze({saveCardError:"Ha ocurrido un error guardando la tarjeta. Inténtalo nuevamente.",removeCardError:"Ha ocurrido un error eliminado la tarjeta. Inténtalo nuevamente.",getCardsError:"Ha ocurrido un error obteniendo las tarjetas del customer. Inténtalo nuevamente.",cardExist:"La tarjeta fue registrada previamente.",removedCard:"Card deleted successfully",errorCheckout:"No se ha podido procesar el pago",cardSaved:"Tarjeta registrada con éxito.",getPaymentMethodsError:"Ha ocurrido un error obteniendo las métodos de pago del customer. Inténtalo nuevamente.",getBusinessError:"Ha ocurrido un error obteniendo los datos del comercio. Inténtalo nuevamente.",secureTokenError:"Ha ocurrido un error obteniendo el token de seguridad."});var v,g,_,A,b,E,T,O,C,S,j,k;class I{constructor({mode:t="stage",customization:e,apiKey:n,apiKeyTonder:o,returnUrl:r,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d}){v.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.card={},this.currency="",g.set(this,void 0),_.set(this,void 0),this.apiKeyTonder=o||n||"",this.returnUrl=r,this.callBack=s,this.mode=t,this.customer={},this.baseUrl=a||p[this.mode]||p.stage,this.abortController=new AbortController,this.customization=Object.assign(Object.assign({},this.customization),e||{}),this.process3ds=new h({apiKey:n,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i}configureCheckout(t){"secureToken"in t&&o(this,v,"m",E).call(this,t.secureToken),o(this,v,"m",A).call(this,t)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const t=yield this.process3ds.verifyTransactionStatus(),e=yield o(this,v,"m",j).call(this,t);return this.process3ds.setPayload(e),this._handle3dsRedirect(e)}))}payment(t){return new Promise(((e,r)=>n(this,void 0,void 0,(function*(){try{o(this,v,"m",A).call(this,t);const n=yield this._checkout(t);this.process3ds.setPayload(n);if(yield this._handle3dsRedirect(n)){try{const t=document.querySelector(`#${this.tonderPayButtonId}`);t&&(t.disabled=!1)}catch(t){}this.callBack&&this.callBack(n),e(n)}}catch(t){r(t)}}))))}getSecureToken(t){return n(this,void 0,void 0,(function*(){try{return yield function(t,e,o=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${t}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:o});if(n.ok)return yield n.json();throw yield l(n)}catch(t){throw c(t)}}))}(this.baseUrl,t)}catch(t){throw u({message:f.secureTokenError},t)}}))}_initializeCheckout(){return n(this,void 0,void 0,(function*(){const t=yield this._fetchMerchantData();t&&t.mercado_pago&&t.mercado_pago.active&&function(){try{const t=document.createElement("script");t.src="https://www.mercadopago.com/v2/security.js",t.setAttribute("view",""),t.onload=()=>{console.log("Mercado Pago script loaded successfully.")},t.onerror=t=>{console.error("Error loading Mercado Pago script:",t)},document.head.appendChild(t)}catch(t){console.error("Error attempting to inject Mercado Pago script:",t)}}()}))}_checkout(t){return n(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(t){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(t=null){return n(this,void 0,void 0,(function*(){return o(this,_,"f")||r(this,_,yield function(t,e,o,r=null){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},signal:r,body:JSON.stringify(i)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,t),"f"),o(this,_,"f")}))}_handleCheckout({card:e,payment_method:r,customer:i,isSandbox:s,returnUrl:d}){return n(this,void 0,void 0,(function*(){const{openpay_keys:c,reference:l,business:u}=this.merchantData,h=Number(this.cartTotal);try{let p;!p&&c.merchant_id&&c.public_key&&!r&&(p=yield y(c.merchant_id,c.public_key,s,this.abortController.signal));const{id:f,auth_token:v}=i,_={business:this.apiKeyTonder,client:v,billing_address_id:null,shipping_address_id:null,amount:h,status:"A",reference:l,is_oneclick:!0,items:this.cartItems},A=yield function(t,e,o){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/orders/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(r)});if(201===i.status)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,_),b=(new Date).toISOString(),E={business_pk:u.pk,client_id:f,amount:h,date:b,order_id:A.id},T=yield function(t,e,o){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/business/${o.business_pk}/payments/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(r)});if(i.status>=200&&i.status<=299)return yield i.json();throw new Error(`Error: ${i.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,E),O=Object.assign(Object.assign(Object.assign({name:t(this.customer,"firstName",t(this.customer,"name","")),last_name:t(this.customer,"lastName",t(this.customer,"lastname","")),email_client:t(this.customer,"email",""),phone_number:t(this.customer,"phone",""),return_url:d||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:h,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:A.id,business_id:u.pk,payment_id:T.pk,source:"sdk",metadata:this.metadata,browser_info:a(),currency:this.currency},r?{payment_method:r}:{card:e}),{apm_config:o(this,g,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),C=yield m(this.baseUrl,this.apiKeyTonder,O);return C||!1}catch(t){throw console.log(t),t}}))}_fetchMerchantData(){return n(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(t){return this.merchantData}}))}_getCustomerCards(t,e){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r,i=null){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":e},signal:i});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield l(s)}catch(t){throw c(t)}}))}(this.baseUrl,t,this.secureToken,e)}))}_saveCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r,i){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${r}/cards/`,s=yield fetch(n,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":e},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield l(s)}catch(t){throw c(t)}}))}(this.baseUrl,t,this.secureToken,e,o)}))}_removeCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r="",i){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${i}/cards/${r}`,s=yield fetch(n,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":e}});if(204===s.status)return f.removedCard;if(s.ok&&"json"in s)return yield s.json();throw yield l(s)}catch(t){throw c(t)}}))}(this.baseUrl,t,this.secureToken,o,e)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(t,e,o={status:"active",pagesize:"10000"},r=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(o).toString(),i=yield fetch(`${t}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();throw yield l(i)}catch(t){throw c(t)}}))}(this.baseUrl,this.apiKeyTonder)}))}_handle3dsRedirect(t){var e,o;return n(this,void 0,void 0,(function*(){if(t&&"next_action"in t?null===(o=null===(e=null==t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t)}));else{if(!this.process3ds.getRedirectUrl())return t;this.process3ds.redirectToChallenge()}}))}}function w({baseUrl:t,apiKey:o,vault_id:r,vault_url:i,data:s}){return n(this,void 0,void 0,(function*(){const a=e.init({vaultID:r,vaultURL:i,getBearerToken:()=>n(this,void 0,void 0,(function*(){return yield function(t,e,o=null){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${t}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${e}`},signal:o});if(n.ok)return(yield n.json()).token;throw new Error("Failed to retrieve bearer token")}))}(t,o)})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}),d=a.container(e.ContainerType.COLLECT),l=yield function(t,o){return n(this,void 0,void 0,(function*(){const r=yield function(t,o){return n(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(t).map((t=>n(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:t,type:e.ElementType.INPUT_FIELD}),key:t}})))))}))}(t,o);return r?r.map((e=>new Promise((n=>{var o;const r=document.createElement("div");r.hidden=!0,r.id=`id-${e.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(r),setTimeout((()=>{e.element.mount(`#id-${e.key}`),setInterval((()=>{if(e.element.isMounted()){const o=t[e.key];return e.element.update({value:o}),n(e.element.isMounted())}}),120)}),120)})))):[]}))}(s,d);if((yield Promise.all(l)).some((t=>!t)))throw c(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const t=yield d.collect();if(t)return t.records[0].fields;throw c(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(t){throw c(t)}}))}g=new WeakMap,_=new WeakMap,v=new WeakSet,A=function(t){var e,n;!t||t&&0===Object.keys(t).length||(o(this,v,"m",b).call(this,t.customer),this._setCartTotal((null===(e=t.cart)||void 0===e?void 0:e.total)||0),o(this,v,"m",T).call(this,(null===(n=t.cart)||void 0===n?void 0:n.items)||[]),o(this,v,"m",O).call(this,t),o(this,v,"m",C).call(this,t),o(this,v,"m",S).call(this,t),o(this,v,"m",k).call(this,t))},b=function(t){t&&(this.customer=t)},E=function(t){this.secureToken=t},T=function(t){this.cartItems=t},O=function(t){this.metadata=null==t?void 0:t.metadata},C=function(t){this.currency=null==t?void 0:t.currency},S=function(t){this.card=null==t?void 0:t.card},j=function(t){var e,o,r;return n(this,void 0,void 0,(function*(){if("Hard"===(null===(e=null==t?void 0:t.decline)||void 0===e?void 0:e.error_type)||(null===(o=null==t?void 0:t.checkout)||void 0===o?void 0:o.is_route_finished)||(null==t?void 0:t.is_route_finished)||["Pending"].includes(null==t?void 0:t.transaction_status))return t;if(["Success","Authorized"].includes(null==t?void 0:t.transaction_status))return t;if(t){const e={checkout_id:(null===(r=t.checkout)||void 0===r?void 0:r.id)||(null==t?void 0:t.checkout_id)};try{return yield m(this.baseUrl,this.apiKeyTonder,e)}catch(t){}return t}}))},k=function(t){r(this,g,null==t?void 0:t.apm_config,"f")};const M=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",OXXOPAY:"OXXOPAY",SPEI:"SPEI",CODI:"CODI",MERCADOPAGO:"MERCADOPAGO",PAYPAL:"PAYPAL",COMERCIALMEXICANA:"COMERCIALMEXICANA",BANCOMER:"BANCOMER",WALMART:"WALMART",BODEGA:"BODEGA",SAMSCLUB:"SAMSCLUB",SUPERAMA:"SUPERAMA",CALIMAX:"CALIMAX",EXTRA:"EXTRA",CIRCULOK:"CIRCULOK",SEVEN11:"7ELEVEN",TELECOMM:"TELECOMM",BANORTE:"BANORTE",BENAVIDES:"BENAVIDES",DELAHORRO:"DELAHORRO",ELASTURIANO:"ELASTURIANO",WALDOS:"WALDOS",ALSUPER:"ALSUPER",KIOSKO:"KIOSKO",STAMARIA:"STAMARIA",LAMASBARATA:"LAMASBARATA",FARMROMA:"FARMROMA",FARMUNION:"FARMUNION",FARMATODO:"FARMATODO",SFDEASIS:"SFDEASIS",FARM911:"FARM911",FARMECONOMICAS:"FARMECONOMICAS",FARMMEDICITY:"FARMMEDICITY",RIANXEIRA:"RIANXEIRA",WESTERNUNION:"WESTERNUNION",ZONAPAGO:"ZONAPAGO",CAJALOSANDES:"CAJALOSANDES",CAJAPAITA:"CAJAPAITA",CAJASANTA:"CAJASANTA",CAJASULLANA:"CAJASULLANA",CAJATRUJILLO:"CAJATRUJILLO",EDPYME:"EDPYME",KASNET:"KASNET",NORANDINO:"NORANDINO",QAPAQ:"QAPAQ",RAIZ:"RAIZ",PAYSER:"PAYSER",WUNION:"WUNION",BANCOCONTINENTAL:"BANCOCONTINENTAL",GMONEY:"GMONEY",GOPAY:"GOPAY",WU:"WU",PUNTOSHEY:"PUNTOSHEY",AMPM:"AMPM",JUMBOMARKET:"JUMBOMARKET",SMELPUEBLO:"SMELPUEBLO",BAM:"BAM",REFACIL:"REFACIL",ACYVALORES:"ACYVALORES"}),R={[M.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[M.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[M.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[M.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[M.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[M.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[M.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[M.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[M.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[M.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[M.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[M.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[M.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[M.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[M.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[M.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[M.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[M.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[M.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[M.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[M.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[M.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[M.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[M.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[M.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[M.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[M.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[M.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[M.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[M.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[M.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[M.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[M.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},U=t=>{const e=t.toUpperCase().trim().replace(/\s+/g,"");return R[e]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class N extends I{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 u({message:f.getCardsError},t)}}))}saveCustomerCard(t){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),{vault_id:n,vault_url:o,business:r}=this.merchantData,i=yield w({vault_id:n,vault_url:o,data:t,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder});return yield this._saveCustomerCard(e,null==r?void 0:r.pk,i)}catch(t){throw u({message:f.saveCardError},t)}}))}removeCustomerCard(t){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),{business:n}=this.merchantData;return yield this._removeCustomerCard(e,null==n?void 0:n.pk,t)}catch(t){throw u({message:f.removeCardError},t)}}))}getCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){try{const t=yield this._fetchCustomerPaymentMethods();return(t&&"results"in t&&t.results.length>0?t.results:[]).filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},U(t.payment_method)))).sort(((t,e)=>t.priority-e.priority))}catch(t){throw u({message:f.getPaymentMethodsError},t)}}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(t){throw u({message:f.getBusinessError},t)}}))}getOpenpayDeviceSessionID(t,e,o){return n(this,void 0,void 0,(function*(){try{return yield y(t,e,o)}catch(t){throw c(t)}}))}getSkyflowTokens({vault_id:t,vault_url:e,data:o}){return n(this,void 0,void 0,(function*(){return yield w({vault_id:t,vault_url:e,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(t){this.cartTotal=t}_checkout({card:t,payment_method:e,isSandbox:o,returnUrl:r}){return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const n=yield this._getCustomer(this.abortController.signal),{vault_id:i,vault_url:s}=this.merchantData;let a;return e&&""!==e&&null!==e||(a="string"==typeof t?{skyflow_id:t}:yield w({vault_id:i,vault_url:s,data:Object.assign(Object.assign({},t),{card_number:t.card_number.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})),yield this._handleCheckout({card:a,payment_method:e,customer:n,isSandbox:o,returnUrl:r})}))}customerRegister(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/customer/`,n={email:t},o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield l(o)}catch(t){throw c(t)}}))}createOrder(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/orders/`,n=t,o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield l(o)}catch(t){throw c(t)}}))}createPayment(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/business/${t.business_pk}/payments/`,n=t,o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield l(o)}catch(t){throw c(t)}}))}startCheckoutRouter(t){return n(this,void 0,void 0,(function*(){const e=yield m(this.baseUrl,this.apiKeyTonder,t);if(yield this.init3DSRedirect(e))return e}))}init3DSRedirect(t){return n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(t),yield this._handle3dsRedirect(t)}))}startCheckoutRouterFull(t){return n(this,void 0,void 0,(function*(){try{const{order:e,total:n,customer:o,skyflowTokens:r,return_url:i,isSandbox:d,metadata:c,currency:l,payment_method:u}=t,h=yield this._fetchMerchantData(),p=yield this.customerRegister(o.email);if(!(p&&"auth_token"in p&&h&&"reference"in h))throw new s({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const t={business:this.apiKeyTonder,client:p.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:e.items},f=yield this.createOrder(t),v=(new Date).toISOString();if(!("id"in f&&"id"in p&&"business"in h))throw new s({code:"500",body:f,name:"Keys error",message:"Order response errors"});{const t={business_pk:h.business.pk,amount:n,date:v,order_id:f.id,client_id:p.id},e=yield this.createPayment(t);let s;const{openpay_keys:g,business:_}=h;g.merchant_id&&g.public_key&&(s=yield y(g.merchant_id,g.public_key,d));const A=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:i,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:n,title_ship:"shipping",description:"transaction",device_session_id:s||null,token_id:"",order_id:"id"in f&&f.id,business_id:_.pk,payment_id:"pk"in e&&e.pk,source:"sdk",metadata:c,browser_info:a(),currency:l},u?{payment_method:u}:{card:r}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),b=yield m(this.baseUrl,this.apiKeyTonder,A);if(yield this.init3DSRedirect(b))return b}}}catch(t){throw c(t)}}))}registerCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${d(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"User-token":e,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(n.ok)return yield n.json();throw yield l(n)}catch(t){throw c(t)}}))}deleteCustomerCard(t,e=""){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${d(this.merchantData)}/cards/${e}`,{method:"DELETE",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(n.ok)return!0;throw yield l(n)}catch(t){throw c(t)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const t=yield function(t,e,o="?status=active&page_size=10000&country=México",r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${t}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield l(n)}catch(t){throw c(t)}}))}(this.baseUrl,this.apiKeyTonder),e=t&&t.results&&t.results.length>0?t.results:[];return this.activeAPMs=e.filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},U(t.payment_method)))).sort(((t,e)=>t.priority-e.priority)),this.activeAPMs}catch(t){return console.error("Error getting APMS",t),[]}}))}}function P(t){return/^\d{12,19}$/.test(t)&&K(t)}function L(t){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(t)}function D(t){return/^\d{3,4}$/.test(t)}function $(t){return/^(0[1-9]|1[0-2])$/.test(t)}function B(t){if(!/^\d{2}$/.test(t))return!1;const e=(new Date).getFullYear()%100;return parseInt(t,10)>=e}const K=t=>{const e=`${t}`.split("").reverse().map((t=>Number.parseInt(t))),n=e.shift();let o=e.reduce(((t,e,n)=>n%2!=0?t+e:t+((e*=2)>9?e-9:e)),0);return o+=n,o%10==0};export{I as BaseInlineCheckout,N as LiteCheckout,D as validateCVV,P as validateCardNumber,L as validateCardholderName,$ as validateExpirationMonth,B as validateExpirationYear};
|
package/dist/types/checkout.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ICustomer } from "./customer";
|
|
2
|
+
import { IMPConfigRequest } from "./mercadoPago";
|
|
2
3
|
export interface IStartCheckoutRequestBase {
|
|
3
4
|
name: any;
|
|
4
5
|
last_name: string;
|
|
@@ -96,6 +97,7 @@ export interface IProcessPaymentRequest {
|
|
|
96
97
|
payment_method?: string;
|
|
97
98
|
card?: ICardFields | string;
|
|
98
99
|
isSandbox?: boolean;
|
|
100
|
+
apm_config?: IMPConfigRequest | Record<string, any>;
|
|
99
101
|
/**
|
|
100
102
|
* @deprecated This property is deprecated and will be removed in a future release.
|
|
101
103
|
* Use the `returnUrl` field when creating the instance of LiteCheckout or InlineCheckout.
|
package/dist/types/commons.d.ts
CHANGED
|
@@ -84,7 +84,7 @@ export interface IConfigureCheckout extends Partial<IProcessPaymentRequest> {
|
|
|
84
84
|
};
|
|
85
85
|
secureToken: string;
|
|
86
86
|
}
|
|
87
|
-
export interface IInlineCheckoutBaseOptions {
|
|
87
|
+
export interface IInlineCheckoutBaseOptions<T extends CustomizationOptions = CustomizationOptions> {
|
|
88
88
|
mode?: "production" | "sandbox" | "stage" | "development";
|
|
89
89
|
/**
|
|
90
90
|
* @deprecated This property is deprecated and will be removed in a future release.
|
|
@@ -104,7 +104,7 @@ export interface IInlineCheckoutBaseOptions {
|
|
|
104
104
|
apiKey: string;
|
|
105
105
|
returnUrl?: string;
|
|
106
106
|
callBack?: (response: IStartCheckoutResponse | Record<string, any>) => void;
|
|
107
|
-
customization?:
|
|
107
|
+
customization?: T;
|
|
108
108
|
tdsIframeId?: string;
|
|
109
109
|
tonderPayButtonId?: string;
|
|
110
110
|
}
|
|
@@ -123,10 +123,5 @@ export interface IPublicError {
|
|
|
123
123
|
detail: Record<string, any> | string;
|
|
124
124
|
}
|
|
125
125
|
export type CustomizationOptions = {
|
|
126
|
-
saveCards?: {
|
|
127
|
-
showSaveCardOption?: boolean;
|
|
128
|
-
showSaved?: boolean;
|
|
129
|
-
autoSave?: boolean;
|
|
130
|
-
};
|
|
131
126
|
redirectOnComplete?: boolean;
|
|
132
127
|
};
|
package/dist/types/customer.d.ts
CHANGED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
export interface IMPConfigRequest {
|
|
2
|
+
payment_methods?: IMPPreferencePaymentMethod;
|
|
3
|
+
binary_mode?: boolean;
|
|
4
|
+
shipments?: IMPPreferenceShipment;
|
|
5
|
+
back_urls?: IMPPreferenceBackUrl;
|
|
6
|
+
statement_descriptor?: string;
|
|
7
|
+
additional_info?: string;
|
|
8
|
+
auto_return?: "approved" | "all";
|
|
9
|
+
expires?: boolean;
|
|
10
|
+
expiration_date_from?: string;
|
|
11
|
+
expiration_date_to?: string;
|
|
12
|
+
marketplace?: string;
|
|
13
|
+
marketplace_fee?: number;
|
|
14
|
+
differential_pricing?: {
|
|
15
|
+
id: number;
|
|
16
|
+
};
|
|
17
|
+
tracks?: {
|
|
18
|
+
type: "google_ad" | "facebook_ad";
|
|
19
|
+
values: {
|
|
20
|
+
conversion_id?: string;
|
|
21
|
+
conversion_label?: string;
|
|
22
|
+
pixel_id?: string;
|
|
23
|
+
};
|
|
24
|
+
}[];
|
|
25
|
+
}
|
|
26
|
+
export interface IMPPreferencePaymentMethod {
|
|
27
|
+
excluded_payment_methods?: {
|
|
28
|
+
id: string;
|
|
29
|
+
}[];
|
|
30
|
+
excluded_payment_types?: {
|
|
31
|
+
id: string;
|
|
32
|
+
}[];
|
|
33
|
+
default_payment_method_id?: string;
|
|
34
|
+
installments?: number;
|
|
35
|
+
default_installments?: number;
|
|
36
|
+
}
|
|
37
|
+
export interface IMPPreferenceShipment {
|
|
38
|
+
mode?: "customer" | "me2" | "not_specified";
|
|
39
|
+
local_pickup?: boolean;
|
|
40
|
+
dimensions?: string;
|
|
41
|
+
default_shipping_method?: number;
|
|
42
|
+
free_methods?: {
|
|
43
|
+
id: number;
|
|
44
|
+
}[];
|
|
45
|
+
cost?: number;
|
|
46
|
+
free_shipping?: boolean;
|
|
47
|
+
receiver_address?: {
|
|
48
|
+
zip_code?: string;
|
|
49
|
+
street_name?: string;
|
|
50
|
+
city_name?: string;
|
|
51
|
+
state_name?: string;
|
|
52
|
+
street_number?: number;
|
|
53
|
+
floor?: string;
|
|
54
|
+
apartment?: string;
|
|
55
|
+
country_name?: string;
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
export interface IMPPreferenceBackUrl {
|
|
59
|
+
success?: string;
|
|
60
|
+
pending?: string;
|
|
61
|
+
failure?: string;
|
|
62
|
+
}
|
package/package.json
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
import { CustomizationOptions } from "../types/commons"
|
|
2
|
-
|
|
3
1
|
type ThreeDSHandlerContructor = {
|
|
4
2
|
payload?: any,
|
|
5
3
|
apiKey?: string,
|
|
6
4
|
baseUrl?: string,
|
|
7
|
-
|
|
5
|
+
redirectOnComplete?: boolean,
|
|
8
6
|
tdsIframeId?: string,
|
|
9
7
|
tonderPayButtonId?: string,
|
|
10
8
|
callBack?: (params: any) => any
|
|
@@ -17,14 +15,7 @@ export class ThreeDSHandler {
|
|
|
17
15
|
apiKey?: string
|
|
18
16
|
payload?: any
|
|
19
17
|
localStorageKey: string = "verify_transaction_status_url"
|
|
20
|
-
|
|
21
|
-
saveCards: {
|
|
22
|
-
showSaveCardOption: true,
|
|
23
|
-
showSaved: true,
|
|
24
|
-
autoSave: false
|
|
25
|
-
},
|
|
26
|
-
redirectOnComplete: true
|
|
27
|
-
}
|
|
18
|
+
redirectOnComplete?: boolean
|
|
28
19
|
tdsIframeId?: string
|
|
29
20
|
tonderPayButtonId?: string
|
|
30
21
|
|
|
@@ -32,7 +23,7 @@ export class ThreeDSHandler {
|
|
|
32
23
|
payload = null,
|
|
33
24
|
apiKey,
|
|
34
25
|
baseUrl,
|
|
35
|
-
|
|
26
|
+
redirectOnComplete,
|
|
36
27
|
tdsIframeId,
|
|
37
28
|
tonderPayButtonId,
|
|
38
29
|
callBack
|
|
@@ -42,14 +33,7 @@ export class ThreeDSHandler {
|
|
|
42
33
|
this.payload = payload
|
|
43
34
|
this.tdsIframeId = tdsIframeId
|
|
44
35
|
this.tonderPayButtonId = tonderPayButtonId
|
|
45
|
-
this.
|
|
46
|
-
...this.customization,
|
|
47
|
-
...(customization || {}),
|
|
48
|
-
saveCards: {
|
|
49
|
-
...this.customization.saveCards,
|
|
50
|
-
...(customization?.saveCards || {}),
|
|
51
|
-
},
|
|
52
|
-
}
|
|
36
|
+
this.redirectOnComplete = redirectOnComplete
|
|
53
37
|
this.callBack = callBack
|
|
54
38
|
}
|
|
55
39
|
|
|
@@ -160,8 +144,7 @@ export class ThreeDSHandler {
|
|
|
160
144
|
const url = this.getRedirectUrl()
|
|
161
145
|
if (url) {
|
|
162
146
|
this.saveVerifyTransactionUrl()
|
|
163
|
-
|
|
164
|
-
if(this.customization?.redirectOnComplete) {
|
|
147
|
+
if(this.redirectOnComplete) {
|
|
165
148
|
window.location = url;
|
|
166
149
|
} else {
|
|
167
150
|
const iframe = document.querySelector(`#${this.tdsIframeId}`)
|
|
@@ -213,9 +196,6 @@ export class ThreeDSHandler {
|
|
|
213
196
|
console.log('No iframe found');
|
|
214
197
|
}
|
|
215
198
|
}
|
|
216
|
-
} else {
|
|
217
|
-
window.location = url;
|
|
218
|
-
}
|
|
219
199
|
} else {
|
|
220
200
|
if (this.callBack) this.callBack!(this.payload);
|
|
221
201
|
}
|
|
@@ -314,7 +294,7 @@ export class ThreeDSHandler {
|
|
|
314
294
|
async verifyTransactionStatus() {
|
|
315
295
|
const verifyUrl = this.getUrlWithExpiration();
|
|
316
296
|
if (verifyUrl) {
|
|
317
|
-
const url = `${this.baseUrl}${verifyUrl}`;
|
|
297
|
+
const url = verifyUrl.startsWith("https://") ? verifyUrl : `${this.baseUrl}${verifyUrl}`;
|
|
318
298
|
try {
|
|
319
299
|
const response = await fetch(url, {
|
|
320
300
|
method: "GET",
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { ThreeDSHandler } from "./3dsHandler";
|
|
2
|
-
import { ErrorResponse } from "./errorResponse";
|
|
3
2
|
import { fetchBusiness } from "../data/businessApi";
|
|
4
3
|
import { injectMercadoPagoSecurity } from "../helpers/mercadopago";
|
|
5
4
|
import { TONDER_URL_BY_MODE } from "../shared/constants/tonderUrl";
|
|
@@ -10,8 +9,6 @@ import {
|
|
|
10
9
|
} from "../data/checkoutApi";
|
|
11
10
|
import { getOpenpayDeviceSessionID } from "../data/openPayApi";
|
|
12
11
|
import {
|
|
13
|
-
buildErrorResponse,
|
|
14
|
-
buildErrorResponseFromCatch,
|
|
15
12
|
formatPublicErrorResponse,
|
|
16
13
|
getBrowserInfo
|
|
17
14
|
} from "../helpers/utils";
|
|
@@ -37,7 +34,8 @@ import {ITransaction} from "../types/transaction";
|
|
|
37
34
|
import {GetSecureTokenResponse} from "../types/responses";
|
|
38
35
|
import {getSecureToken} from "../data/tokenApi";
|
|
39
36
|
import {MESSAGES} from "../shared/constants/messages";
|
|
40
|
-
|
|
37
|
+
import { IMPConfigRequest } from "../types/mercadoPago";
|
|
38
|
+
export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOptions> {
|
|
41
39
|
baseUrl = "";
|
|
42
40
|
cartTotal: string | number = "0";
|
|
43
41
|
process3ds: ThreeDSHandler;
|
|
@@ -51,20 +49,15 @@ export class BaseInlineCheckout {
|
|
|
51
49
|
abortController: AbortController;
|
|
52
50
|
secureToken: string = "";
|
|
53
51
|
customer?: ICustomer | { email: string };
|
|
54
|
-
customization:
|
|
55
|
-
saveCards: {
|
|
56
|
-
showSaveCardOption: true,
|
|
57
|
-
showSaved: true,
|
|
58
|
-
autoSave: false
|
|
59
|
-
},
|
|
52
|
+
customization: T = {
|
|
60
53
|
redirectOnComplete: true
|
|
61
|
-
}
|
|
54
|
+
} as T;
|
|
62
55
|
|
|
63
56
|
cartItems?: IItem[];
|
|
64
57
|
metadata = {};
|
|
65
58
|
card? = {};
|
|
66
59
|
currency?: string = "";
|
|
67
|
-
|
|
60
|
+
#apm_config?:IMPConfigRequest | Record<string, any>
|
|
68
61
|
#customerData?: Record<string, any>;
|
|
69
62
|
|
|
70
63
|
constructor({
|
|
@@ -85,23 +78,20 @@ export class BaseInlineCheckout {
|
|
|
85
78
|
this.customer = {} as ICustomer
|
|
86
79
|
this.baseUrl = baseUrlTonder || TONDER_URL_BY_MODE[this.mode] || TONDER_URL_BY_MODE["stage"];
|
|
87
80
|
this.abortController = new AbortController();
|
|
81
|
+
this.customization = {
|
|
82
|
+
...this.customization,
|
|
83
|
+
...(customization || {}),
|
|
84
|
+
}
|
|
85
|
+
|
|
88
86
|
this.process3ds = new ThreeDSHandler({
|
|
89
87
|
apiKey: apiKey,
|
|
90
88
|
baseUrl: this.baseUrl,
|
|
91
|
-
|
|
89
|
+
redirectOnComplete: this.customization.redirectOnComplete,
|
|
92
90
|
tdsIframeId: tdsIframeId,
|
|
93
91
|
tonderPayButtonId: tonderPayButtonId,
|
|
94
92
|
callBack: callBack
|
|
95
93
|
});
|
|
96
94
|
this.tdsIframeId = tdsIframeId;
|
|
97
|
-
this.customization = {
|
|
98
|
-
...this.customization,
|
|
99
|
-
...(customization || {}),
|
|
100
|
-
saveCards: {
|
|
101
|
-
...this.customization.saveCards,
|
|
102
|
-
...(customization?.saveCards || {})
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
95
|
}
|
|
106
96
|
|
|
107
97
|
configureCheckout(data: IConfigureCheckout) {
|
|
@@ -209,7 +199,8 @@ export class BaseInlineCheckout {
|
|
|
209
199
|
if (
|
|
210
200
|
!deviceSessionIdTonder &&
|
|
211
201
|
openpay_keys.merchant_id &&
|
|
212
|
-
openpay_keys.public_key
|
|
202
|
+
openpay_keys.public_key &&
|
|
203
|
+
!payment_method
|
|
213
204
|
) {
|
|
214
205
|
deviceSessionIdTonder = await getOpenpayDeviceSessionID(
|
|
215
206
|
openpay_keys.merchant_id,
|
|
@@ -283,6 +274,8 @@ export class BaseInlineCheckout {
|
|
|
283
274
|
browser_info: getBrowserInfo(),
|
|
284
275
|
currency: this.currency!,
|
|
285
276
|
...(!!payment_method ? { payment_method } : { card }),
|
|
277
|
+
apm_config: this.#apm_config,
|
|
278
|
+
...(this.customer && "identification" in this.customer ? { identification: this.customer.identification } : {})
|
|
286
279
|
};
|
|
287
280
|
|
|
288
281
|
const jsonResponseRouter = await startCheckoutRouter(
|
|
@@ -310,6 +303,7 @@ export class BaseInlineCheckout {
|
|
|
310
303
|
this.#handleMetadata(data);
|
|
311
304
|
this.#handleCurrency(data);
|
|
312
305
|
this.#handleCard(data);
|
|
306
|
+
this.#handleApmConfig(data);
|
|
313
307
|
}
|
|
314
308
|
|
|
315
309
|
async _fetchMerchantData() {
|
|
@@ -427,7 +421,10 @@ export class BaseInlineCheckout {
|
|
|
427
421
|
|
|
428
422
|
async #resumeCheckout(response: any) {
|
|
429
423
|
// Stop the routing process if the transaction is either hard declined or successful
|
|
430
|
-
if (response?.decline?.error_type === "Hard"
|
|
424
|
+
if (response?.decline?.error_type === "Hard" ||
|
|
425
|
+
!!response?.checkout?.is_route_finished ||
|
|
426
|
+
!!response?.is_route_finished ||
|
|
427
|
+
["Pending"].includes(response?.transaction_status)) {
|
|
431
428
|
return response;
|
|
432
429
|
}
|
|
433
430
|
|
|
@@ -437,7 +434,7 @@ export class BaseInlineCheckout {
|
|
|
437
434
|
|
|
438
435
|
if (response) {
|
|
439
436
|
const routerItems = {
|
|
440
|
-
checkout_id: response.checkout?.id,
|
|
437
|
+
checkout_id: response.checkout?.id || response?.checkout_id,
|
|
441
438
|
};
|
|
442
439
|
|
|
443
440
|
try {
|
|
@@ -452,4 +449,7 @@ export class BaseInlineCheckout {
|
|
|
452
449
|
return response;
|
|
453
450
|
}
|
|
454
451
|
}
|
|
452
|
+
#handleApmConfig(data: {apm_config?: IMPConfigRequest | Record<string, any>;}) {
|
|
453
|
+
this.#apm_config = data?.apm_config;
|
|
454
|
+
}
|
|
455
455
|
}
|
|
@@ -232,7 +232,7 @@ export class LiteCheckout extends BaseInlineCheckout implements ILiteCheckout{
|
|
|
232
232
|
const customer = await this._getCustomer(this.abortController.signal);
|
|
233
233
|
const { vault_id, vault_url } = this.merchantData!;
|
|
234
234
|
let skyflowTokens;
|
|
235
|
-
if (!payment_method || payment_method
|
|
235
|
+
if (!payment_method || payment_method === "" || payment_method === null) {
|
|
236
236
|
if (typeof card === "string") {
|
|
237
237
|
skyflowTokens = {
|
|
238
238
|
skyflow_id: card,
|
|
@@ -14,6 +14,14 @@ const PAYMENT_METHODS_CATALOG = {
|
|
|
14
14
|
label: "CoDi",
|
|
15
15
|
icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png",
|
|
16
16
|
},
|
|
17
|
+
[PAYMENT_METHOD_APM.MERCADOPAGO]: {
|
|
18
|
+
label: "Mercado Pago",
|
|
19
|
+
icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png",
|
|
20
|
+
},
|
|
21
|
+
[PAYMENT_METHOD_APM.OXXOPAY]: {
|
|
22
|
+
label: "Oxxo Pay",
|
|
23
|
+
icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png",
|
|
24
|
+
},
|
|
17
25
|
[PAYMENT_METHOD_APM.SPEI]: {
|
|
18
26
|
label: "SPEI",
|
|
19
27
|
icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png",
|
package/src/types/checkout.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {ICustomer} from "./customer";
|
|
2
|
+
import { IMPConfigRequest } from "./mercadoPago";
|
|
2
3
|
|
|
3
4
|
export interface IStartCheckoutRequestBase {
|
|
4
5
|
name: any;
|
|
@@ -108,6 +109,7 @@ export interface IProcessPaymentRequest {
|
|
|
108
109
|
payment_method?: string;
|
|
109
110
|
card?: ICardFields | string;
|
|
110
111
|
isSandbox?: boolean;
|
|
112
|
+
apm_config?: IMPConfigRequest | Record<string, any>;
|
|
111
113
|
/**
|
|
112
114
|
* @deprecated This property is deprecated and will be removed in a future release.
|
|
113
115
|
* Use the `returnUrl` field when creating the instance of LiteCheckout or InlineCheckout.
|
package/src/types/commons.ts
CHANGED
|
@@ -90,7 +90,7 @@ export interface IConfigureCheckout extends Partial<IProcessPaymentRequest>{
|
|
|
90
90
|
secureToken: string
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
-
export interface IInlineCheckoutBaseOptions {
|
|
93
|
+
export interface IInlineCheckoutBaseOptions<T extends CustomizationOptions = CustomizationOptions> {
|
|
94
94
|
mode?: "production" | "sandbox" | "stage" | "development";
|
|
95
95
|
/**
|
|
96
96
|
* @deprecated This property is deprecated and will be removed in a future release.
|
|
@@ -110,7 +110,7 @@ export interface IInlineCheckoutBaseOptions {
|
|
|
110
110
|
apiKey: string;
|
|
111
111
|
returnUrl?: string;
|
|
112
112
|
callBack?: (response: IStartCheckoutResponse | Record<string, any>) => void;
|
|
113
|
-
customization?:
|
|
113
|
+
customization?: T;
|
|
114
114
|
tdsIframeId?: string,
|
|
115
115
|
tonderPayButtonId?: string
|
|
116
116
|
}
|
|
@@ -134,10 +134,5 @@ export interface IPublicError {
|
|
|
134
134
|
}
|
|
135
135
|
|
|
136
136
|
export type CustomizationOptions = {
|
|
137
|
-
saveCards?: {
|
|
138
|
-
showSaveCardOption?: boolean;
|
|
139
|
-
showSaved?: boolean;
|
|
140
|
-
autoSave?: boolean;
|
|
141
|
-
},
|
|
142
137
|
redirectOnComplete?: boolean
|
|
143
138
|
}
|
package/src/types/customer.ts
CHANGED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
export interface IMPConfigRequest {
|
|
2
|
+
payment_methods?: IMPPreferencePaymentMethod;
|
|
3
|
+
binary_mode?: boolean;
|
|
4
|
+
shipments?: IMPPreferenceShipment;
|
|
5
|
+
back_urls?: IMPPreferenceBackUrl;
|
|
6
|
+
statement_descriptor?: string;
|
|
7
|
+
additional_info?: string;
|
|
8
|
+
auto_return?: "approved" | "all";
|
|
9
|
+
expires?: boolean;
|
|
10
|
+
expiration_date_from?: string;
|
|
11
|
+
expiration_date_to?: string;
|
|
12
|
+
marketplace?: string;
|
|
13
|
+
marketplace_fee?: number;
|
|
14
|
+
differential_pricing?: {
|
|
15
|
+
id: number;
|
|
16
|
+
};
|
|
17
|
+
tracks?: {
|
|
18
|
+
type: "google_ad" | "facebook_ad";
|
|
19
|
+
values: {
|
|
20
|
+
conversion_id?: string;
|
|
21
|
+
conversion_label?: string;
|
|
22
|
+
pixel_id?: string;
|
|
23
|
+
};
|
|
24
|
+
}[];
|
|
25
|
+
}
|
|
26
|
+
export interface IMPPreferencePaymentMethod {
|
|
27
|
+
excluded_payment_methods?: {
|
|
28
|
+
id: string;
|
|
29
|
+
}[];
|
|
30
|
+
excluded_payment_types?: {
|
|
31
|
+
id: string;
|
|
32
|
+
}[];
|
|
33
|
+
default_payment_method_id?: string;
|
|
34
|
+
installments?: number;
|
|
35
|
+
default_installments?: number;
|
|
36
|
+
}
|
|
37
|
+
export interface IMPPreferenceShipment {
|
|
38
|
+
mode?: "customer" | "me2" | "not_specified";
|
|
39
|
+
local_pickup?: boolean;
|
|
40
|
+
dimensions?: string;
|
|
41
|
+
default_shipping_method?: number;
|
|
42
|
+
free_methods?: {
|
|
43
|
+
id: number;
|
|
44
|
+
}[];
|
|
45
|
+
cost?: number;
|
|
46
|
+
free_shipping?: boolean;
|
|
47
|
+
receiver_address?: {
|
|
48
|
+
zip_code?: string;
|
|
49
|
+
street_name?: string;
|
|
50
|
+
city_name?: string;
|
|
51
|
+
state_name?: string;
|
|
52
|
+
street_number?: number;
|
|
53
|
+
floor?: string;
|
|
54
|
+
apartment?: string;
|
|
55
|
+
country_name?: string;
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
export interface IMPPreferenceBackUrl {
|
|
59
|
+
success?: string;
|
|
60
|
+
pending?: string;
|
|
61
|
+
failure?: string;
|
|
62
|
+
}
|