@tonder.io/ionic-lite-sdk 0.0.34-beta → 0.0.34-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.
- package/.idea/workspace.xml +80 -0
- package/dist/classes/3dsHandler.d.ts +1 -3
- package/dist/classes/liteCheckout.d.ts +6 -6
- package/dist/helpers/mercadopago.d.ts +1 -0
- package/dist/helpers/utils.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/types/commons.d.ts +3 -0
- package/package.json +1 -1
- package/src/classes/3dsHandler.ts +1 -5
- package/src/classes/liteCheckout.ts +61 -28
- package/src/helpers/mercadopago.ts +16 -0
- package/src/helpers/utils.ts +3 -0
- package/src/types/commons.ts +3 -0
- package/tests/methods/getCustomerCards.test.ts +4 -4
- package/tests/utils/mockClasses.ts +4 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<project version="4">
|
|
3
|
+
<component name="AutoImportSettings">
|
|
4
|
+
<option name="autoReloadType" value="SELECTIVE" />
|
|
5
|
+
</component>
|
|
6
|
+
<component name="ChangeListManager">
|
|
7
|
+
<list default="true" id="b64575d3-54a7-4180-8179-3c5ce7a82504" name="Changes" comment="">
|
|
8
|
+
<change beforePath="$PROJECT_DIR$/src/classes/liteCheckout.ts" beforeDir="false" afterPath="$PROJECT_DIR$/src/classes/liteCheckout.ts" afterDir="false" />
|
|
9
|
+
</list>
|
|
10
|
+
<option name="SHOW_DIALOG" value="false" />
|
|
11
|
+
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
|
12
|
+
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
|
13
|
+
<option name="LAST_RESOLUTION" value="IGNORE" />
|
|
14
|
+
</component>
|
|
15
|
+
<component name="Git.Settings">
|
|
16
|
+
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
|
|
17
|
+
</component>
|
|
18
|
+
<component name="MarkdownSettingsMigration">
|
|
19
|
+
<option name="stateVersion" value="1" />
|
|
20
|
+
</component>
|
|
21
|
+
<component name="ProjectColorInfo">{
|
|
22
|
+
"associatedIndex": 1
|
|
23
|
+
}</component>
|
|
24
|
+
<component name="ProjectId" id="2jblP8NwzpUzESDMOxdWCnJYVYC" />
|
|
25
|
+
<component name="ProjectViewState">
|
|
26
|
+
<option name="autoscrollFromSource" value="true" />
|
|
27
|
+
<option name="autoscrollToSource" value="true" />
|
|
28
|
+
<option name="hideEmptyMiddlePackages" value="true" />
|
|
29
|
+
<option name="showLibraryContents" value="true" />
|
|
30
|
+
</component>
|
|
31
|
+
<component name="PropertiesComponent"><![CDATA[{
|
|
32
|
+
"keyToString": {
|
|
33
|
+
"RunOnceActivity.OpenProjectViewOnStart": "true",
|
|
34
|
+
"RunOnceActivity.ShowReadmeOnStart": "true",
|
|
35
|
+
"git-widget-placeholder": "DEV-1243",
|
|
36
|
+
"last_opened_file_path": "/Users/davidhernandezalmagro/Desktop/Tonder/ionic-lite/src/helpers",
|
|
37
|
+
"node.js.detected.package.eslint": "true",
|
|
38
|
+
"node.js.detected.package.tslint": "true",
|
|
39
|
+
"node.js.selected.package.eslint": "(autodetect)",
|
|
40
|
+
"node.js.selected.package.tslint": "(autodetect)",
|
|
41
|
+
"nodejs_package_manager_path": "npm",
|
|
42
|
+
"ts.external.directory.path": "/Users/davidhernandezalmagro/Desktop/Tonder/ionic-lite/node_modules/typescript/lib",
|
|
43
|
+
"vue.rearranger.settings.migration": "true"
|
|
44
|
+
}
|
|
45
|
+
}]]></component>
|
|
46
|
+
<component name="RecentsManager">
|
|
47
|
+
<key name="CopyFile.RECENT_KEYS">
|
|
48
|
+
<recent name="$PROJECT_DIR$/src/helpers" />
|
|
49
|
+
</key>
|
|
50
|
+
</component>
|
|
51
|
+
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
|
|
52
|
+
<component name="TaskManager">
|
|
53
|
+
<task active="true" id="Default" summary="Default task">
|
|
54
|
+
<changelist id="b64575d3-54a7-4180-8179-3c5ce7a82504" name="Changes" comment="" />
|
|
55
|
+
<created>1721663630598</created>
|
|
56
|
+
<option name="number" value="Default" />
|
|
57
|
+
<option name="presentableId" value="Default" />
|
|
58
|
+
<updated>1721663630598</updated>
|
|
59
|
+
<workItem from="1721663631623" duration="828000" />
|
|
60
|
+
<workItem from="1723047317052" duration="668000" />
|
|
61
|
+
<workItem from="1723131993043" duration="992000" />
|
|
62
|
+
</task>
|
|
63
|
+
<servers />
|
|
64
|
+
</component>
|
|
65
|
+
<component name="TypeScriptGeneratedFilesManager">
|
|
66
|
+
<option name="version" value="3" />
|
|
67
|
+
</component>
|
|
68
|
+
<component name="XDebuggerManager">
|
|
69
|
+
<breakpoint-manager>
|
|
70
|
+
<breakpoints>
|
|
71
|
+
<line-breakpoint enabled="true" type="javascript">
|
|
72
|
+
<url>file://$PROJECT_DIR$/src/classes/liteCheckout.ts</url>
|
|
73
|
+
<line>240</line>
|
|
74
|
+
<properties lambdaOrdinal="-1" />
|
|
75
|
+
<option name="timeStamp" value="3" />
|
|
76
|
+
</line-breakpoint>
|
|
77
|
+
</breakpoints>
|
|
78
|
+
</breakpoint-manager>
|
|
79
|
+
</component>
|
|
80
|
+
</project>
|
|
@@ -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;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import CollectContainer from "skyflow-js/types/core/external/collect/collect-container";
|
|
2
|
-
import { APM } from "../types/commons";
|
|
2
|
+
import { APM, Business } from "../types/commons";
|
|
3
3
|
import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutRequest, TokensRequest, StartCheckoutFullRequest, StartCheckoutIdRequest } from "../types/requests";
|
|
4
4
|
import { GetBusinessResponse, CustomerRegisterResponse, CreateOrderResponse, CreatePaymentResponse, StartCheckoutResponse, GetCustomerCardsResponse, RegisterCustomerCardResponse } from "../types/responses";
|
|
5
5
|
import { ErrorResponse } from "./errorResponse";
|
|
@@ -13,19 +13,19 @@ 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 {
|
|
18
|
+
#private;
|
|
19
19
|
signal: AbortSignal;
|
|
20
20
|
baseUrlTonder: string;
|
|
21
21
|
apiKeyTonder: string;
|
|
22
22
|
process3ds: ThreeDSHandler;
|
|
23
|
-
successUrl?: string;
|
|
24
23
|
activeAPMs: APM[];
|
|
25
|
-
|
|
24
|
+
merchantData?: Business | ErrorResponse;
|
|
25
|
+
constructor({ signal, baseUrlTonder, apiKeyTonder, }: LiteCheckoutConstructor);
|
|
26
26
|
getOpenpayDeviceSessionID(merchant_id: string, public_key: string, is_sandbox: boolean): Promise<string | ErrorResponse>;
|
|
27
27
|
getBusiness(): Promise<GetBusinessResponse | ErrorResponse>;
|
|
28
|
-
verify3dsTransaction(): Promise<
|
|
28
|
+
verify3dsTransaction(): Promise<false | StartCheckoutResponse | ErrorResponse | undefined>;
|
|
29
29
|
resumeCheckout(response: any): Promise<any>;
|
|
30
30
|
handle3dsRedirect(response: ErrorResponse | StartCheckoutResponse | false | undefined): Promise<false | StartCheckoutResponse | ErrorResponse | undefined>;
|
|
31
31
|
customerRegister(email: string): Promise<CustomerRegisterResponse | ErrorResponse>;
|
|
@@ -39,7 +39,7 @@ export declare class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
39
39
|
getVaultToken(): Promise<string>;
|
|
40
40
|
getFieldsPromise(data: any, collectContainer: CollectContainer): Promise<Promise<boolean>[]>;
|
|
41
41
|
registerCustomerCard(customerToken: string, data: RegisterCustomerCardRequest): Promise<RegisterCustomerCardResponse | ErrorResponse>;
|
|
42
|
-
getCustomerCards(customerToken: string
|
|
42
|
+
getCustomerCards(customerToken: string): Promise<GetCustomerCardsResponse | ErrorResponse>;
|
|
43
43
|
deleteCustomerCard(customerToken: string, skyflowId?: string): Promise<Boolean | ErrorResponse>;
|
|
44
44
|
private getFields;
|
|
45
45
|
getActiveAPMs(): Promise<APM[]>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function injectMercadoPagoSecurity(): void;
|
package/dist/helpers/utils.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ export declare const getBrowserInfo: () => {
|
|
|
8
8
|
screen_height: number | null;
|
|
9
9
|
user_agent: string;
|
|
10
10
|
};
|
|
11
|
+
export declare const getBusinessId: (merchantData: any) => any;
|
|
11
12
|
declare const buildErrorResponseFromCatch: (e: any) => ErrorResponse;
|
|
12
13
|
declare const buildErrorResponse: (response: Response, stack?: string | undefined) => Promise<ErrorResponse>;
|
|
13
14
|
declare const getPaymentMethodDetails: (scheme_data: string) => {
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"skyflow-js";function t(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{d(o.next(e))}catch(e){i(e)}}function a(e){try{d(o.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class n{constructor({code:e,body:t,name:n,message:o,stack:r}){this.code=e,this.body=t,this.name=n,this.message=o,this.stack=r}}var o;!function(e){e.SORIANA="SORIANA",e.OXXO="OXXO",e.SPEI="SPEI",e.CODI="CODI",e.MERCADOPAGO="MERCADOPAGO",e.PAYPAL="PAYPAL",e.COMERCIALMEXICANA="COMERCIALMEXICANA",e.BANCOMER="BANCOMER",e.WALMART="WALMART",e.BODEGA="BODEGA",e.SAMSCLUB="SAMSCLUB",e.SUPERAMA="SUPERAMA",e.CALIMAX="CALIMAX",e.EXTRA="EXTRA",e.CIRCULOK="CIRCULOK",e.SEVEN11="7ELEVEN",e.TELECOMM="TELECOMM",e.BANORTE="BANORTE",e.BENAVIDES="BENAVIDES",e.DELAHORRO="DELAHORRO",e.ELASTURIANO="ELASTURIANO",e.WALDOS="WALDOS",e.ALSUPER="ALSUPER",e.KIOSKO="KIOSKO",e.STAMARIA="STAMARIA",e.LAMASBARATA="LAMASBARATA",e.FARMROMA="FARMROMA",e.FARMUNION="FARMUNION",e.FARMATODO="FARMATODO",e.SFDEASIS="SFDEASIS",e.FARM911="FARM911",e.FARMECONOMICAS="FARMECONOMICAS",e.FARMMEDICITY="FARMMEDICITY",e.RIANXEIRA="RIANXEIRA",e.WESTERNUNION="WESTERNUNION",e.ZONAPAGO="ZONAPAGO",e.CAJALOSANDES="CAJALOSANDES",e.CAJAPAITA="CAJAPAITA",e.CAJASANTA="CAJASANTA",e.CAJASULLANA="CAJASULLANA",e.CAJATRUJILLO="CAJATRUJILLO",e.EDPYME="EDPYME",e.KASNET="KASNET",e.NORANDINO="NORANDINO",e.QAPAQ="QAPAQ",e.RAIZ="RAIZ",e.PAYSER="PAYSER",e.WUNION="WUNION",e.BANCOCONTINENTAL="BANCOCONTINENTAL",e.GMONEY="GMONEY",e.GOPAY="GOPAY",e.WU="WU",e.PUNTOSHEY="PUNTOSHEY",e.AMPM="AMPM",e.JUMBOMARKET="JUMBOMARKET",e.SMELPUEBLO="SMELPUEBLO",e.BAM="BAM",e.REFACIL="REFACIL",e.ACYVALORES="ACYVALORES"}(o||(o={}));const r=e=>new n({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}),i=(e,o=void 0)=>t(void 0,void 0,void 0,(function*(){let t,r,i="Error";e&&"json"in e&&(t=yield null==e?void 0:e.json()),e&&"status"in e&&(r=e.status.toString()),e&&"text"in e&&(i=yield e.text());return new n({code:r,body:t,name:r,message:i,stack:o})})),s=e=>e.trim().replace(/\s+/g,"");class a{constructor({payload:e=null,apiKey:t,baseUrl:n,successUrl:o}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=n,this.apiKey=t,this.payload=e,this.successUrl=o}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,n,o,r,i;const s=null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(i=null===(r=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,n;if(null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((e,t)=>{var n,o,r;const i=null===(r=null===(o=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(o);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,n;return null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const e=this.getRedirectUrl();e?(this.saveVerifyTransactionUrl(),window.location=e):console.log("No redirection found")}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[n,o]of t)e[n]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),console.log("Transacción autorizada."),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return t(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=e.creq,n.value=e.creq,t.appendChild(n);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return t(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}class d{constructor({signal:e,baseUrlTonder:t,apiKeyTonder:n,successUrl:o}){this.activeAPMs=[],this.baseUrlTonder=t,this.signal=e,this.apiKeyTonder=n,this.successUrl=o,this.process3ds=new a({apiKey:this.apiKeyTonder,baseUrl:this.baseUrlTonder,successUrl:o}),this.getActiveAPMs()}getOpenpayDeviceSessionID(e,n,o){return t(this,void 0,void 0,(function*(){try{let t=yield window.OpenPay;return t.setId(e),t.setApiKey(n),t.setSandboxMode(o),yield t.deviceData.setup({signal:this.signal})}catch(e){throw r(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 i(e)}catch(e){throw r(e)}}))}verify3dsTransaction(){return t(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield this.resumeCheckout(e);return this.process3ds.setPayload(t),t&&"is_route_finished"in t&&"provider"in t&&"tonder"===t.provider?t:this.handle3dsRedirect(t)}))}resumeCheckout(e){var n;return t(this,void 0,void 0,(function*(){if(["Failed","Declined","Cancelled"].includes(null==e?void 0:e.status)){const t={checkout_id:null===(n=e.checkout)||void 0===n?void 0:n.id};return yield this.handleCheckoutRouter(t)}return e}))}handle3dsRedirect(e){var n,o;return t(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(n=null==e?void 0:e.next_action)||void 0===n?void 0:n.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((e=>{console.log("Error loading iframe:",e)}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}customerRegister(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/customer/`,n={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal,body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield i(o)}catch(e){throw r(e)}}))}createOrder(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/orders/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield i(o)}catch(e){throw r(e)}}))}createPayment(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/business/${e.business_pk}/payments/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield i(o)}catch(e){throw r(e)}}))}handleCheckoutRouter(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/checkout-router/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield i(o)}catch(e){throw r(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:o,customer:r,skyflowTokens:i,return_url:s,isSandbox:a,metadata:d,currency:l,payment_method:c}=e,u=yield this.getBusiness(),p=yield this.customerRegister(r.email);if(!(p&&"auth_token"in p&&u&&"reference"in u))throw new n({code:"500",body:u,name:"Keys error",message:"Merchant or customer reposne errors"});{const e={business:this.apiKeyTonder,client:p.auth_token,billing_address_id:null,shipping_address_id:null,amount:o,reference:u.reference,is_oneclick:!0,items:t.items},h=yield this.createOrder(e),y=(new Date).toISOString();if(!("id"in h&&"id"in p&&"business"in u))throw new n({code:"500",body:h,name:"Keys error",message:"Order response errors"});{const e={business_pk:u.business.pk,amount:o,date:y,order_id:h.id,client_id:p.id},t=yield this.createPayment(e);let n;const{openpay_keys:m,business:A}=u;m.merchant_id&&m.public_key&&(n=yield this.getOpenpayDeviceSessionID(m.merchant_id,m.public_key,a));const g=Object.assign({name:r.name,last_name:r.lastname,email_client:r.email,phone_number:r.phone,return_url:s,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:o,title_ship:"shipping",description:"transaction",device_session_id:n||null,token_id:"",order_id:"id"in h&&h.id,business_id:A.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:{javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent},currency:l},c?{payment_method:c}:{card:i}),f=yield this.handleCheckoutRouter(g);if(yield this.init3DSRedirect(f))return f}}}catch(e){throw r(e)}}))}init3DSRedirect(e){return t(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this.handle3dsRedirect(e)}))}getSkyflowTokens({vault_id:n,vault_url:o,data:i}){return t(this,void 0,void 0,(function*(){const s=e.init({vaultID:n,vaultURL:o,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield this.getVaultToken()})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}).container(e.ContainerType.COLLECT),a=yield this.getFieldsPromise(i,s);if((yield Promise.all(a)).some((e=>!e)))throw r(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield s.collect();if(e)return e.records[0].fields;throw r(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw r(e)}}))}getVaultToken(){var e;return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal});if(t.ok)return null===(e=yield t.json())||void 0===e?void 0:e.token;throw new Error(`HTTPCODE: ${t.status}`)}catch(e){throw new Error(`Failed to retrieve bearer token; ${"string"==typeof e?e:e.message}`)}}))}getFieldsPromise(e,n){return t(this,void 0,void 0,(function*(){const t=yield this.getFields(e,n);return t?t.map((t=>new Promise((n=>{var o;const r=document.createElement("div");r.hidden=!0,r.id=`id-${t.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(r),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const o=e[t.key];return t.element.update({value:o}),n(t.element.isMounted())}}),120)}),120)})))):[]}))}registerCustomerCard(e,n){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(n)});if(t.ok)return yield t.json();throw yield i(t)}catch(e){throw r(e)}}))}getCustomerCards(e,n=""){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/cards/${n}`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal});if(t.ok)return yield t.json();throw yield i(t)}catch(e){throw r(e)}}))}deleteCustomerCard(e,n=""){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/cards/${n}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal});if(t.ok)return!0;throw yield i(t)}catch(e){throw r(e)}}))}getFields(n,o){return t(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(n).map((n=>t(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:n,type:e.ElementType.INPUT_FIELD}),key:n}})))))}))}getActiveAPMs(){return t(this,void 0,void 0,(function*(){try{const e=yield function(e,n,o="?status=active&page_size=10000&country=México",s=null){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${n}`,"Content-Type":"application/json"},signal:s});if(t.ok)return yield t.json();throw yield i(t)}catch(e){throw r(e)}}))}(this.baseUrlTonder,this.apiKeyTonder),n=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=n.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},(e=>{const t=s(e.toUpperCase());return{[o.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[o.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[o.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[o.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[o.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[o.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[o.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[o.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[o.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[o.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[o.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[o.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[o.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[o.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[o.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[o.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[o.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[o.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[o.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[o.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[o.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[o.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[o.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[o.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[o.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[o.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[o.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[o.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[o.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[o.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[o.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}}[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}})(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}export{d as LiteCheckout};
|
|
1
|
+
import e from"skyflow-js";function t(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{d(o.next(e))}catch(e){i(e)}}function a(e){try{d(o.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}function n(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}"function"==typeof SuppressedError&&SuppressedError;class o{constructor({code:e,body:t,name:n,message:o,stack:r}){this.code=e,this.body=t,this.name=n,this.message=o,this.stack=r}}var r;!function(e){e.SORIANA="SORIANA",e.OXXO="OXXO",e.SPEI="SPEI",e.CODI="CODI",e.MERCADOPAGO="MERCADOPAGO",e.PAYPAL="PAYPAL",e.COMERCIALMEXICANA="COMERCIALMEXICANA",e.BANCOMER="BANCOMER",e.WALMART="WALMART",e.BODEGA="BODEGA",e.SAMSCLUB="SAMSCLUB",e.SUPERAMA="SUPERAMA",e.CALIMAX="CALIMAX",e.EXTRA="EXTRA",e.CIRCULOK="CIRCULOK",e.SEVEN11="7ELEVEN",e.TELECOMM="TELECOMM",e.BANORTE="BANORTE",e.BENAVIDES="BENAVIDES",e.DELAHORRO="DELAHORRO",e.ELASTURIANO="ELASTURIANO",e.WALDOS="WALDOS",e.ALSUPER="ALSUPER",e.KIOSKO="KIOSKO",e.STAMARIA="STAMARIA",e.LAMASBARATA="LAMASBARATA",e.FARMROMA="FARMROMA",e.FARMUNION="FARMUNION",e.FARMATODO="FARMATODO",e.SFDEASIS="SFDEASIS",e.FARM911="FARM911",e.FARMECONOMICAS="FARMECONOMICAS",e.FARMMEDICITY="FARMMEDICITY",e.RIANXEIRA="RIANXEIRA",e.WESTERNUNION="WESTERNUNION",e.ZONAPAGO="ZONAPAGO",e.CAJALOSANDES="CAJALOSANDES",e.CAJAPAITA="CAJAPAITA",e.CAJASANTA="CAJASANTA",e.CAJASULLANA="CAJASULLANA",e.CAJATRUJILLO="CAJATRUJILLO",e.EDPYME="EDPYME",e.KASNET="KASNET",e.NORANDINO="NORANDINO",e.QAPAQ="QAPAQ",e.RAIZ="RAIZ",e.PAYSER="PAYSER",e.WUNION="WUNION",e.BANCOCONTINENTAL="BANCOCONTINENTAL",e.GMONEY="GMONEY",e.GOPAY="GOPAY",e.WU="WU",e.PUNTOSHEY="PUNTOSHEY",e.AMPM="AMPM",e.JUMBOMARKET="JUMBOMARKET",e.SMELPUEBLO="SMELPUEBLO",e.BAM="BAM",e.REFACIL="REFACIL",e.ACYVALORES="ACYVALORES"}(r||(r={}));const i=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},s=e=>new o({code:(null==e?void 0:e.status)?e.status:e.code,body:null==e?void 0:e.body,name:e?"string"==typeof e?"catch":e.name:"Error",message:e?"string"==typeof e?e:e.message:"Error",stack:"string"==typeof e?void 0:e.stack}),a=(e,n=void 0)=>t(void 0,void 0,void 0,(function*(){let t,r,i="Error";e&&"json"in e&&(t=yield null==e?void 0:e.json()),e&&"status"in e&&(r=e.status.toString()),e&&"text"in e&&(i=yield e.text());return new o({code:r,body:t,name:r,message:i,stack:n})})),d=e=>e.trim().replace(/\s+/g,"");class l{constructor({payload:e=null,apiKey:t,baseUrl:n}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=n,this.apiKey=t,this.payload=e}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,n,o,r,i;const s=null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(i=null===(r=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,n;if(null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===n?void 0:n.iframe)return new Promise(((e,t)=>{var n,o,r;const i=null===(r=null===(o=null===(n=this.payload)||void 0===n?void 0:n.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===r?void 0:r.iframe;if(i){this.saveVerifyTransactionUrl();const n=document.createElement("div");n.innerHTML=i,document.body.appendChild(n);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',n.appendChild(o);const r=document.getElementById("tdsMmethodTgtFrame");r?r.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,n;return null===(n=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===n?void 0:n.url}redirectToChallenge(){const e=this.getRedirectUrl();e?(this.saveVerifyTransactionUrl(),window.location=e):console.log("No redirection found")}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[n,o]of t)e[n]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),console.log("Transacción autorizada."),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return t(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const n=document.createElement("input");n.type="hidden",n.name=e.creq,n.value=e.creq,t.appendChild(n);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return t(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}var c,u,h;class p{constructor({signal:e,baseUrlTonder:t,apiKeyTonder:o}){c.add(this),this.activeAPMs=[],this.baseUrlTonder=t,this.signal=e,this.apiKeyTonder=o,this.process3ds=new l({apiKey:this.apiKeyTonder,baseUrl:this.baseUrlTonder}),n(this,c,"m",u).call(this)}getOpenpayDeviceSessionID(e,n,o){return t(this,void 0,void 0,(function*(){try{let t=yield window.OpenPay;return t.setId(e),t.setApiKey(n),t.setSandboxMode(o),yield t.deviceData.setup({signal:this.signal})}catch(e){throw s(e)}}))}getBusiness(){return t(this,void 0,void 0,(function*(){try{const e=yield fetch(`${this.baseUrlTonder}/api/v1/payments/business/${this.apiKeyTonder}`,{headers:{Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal});if(e.ok)return yield e.json();throw yield a(e)}catch(e){throw s(e)}}))}verify3dsTransaction(){return t(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield this.resumeCheckout(e);return this.process3ds.setPayload(t),this.handle3dsRedirect(t)}))}resumeCheckout(e){var n,o;return t(this,void 0,void 0,(function*(){if("Hard"===(null===(n=null==e?void 0:e.decline)||void 0===n?void 0:n.error_type))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:null===(o=null==e?void 0:e.checkout)||void 0===o?void 0:o.id};try{return yield this.handleCheckoutRouter(t)}catch(e){}return e}}))}handle3dsRedirect(e){var n,o;return t(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(n=null==e?void 0:e.next_action)||void 0===n?void 0:n.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((e=>{console.log("Error loading iframe:",e)}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}customerRegister(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/customer/`,n={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal,body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield a(o)}catch(e){throw s(e)}}))}createOrder(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/orders/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield a(o)}catch(e){throw s(e)}}))}createPayment(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/business/${e.business_pk}/payments/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(n)});if(o.ok)return yield o.json();throw yield a(o)}catch(e){throw s(e)}}))}handleCheckoutRouter(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrlTonder}/api/v1/checkout-router/`,n=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(Object.assign(Object.assign({},n),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(o.ok)return yield o.json();throw yield a(o)}catch(e){throw s(e)}}))}startCheckoutRouter(e){return t(this,void 0,void 0,(function*(){const t=yield this.handleCheckoutRouter(e);if(yield this.init3DSRedirect(t))return t}))}startCheckoutRouterFull(e){return t(this,void 0,void 0,(function*(){try{const{order:t,total:n,customer:r,skyflowTokens:i,return_url:s,isSandbox:a,metadata:d,currency:l,payment_method:c}=e,u=yield this.getBusiness(),h=yield this.customerRegister(r.email);if(!(h&&"auth_token"in h&&u&&"reference"in u))throw new o({code:"500",body:u,name:"Keys error",message:"Merchant or customer reposne errors"});{const e={business:this.apiKeyTonder,client:h.auth_token,billing_address_id:null,shipping_address_id:null,amount:n,reference:u.reference,is_oneclick:!0,items:t.items},p=yield this.createOrder(e),m=(new Date).toISOString();if(!("id"in p&&"id"in h&&"business"in u))throw new o({code:"500",body:p,name:"Keys error",message:"Order response errors"});{const e={business_pk:u.business.pk,amount:n,date:m,order_id:p.id,client_id:h.id},t=yield this.createPayment(e);let o;const{openpay_keys:y,business:A}=u;y.merchant_id&&y.public_key&&(o=yield this.getOpenpayDeviceSessionID(y.merchant_id,y.public_key,a));const g=Object.assign(Object.assign({name:r.name,last_name:r.lastname,email_client:r.email,phone_number:r.phone,return_url:s,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:n,title_ship:"shipping",description:"transaction",device_session_id:o||null,token_id:"",order_id:"id"in p&&p.id,business_id:A.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:{javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent},currency:l},c?{payment_method:c}:{card:i}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),f=yield this.handleCheckoutRouter(g);if(yield this.init3DSRedirect(f))return f}}}catch(e){throw s(e)}}))}init3DSRedirect(e){return t(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this.handle3dsRedirect(e)}))}getSkyflowTokens({vault_id:n,vault_url:o,data:r}){return t(this,void 0,void 0,(function*(){const i=e.init({vaultID:n,vaultURL:o,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield this.getVaultToken()})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}).container(e.ContainerType.COLLECT),a=yield this.getFieldsPromise(r,i);if((yield Promise.all(a)).some((e=>!e)))throw s(Error("Ocurrió un error al montar los campos de la tarjeta"));try{const e=yield i.collect();if(e)return e.records[0].fields;throw s(Error("Por favor, verifica todos los campos de tu tarjeta"))}catch(e){throw s(e)}}))}getVaultToken(){var e;return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${this.baseUrlTonder}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${this.apiKeyTonder}`},signal:this.signal});if(t.ok)return null===(e=yield t.json())||void 0===e?void 0:e.token;throw new Error(`HTTPCODE: ${t.status}`)}catch(e){throw new Error(`Failed to retrieve bearer token; ${"string"==typeof e?e:e.message}`)}}))}getFieldsPromise(e,n){return t(this,void 0,void 0,(function*(){const t=yield this.getFields(e,n);return t?t.map((t=>new Promise((n=>{var o;const r=document.createElement("div");r.hidden=!0,r.id=`id-${t.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(r),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const o=e[t.key];return t.element.update({value:o}),n(t.element.isMounted())}}),120)}),120)})))):[]}))}registerCustomerCard(e,o){return t(this,void 0,void 0,(function*(){try{yield n(this,c,"m",h).call(this);const t=yield fetch(`${this.baseUrlTonder}/api/v1/business/${i(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal,body:JSON.stringify(Object.assign({},o))});if(t.ok)return yield t.json();throw yield a(t)}catch(e){throw s(e)}}))}getCustomerCards(e){return t(this,void 0,void 0,(function*(){try{yield n(this,c,"m",h).call(this);const t=yield fetch(`${this.baseUrlTonder}/api/v1/business/${i(this.merchantData)}/cards`,{method:"GET",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal});if(t.ok)return yield t.json();throw yield a(t)}catch(e){throw s(e)}}))}deleteCustomerCard(e,o=""){return t(this,void 0,void 0,(function*(){try{yield n(this,c,"m",h).call(this);const t=yield fetch(`${this.baseUrlTonder}/api/v1/business/${i(this.merchantData)}/cards/${o}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.signal});if(t.ok)return!0;throw yield a(t)}catch(e){throw s(e)}}))}getFields(n,o){return t(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(n).map((n=>t(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:n,type:e.ElementType.INPUT_FIELD}),key:n}})))))}))}getActiveAPMs(){return t(this,void 0,void 0,(function*(){try{const e=yield function(e,n,o="?status=active&page_size=10000&country=México",r=null){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${n}`,"Content-Type":"application/json"},signal:r});if(t.ok)return yield t.json();throw yield a(t)}catch(e){throw s(e)}}))}(this.baseUrlTonder,this.apiKeyTonder),n=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=n.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},(e=>{const t=d(e.toUpperCase());return{[r.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[r.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[r.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[r.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[r.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[r.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[r.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[r.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[r.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[r.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[r.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[r.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[r.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[r.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[r.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[r.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[r.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[r.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[r.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[r.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[r.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[r.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[r.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[r.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[r.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[r.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[r.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[r.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[r.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[r.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[r.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}}[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}})(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}c=new WeakSet,u=function(){return t(this,void 0,void 0,(function*(){this.getActiveAPMs();const{mercado_pago:e}=yield n(this,c,"m",h).call(this);e&&e.active&&function(){try{const e=document.createElement("script");e.src="https://www.mercadopago.com/v2/security.js",e.setAttribute("view",""),e.onload=()=>{console.log("Mercado Pago script loaded successfully.")},e.onerror=e=>{console.error("Error loading Mercado Pago script:",e)},document.head.appendChild(e)}catch(e){console.error("Error attempting to inject Mercado Pago script:",e)}}()}))},h=function(){return t(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield this.getBusiness()),this.merchantData}catch(e){return this.merchantData}}))};export{p as LiteCheckout};
|
package/dist/types/commons.d.ts
CHANGED
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) {
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {injectMercadoPagoSecurity} from "../helpers/mercadopago";
|
|
2
|
+
|
|
3
|
+
declare const MP_DEVICE_SESSION_ID: string | undefined;
|
|
4
|
+
|
|
1
5
|
import Skyflow from "skyflow-js";
|
|
2
6
|
import CollectContainer from "skyflow-js/types/core/external/collect/collect-container";
|
|
3
7
|
import CollectElement from "skyflow-js/types/core/external/collect/collect-element";
|
|
@@ -5,7 +9,7 @@ import { APM, Business, TonderAPM } from "../types/commons";
|
|
|
5
9
|
import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutRequest, TokensRequest, StartCheckoutFullRequest, StartCheckoutIdRequest } from "../types/requests";
|
|
6
10
|
import { GetBusinessResponse, CustomerRegisterResponse, CreateOrderResponse, CreatePaymentResponse, StartCheckoutResponse, GetVaultTokenResponse, IErrorResponse, GetCustomerCardsResponse, RegisterCustomerCardResponse } from "../types/responses";
|
|
7
11
|
import { ErrorResponse } from "./errorResponse";
|
|
8
|
-
import { buildErrorResponse, buildErrorResponseFromCatch, getBrowserInfo, getPaymentMethodDetails } from "../helpers/utils";
|
|
12
|
+
import { buildErrorResponse, buildErrorResponseFromCatch, getBrowserInfo, getPaymentMethodDetails, getBusinessId } from "../helpers/utils";
|
|
9
13
|
import { ThreeDSHandler } from "./3dsHandler";
|
|
10
14
|
import { getCustomerAPMs } from "../data/api";
|
|
11
15
|
|
|
@@ -19,7 +23,6 @@ export type LiteCheckoutConstructor = {
|
|
|
19
23
|
signal: AbortSignal;
|
|
20
24
|
baseUrlTonder: string;
|
|
21
25
|
apiKeyTonder: string;
|
|
22
|
-
successUrl?: string;
|
|
23
26
|
};
|
|
24
27
|
|
|
25
28
|
export class LiteCheckout implements LiteCheckoutConstructor {
|
|
@@ -27,25 +30,30 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
27
30
|
baseUrlTonder: string;
|
|
28
31
|
apiKeyTonder: string;
|
|
29
32
|
process3ds: ThreeDSHandler;
|
|
30
|
-
successUrl?: string
|
|
31
33
|
activeAPMs: APM[] = []
|
|
34
|
+
merchantData?: Business | ErrorResponse;
|
|
35
|
+
|
|
32
36
|
constructor({
|
|
33
37
|
signal,
|
|
34
38
|
baseUrlTonder,
|
|
35
39
|
apiKeyTonder,
|
|
36
|
-
successUrl,
|
|
37
40
|
}: LiteCheckoutConstructor) {
|
|
38
41
|
this.baseUrlTonder = baseUrlTonder;
|
|
39
42
|
this.signal = signal;
|
|
40
43
|
this.apiKeyTonder = apiKeyTonder;
|
|
41
|
-
this.successUrl = successUrl;
|
|
42
|
-
|
|
43
44
|
this.process3ds = new ThreeDSHandler({
|
|
44
45
|
apiKey: this.apiKeyTonder,
|
|
45
|
-
baseUrl: this.baseUrlTonder,
|
|
46
|
-
successUrl: successUrl
|
|
46
|
+
baseUrl: this.baseUrlTonder,
|
|
47
47
|
})
|
|
48
|
+
this.#init()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async #init(){
|
|
48
52
|
this.getActiveAPMs()
|
|
53
|
+
const { mercado_pago } = await this.#fetchMerchantData() as Business
|
|
54
|
+
if (!!mercado_pago && mercado_pago.active){
|
|
55
|
+
injectMercadoPagoSecurity()
|
|
56
|
+
}
|
|
49
57
|
}
|
|
50
58
|
|
|
51
59
|
async getOpenpayDeviceSessionID(
|
|
@@ -65,6 +73,16 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
65
73
|
throw buildErrorResponseFromCatch(e);
|
|
66
74
|
}
|
|
67
75
|
}
|
|
76
|
+
async #fetchMerchantData() {
|
|
77
|
+
try {
|
|
78
|
+
if (!this.merchantData){
|
|
79
|
+
this.merchantData = await this.getBusiness();
|
|
80
|
+
}
|
|
81
|
+
return this.merchantData
|
|
82
|
+
}catch(e){
|
|
83
|
+
return this.merchantData
|
|
84
|
+
}
|
|
85
|
+
}
|
|
68
86
|
|
|
69
87
|
async getBusiness(): Promise<GetBusinessResponse | ErrorResponse> {
|
|
70
88
|
try {
|
|
@@ -90,28 +108,37 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
90
108
|
const result3ds = await this.process3ds.verifyTransactionStatus()
|
|
91
109
|
const resultCheckout = await this.resumeCheckout(result3ds)
|
|
92
110
|
this.process3ds.setPayload(resultCheckout)
|
|
93
|
-
if (resultCheckout && 'is_route_finished' in resultCheckout && 'provider' in resultCheckout && resultCheckout.provider === 'tonder') {
|
|
94
|
-
return resultCheckout
|
|
95
|
-
}
|
|
96
111
|
return this.handle3dsRedirect(resultCheckout)
|
|
97
112
|
}
|
|
98
113
|
|
|
99
114
|
async resumeCheckout(response: any) {
|
|
100
|
-
if
|
|
115
|
+
// Stop the routing process if the transaction is either hard declined or successful
|
|
116
|
+
if (response?.decline?.error_type === "Hard") {
|
|
117
|
+
return response
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (["Success", "Authorized"].includes(response?.transaction_status)) {
|
|
121
|
+
return response;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (response) {
|
|
101
125
|
const routerItems = {
|
|
102
|
-
checkout_id: response
|
|
126
|
+
checkout_id: response?.checkout?.id,
|
|
103
127
|
};
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
128
|
+
try {
|
|
129
|
+
const routerResponse = await this.handleCheckoutRouter(
|
|
130
|
+
routerItems
|
|
131
|
+
);
|
|
132
|
+
return routerResponse
|
|
133
|
+
}catch (error){
|
|
134
|
+
// throw error
|
|
135
|
+
}
|
|
136
|
+
return response
|
|
108
137
|
}
|
|
109
|
-
return response
|
|
110
138
|
}
|
|
111
139
|
|
|
112
140
|
async handle3dsRedirect(response: ErrorResponse | StartCheckoutResponse | false | undefined) {
|
|
113
141
|
const iframe = response && 'next_action' in response ? response?.next_action?.iframe_resources?.iframe:null
|
|
114
|
-
|
|
115
142
|
if (iframe) {
|
|
116
143
|
this.process3ds.loadIframe()!.then(() => {
|
|
117
144
|
//TODO: Check if this will be necessary on the frontend side
|
|
@@ -202,7 +229,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
202
229
|
"Content-Type": "application/json",
|
|
203
230
|
Authorization: `Token ${this.apiKeyTonder}`,
|
|
204
231
|
},
|
|
205
|
-
body: JSON.stringify(data),
|
|
232
|
+
body: JSON.stringify({...data, ...(typeof MP_DEVICE_SESSION_ID !== "undefined" ? {mp_device_session_id: MP_DEVICE_SESSION_ID}:{})}),
|
|
206
233
|
});
|
|
207
234
|
if (response.ok) return await response.json() as StartCheckoutResponse;
|
|
208
235
|
throw await buildErrorResponse(response);
|
|
@@ -231,7 +258,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
231
258
|
isSandbox,
|
|
232
259
|
metadata,
|
|
233
260
|
currency,
|
|
234
|
-
payment_method
|
|
261
|
+
payment_method
|
|
235
262
|
} = routerFullData;
|
|
236
263
|
|
|
237
264
|
const merchantResult = await this.getBusiness();
|
|
@@ -308,7 +335,8 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
308
335
|
...( !!payment_method
|
|
309
336
|
? {payment_method}
|
|
310
337
|
: {card: skyflowTokens}
|
|
311
|
-
)
|
|
338
|
+
),
|
|
339
|
+
...(typeof MP_DEVICE_SESSION_ID !== "undefined" ? {mp_device_session_id: MP_DEVICE_SESSION_ID}:{})
|
|
312
340
|
};
|
|
313
341
|
|
|
314
342
|
const checkoutResult = await this.handleCheckoutRouter(routerItems);
|
|
@@ -428,14 +456,16 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
428
456
|
|
|
429
457
|
async registerCustomerCard(customerToken: string, data: RegisterCustomerCardRequest): Promise<RegisterCustomerCardResponse | ErrorResponse> {
|
|
430
458
|
try {
|
|
431
|
-
|
|
459
|
+
await this.#fetchMerchantData()
|
|
460
|
+
|
|
461
|
+
const response = await fetch(`${this.baseUrlTonder}/api/v1/business/${getBusinessId(this.merchantData)}/cards/`, {
|
|
432
462
|
method: 'POST',
|
|
433
463
|
headers: {
|
|
434
464
|
'Authorization': `Token ${customerToken}`,
|
|
435
465
|
'Content-Type': 'application/json'
|
|
436
466
|
},
|
|
437
467
|
signal: this.signal,
|
|
438
|
-
body: JSON.stringify(data)
|
|
468
|
+
body: JSON.stringify({...data})
|
|
439
469
|
});
|
|
440
470
|
|
|
441
471
|
if (response.ok) return await response.json() as RegisterCustomerCardResponse;
|
|
@@ -445,9 +475,11 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
445
475
|
}
|
|
446
476
|
}
|
|
447
477
|
|
|
448
|
-
async getCustomerCards(customerToken: string
|
|
478
|
+
async getCustomerCards(customerToken: string): Promise<GetCustomerCardsResponse | ErrorResponse> {
|
|
449
479
|
try {
|
|
450
|
-
|
|
480
|
+
await this.#fetchMerchantData()
|
|
481
|
+
|
|
482
|
+
const response = await fetch(`${this.baseUrlTonder}/api/v1/business/${getBusinessId(this.merchantData)}/cards`, {
|
|
451
483
|
method: 'GET',
|
|
452
484
|
headers: {
|
|
453
485
|
'Authorization': `Token ${customerToken}`,
|
|
@@ -465,7 +497,8 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
465
497
|
|
|
466
498
|
async deleteCustomerCard(customerToken: string, skyflowId: string = ""): Promise<Boolean | ErrorResponse> {
|
|
467
499
|
try {
|
|
468
|
-
|
|
500
|
+
await this.#fetchMerchantData()
|
|
501
|
+
const response = await fetch(`${this.baseUrlTonder}/api/v1/business/${getBusinessId(this.merchantData)}/cards/${skyflowId}`, {
|
|
469
502
|
method: 'DELETE',
|
|
470
503
|
headers: {
|
|
471
504
|
'Authorization': `Token ${customerToken}`,
|
|
@@ -512,7 +545,7 @@ export class LiteCheckout implements LiteCheckoutConstructor {
|
|
|
512
545
|
return apm;
|
|
513
546
|
}).sort((a: APM, b: APM) => a.priority - b.priority);
|
|
514
547
|
|
|
515
|
-
return this.activeAPMs
|
|
548
|
+
return this.activeAPMs
|
|
516
549
|
} catch (e) {
|
|
517
550
|
console.error("Error getting APMS", e);
|
|
518
551
|
return [];
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export function injectMercadoPagoSecurity() {
|
|
2
|
+
try {
|
|
3
|
+
const script = document.createElement('script');
|
|
4
|
+
script.src = "https://www.mercadopago.com/v2/security.js";
|
|
5
|
+
script.setAttribute('view', '');
|
|
6
|
+
script.onload = () => {
|
|
7
|
+
console.log("Mercado Pago script loaded successfully.");
|
|
8
|
+
};
|
|
9
|
+
script.onerror = (error) => {
|
|
10
|
+
console.error("Error loading Mercado Pago script:", error);
|
|
11
|
+
};
|
|
12
|
+
document.head.appendChild(script);
|
|
13
|
+
} catch (error) {
|
|
14
|
+
console.error("Error attempting to inject Mercado Pago script:", error);
|
|
15
|
+
}
|
|
16
|
+
}
|
package/src/helpers/utils.ts
CHANGED
|
@@ -15,6 +15,9 @@ export const getBrowserInfo = () => {
|
|
|
15
15
|
return browserInfo;
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
+
export const getBusinessId = (merchantData: any) =>{
|
|
19
|
+
return merchantData && "business" in merchantData ? merchantData?.business?.pk:""
|
|
20
|
+
}
|
|
18
21
|
const buildErrorResponseFromCatch = (e: any): ErrorResponse => {
|
|
19
22
|
|
|
20
23
|
const error = new ErrorResponse({
|
package/src/types/commons.ts
CHANGED
|
@@ -48,7 +48,7 @@ describe("getCustomerCards", () => {
|
|
|
48
48
|
})
|
|
49
49
|
);
|
|
50
50
|
|
|
51
|
-
const response = await liteCheckout.getCustomerCards("1234"
|
|
51
|
+
const response = await liteCheckout.getCustomerCards("1234");
|
|
52
52
|
|
|
53
53
|
expect(response).toStrictEqual({ ...new GetCustomerCardsResponseClass() });
|
|
54
54
|
expect(liteCheckoutSpy).toHaveBeenCalled();
|
|
@@ -65,7 +65,7 @@ describe("getCustomerCards", () => {
|
|
|
65
65
|
})
|
|
66
66
|
);
|
|
67
67
|
|
|
68
|
-
const response = await liteCheckout.getCustomerCards("1234"
|
|
68
|
+
const response = await liteCheckout.getCustomerCards("1234");
|
|
69
69
|
expect(liteCheckoutSpy).toHaveBeenCalled();
|
|
70
70
|
expect(liteCheckoutSpy).toHaveReturned();
|
|
71
71
|
expect(response).toBeUndefined();
|
|
@@ -86,7 +86,7 @@ describe("getCustomerCards", () => {
|
|
|
86
86
|
|
|
87
87
|
try {
|
|
88
88
|
const response = (await liteCheckout.getCustomerCards(
|
|
89
|
-
"1234"
|
|
89
|
+
"1234"
|
|
90
90
|
)) as IErrorResponse;
|
|
91
91
|
} catch (e: any) {
|
|
92
92
|
error = e;
|
|
@@ -104,7 +104,7 @@ describe("getCustomerCards", () => {
|
|
|
104
104
|
|
|
105
105
|
try {
|
|
106
106
|
const response = (await liteCheckout.getCustomerCards(
|
|
107
|
-
"1234"
|
|
107
|
+
"1234"
|
|
108
108
|
)) as IErrorResponse;
|
|
109
109
|
} catch (e: any) {
|
|
110
110
|
error = e;
|
|
@@ -39,6 +39,7 @@ export class BusinessClass implements Business {
|
|
|
39
39
|
vault_url!: string;
|
|
40
40
|
reference!: number;
|
|
41
41
|
is_installments_available!: boolean;
|
|
42
|
+
mercado_pago!: { active: boolean}
|
|
42
43
|
|
|
43
44
|
get mockObject(): GetBusinessResponse {
|
|
44
45
|
return {
|
|
@@ -59,6 +60,9 @@ export class BusinessClass implements Business {
|
|
|
59
60
|
textDetailsColor: '#666666',
|
|
60
61
|
checkout_logo: 'assets/images/checkout-logo.png',
|
|
61
62
|
},
|
|
63
|
+
mercado_pago: {
|
|
64
|
+
active: false
|
|
65
|
+
},
|
|
62
66
|
vault_id: 'mock-vault-id-123',
|
|
63
67
|
vault_url: 'https://mock-vault.com',
|
|
64
68
|
reference: 987654,
|