@tonder.io/ionic-lite-sdk 0.0.33-beta.10 → 0.0.33-beta.11
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.
|
@@ -2,15 +2,13 @@ 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,
|
|
11
|
+
constructor({ payload, apiKey, baseUrl, }: ThreeDSHandlerContructor);
|
|
14
12
|
setStorageItem(data: any): void;
|
|
15
13
|
getStorageItem(): string | null;
|
|
16
14
|
removeStorageItem(): void;
|
|
@@ -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,8 @@ export declare class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
21
20
|
baseUrlTonder: string;
|
|
22
21
|
apiKeyTonder: string;
|
|
23
22
|
process3ds: ThreeDSHandler;
|
|
24
|
-
successUrl?: string;
|
|
25
23
|
merchantData?: Business | ErrorResponse;
|
|
26
|
-
constructor({ signal, baseUrlTonder, apiKeyTonder,
|
|
24
|
+
constructor({ signal, baseUrlTonder, apiKeyTonder, }: LiteCheckoutConstructor);
|
|
27
25
|
getOpenpayDeviceSessionID(merchant_id: string, public_key: string, is_sandbox: boolean): Promise<string | ErrorResponse>;
|
|
28
26
|
getBusiness(): Promise<GetBusinessResponse | ErrorResponse>;
|
|
29
27
|
verify3dsTransaction(): Promise<any>;
|
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 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}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=i,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,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}){s.add(this),this.baseUrlTonder=t,this.signal=e,this.apiKeyTonder=i,this.process3ds=new n({apiKey:this.apiKeyTonder,baseUrl:this.baseUrlTonder})}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
|
@@ -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) {
|
|
@@ -18,7 +18,6 @@ export type LiteCheckoutConstructor = {
|
|
|
18
18
|
signal: AbortSignal;
|
|
19
19
|
baseUrlTonder: string;
|
|
20
20
|
apiKeyTonder: string;
|
|
21
|
-
successUrl?: string;
|
|
22
21
|
};
|
|
23
22
|
|
|
24
23
|
export class LiteCheckout implements LiteCheckoutConstructor {
|
|
@@ -26,23 +25,19 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
26
25
|
baseUrlTonder: string;
|
|
27
26
|
apiKeyTonder: string;
|
|
28
27
|
process3ds: ThreeDSHandler;
|
|
29
|
-
successUrl?: string
|
|
30
28
|
merchantData?: Business | ErrorResponse;
|
|
31
29
|
|
|
32
30
|
constructor({
|
|
33
31
|
signal,
|
|
34
32
|
baseUrlTonder,
|
|
35
33
|
apiKeyTonder,
|
|
36
|
-
successUrl,
|
|
37
34
|
}: LiteCheckoutConstructor) {
|
|
38
35
|
this.baseUrlTonder = baseUrlTonder;
|
|
39
36
|
this.signal = signal;
|
|
40
37
|
this.apiKeyTonder = apiKeyTonder;
|
|
41
|
-
this.successUrl = successUrl;
|
|
42
38
|
this.process3ds = new ThreeDSHandler({
|
|
43
39
|
apiKey: this.apiKeyTonder,
|
|
44
40
|
baseUrl: this.baseUrlTonder,
|
|
45
|
-
successUrl: successUrl
|
|
46
41
|
})
|
|
47
42
|
}
|
|
48
43
|
|
|
@@ -458,7 +453,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
458
453
|
if(!this.merchantData){
|
|
459
454
|
await this.#fetchMerchantData()
|
|
460
455
|
}
|
|
461
|
-
|
|
456
|
+
|
|
462
457
|
const response = await fetch(`${this.baseUrlTonder}/api/v1/cards?business=${getBusinessId(this.merchantData)}`, {
|
|
463
458
|
method: 'GET',
|
|
464
459
|
headers: {
|