@tonder.io/ionic-lite-sdk 0.0.35-beta.22 → 0.0.35-beta.24
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/.idea/workspace.xml +20 -3
- package/README.md +403 -112
- package/dist/classes/BaseInlineCheckout.d.ts +4 -5
- package/dist/classes/liteCheckout.d.ts +6 -42
- package/dist/index.js +1 -1
- package/dist/types/commons.d.ts +2 -0
- package/dist/types/liteInlineCheckout.d.ts +147 -0
- package/package.json +1 -1
- package/src/classes/BaseInlineCheckout.ts +6 -5
- package/src/classes/liteCheckout.ts +7 -43
- package/src/types/commons.ts +3 -0
- package/src/types/{liteInlineCheckout.d.ts → liteInlineCheckout.ts} +4 -7
- package/tests/classes/liteCheckout.test.ts +2 -2
- package/tests/methods/createOrder.test.ts +3 -4
- package/tests/methods/createPayment.test.ts +2 -3
- package/tests/methods/customerRegister.test.ts +3 -4
- package/tests/methods/getBusiness.test.ts +2 -3
- package/tests/methods/getCustomerCards.test.ts +2 -3
- package/tests/methods/registerCustomerCard.test.ts +2 -2
- package/tests/methods/startCheckoutRouter.test.ts +2 -2
- package/tests/methods/startCheckoutRouterFull.test.ts +2 -2
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import { ThreeDSHandler } from "./3dsHandler";
|
|
2
|
-
import { ErrorResponse } from "./errorResponse";
|
|
3
2
|
import { Business, IConfigureCheckout, IInlineCheckoutBaseOptions } from "../types/commons";
|
|
4
3
|
import { ICustomer } from "../types/customer";
|
|
5
4
|
import { IItem, IProcessPaymentRequest, IStartCheckoutResponse } from "../types/checkout";
|
|
6
5
|
import { ICustomerCardsResponse, ISaveCardResponse, ISaveCardSkyflowRequest } from "../types/card";
|
|
7
6
|
import { IPaymentMethodResponse } from "../types/paymentMethod";
|
|
8
|
-
import {
|
|
7
|
+
import { ITransaction } from "../types/transaction";
|
|
9
8
|
export declare class BaseInlineCheckout {
|
|
10
9
|
#private;
|
|
11
10
|
baseUrl: string;
|
|
@@ -24,9 +23,9 @@ export declare class BaseInlineCheckout {
|
|
|
24
23
|
metadata: {};
|
|
25
24
|
card?: {} | undefined;
|
|
26
25
|
currency?: string;
|
|
27
|
-
constructor({ mode, apiKey, apiKeyTonder, returnUrl, callBack, }: IInlineCheckoutBaseOptions);
|
|
26
|
+
constructor({ mode, apiKey, apiKeyTonder, returnUrl, callBack, baseUrlTonder }: IInlineCheckoutBaseOptions);
|
|
28
27
|
configureCheckout(data: IConfigureCheckout): void;
|
|
29
|
-
verify3dsTransaction(): Promise<
|
|
28
|
+
verify3dsTransaction(): Promise<ITransaction | IStartCheckoutResponse | void>;
|
|
30
29
|
payment(data: IProcessPaymentRequest): Promise<IStartCheckoutResponse>;
|
|
31
30
|
_initializeCheckout(): Promise<void>;
|
|
32
31
|
_checkout(data: any): Promise<any>;
|
|
@@ -43,5 +42,5 @@ export declare class BaseInlineCheckout {
|
|
|
43
42
|
_saveCustomerCard(authToken: string, businessId: string | number, skyflowTokens: ISaveCardSkyflowRequest): Promise<ISaveCardResponse>;
|
|
44
43
|
_removeCustomerCard(authToken: string, businessId: string | number, skyflowId: string): Promise<string>;
|
|
45
44
|
_fetchCustomerPaymentMethods(): Promise<IPaymentMethodResponse>;
|
|
46
|
-
_handle3dsRedirect(response:
|
|
45
|
+
_handle3dsRedirect(response: ITransaction | IStartCheckoutResponse | void): Promise<void | IStartCheckoutResponse | ITransaction>;
|
|
47
46
|
}
|
|
@@ -1,21 +1,20 @@
|
|
|
1
1
|
import { ErrorResponse } from "./errorResponse";
|
|
2
2
|
import { BaseInlineCheckout } from "./BaseInlineCheckout";
|
|
3
|
-
import { APM,
|
|
3
|
+
import { APM, IInlineLiteCheckoutOptions } from "../types/commons";
|
|
4
4
|
import { ICustomerCardsResponse, ISaveCardRequest, ISaveCardResponse } from "../types/card";
|
|
5
5
|
import { IPaymentMethod } from "../types/paymentMethod";
|
|
6
6
|
import { CreateOrderResponse, CreatePaymentResponse, CustomerRegisterResponse, GetBusinessResponse, RegisterCustomerCardResponse, StartCheckoutResponse } from "../types/responses";
|
|
7
7
|
import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutFullRequest, StartCheckoutIdRequest, StartCheckoutRequest, TokensRequest } from "../types/requests";
|
|
8
|
-
import { ICardFields } from "../types/checkout";
|
|
8
|
+
import { ICardFields, IStartCheckoutResponse } from "../types/checkout";
|
|
9
|
+
import { ILiteCheckout } from "../types/liteInlineCheckout";
|
|
9
10
|
declare global {
|
|
10
11
|
interface Window {
|
|
11
12
|
OpenPay: any;
|
|
12
13
|
}
|
|
13
14
|
}
|
|
14
|
-
export
|
|
15
|
-
}
|
|
16
|
-
export declare class LiteCheckout extends BaseInlineCheckout {
|
|
15
|
+
export declare class LiteCheckout extends BaseInlineCheckout implements ILiteCheckout {
|
|
17
16
|
activeAPMs: APM[];
|
|
18
|
-
constructor({ apiKey, mode, returnUrl, callBack }:
|
|
17
|
+
constructor({ apiKey, mode, returnUrl, callBack, apiKeyTonder, baseUrlTonder }: IInlineLiteCheckoutOptions);
|
|
19
18
|
injectCheckout(): Promise<void>;
|
|
20
19
|
getCustomerCards(): Promise<ICustomerCardsResponse>;
|
|
21
20
|
saveCustomerCard(card: ISaveCardRequest): Promise<ISaveCardResponse>;
|
|
@@ -30,48 +29,13 @@ export declare class LiteCheckout extends BaseInlineCheckout {
|
|
|
30
29
|
payment_method?: string;
|
|
31
30
|
isSandbox?: boolean;
|
|
32
31
|
}): Promise<any>;
|
|
33
|
-
/**
|
|
34
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
35
|
-
* It is no longer necessary to use this method as customer registration is now automatically handled
|
|
36
|
-
* during the payment process or when using card management methods.
|
|
37
|
-
*/
|
|
38
32
|
customerRegister(email: string): Promise<CustomerRegisterResponse | ErrorResponse>;
|
|
39
|
-
/**
|
|
40
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
41
|
-
* It is no longer necessary to use this method as order creation is now automatically
|
|
42
|
-
* handled when making a payment through the `payment` function.
|
|
43
|
-
*/
|
|
44
33
|
createOrder(orderItems: CreateOrderRequest): Promise<CreateOrderResponse | ErrorResponse>;
|
|
45
|
-
/**
|
|
46
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
47
|
-
* It is no longer necessary to use this method as payment creation is now automatically
|
|
48
|
-
* handled when making a payment through the `payment` function.
|
|
49
|
-
*/
|
|
50
34
|
createPayment(paymentItems: CreatePaymentRequest): Promise<CreatePaymentResponse | ErrorResponse>;
|
|
51
|
-
/**
|
|
52
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
53
|
-
* Use the {@link payment} method
|
|
54
|
-
*/
|
|
55
35
|
startCheckoutRouter(routerData: StartCheckoutRequest | StartCheckoutIdRequest): Promise<StartCheckoutResponse | ErrorResponse | undefined>;
|
|
56
|
-
init3DSRedirect(checkoutResult:
|
|
57
|
-
/**
|
|
58
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
59
|
-
* Use the {@link payment} method
|
|
60
|
-
*/
|
|
36
|
+
init3DSRedirect(checkoutResult: IStartCheckoutResponse): Promise<void | IStartCheckoutResponse | import("../types/transaction").ITransaction>;
|
|
61
37
|
startCheckoutRouterFull(routerFullData: StartCheckoutFullRequest): Promise<StartCheckoutResponse | ErrorResponse | undefined>;
|
|
62
|
-
/**
|
|
63
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
64
|
-
* Use the {@link saveCustomerCard} method
|
|
65
|
-
*/
|
|
66
38
|
registerCustomerCard(customerToken: string, data: RegisterCustomerCardRequest): Promise<RegisterCustomerCardResponse | ErrorResponse>;
|
|
67
|
-
/**
|
|
68
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
69
|
-
* Use the {@link removeCustomerCard} method
|
|
70
|
-
*/
|
|
71
39
|
deleteCustomerCard(customerToken: string, skyflowId?: string): Promise<Boolean | ErrorResponse>;
|
|
72
|
-
/**
|
|
73
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
74
|
-
* Use the {@link getCustomerPaymentMethods} method
|
|
75
|
-
*/
|
|
76
40
|
getActiveAPMs(): Promise<APM[]>;
|
|
77
41
|
}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{get as t}from"lodash";import e from"skyflow-js";function n(t,e,n,o){return new(n||(n=Promise))((function(r,i){function s(t){try{d(o.next(t))}catch(t){i(t)}}function a(t){try{d(o.throw(t))}catch(t){i(t)}}function d(t){var e;t.done?r(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}d((o=o.apply(t,e||[])).next())}))}function o(t,e,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!o:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(t):o?o.value:e.get(t)}function r(t,e,o){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${t}/api/v1/payments/business/${e}`,{headers:{Authorization:`Token ${e}`},signal:o});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class i{constructor({code:t,body:e,name:n,message:o,stack:r}){this.code=t,this.body=e,this.name=n,this.message=o,this.stack=r}}const s=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),a=t=>{var e;return t&&"business"in t?null===(e=null==t?void 0:t.business)||void 0===e?void 0:e.pk:""},d=t=>new i({code:(null==t?void 0:t.status)?t.status:t.code,body:null==t?void 0:t.body,name:t?"string"==typeof t?"catch":t.name:"Error",message:t?"string"==typeof t?t:t.message:"Error",stack:"string"==typeof t?void 0:t.stack}),c=(t,e=void 0)=>n(void 0,void 0,void 0,(function*(){let n,o,r="Error";t&&"json"in t&&(n=yield null==t?void 0:t.json()),t&&"status"in t&&(o=t.status.toString()),!n&&t&&"text"in t&&(r=yield t.text()),(null==n?void 0:n.detail)&&(r=n.detail);return new i({code:o,body:n,name:o,message:r,stack:e})}));function l(t,e){var n,o;let r=200;try{r=Number((null==e?void 0:e.code)||200)}catch(t){}const i={status:"error",code:r,message:"",detail:(null===(n=null==e?void 0:e.body)||void 0===n?void 0:n.detail)||(null===(o=null==e?void 0:e.body)||void 0===o?void 0:o.error)||e.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),t)}class u{constructor({payload:t=null,apiKey:e,baseUrl:n}){this.localStorageKey="verify_transaction_status_url",this.setPayload=t=>{this.payload=t},this.baseUrl=n,this.apiKey=e,this.payload=t}setStorageItem(t){return localStorage.setItem(this.localStorageKey,JSON.stringify(t))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var t,e,n,o,r,i;const s=null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const t=null===(i=null===(r=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;t?this.saveUrlWithExpiration(t):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(t){try{const e={url:t,expires:(new Date).getTime()+12e5};this.setStorageItem(e)}catch(t){console.log("error: ",t)}}getUrlWithExpiration(){const t=this.getStorageItem();if(t){const e=JSON.parse(t);if(!e)return;return(new Date).getTime()>e.expires?(this.removeVerifyTransactionUrl(),null):e.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var t,e,n;if(null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((t,e)=>{var n,o,r;const i=null===(r=null===(o=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(o);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>t(!0):(console.log("No redirection found"),e(!1))}else console.log("No redirection found"),e(!1)}))}getRedirectUrl(){var t,e,n;return null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const t=this.getRedirectUrl();t?(this.saveVerifyTransactionUrl(),window.location=t):console.log("No redirection found")}getURLParameters(){const t={},e=new URLSearchParams(window.location.search);for(const[n,o]of e)t[n]=o;return t}handleSuccessTransaction(t){return this.removeVerifyTransactionUrl(),console.log("Transacción autorizada."),t}handleDeclinedTransaction(t){return this.removeVerifyTransactionUrl(),t}handle3dsChallenge(t){return n(this,void 0,void 0,(function*(){const e=document.createElement("form");e.name="frm",e.method="POST",e.action=t.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=t.creq,n.value=t.creq,e.appendChild(n);const o=document.createElement("input");o.type="hidden",o.name=t.term_url,o.value=t.TermUrl,e.appendChild(o),document.body.appendChild(e),e.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(t){return n(this,void 0,void 0,(function*(){const e=yield t.json();return"Pending"===e.status&&e.redirect_post_url?yield this.handle3dsChallenge(e):["Success","Authorized"].includes(e.status)?this.handleSuccessTransaction(e):(this.handleDeclinedTransaction(t),e)}))}verifyTransactionStatus(){return n(this,void 0,void 0,(function*(){const t=this.getUrlWithExpiration();if(t){const e=`${this.baseUrl}${t}`;try{const t=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==t.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),t):yield this.handleTransactionResponse(t)}catch(t){console.error("Error al verificar la transacción:",t),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const h=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function p(t,e,o){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/checkout-router/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(Object.assign(Object.assign({},r),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.status>=200&&i.status<=299)return yield i.json();{const t=yield i.json(),e=new Error("Failed to start checkout router");throw e.details=t,e}}catch(t){throw t}}))}function m(t,e,o=!0,r=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(t),n.setApiKey(e),n.setSandboxMode(o),yield n.deviceData.setup({signal:r})}))}const y=Object.freeze({saveCardError:"Ha ocurrido un error guardando la tarjeta. Inténtalo nuevamente.",removeCardError:"Ha ocurrido un error eliminado la tarjeta. Inténtalo nuevamente.",getCardsError:"Ha ocurrido un error obteniendo las tarjetas del customer. Inténtalo nuevamente.",cardExist:"La tarjeta fue registrada previamente.",removedCard:"Card deleted successfully",errorCheckout:"No se ha podido procesar el pago",cardSaved:"Tarjeta registrada con éxito.",getPaymentMethodsError:"Ha ocurrido un error obteniendo las métodos de pago del customer. Inténtalo nuevamente.",getBusinessError:"Ha ocurrido un error obteniendo los datos del comercio. Inténtalo nuevamente."});var f,g,v,_,A,b,E,T;class C{constructor({mode:t="stage",apiKey:e,apiKeyTonder:n,returnUrl:o,callBack:r=(()=>{})}){f.add(this),this.baseUrl="",this.cartTotal="0",this.metadata={},this.card={},this.currency="",g.set(this,void 0),this.apiKeyTonder=e||n||"",this.returnUrl=o,this.callBack=r,this.mode=t,this.customer={},this.baseUrl=h[this.mode]||h.stage,this.abortController=new AbortController,this.process3ds=new u({apiKey:e,baseUrl:this.baseUrl})}configureCheckout(t){"customer"in t&&o(this,f,"m",v).call(this,t.customer)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const t=yield this.process3ds.verifyTransactionStatus(),e=yield o(this,f,"m",T).call(this,t);return this.process3ds.setPayload(e),this._handle3dsRedirect(e)}))}payment(t){return new Promise(((e,r)=>n(this,void 0,void 0,(function*(){var n,i;try{o(this,f,"m",v).call(this,t.customer),this._setCartTotal(null===(n=t.cart)||void 0===n?void 0:n.total),o(this,f,"m",_).call(this,null===(i=t.cart)||void 0===i?void 0:i.items),o(this,f,"m",A).call(this,t),o(this,f,"m",b).call(this,t),o(this,f,"m",E).call(this,t);const r=yield this._checkout(t);this.process3ds.setPayload(r),this.callBack&&this.callBack(r);(yield this._handle3dsRedirect(r))&&e(r)}catch(t){r(t)}}))))}_initializeCheckout(){return n(this,void 0,void 0,(function*(){const t=yield this._fetchMerchantData();t&&t.mercado_pago&&t.mercado_pago.active&&function(){try{const t=document.createElement("script");t.src="https://www.mercadopago.com/v2/security.js",t.setAttribute("view",""),t.onload=()=>{console.log("Mercado Pago script loaded successfully.")},t.onerror=t=>{console.error("Error loading Mercado Pago script:",t)},document.head.appendChild(t)}catch(t){console.error("Error attempting to inject Mercado Pago script:",t)}}()}))}_checkout(t){return n(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(t){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(t=null){return n(this,void 0,void 0,(function*(){return o(this,g,"f")||function(t,e,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===o?r.call(t,n):r?r.value=n:e.set(t,n)}(this,g,yield function(t,e,o,r=null){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},signal:r,body:JSON.stringify(i)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,t),"f"),o(this,g,"f")}))}_handleCheckout({card:e,payment_method:o,customer:r,isSandbox:i}){return n(this,void 0,void 0,(function*(){const{openpay_keys:a,reference:d,business:c}=this.merchantData,l=Number(this.cartTotal);try{let u;!u&&a.merchant_id&&a.public_key&&(u=yield m(a.merchant_id,a.public_key,i,this.abortController.signal));const{id:h,auth_token:y}=r,f={business:this.apiKeyTonder,client:y,billing_address_id:null,shipping_address_id:null,amount:l,status:"A",reference:d,is_oneclick:!0,items:this.cartItems},g=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,f),v=(new Date).toISOString(),_={business_pk:c.pk,client_id:h,amount:l,date:v,order_id:g.id},A=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,_),b=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:this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:l,title_ship:"shipping",description:"transaction",device_session_id:u||null,token_id:"",order_id:g.id,business_id:c.pk,payment_id:A.pk,source:"sdk",metadata:this.metadata,browser_info:s(),currency:this.currency},o?{payment_method:o}:{card:e}),E=yield p(this.baseUrl,this.apiKeyTonder,b);return E||!1}catch(t){throw console.log(t),t}}))}_fetchMerchantData(){return n(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield r(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(t){return this.merchantData}}))}_getCustomerCards(t,e){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r=null){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${o}/cards/`,i=yield fetch(n,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();const s=yield i.json();throw yield c(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,t,e)}))}_saveCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${o}/cards/`,i=yield fetch(n,{method:"POST",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(i.ok)return yield i.json();const s=yield i.json();throw yield c(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,t,e,o)}))}_removeCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){return yield function(t,e,o="",r){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${r}/cards/${o}`,i=yield fetch(n,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"}});if(204===i.status)return y.cardSaved;if(i.ok&&"json"in i)return yield i.json();const s=yield i.json();throw yield c(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,t,o,e)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(t,e,o={status:"active",pagesize:"10000"},r=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(o).toString(),i=yield fetch(`${t}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();const s=yield i.json();throw yield c(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,this.apiKeyTonder)}))}_handle3dsRedirect(t){var e,o;return n(this,void 0,void 0,(function*(){if(t&&"next_action"in t?null===(o=null===(e=null==t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t)}));else{if(!this.process3ds.getRedirectUrl())return t;this.process3ds.redirectToChallenge()}}))}}function O({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}}),c=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,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)}}))}g=new WeakMap,f=new WeakSet,v=function(t){t&&(this.customer=t)},_=function(t){this.cartItems=t},A=function(t){this.metadata=null==t?void 0:t.metadata},b=function(t){this.currency=null==t?void 0:t.currency},E=function(t){this.card=null==t?void 0:t.card},T=function(t){var e,o;return n(this,void 0,void 0,(function*(){if("Hard"===(null===(e=null==t?void 0:t.decline)||void 0===e?void 0:e.error_type))return t;if(["Success","Authorized"].includes(null==t?void 0:t.transaction_status))return t;if(t){const e={checkout_id:null===(o=t.checkout)||void 0===o?void 0:o.id};try{return yield p(this.baseUrl,this.apiKeyTonder,e)}catch(t){}return t}}))};const S=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"}),j={[S.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[S.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[S.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[S.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[S.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[S.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[S.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[S.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[S.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[S.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[S.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[S.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[S.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[S.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[S.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[S.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[S.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[S.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[S.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[S.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[S.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[S.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[S.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[S.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[S.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[S.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[S.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[S.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[S.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[S.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},w=t=>{const e=t.toUpperCase().trim().replace(/\s+/g,"");return j[e]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class M extends C{constructor({apiKey:t,mode:e,returnUrl:n,callBack:o}){super({mode:e,apiKey:t,returnUrl:n,callBack:o}),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 l({message:y.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 O({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 l({message:y.saveCardError},t)}}))}removeCustomerCard(t){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),{business:n}=this.merchantData;return yield this._removeCustomerCard(e,null==n?void 0:n.pk,t)}catch(t){throw l({message:y.removeCardError},t)}}))}getCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){try{const t=yield this._fetchCustomerPaymentMethods();return(t&&"results"in t&&t.results.length>0?t.results:[]).filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},w(t.payment_method)))).sort(((t,e)=>t.priority-e.priority))}catch(t){throw l({message:y.getPaymentMethodsError},t)}}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield r(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(t){throw l({message:y.getBusinessError},t)}}))}getOpenpayDeviceSessionID(t,e,o){return n(this,void 0,void 0,(function*(){try{return yield m(t,e,o)}catch(t){throw d(t)}}))}getSkyflowTokens({vault_id:t,vault_url:e,data:o}){return n(this,void 0,void 0,(function*(){return yield O({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}){return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const n=yield this._getCustomer(this.abortController.signal),{vault_id:r,vault_url:i}=this.merchantData;let s;return e&&""===e&&null!==e||(s="string"==typeof t?{skyflow_id:t}:yield O({vault_id:r,vault_url:i,data:Object.assign(Object.assign({},t),{card_number:t.card_number.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})),yield this._handleCheckout({card:s,payment_method:e,customer:n,isSandbox:o})}))}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 c(o)}catch(t){throw d(t)}}))}createOrder(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/orders/`,n=t,o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(t){throw d(t)}}))}createPayment(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/business/${t.business_pk}/payments/`,n=t,o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(t){throw d(t)}}))}startCheckoutRouter(t){return n(this,void 0,void 0,(function*(){const e=yield p(this.baseUrl,this.apiKeyTonder,t);if(yield this.init3DSRedirect(e))return e}))}init3DSRedirect(t){return n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(t),yield this._handle3dsRedirect(t)}))}startCheckoutRouterFull(t){return n(this,void 0,void 0,(function*(){try{const{order:e,total:n,customer:o,skyflowTokens:r,return_url:a,isSandbox:d,metadata:c,currency:l,payment_method:u}=t,h=yield this._fetchMerchantData(),y=yield this.customerRegister(o.email);if(!(y&&"auth_token"in y&&h&&"reference"in h))throw new i({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const t={business:this.apiKeyTonder,client:y.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:e.items},f=yield this.createOrder(t),g=(new Date).toISOString();if(!("id"in f&&"id"in y&&"business"in h))throw new i({code:"500",body:f,name:"Keys error",message:"Order response errors"});{const t={business_pk:h.business.pk,amount:n,date:g,order_id:f.id,client_id:y.id},e=yield this.createPayment(t);let i;const{openpay_keys:v,business:_}=h;v.merchant_id&&v.public_key&&(i=yield m(v.merchant_id,v.public_key,d));const A=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:a,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:n,title_ship:"shipping",description:"transaction",device_session_id:i||null,token_id:"",order_id:"id"in f&&f.id,business_id:_.pk,payment_id:"pk"in e&&e.pk,source:"sdk",metadata: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){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${a(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},e))});if(n.ok)return yield n.json();throw yield c(n)}catch(t){throw d(t)}}))}deleteCustomerCard(t,e=""){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${a(this.merchantData)}/cards/${e}`,{method:"DELETE",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(n.ok)return!0;throw yield c(n)}catch(t){throw d(t)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const t=yield function(t,e,o="?status=active&page_size=10000&country=México",r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${t}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield c(n)}catch(t){throw d(t)}}))}(this.baseUrl,this.apiKeyTonder),e=t&&t.results&&t.results.length>0?t.results:[];return this.activeAPMs=e.filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},w(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)&&P(t)}function I(t){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(t)}function N(t){return/^\d{3,4}$/.test(t)}function k(t){return/^(0[1-9]|1[0-2])$/.test(t)}function U(t){if(!/^\d{2}$/.test(t))return!1;const e=(new Date).getFullYear()%100;return parseInt(t,10)>=e}const P=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{C as BaseInlineCheckout,M as LiteCheckout,N as validateCVV,R as validateCardNumber,I as validateCardholderName,k as validateExpirationMonth,U 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,o){return n(this,void 0,void 0,(function*(){const n=yield fetch(`${t}/api/v1/payments/business/${e}`,{headers:{Authorization:`Token ${e}`},signal:o});return yield n.json()}))}"function"==typeof SuppressedError&&SuppressedError;class i{constructor({code:t,body:e,name:n,message:o,stack:r}){this.code=t,this.body=e,this.name=n,this.message=o,this.stack=r}}const s=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),a=t=>{var e;return t&&"business"in t?null===(e=null==t?void 0:t.business)||void 0===e?void 0:e.pk:""},d=t=>new i({code:(null==t?void 0:t.status)?t.status:t.code,body:null==t?void 0:t.body,name:t?"string"==typeof t?"catch":t.name:"Error",message:t?"string"==typeof t?t:t.message:"Error",stack:"string"==typeof t?void 0:t.stack}),c=(t,e=void 0)=>n(void 0,void 0,void 0,(function*(){let n,o,r="Error";t&&"json"in t&&(n=yield null==t?void 0:t.json()),t&&"status"in t&&(o=t.status.toString()),!n&&t&&"text"in t&&(r=yield t.text()),(null==n?void 0:n.detail)&&(r=n.detail);return new i({code:o,body:n,name:o,message:r,stack:e})}));function l(t,e){var n,o;let r=200;try{r=Number((null==e?void 0:e.code)||200)}catch(t){}const i={status:"error",code:r,message:"",detail:(null===(n=null==e?void 0:e.body)||void 0===n?void 0:n.detail)||(null===(o=null==e?void 0:e.body)||void 0===o?void 0:o.error)||e.body||"Ocurrio un error inesperado."};return Object.assign(Object.assign({},i),t)}class u{constructor({payload:t=null,apiKey:e,baseUrl:n}){this.localStorageKey="verify_transaction_status_url",this.setPayload=t=>{this.payload=t},this.baseUrl=n,this.apiKey=e,this.payload=t}setStorageItem(t){return localStorage.setItem(this.localStorageKey,JSON.stringify(t))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var t,e,n,o,r,i;const s=null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const t=null===(i=null===(r=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;t?this.saveUrlWithExpiration(t):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(t){try{const e={url:t,expires:(new Date).getTime()+12e5};this.setStorageItem(e)}catch(t){console.log("error: ",t)}}getUrlWithExpiration(){const t=this.getStorageItem();if(t){const e=JSON.parse(t);if(!e)return;return(new Date).getTime()>e.expires?(this.removeVerifyTransactionUrl(),null):e.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var t,e,n;if(null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((t,e)=>{var n,o,r;const i=null===(r=null===(o=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(o);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>t(!0):(console.log("No redirection found"),e(!1))}else console.log("No redirection found"),e(!1)}))}getRedirectUrl(){var t,e,n;return null===(n=null===(e=null===(t=this.payload)||void 0===t?void 0:t.next_action)||void 0===e?void 0:e.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const t=this.getRedirectUrl();t?(this.saveVerifyTransactionUrl(),window.location=t):console.log("No redirection found")}getURLParameters(){const t={},e=new URLSearchParams(window.location.search);for(const[n,o]of e)t[n]=o;return t}handleSuccessTransaction(t){return this.removeVerifyTransactionUrl(),console.log("Transacción autorizada."),t}handleDeclinedTransaction(t){return this.removeVerifyTransactionUrl(),t}handle3dsChallenge(t){return n(this,void 0,void 0,(function*(){const e=document.createElement("form");e.name="frm",e.method="POST",e.action=t.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=t.creq,n.value=t.creq,e.appendChild(n);const o=document.createElement("input");o.type="hidden",o.name=t.term_url,o.value=t.TermUrl,e.appendChild(o),document.body.appendChild(e),e.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(t){return n(this,void 0,void 0,(function*(){const e=yield t.json();return"Pending"===e.status&&e.redirect_post_url?yield this.handle3dsChallenge(e):["Success","Authorized"].includes(e.status)?this.handleSuccessTransaction(e):(this.handleDeclinedTransaction(t),e)}))}verifyTransactionStatus(){return n(this,void 0,void 0,(function*(){const t=this.getUrlWithExpiration();if(t){const e=`${this.baseUrl}${t}`;try{const t=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==t.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),t):yield this.handleTransactionResponse(t)}catch(t){console.error("Error al verificar la transacción:",t),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const h=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function p(t,e,o){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/checkout-router/`,r=o,i=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(Object.assign(Object.assign({},r),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.status>=200&&i.status<=299)return yield i.json();{const t=yield i.json(),e=new Error("Failed to start checkout router");throw e.details=t,e}}catch(t){throw t}}))}function m(t,e,o=!0,r=null){return n(this,void 0,void 0,(function*(){let n=yield window.OpenPay;return n.setId(t),n.setApiKey(e),n.setSandboxMode(o),yield n.deviceData.setup({signal:r})}))}const y=Object.freeze({saveCardError:"Ha ocurrido un error guardando la tarjeta. Inténtalo nuevamente.",removeCardError:"Ha ocurrido un error eliminado la tarjeta. Inténtalo nuevamente.",getCardsError:"Ha ocurrido un error obteniendo las tarjetas del customer. Inténtalo nuevamente.",cardExist:"La tarjeta fue registrada previamente.",removedCard:"Card deleted successfully",errorCheckout:"No se ha podido procesar el pago",cardSaved:"Tarjeta registrada con éxito.",getPaymentMethodsError:"Ha ocurrido un error obteniendo las métodos de pago del customer. Inténtalo nuevamente.",getBusinessError:"Ha ocurrido un error obteniendo los datos del comercio. Inténtalo nuevamente."});var f,g,v,_,A,b,E,T;class C{constructor({mode:t="stage",apiKey:e,apiKeyTonder:n,returnUrl:o,callBack:r=(()=>{}),baseUrlTonder:i}){f.add(this),this.baseUrl="",this.cartTotal="0",this.metadata={},this.card={},this.currency="",g.set(this,void 0),this.apiKeyTonder=n||e||"",this.returnUrl=o,this.callBack=r,this.mode=t,this.customer={},this.baseUrl=i||h[this.mode]||h.stage,this.abortController=new AbortController,this.process3ds=new u({apiKey:e,baseUrl:this.baseUrl})}configureCheckout(t){"customer"in t&&o(this,f,"m",v).call(this,t.customer)}verify3dsTransaction(){return n(this,void 0,void 0,(function*(){const t=yield this.process3ds.verifyTransactionStatus(),e=yield o(this,f,"m",T).call(this,t);return this.process3ds.setPayload(e),this._handle3dsRedirect(e)}))}payment(t){return new Promise(((e,r)=>n(this,void 0,void 0,(function*(){var n,i;try{o(this,f,"m",v).call(this,t.customer),this._setCartTotal(null===(n=t.cart)||void 0===n?void 0:n.total),o(this,f,"m",_).call(this,null===(i=t.cart)||void 0===i?void 0:i.items),o(this,f,"m",A).call(this,t),o(this,f,"m",b).call(this,t),o(this,f,"m",E).call(this,t);const r=yield this._checkout(t);this.process3ds.setPayload(r),this.callBack&&this.callBack(r);(yield this._handle3dsRedirect(r))&&e(r)}catch(t){r(t)}}))))}_initializeCheckout(){return n(this,void 0,void 0,(function*(){const t=yield this._fetchMerchantData();t&&t.mercado_pago&&t.mercado_pago.active&&function(){try{const t=document.createElement("script");t.src="https://www.mercadopago.com/v2/security.js",t.setAttribute("view",""),t.onload=()=>{console.log("Mercado Pago script loaded successfully.")},t.onerror=t=>{console.error("Error loading Mercado Pago script:",t)},document.head.appendChild(t)}catch(t){console.error("Error attempting to inject Mercado Pago script:",t)}}()}))}_checkout(t){return n(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(t){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(t=null){return n(this,void 0,void 0,(function*(){return o(this,g,"f")||function(t,e,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===o?r.call(t,n):r?r.value=n:e.set(t,n)}(this,g,yield function(t,e,o,r=null){return n(this,void 0,void 0,(function*(){const n=`${t}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},s=yield fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},signal:r,body:JSON.stringify(i)});if(201===s.status)return yield s.json();throw new Error(`Error: ${s.statusText}`)}))}(this.baseUrl,this.apiKeyTonder,this.customer,t),"f"),o(this,g,"f")}))}_handleCheckout({card:e,payment_method:o,customer:r,isSandbox:i}){return n(this,void 0,void 0,(function*(){const{openpay_keys:a,reference:d,business:c}=this.merchantData,l=Number(this.cartTotal);try{let u;!u&&a.merchant_id&&a.public_key&&(u=yield m(a.merchant_id,a.public_key,i,this.abortController.signal));const{id:h,auth_token:y}=r,f={business:this.apiKeyTonder,client:y,billing_address_id:null,shipping_address_id:null,amount:l,status:"A",reference:d,is_oneclick:!0,items:this.cartItems},g=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,f),v=(new Date).toISOString(),_={business_pk:c.pk,client_id:h,amount:l,date:v,order_id:g.id},A=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,_),b=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:this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:l,title_ship:"shipping",description:"transaction",device_session_id:u||null,token_id:"",order_id:g.id,business_id:c.pk,payment_id:A.pk,source:"sdk",metadata:this.metadata,browser_info:s(),currency:this.currency},o?{payment_method:o}:{card:e}),E=yield p(this.baseUrl,this.apiKeyTonder,b);return E||!1}catch(t){throw console.log(t),t}}))}_fetchMerchantData(){return n(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield r(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(t){return this.merchantData}}))}_getCustomerCards(t,e){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r=null){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${o}/cards/`,i=yield fetch(n,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();const s=yield i.json();throw yield c(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,t,e)}))}_saveCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){return yield function(t,e,o,r){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${o}/cards/`,i=yield fetch(n,{method:"POST",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(i.ok)return yield i.json();const s=yield i.json();throw yield c(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,t,e,o)}))}_removeCustomerCard(t,e,o){return n(this,void 0,void 0,(function*(){return yield function(t,e,o="",r){return n(this,void 0,void 0,(function*(){try{const n=`${t}/api/v1/business/${r}/cards/${o}`,i=yield fetch(n,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"}});if(204===i.status)return y.cardSaved;if(i.ok&&"json"in i)return yield i.json();const s=yield i.json();throw yield c(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,t,o,e)}))}_fetchCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){return yield function(t,e,o={status:"active",pagesize:"10000"},r=null){return n(this,void 0,void 0,(function*(){try{const n=new URLSearchParams(o).toString(),i=yield fetch(`${t}/api/v1/payment_methods?${n}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(i.ok)return yield i.json();const s=yield i.json();throw yield c(i,s)}catch(t){throw d(t)}}))}(this.baseUrl,this.apiKeyTonder)}))}_handle3dsRedirect(t){var e,o;return n(this,void 0,void 0,(function*(){if(t&&"next_action"in t?null===(o=null===(e=null==t?void 0:t.next_action)||void 0===e?void 0:e.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t)}));else{if(!this.process3ds.getRedirectUrl())return t;this.process3ds.redirectToChallenge()}}))}}function O({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}}),c=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,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)}}))}g=new WeakMap,f=new WeakSet,v=function(t){t&&(this.customer=t)},_=function(t){this.cartItems=t},A=function(t){this.metadata=null==t?void 0:t.metadata},b=function(t){this.currency=null==t?void 0:t.currency},E=function(t){this.card=null==t?void 0:t.card},T=function(t){var e,o;return n(this,void 0,void 0,(function*(){if("Hard"===(null===(e=null==t?void 0:t.decline)||void 0===e?void 0:e.error_type))return t;if(["Success","Authorized"].includes(null==t?void 0:t.transaction_status))return t;if(t){const e={checkout_id:null===(o=t.checkout)||void 0===o?void 0:o.id};try{return yield p(this.baseUrl,this.apiKeyTonder,e)}catch(t){}return t}}))};const S=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"}),j={[S.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[S.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[S.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[S.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[S.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[S.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[S.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[S.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[S.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[S.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[S.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[S.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[S.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[S.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[S.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[S.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[S.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[S.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[S.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[S.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[S.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[S.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[S.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[S.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[S.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[S.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[S.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[S.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[S.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[S.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[S.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},w=t=>{const e=t.toUpperCase().trim().replace(/\s+/g,"");return j[e]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class M extends C{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 l({message:y.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 O({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 l({message:y.saveCardError},t)}}))}removeCustomerCard(t){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),{business:n}=this.merchantData;return yield this._removeCustomerCard(e,null==n?void 0:n.pk,t)}catch(t){throw l({message:y.removeCardError},t)}}))}getCustomerPaymentMethods(){return n(this,void 0,void 0,(function*(){try{const t=yield this._fetchCustomerPaymentMethods();return(t&&"results"in t&&t.results.length>0?t.results:[]).filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},w(t.payment_method)))).sort(((t,e)=>t.priority-e.priority))}catch(t){throw l({message:y.getPaymentMethodsError},t)}}))}getBusiness(){return n(this,void 0,void 0,(function*(){try{return yield r(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(t){throw l({message:y.getBusinessError},t)}}))}getOpenpayDeviceSessionID(t,e,o){return n(this,void 0,void 0,(function*(){try{return yield m(t,e,o)}catch(t){throw d(t)}}))}getSkyflowTokens({vault_id:t,vault_url:e,data:o}){return n(this,void 0,void 0,(function*(){return yield O({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}){return n(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const n=yield this._getCustomer(this.abortController.signal),{vault_id:r,vault_url:i}=this.merchantData;let s;return e&&""===e&&null!==e||(s="string"==typeof t?{skyflow_id:t}:yield O({vault_id:r,vault_url:i,data:Object.assign(Object.assign({},t),{card_number:t.card_number.replace(/\s+/g,"")}),baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})),yield this._handleCheckout({card:s,payment_method:e,customer:n,isSandbox:o})}))}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 c(o)}catch(t){throw d(t)}}))}createOrder(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/orders/`,n=t,o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(t){throw d(t)}}))}createPayment(t){return n(this,void 0,void 0,(function*(){try{const e=`${this.baseUrl}/api/v1/business/${t.business_pk}/payments/`,n=t,o=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield c(o)}catch(t){throw d(t)}}))}startCheckoutRouter(t){return n(this,void 0,void 0,(function*(){const e=yield p(this.baseUrl,this.apiKeyTonder,t);if(yield this.init3DSRedirect(e))return e}))}init3DSRedirect(t){return n(this,void 0,void 0,(function*(){return this.process3ds.setPayload(t),yield this._handle3dsRedirect(t)}))}startCheckoutRouterFull(t){return n(this,void 0,void 0,(function*(){try{const{order:e,total:n,customer:o,skyflowTokens:r,return_url:a,isSandbox:d,metadata:c,currency:l,payment_method:u}=t,h=yield this._fetchMerchantData(),y=yield this.customerRegister(o.email);if(!(y&&"auth_token"in y&&h&&"reference"in h))throw new i({code:"500",body:h,name:"Keys error",message:"Merchant or customer reposne errors"});{const t={business:this.apiKeyTonder,client:y.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:h.reference,is_oneclick:!0,items:e.items},f=yield this.createOrder(t),g=(new Date).toISOString();if(!("id"in f&&"id"in y&&"business"in h))throw new i({code:"500",body:f,name:"Keys error",message:"Order response errors"});{const t={business_pk:h.business.pk,amount:n,date:g,order_id:f.id,client_id:y.id},e=yield this.createPayment(t);let i;const{openpay_keys:v,business:_}=h;v.merchant_id&&v.public_key&&(i=yield m(v.merchant_id,v.public_key,d));const A=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:a,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:n,title_ship:"shipping",description:"transaction",device_session_id:i||null,token_id:"",order_id:"id"in f&&f.id,business_id:_.pk,payment_id:"pk"in e&&e.pk,source:"sdk",metadata: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){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${a(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},e))});if(n.ok)return yield n.json();throw yield c(n)}catch(t){throw d(t)}}))}deleteCustomerCard(t,e=""){return n(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const n=yield fetch(`${this.baseUrl}/api/v1/business/${a(this.merchantData)}/cards/${e}`,{method:"DELETE",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(n.ok)return!0;throw yield c(n)}catch(t){throw d(t)}}))}getActiveAPMs(){return n(this,void 0,void 0,(function*(){try{const t=yield function(t,e,o="?status=active&page_size=10000&country=México",r=null){return n(this,void 0,void 0,(function*(){try{const n=yield fetch(`${t}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:r});if(n.ok)return yield n.json();throw yield c(n)}catch(t){throw d(t)}}))}(this.baseUrl,this.apiKeyTonder),e=t&&t.results&&t.results.length>0?t.results:[];return this.activeAPMs=e.filter((t=>"cards"!==t.category.toLowerCase())).map((t=>Object.assign({id:t.pk,payment_method:t.payment_method,priority:t.priority,category:t.category},w(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)&&P(t)}function I(t){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(t)}function N(t){return/^\d{3,4}$/.test(t)}function k(t){return/^(0[1-9]|1[0-2])$/.test(t)}function U(t){if(!/^\d{2}$/.test(t))return!1;const e=(new Date).getFullYear()%100;return parseInt(t,10)>=e}const P=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{C as BaseInlineCheckout,M as LiteCheckout,N as validateCVV,R as validateCardNumber,I as validateCardholderName,k as validateExpirationMonth,U as validateExpirationYear};
|
package/dist/types/commons.d.ts
CHANGED
|
@@ -104,6 +104,8 @@ export interface IInlineCheckoutBaseOptions {
|
|
|
104
104
|
returnUrl?: string;
|
|
105
105
|
callBack?: (response: IStartCheckoutResponse | Record<string, any>) => void;
|
|
106
106
|
}
|
|
107
|
+
export interface IInlineLiteCheckoutOptions extends IInlineCheckoutBaseOptions {
|
|
108
|
+
}
|
|
107
109
|
export interface IApiError {
|
|
108
110
|
code: string;
|
|
109
111
|
body: Record<string, string> | string;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { IConfigureCheckout } from "./commons";
|
|
2
|
+
import { ICustomerCardsResponse, ISaveCardRequest, ISaveCardResponse } from "./card";
|
|
3
|
+
import { IPaymentMethod } from "./paymentMethod";
|
|
4
|
+
import { IProcessPaymentRequest, IStartCheckoutResponse } from "./checkout";
|
|
5
|
+
import { ITransaction } from "./transaction";
|
|
6
|
+
import { APM } from "./commons";
|
|
7
|
+
import { ErrorResponse } from "../classes/errorResponse";
|
|
8
|
+
import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutFullRequest, StartCheckoutIdRequest, StartCheckoutRequest, TokensRequest } from "./requests";
|
|
9
|
+
import { CreateOrderResponse, CreatePaymentResponse, CustomerRegisterResponse, GetBusinessResponse, RegisterCustomerCardResponse, StartCheckoutResponse } from "./responses";
|
|
10
|
+
export interface ILiteCheckout {
|
|
11
|
+
/**
|
|
12
|
+
* The configureCheckout function allows you to set initial information, such as the customer's email, which is used to retrieve a list of saved cards.
|
|
13
|
+
* @param {import("./index").IConfigureCheckout} data - Configuration data including customer information and potentially other settings.
|
|
14
|
+
* @returns {Promise<void>}.
|
|
15
|
+
* @public
|
|
16
|
+
*/
|
|
17
|
+
configureCheckout(data: IConfigureCheckout): void;
|
|
18
|
+
/**
|
|
19
|
+
* Initializes and prepares the checkout for use.
|
|
20
|
+
* This method set up the initial environment.
|
|
21
|
+
* @returns {Promise<void>} A promise that resolves when the checkout has been initialized.
|
|
22
|
+
* @throws {Error} If there's any problem during the checkout initialization.
|
|
23
|
+
* @public
|
|
24
|
+
*/
|
|
25
|
+
injectCheckout(): Promise<void>;
|
|
26
|
+
/**
|
|
27
|
+
* Processes a payment.
|
|
28
|
+
* @param {import("./index").IProcessPaymentRequest} data - Payment data including customer, cart, and other relevant information.
|
|
29
|
+
* @returns {Promise<import("./index").IStartCheckoutResponse>} A promise that resolves with the payment response or 3DS redirect or is rejected with an error.
|
|
30
|
+
*
|
|
31
|
+
* @throws {Error} Throws an error if the checkout process fails. The error object contains
|
|
32
|
+
* additional `details` property with the response from the server if available.
|
|
33
|
+
* @property {import("./index").IStartCheckoutErrorResponse} error.details - The response body from the server when an error occurs.
|
|
34
|
+
*
|
|
35
|
+
* @public
|
|
36
|
+
*/
|
|
37
|
+
payment(data: IProcessPaymentRequest): Promise<IStartCheckoutResponse>;
|
|
38
|
+
/**
|
|
39
|
+
* Verifies the 3DS transaction status.
|
|
40
|
+
* @returns {Promise<import("./index").ITransaction | import("./index").IStartCheckoutResponse | void>} The result of the 3DS verification and checkout resumption.
|
|
41
|
+
* @public
|
|
42
|
+
*/
|
|
43
|
+
verify3dsTransaction(): Promise<ITransaction | IStartCheckoutResponse | void>;
|
|
44
|
+
/**
|
|
45
|
+
* Retrieves the list of cards associated with a customer.
|
|
46
|
+
* @returns {Promise<import("./index").ICustomerCardsResponse>} A promise that resolves with the customer's card data.
|
|
47
|
+
*
|
|
48
|
+
* @throws {import("./index").IPublicError} Throws an error object if the operation fails.
|
|
49
|
+
*
|
|
50
|
+
* @public
|
|
51
|
+
*/
|
|
52
|
+
getCustomerCards(): Promise<ICustomerCardsResponse>;
|
|
53
|
+
/**
|
|
54
|
+
* Saves a card to a customer's account. This method can be used to add a new card
|
|
55
|
+
* or update an existing one.
|
|
56
|
+
* @param {import("./index").ISaveCardRequest} card - The card information to be saved.
|
|
57
|
+
* @returns {Promise<import("./index").ISaveCardResponse>} A promise that resolves with the saved card data.
|
|
58
|
+
*
|
|
59
|
+
* @throws {import("./index").IPublicError} Throws an error object if the operation fails.
|
|
60
|
+
*
|
|
61
|
+
* @public
|
|
62
|
+
*/
|
|
63
|
+
saveCustomerCard(card: ISaveCardRequest): Promise<ISaveCardResponse>;
|
|
64
|
+
/**
|
|
65
|
+
* Removes a card from a customer's account.
|
|
66
|
+
* @param {string} skyflowId - The unique identifier of the card to be deleted.
|
|
67
|
+
* @returns {Promise<string>} A promise that resolves when the card is successfully deleted.
|
|
68
|
+
*
|
|
69
|
+
* @throws {import("./index").IPublicError} Throws an error object if the operation fails.
|
|
70
|
+
*
|
|
71
|
+
* @public
|
|
72
|
+
*/
|
|
73
|
+
removeCustomerCard(skyflowId: string): Promise<string>;
|
|
74
|
+
/**
|
|
75
|
+
* Retrieves the list of available Alternative Payment Methods (APMs).
|
|
76
|
+
* @returns {Promise<import("./index").IPaymentMethod[]>} A promise that resolves with the list of APMs.
|
|
77
|
+
*
|
|
78
|
+
* @throws {import("./index").IPublicError} Throws an error object if the operation fails.
|
|
79
|
+
*
|
|
80
|
+
* @public
|
|
81
|
+
*/
|
|
82
|
+
getCustomerPaymentMethods(): Promise<IPaymentMethod[]>;
|
|
83
|
+
/**
|
|
84
|
+
* Retrieves the business information.
|
|
85
|
+
* @returns {Promise<import("./index").GetBusinessResponse>} A promise that resolves with the business information.
|
|
86
|
+
*
|
|
87
|
+
* @throws {import("./index").IPublicError} Throws an error object if the operation fails.
|
|
88
|
+
*
|
|
89
|
+
* @public
|
|
90
|
+
*/
|
|
91
|
+
getBusiness(): Promise<GetBusinessResponse>;
|
|
92
|
+
/**
|
|
93
|
+
* @deprecated This method is deprecated and will be removed in a future release.
|
|
94
|
+
* It is no longer necessary to use this method as customer registration is now automatically handled
|
|
95
|
+
* during the payment process or when using card management methods.
|
|
96
|
+
*/
|
|
97
|
+
customerRegister(email: string): Promise<CustomerRegisterResponse | ErrorResponse>;
|
|
98
|
+
/**
|
|
99
|
+
* @deprecated This method is deprecated and will be removed in a future release.
|
|
100
|
+
* It is no longer necessary to use this method as order creation is now automatically
|
|
101
|
+
* handled when making a payment through the `payment` function.
|
|
102
|
+
*/
|
|
103
|
+
createOrder(orderItems: CreateOrderRequest): Promise<CreateOrderResponse | ErrorResponse>;
|
|
104
|
+
/**
|
|
105
|
+
* @deprecated This method is deprecated and will be removed in a future release.
|
|
106
|
+
* It is no longer necessary to use this method as payment creation is now automatically
|
|
107
|
+
* handled when making a payment through the `payment` function.
|
|
108
|
+
*/
|
|
109
|
+
createPayment(paymentItems: CreatePaymentRequest): Promise<CreatePaymentResponse | ErrorResponse>;
|
|
110
|
+
/**
|
|
111
|
+
* @deprecated This method is deprecated and will be removed in a future release.
|
|
112
|
+
* Use the {@link payment} method
|
|
113
|
+
*/
|
|
114
|
+
startCheckoutRouter(routerData: StartCheckoutRequest | StartCheckoutIdRequest): Promise<StartCheckoutResponse | ErrorResponse | undefined>;
|
|
115
|
+
/**
|
|
116
|
+
* @deprecated This method is deprecated and will be removed in a future release.
|
|
117
|
+
* Use the {@link payment} method
|
|
118
|
+
*/
|
|
119
|
+
startCheckoutRouterFull(routerFullData: StartCheckoutFullRequest): Promise<StartCheckoutResponse | ErrorResponse | undefined>;
|
|
120
|
+
/**
|
|
121
|
+
* @deprecated This method is deprecated and will be removed in a future release.
|
|
122
|
+
* Use the {@link saveCustomerCard} method
|
|
123
|
+
*/
|
|
124
|
+
registerCustomerCard(customerToken: string, data: RegisterCustomerCardRequest): Promise<RegisterCustomerCardResponse | ErrorResponse>;
|
|
125
|
+
/**
|
|
126
|
+
* @deprecated This method is deprecated and will be removed in a future release.
|
|
127
|
+
* Use the {@link removeCustomerCard} method
|
|
128
|
+
*/
|
|
129
|
+
deleteCustomerCard(customerToken: string, skyflowId: string): Promise<Boolean | ErrorResponse>;
|
|
130
|
+
/**
|
|
131
|
+
* @deprecated This method is deprecated and will be removed in a future release.
|
|
132
|
+
* Use the {@link getCustomerPaymentMethods} method
|
|
133
|
+
*/
|
|
134
|
+
getActiveAPMs(): Promise<APM[]>;
|
|
135
|
+
/**
|
|
136
|
+
* @deprecated This method is deprecated and will be removed in a future release.
|
|
137
|
+
* It is no longer necessary to use this method as card registration or as checkout is now automatically handled
|
|
138
|
+
* during the payment process or when using card management methods.
|
|
139
|
+
*/
|
|
140
|
+
getSkyflowTokens({ vault_id, vault_url, data, }: TokensRequest): Promise<any | ErrorResponse>;
|
|
141
|
+
/**
|
|
142
|
+
* @deprecated This method is deprecated and will be removed in a future release.
|
|
143
|
+
* It is no longer necessary to use this method is now automatically handled
|
|
144
|
+
* during the payment process.
|
|
145
|
+
*/
|
|
146
|
+
getOpenpayDeviceSessionID(merchant_id: string, public_key: string, is_sandbox: boolean): Promise<string | ErrorResponse>;
|
|
147
|
+
}
|
package/package.json
CHANGED
|
@@ -23,7 +23,7 @@ import {ICustomer} from "../types/customer";
|
|
|
23
23
|
import {ICardFields, IItem, IProcessPaymentRequest, IStartCheckoutResponse} from "../types/checkout";
|
|
24
24
|
import {ICustomerCardsResponse, ISaveCardResponse, ISaveCardSkyflowRequest} from "../types/card";
|
|
25
25
|
import {IPaymentMethodResponse} from "../types/paymentMethod";
|
|
26
|
-
import {
|
|
26
|
+
import {ITransaction} from "../types/transaction";
|
|
27
27
|
export class BaseInlineCheckout {
|
|
28
28
|
baseUrl = "";
|
|
29
29
|
cartTotal = "0";
|
|
@@ -50,13 +50,14 @@ export class BaseInlineCheckout {
|
|
|
50
50
|
apiKeyTonder,
|
|
51
51
|
returnUrl,
|
|
52
52
|
callBack = () => {},
|
|
53
|
+
baseUrlTonder
|
|
53
54
|
}: IInlineCheckoutBaseOptions) {
|
|
54
|
-
this.apiKeyTonder =
|
|
55
|
+
this.apiKeyTonder = apiKeyTonder || apiKey || "";
|
|
55
56
|
this.returnUrl = returnUrl;
|
|
56
57
|
this.callBack = callBack;
|
|
57
58
|
this.mode = mode;
|
|
58
59
|
this.customer = {} as ICustomer
|
|
59
|
-
this.baseUrl = TONDER_URL_BY_MODE[this.mode] || TONDER_URL_BY_MODE["stage"];
|
|
60
|
+
this.baseUrl = baseUrlTonder || TONDER_URL_BY_MODE[this.mode] || TONDER_URL_BY_MODE["stage"];
|
|
60
61
|
this.abortController = new AbortController();
|
|
61
62
|
this.process3ds = new ThreeDSHandler({
|
|
62
63
|
apiKey: apiKey,
|
|
@@ -68,7 +69,7 @@ export class BaseInlineCheckout {
|
|
|
68
69
|
if ("customer" in data) this.#handleCustomer(data["customer"]);
|
|
69
70
|
}
|
|
70
71
|
|
|
71
|
-
async verify3dsTransaction() {
|
|
72
|
+
async verify3dsTransaction(): Promise<ITransaction | IStartCheckoutResponse | void> {
|
|
72
73
|
const result3ds = await this.process3ds.verifyTransactionStatus();
|
|
73
74
|
const resultCheckout = await this.#resumeCheckout(result3ds);
|
|
74
75
|
this.process3ds.setPayload(resultCheckout);
|
|
@@ -319,7 +320,7 @@ export class BaseInlineCheckout {
|
|
|
319
320
|
|
|
320
321
|
// TODO: Make private after remove deprecated functions of liteCheckout
|
|
321
322
|
async _handle3dsRedirect(
|
|
322
|
-
response:
|
|
323
|
+
response: ITransaction | IStartCheckoutResponse | void,
|
|
323
324
|
) {
|
|
324
325
|
const iframe =
|
|
325
326
|
response && "next_action" in response
|
|
@@ -17,7 +17,7 @@ import { getSkyflowTokens } from "../helpers/skyflow";
|
|
|
17
17
|
import { startCheckoutRouter } from "../data/checkoutApi";
|
|
18
18
|
import { getOpenpayDeviceSessionID } from "../data/openPayApi";
|
|
19
19
|
import { getPaymentMethodDetails } from "../shared/catalog/paymentMethodsCatalog";
|
|
20
|
-
import {APM,
|
|
20
|
+
import {APM, IInlineLiteCheckoutOptions, TonderAPM} from "../types/commons";
|
|
21
21
|
import {ICustomerCardsResponse, ISaveCardRequest, ISaveCardResponse, ISaveCardSkyflowRequest} from "../types/card";
|
|
22
22
|
import {IPaymentMethod} from "../types/paymentMethod";
|
|
23
23
|
import {
|
|
@@ -33,7 +33,8 @@ import {
|
|
|
33
33
|
StartCheckoutRequest,
|
|
34
34
|
TokensRequest
|
|
35
35
|
} from "../types/requests";
|
|
36
|
-
import {ICardFields} from "../types/checkout";
|
|
36
|
+
import {ICardFields, IStartCheckoutResponse} from "../types/checkout";
|
|
37
|
+
import {ILiteCheckout} from "../types/liteInlineCheckout";
|
|
37
38
|
|
|
38
39
|
declare global {
|
|
39
40
|
interface Window {
|
|
@@ -41,13 +42,11 @@ declare global {
|
|
|
41
42
|
}
|
|
42
43
|
}
|
|
43
44
|
|
|
44
|
-
export
|
|
45
|
-
|
|
46
|
-
export class LiteCheckout extends BaseInlineCheckout {
|
|
45
|
+
export class LiteCheckout extends BaseInlineCheckout implements ILiteCheckout{
|
|
47
46
|
activeAPMs: APM[] = [];
|
|
48
47
|
|
|
49
|
-
constructor({ apiKey, mode, returnUrl, callBack }:
|
|
50
|
-
super({ mode, apiKey, returnUrl, callBack });
|
|
48
|
+
constructor({ apiKey, mode, returnUrl, callBack, apiKeyTonder, baseUrlTonder }: IInlineLiteCheckoutOptions) {
|
|
49
|
+
super({ mode, apiKey, returnUrl, callBack, apiKeyTonder, baseUrlTonder });
|
|
51
50
|
}
|
|
52
51
|
|
|
53
52
|
public async injectCheckout() {
|
|
@@ -255,11 +254,6 @@ export class LiteCheckout extends BaseInlineCheckout {
|
|
|
255
254
|
}
|
|
256
255
|
|
|
257
256
|
// TODO: DEPRECATED
|
|
258
|
-
/**
|
|
259
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
260
|
-
* It is no longer necessary to use this method as customer registration is now automatically handled
|
|
261
|
-
* during the payment process or when using card management methods.
|
|
262
|
-
*/
|
|
263
257
|
async customerRegister(
|
|
264
258
|
email: string,
|
|
265
259
|
): Promise<CustomerRegisterResponse | ErrorResponse> {
|
|
@@ -285,11 +279,6 @@ export class LiteCheckout extends BaseInlineCheckout {
|
|
|
285
279
|
}
|
|
286
280
|
|
|
287
281
|
// TODO: DEPRECATED
|
|
288
|
-
/**
|
|
289
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
290
|
-
* It is no longer necessary to use this method as order creation is now automatically
|
|
291
|
-
* handled when making a payment through the `payment` function.
|
|
292
|
-
*/
|
|
293
282
|
async createOrder(
|
|
294
283
|
orderItems: CreateOrderRequest,
|
|
295
284
|
): Promise<CreateOrderResponse | ErrorResponse> {
|
|
@@ -312,11 +301,6 @@ export class LiteCheckout extends BaseInlineCheckout {
|
|
|
312
301
|
}
|
|
313
302
|
|
|
314
303
|
// TODO: DEPRECATED
|
|
315
|
-
/**
|
|
316
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
317
|
-
* It is no longer necessary to use this method as payment creation is now automatically
|
|
318
|
-
* handled when making a payment through the `payment` function.
|
|
319
|
-
*/
|
|
320
304
|
async createPayment(
|
|
321
305
|
paymentItems: CreatePaymentRequest,
|
|
322
306
|
): Promise<CreatePaymentResponse | ErrorResponse> {
|
|
@@ -339,10 +323,6 @@ export class LiteCheckout extends BaseInlineCheckout {
|
|
|
339
323
|
}
|
|
340
324
|
|
|
341
325
|
// TODO: DEPRECATED
|
|
342
|
-
/**
|
|
343
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
344
|
-
* Use the {@link payment} method
|
|
345
|
-
*/
|
|
346
326
|
async startCheckoutRouter(
|
|
347
327
|
routerData: StartCheckoutRequest | StartCheckoutIdRequest,
|
|
348
328
|
): Promise<StartCheckoutResponse | ErrorResponse | undefined> {
|
|
@@ -356,16 +336,12 @@ export class LiteCheckout extends BaseInlineCheckout {
|
|
|
356
336
|
}
|
|
357
337
|
|
|
358
338
|
// TODO: DEPRECATED
|
|
359
|
-
async init3DSRedirect(checkoutResult:
|
|
339
|
+
async init3DSRedirect(checkoutResult: IStartCheckoutResponse) {
|
|
360
340
|
this.process3ds.setPayload(checkoutResult);
|
|
361
341
|
return await this._handle3dsRedirect(checkoutResult);
|
|
362
342
|
}
|
|
363
343
|
|
|
364
344
|
// TODO: DEPRECATED
|
|
365
|
-
/**
|
|
366
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
367
|
-
* Use the {@link payment} method
|
|
368
|
-
*/
|
|
369
345
|
async startCheckoutRouterFull(
|
|
370
346
|
routerFullData: StartCheckoutFullRequest,
|
|
371
347
|
): Promise<StartCheckoutResponse | ErrorResponse | undefined> {
|
|
@@ -498,10 +474,6 @@ export class LiteCheckout extends BaseInlineCheckout {
|
|
|
498
474
|
}
|
|
499
475
|
|
|
500
476
|
// TODO: DEPRECATED
|
|
501
|
-
/**
|
|
502
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
503
|
-
* Use the {@link saveCustomerCard} method
|
|
504
|
-
*/
|
|
505
477
|
async registerCustomerCard(
|
|
506
478
|
customerToken: string,
|
|
507
479
|
data: RegisterCustomerCardRequest,
|
|
@@ -530,10 +502,6 @@ export class LiteCheckout extends BaseInlineCheckout {
|
|
|
530
502
|
}
|
|
531
503
|
|
|
532
504
|
// TODO: DEPRECATED
|
|
533
|
-
/**
|
|
534
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
535
|
-
* Use the {@link removeCustomerCard} method
|
|
536
|
-
*/
|
|
537
505
|
async deleteCustomerCard(
|
|
538
506
|
customerToken: string,
|
|
539
507
|
skyflowId: string = "",
|
|
@@ -560,10 +528,6 @@ export class LiteCheckout extends BaseInlineCheckout {
|
|
|
560
528
|
}
|
|
561
529
|
|
|
562
530
|
// TODO: DEPRECATED
|
|
563
|
-
/**
|
|
564
|
-
* @deprecated This method is deprecated and will be removed in a future release.
|
|
565
|
-
* Use the {@link getCustomerPaymentMethods} method
|
|
566
|
-
*/
|
|
567
531
|
async getActiveAPMs(): Promise<APM[]> {
|
|
568
532
|
try {
|
|
569
533
|
const apms_response = await getCustomerAPMs(
|