@tonder.io/ionic-lite-sdk 0.0.33-beta.1 → 0.0.33-beta.10
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.
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import CollectContainer from "skyflow-js/types/core/external/collect/collect-container";
|
|
2
|
+
import { Business } from "../types/commons";
|
|
2
3
|
import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutRequest, TokensRequest, StartCheckoutFullRequest, StartCheckoutIdRequest } from "../types/requests";
|
|
3
4
|
import { GetBusinessResponse, CustomerRegisterResponse, CreateOrderResponse, CreatePaymentResponse, StartCheckoutResponse, GetCustomerCardsResponse, RegisterCustomerCardResponse } from "../types/responses";
|
|
4
5
|
import { ErrorResponse } from "./errorResponse";
|
|
@@ -15,11 +16,13 @@ export type LiteCheckoutConstructor = {
|
|
|
15
16
|
successUrl?: string;
|
|
16
17
|
};
|
|
17
18
|
export declare class LiteCheckout implements LiteCheckoutConstructor {
|
|
19
|
+
#private;
|
|
18
20
|
signal: AbortSignal;
|
|
19
21
|
baseUrlTonder: string;
|
|
20
22
|
apiKeyTonder: string;
|
|
21
23
|
process3ds: ThreeDSHandler;
|
|
22
24
|
successUrl?: string;
|
|
25
|
+
merchantData?: Business | ErrorResponse;
|
|
23
26
|
constructor({ signal, baseUrlTonder, apiKeyTonder, successUrl, }: LiteCheckoutConstructor);
|
|
24
27
|
getOpenpayDeviceSessionID(merchant_id: string, public_key: string, is_sandbox: boolean): Promise<string | ErrorResponse>;
|
|
25
28
|
getBusiness(): Promise<GetBusinessResponse | ErrorResponse>;
|
|
@@ -37,7 +40,7 @@ export declare class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
37
40
|
getVaultToken(): Promise<string>;
|
|
38
41
|
getFieldsPromise(data: any, collectContainer: CollectContainer): Promise<Promise<boolean>[]>;
|
|
39
42
|
registerCustomerCard(customerToken: string, data: RegisterCustomerCardRequest): Promise<RegisterCustomerCardResponse | ErrorResponse>;
|
|
40
|
-
getCustomerCards(customerToken: string
|
|
43
|
+
getCustomerCards(customerToken: string): Promise<GetCustomerCardsResponse | ErrorResponse>;
|
|
41
44
|
deleteCustomerCard(customerToken: string, skyflowId?: string): Promise<Boolean | ErrorResponse>;
|
|
42
45
|
private buildErrorResponseFromCatch;
|
|
43
46
|
private buildErrorResponse;
|
package/dist/helpers/utils.d.ts
CHANGED
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"==typeof SuppressedError&&SuppressedError;class i{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}}class r{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")}))}}class o{constructor({signal:e,baseUrlTonder:t,apiKeyTonder:i,successUrl:o}){this.baseUrlTonder=t,this.signal=e,this.apiKeyTonder=i,this.successUrl=o,this.process3ds=new r({apiKey:this.apiKeyTonder,baseUrl:this.baseUrlTonder,successUrl:o})}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:r,customer:o,skyflowTokens:n,return_url:s,isSandbox:a,metadata:d,currency:l}=e,c=yield this.getBusiness(),u=yield this.customerRegister(o.email);if(!(u&&"auth_token"in u&&c&&"reference"in c))throw new i({code:"500",body:c,name:"Keys error",message:"Merchant or customer reposne errors"});{const e={business:this.apiKeyTonder,client:u.auth_token,billing_address_id:null,shipping_address_id:null,amount:r,reference:c.reference,is_oneclick:!0,items:t.items},h=yield this.createOrder(e),y=(new Date).toISOString();if(!("id"in h&&"id"in u&&"business"in c))throw new i({code:"500",body:h,name:"Keys error",message:"Order response errors"});{const e={business_pk:c.business.pk,amount:r,date:y,order_id:h.id,client_id:u.id},t=yield this.createPayment(e);let i;const{openpay_keys:p,business:v}=c;p.merchant_id&&p.public_key&&(i=yield this.getOpenpayDeviceSessionID(p.merchant_id,p.public_key,a));const m={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:r,title_ship:"shipping",description:"transaction",device_session_id:i||null,token_id:"",order_id:"id"in h&&h.id,business_id:v.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(m);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,i){return t(this,void 0,void 0,(function*(){try{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(i)});if(t.ok)return yield t.json();throw yield this.buildErrorResponse(t)}catch(e){throw this.buildErrorResponseFromCatch(e)}}))}getCustomerCards(e,i=""){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/cards?business=${i}`,{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 i({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,r=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 i({code:o,body:t,name:o,message:n,stack:r})}))}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}})))))}))}}export{o as LiteCheckout};
|
|
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:p,business:v}=c;p.merchant_id&&p.public_key&&(r=yield this.getOpenpayDeviceSessionID(p.merchant_id,p.public_key,a));const m={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:v.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(m);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{this.merchantData||(yield i(this,s,"m",a).call(this));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};
|
package/package.json
CHANGED
|
@@ -5,7 +5,7 @@ import { Business } 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 } from "../helpers/utils";
|
|
8
|
+
import { getBrowserInfo, getBusinessId } from "../helpers/utils";
|
|
9
9
|
import { ThreeDSHandler } from "./3dsHandler";
|
|
10
10
|
|
|
11
11
|
declare global {
|
|
@@ -27,6 +27,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
27
27
|
apiKeyTonder: string;
|
|
28
28
|
process3ds: ThreeDSHandler;
|
|
29
29
|
successUrl?: string
|
|
30
|
+
merchantData?: Business | ErrorResponse;
|
|
30
31
|
|
|
31
32
|
constructor({
|
|
32
33
|
signal,
|
|
@@ -38,7 +39,6 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
38
39
|
this.signal = signal;
|
|
39
40
|
this.apiKeyTonder = apiKeyTonder;
|
|
40
41
|
this.successUrl = successUrl;
|
|
41
|
-
|
|
42
42
|
this.process3ds = new ThreeDSHandler({
|
|
43
43
|
apiKey: this.apiKeyTonder,
|
|
44
44
|
baseUrl: this.baseUrlTonder,
|
|
@@ -63,6 +63,14 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
63
63
|
throw this.buildErrorResponseFromCatch(e);
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
|
+
async #fetchMerchantData() {
|
|
67
|
+
try {
|
|
68
|
+
this.merchantData = await this.getBusiness();
|
|
69
|
+
return this.merchantData
|
|
70
|
+
}catch(e){
|
|
71
|
+
return this.merchantData
|
|
72
|
+
}
|
|
73
|
+
}
|
|
66
74
|
|
|
67
75
|
async getBusiness(): Promise<GetBusinessResponse | ErrorResponse> {
|
|
68
76
|
try {
|
|
@@ -424,6 +432,10 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
424
432
|
|
|
425
433
|
async registerCustomerCard(customerToken: string, data: RegisterCustomerCardRequest): Promise<RegisterCustomerCardResponse | ErrorResponse> {
|
|
426
434
|
try {
|
|
435
|
+
if(!this.merchantData){
|
|
436
|
+
await this.#fetchMerchantData()
|
|
437
|
+
}
|
|
438
|
+
|
|
427
439
|
const response = await fetch(`${this.baseUrlTonder}/api/v1/cards/`, {
|
|
428
440
|
method: 'POST',
|
|
429
441
|
headers: {
|
|
@@ -431,7 +443,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
431
443
|
'Content-Type': 'application/json'
|
|
432
444
|
},
|
|
433
445
|
signal: this.signal,
|
|
434
|
-
body: JSON.stringify(data)
|
|
446
|
+
body: JSON.stringify({...data, business_id: getBusinessId(this.merchantData) })
|
|
435
447
|
});
|
|
436
448
|
|
|
437
449
|
if (response.ok) return await response.json() as RegisterCustomerCardResponse;
|
|
@@ -441,9 +453,13 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
441
453
|
}
|
|
442
454
|
}
|
|
443
455
|
|
|
444
|
-
async getCustomerCards(customerToken: string
|
|
456
|
+
async getCustomerCards(customerToken: string): Promise<GetCustomerCardsResponse | ErrorResponse> {
|
|
445
457
|
try {
|
|
446
|
-
|
|
458
|
+
if(!this.merchantData){
|
|
459
|
+
await this.#fetchMerchantData()
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
const response = await fetch(`${this.baseUrlTonder}/api/v1/cards?business=${getBusinessId(this.merchantData)}`, {
|
|
447
463
|
method: 'GET',
|
|
448
464
|
headers: {
|
|
449
465
|
'Authorization': `Token ${customerToken}`,
|