@tonder.io/ionic-lite-sdk 0.0.33-beta.8 → 0.0.34-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.idea/aws.xml ADDED
@@ -0,0 +1,17 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="accountSettings">
4
+ <option name="activeProfile" value="profile:default" />
5
+ <option name="activeRegion" value="us-east-1" />
6
+ <option name="recentlyUsedProfiles">
7
+ <list>
8
+ <option value="profile:default" />
9
+ </list>
10
+ </option>
11
+ <option name="recentlyUsedRegions">
12
+ <list>
13
+ <option value="us-east-1" />
14
+ </list>
15
+ </option>
16
+ </component>
17
+ </project>
@@ -2,23 +2,18 @@ type ThreeDSHandlerContructor = {
2
2
  payload?: any;
3
3
  apiKey?: string;
4
4
  baseUrl?: string;
5
- successUrl?: Location | string;
6
5
  };
7
6
  export declare class ThreeDSHandler {
8
7
  baseUrl?: string;
9
8
  apiKey?: string;
10
9
  payload?: any;
11
- successUrl?: Location | string;
12
10
  localStorageKey: string;
13
- constructor({ payload, apiKey, baseUrl, successUrl }: ThreeDSHandlerContructor);
11
+ constructor({ payload, apiKey, baseUrl, }: ThreeDSHandlerContructor);
14
12
  setStorageItem(data: any): void;
15
13
  getStorageItem(): string | null;
16
14
  removeStorageItem(): void;
17
15
  saveVerifyTransactionUrl(): void;
18
16
  saveUrlWithExpiration(url: string): void;
19
- saveCheckoutId(checkoutId: any): void;
20
- removeCheckoutId(): void;
21
- getCurrentCheckoutId(): any;
22
17
  getUrlWithExpiration(): any;
23
18
  removeVerifyTransactionUrl(): void;
24
19
  getVerifyTransactionUrl(): string | null;
@@ -1,5 +1,5 @@
1
1
  import CollectContainer from "skyflow-js/types/core/external/collect/collect-container";
2
- import { Business } from "../types/commons";
2
+ import { APM, Business } from "../types/commons";
3
3
  import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutRequest, TokensRequest, StartCheckoutFullRequest, StartCheckoutIdRequest } from "../types/requests";
4
4
  import { GetBusinessResponse, CustomerRegisterResponse, CreateOrderResponse, CreatePaymentResponse, StartCheckoutResponse, GetCustomerCardsResponse, RegisterCustomerCardResponse } from "../types/responses";
5
5
  import { ErrorResponse } from "./errorResponse";
@@ -13,7 +13,6 @@ export type LiteCheckoutConstructor = {
13
13
  signal: AbortSignal;
14
14
  baseUrlTonder: string;
15
15
  apiKeyTonder: string;
16
- successUrl?: string;
17
16
  };
