@tonder.io/ionic-lite-sdk 0.0.33-beta.10 → 0.0.33-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import CollectContainer from "skyflow-js/types/core/external/collect/collect-container";
|
|
2
|
-
import { Business } from "../types/commons";
|
|
3
2
|
import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutRequest, TokensRequest, StartCheckoutFullRequest, StartCheckoutIdRequest } from "../types/requests";
|
|
4
3
|
import { GetBusinessResponse, CustomerRegisterResponse, CreateOrderResponse, CreatePaymentResponse, StartCheckoutResponse, GetCustomerCardsResponse, RegisterCustomerCardResponse } from "../types/responses";
|
|
5
4
|
import { ErrorResponse } from "./errorResponse";
|
|
@@ -16,13 +15,11 @@ export type LiteCheckoutConstructor = {
|
|
|
16
15
|
successUrl?: string;
|
|
17
16
|
};
|
|
18
17
|
export declare class LiteCheckout implements LiteCheckoutConstructor {
|
|
19
|
-
#private;
|
|
20
18
|
signal: AbortSignal;
|
|
21
19
|
baseUrlTonder: string;
|
|
22
20
|
apiKeyTonder: string;
|
|
23
21
|
process3ds: ThreeDSHandler;
|
|
24
22
|
successUrl?: string;
|
|
25
|
-
merchantData?: Business | ErrorResponse;
|
|
26
23
|
constructor({ signal, baseUrlTonder, apiKeyTonder, successUrl, }: LiteCheckoutConstructor);
|
|
27
24
|
getOpenpayDeviceSessionID(merchant_id: string, public_key: string, is_sandbox: boolean): Promise<string | ErrorResponse>;
|
|
28
25
|
getBusiness(): Promise<GetBusinessResponse | ErrorResponse>;
|
|
@@ -40,7 +37,7 @@ export declare class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
40
37
|
getVaultToken(): Promise<string>;
|
|
41
38
|
getFieldsPromise(data: any, collectContainer: CollectContainer): Promise<Promise<boolean>[]>;
|
|
42
39
|
registerCustomerCard(customerToken: string, data: RegisterCustomerCardRequest): Promise<RegisterCustomerCardResponse | ErrorResponse>;
|
|
43
|
-
getCustomerCards(customerToken: string): Promise<GetCustomerCardsResponse | ErrorResponse>;
|
|
40
|
+
getCustomerCards(customerToken: string, business_id?: string | number): Promise<GetCustomerCardsResponse | ErrorResponse>;
|
|
44
41
|
deleteCustomerCard(customerToken: string, skyflowId?: string): Promise<Boolean | ErrorResponse>;
|
|
45
42
|
private buildErrorResponseFromCatch;
|
|
46
43
|
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 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};
|
|
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};
|
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
|
|
8
|
+
import { getBrowserInfo } from "../helpers/utils";
|
|
9
9
|
import { ThreeDSHandler } from "./3dsHandler";
|
|
10
10
|
|
|
11
11
|
declare global {
|
|
@@ -27,7 +27,6 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
27
27
|
apiKeyTonder: string;
|
|
28
28
|
process3ds: ThreeDSHandler;
|
|
29
29
|
successUrl?: string
|
|
30
|
-
merchantData?: Business | ErrorResponse;
|
|
31
30
|
|
|
32
31
|
constructor({
|
|
33
32
|
signal,
|
|
@@ -39,6 +38,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
39
38
|
this.signal = signal;
|
|
40
39
|
this.apiKeyTonder = apiKeyTonder;
|
|
41
40
|
this.successUrl = successUrl;
|
|
41
|
+
|
|
42
42
|
this.process3ds = new ThreeDSHandler({
|
|
43
43
|
apiKey: this.apiKeyTonder,
|
|
44
44
|
baseUrl: this.baseUrlTonder,
|
|
@@ -63,14 +63,6 @@ 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
|
-
}
|
|
74
66
|
|
|
75
67
|
async getBusiness(): Promise<GetBusinessResponse | ErrorResponse> {
|
|
76
68
|
try {
|
|
@@ -432,10 +424,6 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
432
424
|
|
|
433
425
|
async registerCustomerCard(customerToken: string, data: RegisterCustomerCardRequest): Promise<RegisterCustomerCardResponse | ErrorResponse> {
|
|
434
426
|
try {
|
|
435
|
-
if(!this.merchantData){
|
|
436
|
-
await this.#fetchMerchantData()
|
|
437
|
-
}
|
|
438
|
-
|
|
439
427
|
const response = await fetch(`${this.baseUrlTonder}/api/v1/cards/`, {
|
|
440
428
|
method: 'POST',
|
|
441
429
|
headers: {
|
|
@@ -443,7 +431,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
443
431
|
'Content-Type': 'application/json'
|
|
444
432
|
},
|
|
445
433
|
signal: this.signal,
|
|
446
|
-
body: JSON.stringify(
|
|
434
|
+
body: JSON.stringify(data)
|
|
447
435
|
});
|
|
448
436
|
|
|
449
437
|
if (response.ok) return await response.json() as RegisterCustomerCardResponse;
|
|
@@ -453,13 +441,9 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
453
441
|
}
|
|
454
442
|
}
|
|
455
443
|
|
|
456
|
-
async getCustomerCards(customerToken: string): Promise<GetCustomerCardsResponse | ErrorResponse> {
|
|
444
|
+
async getCustomerCards(customerToken: string, business_id: string | number = ""): Promise<GetCustomerCardsResponse | ErrorResponse> {
|
|
457
445
|
try {
|
|
458
|
-
|
|
459
|
-
await this.#fetchMerchantData()
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
const response = await fetch(`${this.baseUrlTonder}/api/v1/cards?business=${getBusinessId(this.merchantData)}`, {
|
|
446
|
+
const response = await fetch(`${this.baseUrlTonder}/api/v1/cards?business=${business_id}`, {
|
|
463
447
|
method: 'GET',
|
|
464
448
|
headers: {
|
|
465
449
|
'Authorization': `Token ${customerToken}`,
|