18
17
  export declare class LiteCheckout implements LiteCheckoutConstructor {
19
18
  #private;
@@ -21,9 +20,9 @@ export declare class LiteCheckout implements LiteCheckoutConstructor {
21
20
  baseUrlTonder: string;
22
21
  apiKeyTonder: string;
23
22
  process3ds: ThreeDSHandler;
24
- successUrl?: string;
23
+ activeAPMs: APM[];
25
24
  merchantData?: Business | ErrorResponse;
26
- constructor({ signal, baseUrlTonder, apiKeyTonder, successUrl, }: LiteCheckoutConstructor);
25
+ constructor({ signal, baseUrlTonder, apiKeyTonder, }: LiteCheckoutConstructor);
27
26
  getOpenpayDeviceSessionID(merchant_id: string, public_key: string, is_sandbox: boolean): Promise<string | ErrorResponse>;
28
27
  getBusiness(): Promise<GetBusinessResponse | ErrorResponse>;
29
28
  verify3dsTransaction(): Promise<any>;
@@ -42,7 +41,6 @@ export declare class LiteCheckout implements LiteCheckoutConstructor {
42
41
  registerCustomerCard(customerToken: string, data: RegisterCustomerCardRequest): Promise<RegisterCustomerCardResponse | ErrorResponse>;
43
42
  getCustomerCards(customerToken: string): Promise<GetCustomerCardsResponse | ErrorResponse>;
44
43
  deleteCustomerCard(customerToken: string, skyflowId?: string): Promise<Boolean | ErrorResponse>;
45
- private buildErrorResponseFromCatch;
46
- private buildErrorResponse;
47
44
  private getFields;
45
+ getActiveAPMs(): Promise<APM[]>;
48
46
  }
@@ -1,3 +1,4 @@
1
+ import { ErrorResponse } from "../classes/errorResponse";
1
2
  export declare const getBrowserInfo: () => {
2
3
  javascript_enabled: boolean;
3
4
  time_zone: number;
@@ -8,3 +9,10 @@ export declare const getBrowserInfo: () => {
8
9
  user_agent: string;
9
10
  };
10
11
  export declare const getBusinessId: (merchantData: any) => any;
12
+ declare const buildErrorResponseFromCatch: (e: any) => ErrorResponse;
13
+ declare const buildErrorResponse: (response: Response, stack?: string | undefined) => Promise<ErrorResponse>;
14
+ declare const getPaymentMethodDetails: (scheme_data: string) => {
15
+ icon: string;
16
+ label: string;
17
+ };
18
+ export { buildErrorResponseFromCatch, buildErrorResponse, getPaymentMethodDetails };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import e from"skyflow-js";function t(e,t,i,r){return new(i||(i=Promise))((function(o,n){function s(e){try{d(r.next(e))}catch(e){n(e)}}function a(e){try{d(r.throw(e))}catch(e){n(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}d((r=r.apply(e,t||[])).next())}))}function i(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)}"function"==typeof SuppressedError&&SuppressedError;class r{constructor({code:e,body:t,name:i,message:r,stack:o}){this.code=e,this.body=t,this.name=i,this.message=r,this.stack=o}}const o=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""};class n{constructor({payload:e=null,apiKey:t,baseUrl:i,successUrl:r}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=i,this.apiKey=t,this.payload=e,this.successUrl=r}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,i,r,o,n;const s=null===(i=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===i?void 0:i.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(n=null===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===n?void 0:n.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}saveCheckoutId(e){localStorage.setItem("checkout_id",JSON.stringify(e))}removeCheckoutId(){localStorage.removeItem("checkout_id")}getCurrentCheckoutId(){const e=localStorage.getItem("checkout_id");return e?JSON.parse(e):null}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,i;if(null===(i=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===i?void 0:i.iframe)return new Promise(((e,t)=>{var i,r,o;const n=null===(o=null===(r=null===(i=this.payload)||void 0===i?void 0:i.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===o?void 0:o.iframe;if(n){this.saveVerifyTransactionUrl();const i=document.createElement("div");i.innerHTML=n,document.body.appendChild(i);const r=document.createElement("script");r.textContent='document.getElementById("tdsMmethodForm").submit();',i.appendChild(r);const o=document.getElementById("tdsMmethodTgtFrame");o?o.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,i;return null===(i=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===i?void 0:i.url}redirectToChallenge(){const e=this.getRedirectUrl();e?(this.saveVerifyTransactionUrl(),window.location=e):console.log("No redirection found")}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[i,r]of t)e[i]=r;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),console.log("Transacción autorizada."),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return t(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const i=document.createElement("input");i.type="hidden",i.name=e.creq,i.value=e.creq,t.appendChild(i);const r=document.createElement("input");r.type="hidden",r.name=e.term_url,r.value=e.TermUrl,t.appendChild(r),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return t(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}var s,a;class d{constructor({signal:e,baseUrlTonder:t,apiKeyTonder:i,successUrl:r}){s.add(this),this.baseUrlTonder=t,this.signal=e,this.apiKeyTonder=i,this.successUrl=r,this.process3ds=new n({apiKey:this.apiKeyTonder,baseUrl:this.baseUrlTonder,successUrl:r})}getOpenpayDeviceSessionID(e,i,r){return t(this,void 0,void 0,(function*(){try{let t=yield window.OpenPay;return t.setId(e),t.setApiKey(i),t.setSandboxMode(r),yield t.deviceData.setup({signal:this.signal})}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}getBusiness(){return t(this,void 0,void 0,(function*(){try{const e=yield fetch(`${this.baseUrlTonder}/api/v1/payments/business/${this.apiKeyTonder}`,{headers:{Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal});if(e.ok)return yield e.json();throw yield this.buildErrorResponse(e)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}verify3dsTransaction(){return t(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield this.resumeCheckout(e);return this.process3ds.setPayload(t),t&&"is_route_finished"in t&&"provider"in t&&"tonder"===t.provider?t:this.handle3dsRedirect(t)}))}resumeCheckout(e){return t(this,void 0,void 0,(function*(){if(["Failed","Declined","Cancelled"].includes(null==e?void 0:e.status)){const e={checkout_id:this.process3ds.getCurrentCheckoutId()};return yield this.handleCheckoutRouter(e)}return e}))}handle3dsRedirect(e){var i,r;return t(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(r=null===(i=null==e?void 0:e.next_action)||void 0===i?void 0:i.iframe_resources)||void 0===r?void 0:r.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((e=>{console.log("Error loading iframe:",e)}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}customerRegister(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/customer/`,i={email:e},r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal,body:JSON.stringify(i)});if(r.ok)return yield r.json();throw yield this.buildErrorResponse(r)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}createOrder(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/orders/`,i=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(i)});if(r.ok)return yield r.json();throw yield this.buildErrorResponse(r)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}createPayment(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/business/${e.business_pk}/payments/`,i=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(i)});if(r.ok)return yield r.json();throw yield this.buildErrorResponse(r)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}handleCheckoutRouter(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/checkout-router/`,i=e,r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(i)});if(r.ok)return yield r.json();throw yield this.buildErrorResponse(r)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}startCheckoutRouter(e){return t(this,void 0,void 0,(function*(){const t=yield this.handleCheckoutRouter(e);if(yield this.init3DSRedirect(t))return t}))}startCheckoutRouterFull(e){return t(this,void 0,void 0,(function*(){try{const{order:t,total:i,customer:o,skyflowTokens:n,return_url:s,isSandbox:a,metadata:d,currency:l}=e,c=yield this.getBusiness(),h=yield this.customerRegister(o.email);if(!(h&&"auth_token"in h&&c&&"reference"in c))throw new r({code:"500",body:c,name:"Keys error",message:"Merchant or customer reposne errors"});{const e={business:this.apiKeyTonder,client:h.auth_token,billing_address_id:null,shipping_address_id:null,amount:i,reference:c.reference,is_oneclick:!0,items:t.items},u=yield this.createOrder(e),y=(new Date).toISOString();if(!("id"in u&&"id"in h&&"business"in c))throw new r({code:"500",body:u,name:"Keys error",message:"Order response errors"});{const e={business_pk:c.business.pk,amount:i,date:y,order_id:u.id,client_id:h.id},t=yield this.createPayment(e);let r;const{openpay_keys:m,business:p}=c;m.merchant_id&&m.public_key&&(r=yield this.getOpenpayDeviceSessionID(m.merchant_id,m.public_key,a));const v={card:n,name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:s,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:i,title_ship:"shipping",description:"transaction",device_session_id:r||null,token_id:"",order_id:"id"in u&&u.id,business_id:p.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:{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},currency:l},f=yield this.handleCheckoutRouter(v);if(yield this.init3DSRedirect(f))return f}}}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}init3DSRedirect(e){return t(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),this.process3ds.saveCheckoutId(e&&"checkout_id"in e?e.checkout_id:""),yield this.handle3dsRedirect(e)}))}getSkyflowTokens({vault_id:i,vault_url:r,data:o}){return t(this,void 0,void 0,(function*(){const n=e.init({vaultID:i,vaultURL:r,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield this.getVaultToken()})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}).container(e.ContainerType.COLLECT),s=yield this.getFieldsPromise(o,n);if((yield Promise.all(s)).some((e=>!e)))throw this.buildErrorResponseFromCatch(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield n.collect();if(e)return e.records[0].fields;throw this.buildErrorResponseFromCatch(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}getVaultToken(){var e;return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal});if(t.ok)return null===(e=yield t.json())||void 0===e?void 0:e.token;throw new Error(`HTTPCODE: ${t.status}`)}catch(e){throw new Error(`Failed to retrieve bearer token; ${"string"==typeof e?e:e.message}`)}}))}getFieldsPromise(e,i){return t(this,void 0,void 0,(function*(){const t=yield this.getFields(e,i);return t?t.map((t=>new Promise((i=>{var r;const o=document.createElement("div");o.hidden=!0,o.id=`id-${t.key}`,null===(r=document.querySelector("body"))||void 0===r||r.appendChild(o),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const r=e[t.key];return t.element.update({value:r}),i(t.element.isMounted())}}),120)}),120)})))):[]}))}registerCustomerCard(e,r){return t(this,void 0,void 0,(function*(){try{this.merchantData||(yield i(this,s,"m",a).call(this));const t=yield fetch(`${this.baseUrlTonder}/api/v1/cards/`,{method:"POST",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal,body:JSON.stringify(Object.assign(Object.assign({},r),{business_id:o(this.merchantData)}))});if(t.ok)return yield t.json();throw yield this.buildErrorResponse(t)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}getCustomerCards(e){return t(this,void 0,void 0,(function*(){try{console.log("HERE INTI: ",this.merchantData),this.merchantData||(console.log("HERE INTI GECT****: ",this.merchantData),yield i(this,s,"m",a).call(this)),console.log("HERE INTI AFTER***: ",this.merchantData,o(this.merchantData));const t=yield fetch(`${this.baseUrlTonder}/api/v1/cards?business=${o(this.merchantData)}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal});if(t.ok)return yield t.json();throw yield this.buildErrorResponse(t)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}deleteCustomerCard(e,i=""){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/cards/${i}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal});if(t.ok)return!0;throw yield this.buildErrorResponse(t)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}buildErrorResponseFromCatch(e){return new r({code:(null==e?void 0:e.status)?e.status:e.code,body:null==e?void 0:e.body,name:e?"string"==typeof e?"catch":e.name:"Error",message:e?"string"==typeof e?e:e.message:"Error",stack:"string"==typeof e?void 0:e.stack})}buildErrorResponse(e,i=void 0){return t(this,void 0,void 0,(function*(){let t,o,n="Error";e&&"json"in e&&(t=yield null==e?void 0:e.json()),e&&"status"in e&&(o=e.status.toString()),e&&"text"in e&&(n=yield e.text());return new r({code:o,body:t,name:o,message:n,stack:i})}))}getFields(i,r){return t(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(i).map((i=>t(this,void 0,void 0,(function*(){return{element:yield r.create({table:"cards",column:i,type:e.ElementType.INPUT_FIELD}),key:i}})))))}))}}s=new WeakSet,a=function(){return t(this,void 0,void 0,(function*(){try{return this.merchantData=yield this.getBusiness(),this.merchantData}catch(e){return this.merchantData}}))};export{d as LiteCheckout};
1
+ import e from"skyflow-js";function t(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{d(o.next(e))}catch(e){i(e)}}function a(e){try{d(o.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}function n(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}"function"==typeof SuppressedError&&SuppressedError;class o{constructor({code:e,body:t,name:n,message:o,stack:r}){this.code=e,this.body=t,this.name=n,this.message=o,this.stack=r}}var r;!function(e){e.SORIANA="SORIANA",e.OXXO="OXXO",e.SPEI="SPEI",e.CODI="CODI",e.MERCADOPAGO="MERCADOPAGO",e.PAYPAL="PAYPAL",e.COMERCIALMEXICANA="COMERCIALMEXICANA",e.BANCOMER="BANCOMER",e.WALMART="WALMART",e.BODEGA="BODEGA",e.SAMSCLUB="SAMSCLUB",e.SUPERAMA="SUPERAMA",e.CALIMAX="CALIMAX",e.EXTRA="EXTRA",e.CIRCULOK="CIRCULOK",e.SEVEN11="7ELEVEN",e.TELECOMM="TELECOMM",e.BANORTE="BANORTE",e.BENAVIDES="BENAVIDES",e.DELAHORRO="DELAHORRO",e.ELASTURIANO="ELASTURIANO",e.WALDOS="WALDOS",e.ALSUPER="ALSUPER",e.KIOSKO="KIOSKO",e.STAMARIA="STAMARIA",e.LAMASBARATA="LAMASBARATA",e.FARMROMA="FARMROMA",e.FARMUNION="FARMUNION",e.FARMATODO="FARMATODO",e.SFDEASIS="SFDEASIS",e.FARM911="FARM911",e.FARMECONOMICAS="FARMECONOMICAS",e.FARMMEDICITY="FARMMEDICITY",e.RIANXEIRA="RIANXEIRA",e.WESTERNUNION="WESTERNUNION",e.ZONAPAGO="ZONAPAGO",e.CAJALOSANDES="CAJALOSANDES",e.CAJAPAITA="CAJAPAITA",e.CAJASANTA="CAJASANTA",e.CAJASULLANA="CAJASULLANA",e.CAJATRUJILLO="CAJATRUJILLO",e.EDPYME="EDPYME",e.KASNET="KASNET",e.NORANDINO="NORANDINO",e.QAPAQ="QAPAQ",e.RAIZ="RAIZ",e.PAYSER="PAYSER",e.WUNION="WUNION",e.BANCOCONTINENTAL="BANCOCONTINENTAL",e.GMONEY="GMONEY",e.GOPAY="GOPAY",e.WU="WU",e.PUNTOSHEY="PUNTOSHEY",e.AMPM="AMPM",e.JUMBOMARKET="JUMBOMARKET",e.SMELPUEBLO="SMELPUEBLO",e.BAM="BAM",e.REFACIL="REFACIL",e.ACYVALORES="ACYVALORES"}(r||(r={}));const i=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},s=e=>new o({code:(null==e?void 0:e.status)?e.status:e.code,body:null==e?void 0:e.body,name:e?"string"==typeof e?"catch":e.name:"Error",message:e?"string"==typeof e?e:e.message:"Error",stack:"string"==typeof e?void 0:e.stack}),a=(e,n=void 0)=>t(void 0,void 0,void 0,(function*(){let t,r,i="Error";e&&"json"in e&&(t=yield null==e?void 0:e.json()),e&&"status"in e&&(r=e.status.toString()),e&&"text"in e&&(i=yield e.text());return new o({code:r,body:t,name:r,message:i,stack:n})})),d=e=>e.trim().replace(/\s+/g,"");class l{constructor({payload:e=null,apiKey:t,baseUrl:n}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=n,this.apiKey=t,this.payload=e}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,n,o,r,i;const s=null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(i=null===(r=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,n;if(null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((e,t)=>{var n,o,r;const i=null===(r=null===(o=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(o);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,n;return null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const e=this.getRedirectUrl();e?(this.saveVerifyTransactionUrl(),window.location=e):console.log("No redirection found")}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[n,o]of t)e[n]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),console.log("Transacción autorizada."),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return t(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=e.creq,n.value=e.creq,t.appendChild(n);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return t(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}var c,u;class h{constructor({signal:e,baseUrlTonder:t,apiKeyTonder:n}){c.add(this),this.activeAPMs=[],this.baseUrlTonder=t,this.signal=e,this.apiKeyTonder=n,this.process3ds=new l({apiKey:this.apiKeyTonder,baseUrl:this.baseUrlTonder}),this.getActiveAPMs()}getOpenpayDeviceSessionID(e,n,o){return t(this,void 0,void 0,(function*(){try{let t=yield window.OpenPay;return t.setId(e),t.setApiKey(n),t.setSandboxMode(o),yield t.deviceData.setup({signal:this.signal})}catch(e){throw s(e)}}))}getBusiness(){return t(this,void 0,void 0,(function*(){try{const e=yield fetch(`${this.baseUrlTonder}/api/v1/payments/business/${this.apiKeyTonder}`,{headers:{Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal});if(e.ok)return yield e.json();throw yield a(e)}catch(e){throw s(e)}}))}verify3dsTransaction(){return t(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield this.resumeCheckout(e);return this.process3ds.setPayload(t),t&&"is_route_finished"in t&&"provider"in t&&"tonder"===t.provider?t:this.handle3dsRedirect(t)}))}resumeCheckout(e){var n;return t(this,void 0,void 0,(function*(){if(["Failed","Declined","Cancelled"].includes(null==e?void 0:e.status)){const t={checkout_id:null===(n=e.checkout)||void 0===n?void 0:n.id};return yield this.handleCheckoutRouter(t)}return e}))}handle3dsRedirect(e){var n,o;return t(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(n=null==e?void 0:e.next_action)||void 0===n?void 0:n.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((e=>{console.log("Error loading iframe:",e)}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}customerRegister(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/customer/`,n={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal,body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield a(o)}catch(e){throw s(e)}}))}createOrder(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/orders/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield a(o)}catch(e){throw s(e)}}))}createPayment(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/business/${e.business_pk}/payments/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield a(o)}catch(e){throw s(e)}}))}handleCheckoutRouter(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/checkout-router/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield a(o)}catch(e){throw s(e)}}))}startCheckoutRouter(e){return t(this,void 0,void 0,(function*(){const t=yield this.handleCheckoutRouter(e);if(yield this.init3DSRedirect(t))return t}))}startCheckoutRouterFull(e){return t(this,void 0,void 0,(function*(){try{const{order:t,total:n,customer:r,skyflowTokens:i,return_url:s,isSandbox:a,metadata:d,currency:l,payment_method:c}=e,u=yield this.getBusiness(),h=yield this.customerRegister(r.email);if(!(h&&"auth_token"in h&&u&&"reference"in u))throw new o({code:"500",body:u,name:"Keys error",message:"Merchant or customer reposne errors"});{const e={business:this.apiKeyTonder,client:h.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:u.reference,is_oneclick:!0,items:t.items},p=yield this.createOrder(e),m=(new Date).toISOString();if(!("id"in p&&"id"in h&&"business"in u))throw new o({code:"500",body:p,name:"Keys error",message:"Order response errors"});{const e={business_pk:u.business.pk,amount:n,date:m,order_id:p.id,client_id:h.id},t=yield this.createPayment(e);let o;const{openpay_keys:y,business:A}=u;y.merchant_id&&y.public_key&&(o=yield this.getOpenpayDeviceSessionID(y.merchant_id,y.public_key,a));const g=Object.assign({name:r.name,last_name:r.lastname,email_client:r.email,phone_number:r.phone,return_url:s,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:n,title_ship:"shipping",description:"transaction",device_session_id:o||null,token_id:"",order_id:"id"in p&&p.id,business_id:A.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:{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},currency:l},c?{payment_method:c}:{card:i}),f=yield this.handleCheckoutRouter(g);if(yield this.init3DSRedirect(f))return f}}}catch(e){throw s(e)}}))}init3DSRedirect(e){return t(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this.handle3dsRedirect(e)}))}getSkyflowTokens({vault_id:n,vault_url:o,data:r}){return t(this,void 0,void 0,(function*(){const i=e.init({vaultID:n,vaultURL:o,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield this.getVaultToken()})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}).container(e.ContainerType.COLLECT),a=yield this.getFieldsPromise(r,i);if((yield Promise.all(a)).some((e=>!e)))throw s(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield i.collect();if(e)return e.records[0].fields;throw s(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw s(e)}}))}getVaultToken(){var e;return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal});if(t.ok)return null===(e=yield t.json())||void 0===e?void 0:e.token;throw new Error(`HTTPCODE: ${t.status}`)}catch(e){throw new Error(`Failed to retrieve bearer token; ${"string"==typeof e?e:e.message}`)}}))}getFieldsPromise(e,n){return t(this,void 0,void 0,(function*(){const t=yield this.getFields(e,n);return t?t.map((t=>new Promise((n=>{var o;const r=document.createElement("div");r.hidden=!0,r.id=`id-${t.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(r),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const o=e[t.key];return t.element.update({value:o}),n(t.element.isMounted())}}),120)}),120)})))):[]}))}registerCustomerCard(e,o){return t(this,void 0,void 0,(function*(){try{this.merchantData||(yield n(this,c,"m",u).call(this));const t=yield fetch(`${this.baseUrlTonder}/api/v1/business/${i(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal,body:JSON.stringify(Object.assign({},o))});if(t.ok)return yield t.json();throw yield a(t)}catch(e){throw s(e)}}))}getCustomerCards(e){return t(this,void 0,void 0,(function*(){try{this.merchantData||(yield n(this,c,"m",u).call(this));const t=yield fetch(`${this.baseUrlTonder}/api/v1/business/${i(this.merchantData)}/cards`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal});if(t.ok)return yield t.json();throw yield a(t)}catch(e){throw s(e)}}))}deleteCustomerCard(e,o=""){return t(this,void 0,void 0,(function*(){try{this.merchantData||(yield n(this,c,"m",u).call(this));const t=yield fetch(`${this.baseUrlTonder}/api/v1/business/${i(this.merchantData)}/cards/${o}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal});if(t.ok)return!0;throw yield a(t)}catch(e){throw s(e)}}))}getFields(n,o){return t(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(n).map((n=>t(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:n,type:e.ElementType.INPUT_FIELD}),key:n}})))))}))}getActiveAPMs(){return t(this,void 0,void 0,(function*(){try{const e=yield function(e,n,o="?status=active&page_size=10000&country=México",r=null){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${n}`,"Content-Type":"application/json"},signal:r});if(t.ok)return yield t.json();throw yield a(t)}catch(e){throw s(e)}}))}(this.baseUrlTonder,this.apiKeyTonder),n=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=n.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},(e=>{const t=d(e.toUpperCase());return{[r.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[r.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[r.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[r.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[r.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[r.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[r.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[r.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[r.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[r.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[r.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[r.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[r.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[r.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[r.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[r.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[r.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[r.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[r.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[r.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[r.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[r.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[r.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[r.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[r.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[r.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[r.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[r.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[r.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[r.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}}[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}})(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}c=new WeakSet,u=function(){return t(this,void 0,void 0,(function*(){try{return this.merchantData=yield this.getBusiness(),this.merchantData}catch(e){return this.merchantData}}))};export{h as LiteCheckout};
@@ -57,3 +57,19 @@ export type PaymentData = {
57
57
  items: OrderItem[];
58
58
  };
59
59
  };
60
+ export type TonderAPM = {
61
+ pk: string;
62
+ payment_method: string;
63
+ priority: number;
64
+ category: string;
65
+ unavailable_countries: string[];
66
+ status: string;
67
+ };
68
+ export type APM = {
69
+ id: string;
70
+ payment_method: string;
71
+ priority: number;
72
+ category: string;
73
+ icon: string;
74
+ label: string;
75
+ };
@@ -18,8 +18,7 @@ export type CreatePaymentRequest = {
18
18
  order_id?: string | number;
19
19
  client_id?: string | number;
20
20
  };
21
- export type StartCheckoutRequest = {
22
- card: any;
21
+ export type StartCheckoutRequestBase = {
23
22
  name: any;
24
23
  last_name: string;
25
24
  email_client: any;
@@ -42,6 +41,15 @@ export type StartCheckoutRequest = {
42
41
  metadata: any;
43
42
  currency: string;
44
43
  };
44
+ export type StartCheckoutRequestWithCard = StartCheckoutRequestBase & {
45
+ card: any;
46
+ payment_method?: never;
47
+ };
48
+ export type StartCheckoutRequestWithPaymentMethod = StartCheckoutRequestBase & {
49
+ card?: never;
50
+ payment_method: string;
51
+ };
52
+ export type StartCheckoutRequest = StartCheckoutRequestWithCard | StartCheckoutRequestWithPaymentMethod;
45
53
  export type StartCheckoutIdRequest = {
46
54
  checkout_id: any;
47
55
  };
@@ -83,4 +91,5 @@ export type StartCheckoutFullRequest = {
83
91
  isSandbox: boolean;
84
92
  metadata: any;
85
93
  currency: string;
94
+ payment_method?: string;
86
95
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tonder.io/ionic-lite-sdk",
3
- "version": "0.0.33-beta.8",
3
+ "version": "0.0.34-beta.1",
4
4
  "description": "Tonder ionic lite SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -2,7 +2,6 @@ type ThreeDSHandlerContructor = {
2
2
  payload?: any,
3
3
  apiKey?: string,
4
4
  baseUrl?: string,
5
- successUrl?: Location | string
6
5
  }
7
6
 
8
7
  export class ThreeDSHandler {
@@ -10,19 +9,16 @@ export class ThreeDSHandler {
10
9
  baseUrl?: string
11
10
  apiKey?: string
12
11
  payload?: any
13
- successUrl?: Location | string
14
12
  localStorageKey: string = "verify_transaction_status_url"
15
13
 
16
14
  constructor({
17
15
  payload = null,
18
16
  apiKey,
19
17
  baseUrl,
20
- successUrl
21
18
  }: ThreeDSHandlerContructor) {
22
19
  this.baseUrl = baseUrl,
23
20
  this.apiKey = apiKey,
24
- this.payload = payload,
25
- this.successUrl = successUrl
21
+ this.payload = payload
26
22
  }
27
23
 
28
24
  setStorageItem (data: any) {
@@ -65,19 +61,6 @@ export class ThreeDSHandler {
65
61
  }
66
62
  }
67
63
 
68
- saveCheckoutId(checkoutId: any) {
69
- localStorage.setItem('checkout_id', JSON.stringify(checkoutId))
70
- }
71
-
72
- removeCheckoutId() {
73
- localStorage.removeItem("checkout_id")
74
- }
75
-
76
- getCurrentCheckoutId() {
77
- const checkout_id = localStorage.getItem("checkout_id")
78
- return checkout_id ? JSON.parse(checkout_id):null;
79
- }
80
-
81
64
  getUrlWithExpiration() {
82
65
  const status = this.getStorageItem();
83
66
  if(status) {
@@ -1,12 +1,13 @@
1
1
  import Skyflow from "skyflow-js";
2
2
  import CollectContainer from "skyflow-js/types/core/external/collect/collect-container";
3
3
  import CollectElement from "skyflow-js/types/core/external/collect/collect-element";
4
- import { Business } from "../types/commons";
4
+ import { APM, Business, TonderAPM } from "../types/commons";
5
5
  import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutRequest, TokensRequest, StartCheckoutFullRequest, StartCheckoutIdRequest } from "../types/requests";
6
6
  import { GetBusinessResponse, CustomerRegisterResponse, CreateOrderResponse, CreatePaymentResponse, StartCheckoutResponse, GetVaultTokenResponse, IErrorResponse, GetCustomerCardsResponse, RegisterCustomerCardResponse } from "../types/responses";
7
7
  import { ErrorResponse } from "./errorResponse";
8
- import { getBrowserInfo, getBusinessId } from "../helpers/utils";
8
+ import { buildErrorResponse, buildErrorResponseFromCatch, getBrowserInfo, getPaymentMethodDetails, getBusinessId } from "../helpers/utils";
9
9
  import { ThreeDSHandler } from "./3dsHandler";
10
+ import { getCustomerAPMs } from "../data/api";
10
11
 
11
12
  declare global {
12
13
  interface Window {
@@ -18,7 +19,6 @@ export type LiteCheckoutConstructor = {
18
19
  signal: AbortSignal;
19
20
  baseUrlTonder: string;
20
21
  apiKeyTonder: string;
21
- successUrl?: string;
22
22
  };
23
23
 
24
24
  export class LiteCheckout implements LiteCheckoutConstructor {
@@ -26,24 +26,22 @@ export class LiteCheckout implements LiteCheckoutConstructor {
26
26
  baseUrlTonder: string;
27
27
  apiKeyTonder: string;
28
28
  process3ds: ThreeDSHandler;
29
- successUrl?: string
29
+ activeAPMs: APM[] = []
30
30
  merchantData?: Business | ErrorResponse;
31
31
 
32
32
  constructor({
33
33
  signal,
34
34
  baseUrlTonder,
35
35
  apiKeyTonder,
36
- successUrl,
37
36
  }: LiteCheckoutConstructor) {
38
37
  this.baseUrlTonder = baseUrlTonder;
39
38
  this.signal = signal;
40
39
  this.apiKeyTonder = apiKeyTonder;
41
- this.successUrl = successUrl;
42
40
  this.process3ds = new ThreeDSHandler({
43
41
  apiKey: this.apiKeyTonder,
44
- baseUrl: this.baseUrlTonder,
45
- successUrl: successUrl
42
+ baseUrl: this.baseUrlTonder,
46
43
  })
44
+ this.getActiveAPMs()
47
45
  }
48
46
 
49
47
  async getOpenpayDeviceSessionID(
@@ -60,7 +58,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
60
58
  signal: this.signal,
61
59
  }) as string;
62
60
  } catch (e) {
63
- throw this.buildErrorResponseFromCatch(e);
61
+ throw buildErrorResponseFromCatch(e);
64
62
  }
65
63
  }
66
64
  async #fetchMerchantData() {
@@ -86,9 +84,9 @@ export class LiteCheckout implements LiteCheckoutConstructor {
86
84
 
87
85
  if (getBusiness.ok) return (await getBusiness.json()) as Business;
88
86
 
89
- throw await this.buildErrorResponse(getBusiness);
87
+ throw await buildErrorResponse(getBusiness);
90
88
  } catch (e) {
91
- throw this.buildErrorResponseFromCatch(e);
89
+ throw buildErrorResponseFromCatch(e);
92
90
  }
93
91
  }
94
92
 
@@ -105,8 +103,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
105
103
  async resumeCheckout(response: any) {
106
104
  if (["Failed", "Declined", "Cancelled"].includes(response?.status)) {
107
105
  const routerItems = {
108
- // TODO: Replace this with reponse.checkout_id
109
- checkout_id: this.process3ds.getCurrentCheckoutId(),
106
+ checkout_id: response.checkout?.id,
110
107
  };
111
108
  const routerResponse = await this.handleCheckoutRouter(
112
109
  routerItems
@@ -156,9 +153,9 @@ export class LiteCheckout implements LiteCheckoutConstructor {
156
153
  });
157
154
 
158
155
  if (response.ok) return await response.json() as CustomerRegisterResponse;
159
- throw await this.buildErrorResponse(response);
156
+ throw await buildErrorResponse(response);
160
157
  } catch (e) {
161
- throw this.buildErrorResponseFromCatch(e);
158
+ throw buildErrorResponseFromCatch(e);
162
159
  }
163
160
  }
164
161
 
@@ -175,9 +172,9 @@ export class LiteCheckout implements LiteCheckoutConstructor {
175
172
  body: JSON.stringify(data),
176
173
  });
177
174
  if (response.ok) return await response.json() as CreateOrderResponse;
178
- throw await this.buildErrorResponse(response);
175
+ throw await buildErrorResponse(response);
179
176
  } catch (e) {
180
- throw this.buildErrorResponseFromCatch(e);
177
+ throw buildErrorResponseFromCatch(e);
181
178
  }
182
179
  }
183
180
 
@@ -194,9 +191,9 @@ export class LiteCheckout implements LiteCheckoutConstructor {
194
191
  body: JSON.stringify(data),
195
192
  });
196
193
  if (response.ok) return await response.json() as CreatePaymentResponse;
197
- throw await this.buildErrorResponse(response);
194
+ throw await buildErrorResponse(response);
198
195
  } catch (e) {
199
- throw this.buildErrorResponseFromCatch(e);
196
+ throw buildErrorResponseFromCatch(e);
200
197
  }
201
198
  }
202
199
  async handleCheckoutRouter(routerData: StartCheckoutRequest | StartCheckoutIdRequest){
@@ -212,9 +209,9 @@ export class LiteCheckout implements LiteCheckoutConstructor {
212
209
  body: JSON.stringify(data),
213
210
  });
214
211
  if (response.ok) return await response.json() as StartCheckoutResponse;
215
- throw await this.buildErrorResponse(response);
212
+ throw await buildErrorResponse(response);
216
213
  } catch (e) {
217
- throw this.buildErrorResponseFromCatch(e);
214
+ throw buildErrorResponseFromCatch(e);
218
215
  }
219
216
  }
220
217
 
@@ -237,7 +234,8 @@ export class LiteCheckout implements LiteCheckoutConstructor {
237
234
  return_url,
238
235
  isSandbox,
239
236
  metadata,
240
- currency
237
+ currency,
238
+ payment_method
241
239
  } = routerFullData;
242
240
 
243
241
  const merchantResult = await this.getBusiness();
@@ -290,7 +288,6 @@ export class LiteCheckout implements LiteCheckoutConstructor {
290
288
  }
291
289
 
292
290
  const routerItems: StartCheckoutRequest = {
293
- card: skyflowTokens,
294
291
  name: customer.name,
295
292
  last_name: customer.lastname,
296
293
  email_client: customer.email,
@@ -311,7 +308,11 @@ export class LiteCheckout implements LiteCheckoutConstructor {
311
308
  source: 'sdk',
312
309
  metadata: metadata,
313
310
  browser_info: getBrowserInfo(),
314
- currency: currency
311
+ currency: currency,
312
+ ...( !!payment_method
313
+ ? {payment_method}
314
+ : {card: skyflowTokens}
315
+ )
315
316
  };
316
317
 
317
318
  const checkoutResult = await this.handleCheckoutRouter(routerItems);
@@ -341,14 +342,13 @@ export class LiteCheckout implements LiteCheckoutConstructor {
341
342
  }
342
343
  } catch (e) {
343
344
 
344
- throw this.buildErrorResponseFromCatch(e);
345
+ throw buildErrorResponseFromCatch(e);
345
346
 
346
347
  }
347
348
  }
348
349
 
349
350
  async init3DSRedirect(checkoutResult: ErrorResponse | StartCheckoutResponse){
350
351
  this.process3ds.setPayload(checkoutResult)
351
- this.process3ds.saveCheckoutId(checkoutResult && 'checkout_id' in checkoutResult ? checkoutResult.checkout_id:"")
352
352
  return await this.handle3dsRedirect(checkoutResult)
353
353
  }
354
354
 
@@ -378,14 +378,14 @@ export class LiteCheckout implements LiteCheckoutConstructor {
378
378
  const mountFail = result.some((item: boolean) => !item);
379
379
 
380
380
  if (mountFail) {
381
- throw this.buildErrorResponseFromCatch(Error("Ocurrió un error al montar los campos de la tarjeta"));
381
+ throw buildErrorResponseFromCatch(Error("Ocurrió un error al montar los campos de la tarjeta"));
382
382
  } else {
383
383
  try {
384
384
  const collectResponseSkyflowTonder = await collectContainer.collect() as any;
385
385
  if (collectResponseSkyflowTonder) return collectResponseSkyflowTonder["records"][0]["fields"];
386
- throw this.buildErrorResponseFromCatch(Error("Por favor, verifica todos los campos de tu tarjeta"))
386
+ throw buildErrorResponseFromCatch(Error("Por favor, verifica todos los campos de tu tarjeta"))
387
387
  } catch (error) {
388
- throw this.buildErrorResponseFromCatch(error);
388
+ throw buildErrorResponseFromCatch(error);
389
389
  }
390
390
  }
391
391
  }
@@ -436,33 +436,30 @@ export class LiteCheckout implements LiteCheckoutConstructor {
436
436
  await this.#fetchMerchantData()
437
437
  }
438
438
 
439
- const response = await fetch(`${this.baseUrlTonder}/api/v1/cards/`, {
439
+ const response = await fetch(`${this.baseUrlTonder}/api/v1/business/${getBusinessId(this.merchantData)}/cards/`, {
440
440
  method: 'POST',
441
441
  headers: {
442
442
  'Authorization': `Token ${customerToken}`,
443
443
  'Content-Type': 'application/json'
444
444
  },
445
445
  signal: this.signal,
446
- body: JSON.stringify({...data, business_id: getBusinessId(this.merchantData) })
446
+ body: JSON.stringify({...data})
447
447
  });
448
448
 
449
449
  if (response.ok) return await response.json() as RegisterCustomerCardResponse;
450
- throw await this.buildErrorResponse(response);
450
+ throw await buildErrorResponse(response);
451
451
  } catch (error) {
452
- throw this.buildErrorResponseFromCatch(error);
452
+ throw buildErrorResponseFromCatch(error);
453
453
  }
454
454
  }
455
455
 
456
456
  async getCustomerCards(customerToken: string): Promise<GetCustomerCardsResponse | ErrorResponse> {
457
457
  try {
458
- console.log("HERE INTI: ", this.merchantData)
459
458
  if(!this.merchantData){
460
- console.log("HERE INTI GECT****: ", this.merchantData)
461
459
  await this.#fetchMerchantData()
462
460
  }
463
- console.log("HERE INTI AFTER***: ", this.merchantData, getBusinessId(this.merchantData))
464
461
 
465
- const response = await fetch(`${this.baseUrlTonder}/api/v1/cards?business=${getBusinessId(this.merchantData)}`, {
462
+ const response = await fetch(`${this.baseUrlTonder}/api/v1/business/${getBusinessId(this.merchantData)}/cards`, {
466
463
  method: 'GET',
467
464
  headers: {
468
465
  'Authorization': `Token ${customerToken}`,
@@ -472,15 +469,19 @@ export class LiteCheckout implements LiteCheckoutConstructor {
472
469
  });
473
470
 
474
471
  if (response.ok) return await response.json() as GetCustomerCardsResponse;
475
- throw await this.buildErrorResponse(response);
472
+ throw await buildErrorResponse(response);
476
473
  } catch (error) {
477
- throw this.buildErrorResponseFromCatch(error);
474
+ throw buildErrorResponseFromCatch(error);
478
475
  }
479
476
  }
480
477
 
481
478
  async deleteCustomerCard(customerToken: string, skyflowId: string = ""): Promise<Boolean | ErrorResponse> {
482
479
  try {
483
- const response = await fetch(`${this.baseUrlTonder}/api/v1/cards/${skyflowId}`, {
480
+ if(!this.merchantData){
481
+ await this.#fetchMerchantData()
482
+ }
483
+
484
+ const response = await fetch(`${this.baseUrlTonder}/api/v1/business/${getBusinessId(this.merchantData)}/cards/${skyflowId}`, {
484
485
  method: 'DELETE',
485
486
  headers: {
486
487
  'Authorization': `Token ${customerToken}`,
@@ -490,55 +491,12 @@ export class LiteCheckout implements LiteCheckoutConstructor {
490
491
  });
491
492
 
492
493
  if (response.ok) return true;
493
- throw await this.buildErrorResponse(response);
494
+ throw await buildErrorResponse(response);
494
495
  } catch (error) {
495
- throw this.buildErrorResponseFromCatch(error);
496
+ throw buildErrorResponseFromCatch(error);
496
497
  }
497
498
  }
498
499
 
499
- private buildErrorResponseFromCatch(e: any): ErrorResponse {
500
-
501
- const error = new ErrorResponse({
502
- code: e?.status ? e.status : e.code,
503
- body: e?.body,
504
- name: e ? typeof e == "string" ? "catch" : (e as Error).name : "Error",
505
- message: e ? (typeof e == "string" ? e : (e as Error).message) : "Error",
506
- stack: typeof e == "string" ? undefined : (e as Error).stack,
507
- })
508
-
509
- return error;
510
- }
511
-
512
- private async buildErrorResponse(
513
- response: Response,
514
- stack: string | undefined = undefined
515
- ): Promise<ErrorResponse> {
516
-
517
- let body, status, message = "Error";
518
-
519
- if(response && "json" in response) {
520
- body = await response?.json();
521
- }
522
-
523
- if(response && "status" in response) {
524
- status = response.status.toString();
525
- }
526
-
527
- if(response && "text" in response) {
528
- message = await response.text();
529
- }
530
-
531
- const error = new ErrorResponse({
532
- code: status,
533
- body: body,
534
- name: status,
535
- message: message,
536
- stack,
537
- } as IErrorResponse)
538
-
539
- return error;
540
- }
541
-
542
500
  private async getFields(data: any, collectContainer: CollectContainer): Promise<{ element: CollectElement, key: string }[]> {
543
501
  return await Promise.all(
544
502
  Object.keys(data).map(async (key) => {
@@ -551,4 +509,29 @@ export class LiteCheckout implements LiteCheckoutConstructor {
551
509
  })
552
510
  )
553
511
  }
512
+
513
+ async getActiveAPMs(): Promise<APM[]> {
514
+ try {
515
+ const apms_response = await getCustomerAPMs(this.baseUrlTonder, this.apiKeyTonder);
516
+ const apms_results = apms_response && apms_response['results'] && apms_response['results'].length > 0 ? apms_response['results'] : []
517
+ this.activeAPMs = apms_results
518
+ .filter((apmItem: TonderAPM) =>
519
+ apmItem.category.toLowerCase() !== 'cards')
520
+ .map((apmItem: TonderAPM) => {
521
+ const apm: APM = {
522
+ id: apmItem.pk,
523
+ payment_method: apmItem.payment_method,
524
+ priority: apmItem.priority,
525
+ category: apmItem.category,
526
+ ...getPaymentMethodDetails(apmItem.payment_method,)
527
+ }
528
+ return apm;
529
+ }).sort((a: APM, b: APM) => a.priority - b.priority);
530
+
531
+ return this.activeAPMs
532
+ } catch (e) {
533
+ console.error("Error getting APMS", e);
534
+ return [];
535
+ }
536
+ }
554
537
  }
@@ -0,0 +1,21 @@
1
+ import { buildErrorResponse, buildErrorResponseFromCatch } from "../helpers/utils";
2
+
3
+ export async function getCustomerAPMs(baseUrlTonder: string, apiKeyTonder: string, query: string = "?status=active&page_size=10000&country=México", signal: AbortSignal | null | undefined = null) {
4
+ try {
5
+ const response = await fetch(
6
+ `${baseUrlTonder}/api/v1/payment_methods${query}`,
7
+ {
8
+ method: 'GET',
9
+ headers: {
10
+ Authorization: `Token ${apiKeyTonder}`,
11
+ 'Content-Type': 'application/json'
12
+ },
13
+ signal
14
+ });
15
+
16
+ if (response.ok) return await response.json();
17
+ throw await buildErrorResponse(response);
18
+ } catch (error) {
19
+ throw buildErrorResponseFromCatch(error);
20
+ }
21
+ }
@@ -0,0 +1,64 @@
1
+ enum PAYMENT_METHOD {
2
+ SORIANA = "SORIANA",
3
+ OXXO = "OXXO",
4
+ SPEI= "SPEI",
5
+ CODI= "CODI",
6
+ MERCADOPAGO= "MERCADOPAGO",
7
+ PAYPAL= "PAYPAL",
8
+ COMERCIALMEXICANA= "COMERCIALMEXICANA",
9
+ BANCOMER= "BANCOMER",
10
+ WALMART= "WALMART",
11
+ BODEGA= "BODEGA",
12
+ SAMSCLUB= "SAMSCLUB",
13
+ SUPERAMA= "SUPERAMA",
14
+ CALIMAX= "CALIMAX",
15
+ EXTRA= "EXTRA",
16
+ CIRCULOK= "CIRCULOK",
17
+ SEVEN11= "7ELEVEN",
18
+ TELECOMM= "TELECOMM",
19
+ BANORTE= "BANORTE",
20
+ BENAVIDES= "BENAVIDES",
21
+ DELAHORRO= "DELAHORRO",
22
+ ELASTURIANO= "ELASTURIANO",
23
+ WALDOS= "WALDOS",
24
+ ALSUPER= "ALSUPER",
25
+ KIOSKO= "KIOSKO",
26
+ STAMARIA= "STAMARIA",
27
+ LAMASBARATA= "LAMASBARATA",
28
+ FARMROMA= "FARMROMA",
29
+ FARMUNION= "FARMUNION",
30
+ FARMATODO= "FARMATODO",
31
+ SFDEASIS= "SFDEASIS",
32
+ FARM911= "FARM911",
33
+ FARMECONOMICAS= "FARMECONOMICAS",
34
+ FARMMEDICITY= "FARMMEDICITY",
35
+ RIANXEIRA= "RIANXEIRA",
36
+ WESTERNUNION= "WESTERNUNION",
37
+ ZONAPAGO= "ZONAPAGO",
38
+ CAJALOSANDES= "CAJALOSANDES",
39
+ CAJAPAITA= "CAJAPAITA",
40
+ CAJASANTA= "CAJASANTA",
41
+ CAJASULLANA= "CAJASULLANA",
42
+ CAJATRUJILLO= "CAJATRUJILLO",
43
+ EDPYME= "EDPYME",
44
+ KASNET= "KASNET",
45
+ NORANDINO= "NORANDINO",
46
+ QAPAQ= "QAPAQ",
47
+ RAIZ= "RAIZ",
48
+ PAYSER= "PAYSER",
49
+ WUNION= "WUNION",
50
+ BANCOCONTINENTAL= "BANCOCONTINENTAL",
51
+ GMONEY= "GMONEY",
52
+ GOPAY= "GOPAY",
53
+ WU= "WU",
54
+ PUNTOSHEY= "PUNTOSHEY",
55
+ AMPM= "AMPM",
56
+ JUMBOMARKET= "JUMBOMARKET",
57
+ SMELPUEBLO= "SMELPUEBLO",
58
+ BAM= "BAM",
59
+ REFACIL= "REFACIL",
60
+ ACYVALORES= "ACYVALORES"
61
+ }
62
+
63
+ export { PAYMENT_METHOD }
64
+
@@ -1,3 +1,7 @@
1
+ import { ErrorResponse } from "../classes/errorResponse";
2
+ import { IErrorResponse } from "../types/responses";
3
+ import { PAYMENT_METHOD } from "./constants";
4
+
1
5
  export const getBrowserInfo = () => {
2
6
  const browserInfo = {
3
7
  javascript_enabled: true, // Assumed since JavaScript is running
@@ -13,4 +17,302 @@ export const getBrowserInfo = () => {
13
17
 
14
18
  export const getBusinessId = (merchantData: any) =>{
15
19
  return merchantData && "business" in merchantData ? merchantData?.business?.pk:""
20
+ }
21
+ const buildErrorResponseFromCatch = (e: any): ErrorResponse => {
22
+
23
+ const error = new ErrorResponse({
24
+ code: e?.status ? e.status : e.code,
25
+ body: e?.body,
26
+ name: e ? typeof e == "string" ? "catch" : (e as Error).name : "Error",
27
+ message: e ? (typeof e == "string" ? e : (e as Error).message) : "Error",
28
+ stack: typeof e == "string" ? undefined : (e as Error).stack,
29
+ })
30
+
31
+ return error;
32
+ }
33
+
34
+ const buildErrorResponse = async (
35
+ response: Response,
36
+ stack: string | undefined = undefined
37
+ ): Promise<ErrorResponse> => {
38
+
39
+ let body, status, message = "Error";
40
+
41
+ if (response && "json" in response) {
42
+ body = await response?.json();
43
+ }
44
+
45
+ if (response && "status" in response) {
46
+ status = response.status.toString();
47
+ }
48
+
49
+ if (response && "text" in response) {
50
+ message = await response.text();
51
+ }
52
+
53
+ const error = new ErrorResponse({
54
+ code: status,
55
+ body: body,
56
+ name: status,
57
+ message: message,
58
+ stack,
59
+ } as IErrorResponse)
60
+
61
+ return error;
62
+ }
63
+
64
+ const getPaymentMethodDetails = (scheme_data: string): {icon: string; label: string} => {
65
+ const scheme: PAYMENT_METHOD = clearSpace(scheme_data.toUpperCase()) as PAYMENT_METHOD;
66
+
67
+ const PAYMENT_METHODS_CATALOG: Partial<Record<PAYMENT_METHOD, { icon: string, label: string }>> = {
68
+ [PAYMENT_METHOD.SORIANA]: {
69
+ label: "Soriana",
70
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png",
71
+ },
72
+ [PAYMENT_METHOD.OXXO]: {
73
+ label: "Oxxo",
74
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png",
75
+ },
76
+ [PAYMENT_METHOD.CODI]: {
77
+ label: "CoDi",
78
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png",
79
+ },
80
+ [PAYMENT_METHOD.SPEI]: {
81
+ label: "SPEI",
82
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png",
83
+ },
84
+ [PAYMENT_METHOD.PAYPAL]: {
85
+ label: "Paypal",
86
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png",
87
+ },
88
+ [PAYMENT_METHOD.COMERCIALMEXICANA]: {
89
+ label: "Comercial Mexicana",
90
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png",
91
+ },
92
+ [PAYMENT_METHOD.BANCOMER]: {
93
+ label: "Bancomer",
94
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png",
95
+ },
96
+ [PAYMENT_METHOD.WALMART]: {
97
+ label: "Walmart",
98
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png",
99
+ },
100
+ [PAYMENT_METHOD.BODEGA]: {
101
+ label: "Bodega Aurrera",
102
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png",
103
+ },
104
+ [PAYMENT_METHOD.SAMSCLUB]: {
105
+ label: "Sam´s Club",
106
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png",
107
+ },
108
+ [PAYMENT_METHOD.SUPERAMA]: {
109
+ label: "Superama",
110
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png",
111
+ },
112
+ [PAYMENT_METHOD.CALIMAX]: {
113
+ label: "Calimax",
114
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png",
115
+ },
116
+ [PAYMENT_METHOD.EXTRA]: {
117
+ label: "Tiendas Extra",
118
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png",
119
+ },
120
+ [PAYMENT_METHOD.CIRCULOK]: {
121
+ label: "Círculo K",
122
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png",
123
+ },
124
+ [PAYMENT_METHOD.SEVEN11]: {
125
+ label: "7 Eleven",
126
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png",
127
+ },
128
+ [PAYMENT_METHOD.TELECOMM]: {
129
+ label: "Telecomm",
130
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png",
131
+ },
132
+ [PAYMENT_METHOD.BANORTE]: {
133
+ label: "Banorte",
134
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png",
135
+ },
136
+ [PAYMENT_METHOD.BENAVIDES]: {
137
+ label: "Farmacias Benavides",
138
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png",
139
+ },
140
+ [PAYMENT_METHOD.DELAHORRO]: {
141
+ label: "Farmacias del Ahorro",
142
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png",
143
+ },
144
+ [PAYMENT_METHOD.ELASTURIANO]: {
145
+ label: "El Asturiano",
146
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png",
147
+ },
148
+ [PAYMENT_METHOD.WALDOS]: {
149
+ label: "Waldos",
150
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png",
151
+ },
152
+ [PAYMENT_METHOD.ALSUPER]: {
153
+ label: "Alsuper",
154
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png",
155
+ },
156
+ [PAYMENT_METHOD.KIOSKO]: {
157
+ label: "Kiosko",
158
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png",
159
+ },
160
+ [PAYMENT_METHOD.STAMARIA]: {
161
+ label: "Farmacias Santa María",
162
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png",
163
+ },
164
+ [PAYMENT_METHOD.LAMASBARATA]: {
165
+ label: "Farmacias la más barata",
166
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png",
167
+ },
168
+ [PAYMENT_METHOD.FARMROMA]: {
169
+ label: "Farmacias Roma",
170
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png",
171
+ },
172
+ [PAYMENT_METHOD.FARMUNION]: {
173
+ label: "Pago en Farmacias Unión",
174
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png",
175
+ },
176
+ [PAYMENT_METHOD.FARMATODO]: {
177
+ label: "Pago en Farmacias Farmatodo",
178
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png ",
179
+ },
180
+ [PAYMENT_METHOD.SFDEASIS]: {
181
+ label: "Pago en Farmacias San Francisco de Asís",
182
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png",
183
+ },
184
+ [PAYMENT_METHOD.FARM911]: {
185
+ label: "Farmacias 911",
186
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
187
+ },
188
+ [PAYMENT_METHOD.FARMECONOMICAS]: {
189
+ label: "Farmacias Economicas",
190
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
191
+ },
192
+ [PAYMENT_METHOD.FARMMEDICITY]: {
193
+ label: "Farmacias Medicity",
194
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
195
+ },
196
+ [PAYMENT_METHOD.RIANXEIRA]: {
197
+ label: "Rianxeira",
198
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
199
+ },
200
+ [PAYMENT_METHOD.WESTERNUNION]: {
201
+ label: "Western Union",
202
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
203
+ },
204
+ [PAYMENT_METHOD.ZONAPAGO]: {
205
+ label: "Zona Pago",
206
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
207
+ },
208
+ [PAYMENT_METHOD.CAJALOSANDES]: {
209
+ label: "Caja Los Andes",
210
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
211
+ },
212
+ [PAYMENT_METHOD.CAJAPAITA]: {
213
+ label: "Caja Paita",
214
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
215
+ },
216
+ [PAYMENT_METHOD.CAJASANTA]: {
217
+ label: "Caja Santa",
218
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
219
+ },
220
+ [PAYMENT_METHOD.CAJASULLANA]: {
221
+ label: "Caja Sullana",
222
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
223
+ },
224
+ [PAYMENT_METHOD.CAJATRUJILLO]: {
225
+ label: "Caja Trujillo",
226
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
227
+ },
228
+ [PAYMENT_METHOD.EDPYME]: {
229
+ label: "Edpyme",
230
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
231
+ },
232
+ [PAYMENT_METHOD.KASNET]: {
233
+ label: "KasNet",
234
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
235
+ },
236
+ [PAYMENT_METHOD.NORANDINO]: {
237
+ label: "Norandino",
238
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
239
+ },
240
+ [PAYMENT_METHOD.QAPAQ]: {
241
+ label: "Qapaq",
242
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
243
+ },
244
+ [PAYMENT_METHOD.RAIZ]: {
245
+ label: "Raiz",
246
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
247
+ },
248
+ [PAYMENT_METHOD.PAYSER]: {
249
+ label: "Paysera",
250
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
251
+ },
252
+ [PAYMENT_METHOD.WUNION]: {
253
+ label: "Western Union",
254
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
255
+ },
256
+ [PAYMENT_METHOD.BANCOCONTINENTAL]: {
257
+ label: "Banco Continental",
258
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
259
+ },
260
+ [PAYMENT_METHOD.GMONEY]: {
261
+ label: "Go money",
262
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
263
+ },
264
+ [PAYMENT_METHOD.GOPAY]: {
265
+ label: "Go pay",
266
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
267
+ },
268
+ [PAYMENT_METHOD.WU]: {
269
+ label: "Western Union",
270
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
271
+ },
272
+ [PAYMENT_METHOD.PUNTOSHEY]: {
273
+ label: "Puntoshey",
274
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
275
+ },
276
+ [PAYMENT_METHOD.AMPM]: {
277
+ label: "Ampm",
278
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
279
+ },
280
+ [PAYMENT_METHOD.JUMBOMARKET]: {
281
+ label: "Jumbomarket",
282
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
283
+ },
284
+ [PAYMENT_METHOD.SMELPUEBLO]: {
285
+ label: "Smelpueblo",
286
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
287
+ },
288
+ [PAYMENT_METHOD.BAM]: {
289
+ label: "Bam",
290
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
291
+ },
292
+ [PAYMENT_METHOD.REFACIL]: {
293
+ label: "Refacil",
294
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
295
+ },
296
+ [PAYMENT_METHOD.ACYVALORES]: {
297
+ label: "Acyvalores",
298
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
299
+ },
300
+ };
301
+
302
+ const _default = {
303
+ icon: "https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",
304
+ label: ""
305
+ };
306
+
307
+ return PAYMENT_METHODS_CATALOG[scheme] || _default;
308
+ }
309
+
310
+ const clearSpace = (text: string) => {
311
+ return text.trim().replace(/\s+/g, '');
312
+ }
313
+
314
+ export {
315
+ buildErrorResponseFromCatch,
316
+ buildErrorResponse,
317
+ getPaymentMethodDetails
16
318
  }
@@ -60,3 +60,21 @@ export type PaymentData = {
60
60
  items: OrderItem[];
61
61
  };
62
62
  };
63
+
64
+ export type TonderAPM = {
65
+ pk: string;
66
+ payment_method: string;
67
+ priority: number;
68
+ category: string;
69
+ unavailable_countries: string[];
70
+ status: string;
71
+ }
72
+
73
+ export type APM = {
74
+ id: string;
75
+ payment_method: string;
76
+ priority: number;
77
+ category: string;
78
+ icon: string;
79
+ label: string;
80
+ }
@@ -21,8 +21,7 @@ export type CreatePaymentRequest = {
21
21
  client_id?: string | number
22
22
  }
23
23
 
24
- export type StartCheckoutRequest = {
25
- card: any,
24
+ export type StartCheckoutRequestBase = {
26
25
  name: any,
27
26
  last_name: string,
28
27
  email_client: any,
@@ -43,9 +42,21 @@ export type StartCheckoutRequest = {
43
42
  source: string,
44
43
  browser_info?: any,
45
44
  metadata: any,
46
- currency: string
45
+ currency: string,
46
+ }
47
+
48
+ export type StartCheckoutRequestWithCard = StartCheckoutRequestBase & {
49
+ card: any,
50
+ payment_method?: never,
47
51
  }
48
52
 
53
+ export type StartCheckoutRequestWithPaymentMethod = StartCheckoutRequestBase & {
54
+ card?: never,
55
+ payment_method: string,
56
+ }
57
+
58
+ export type StartCheckoutRequest = StartCheckoutRequestWithCard | StartCheckoutRequestWithPaymentMethod;
59
+
49
60
  export type StartCheckoutIdRequest = {
50
61
  checkout_id: any
51
62
  }
@@ -91,4 +102,5 @@ export type StartCheckoutFullRequest = {
91
102
  isSandbox: boolean;
92
103
  metadata: any;
93
104
  currency: string;
105
+ payment_method?: string;
94
106
  }
@@ -5,7 +5,8 @@ import {
5
5
  RegisterCustomerCardRequest,
6
6
  StartCheckoutRequest,
7
7
  TokensRequest,
8
- StartCheckoutFullRequest
8
+ StartCheckoutFullRequest,
9
+ StartCheckoutRequestWithCard
9
10
  } from "../../src/types/requests";
10
11
  import {
11
12
  CreateOrderResponse,
@@ -312,7 +313,7 @@ export class CreatePaymentResponseClass implements CreatePaymentResponse {
312
313
  }
313
314
  }
314
315
 
315
- export class StartCheckoutRequestClass implements StartCheckoutRequest {
316
+ export class StartCheckoutRequestClass implements StartCheckoutRequestWithCard {
316
317
  card: any;
317
318
  name: any;
318
319
  last_name!: string;