@tonder.io/ionic-lite-sdk 1.0.2-beta.TEC-1207.a1f8325 → 1.0.2-beta.develop.05dedd2

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.
@@ -79,7 +79,7 @@ export type RegisterCustomerCardRequest = {
79
79
  }
80
80
 
81
81
  export type TokensSkyflowRequest = {
82
- baseUrl: string;
82
+ coreBaseUrl: string;
83
83
  apiKey: string;
84
84
  vault_id: string,
85
85
  vault_url: string,
@@ -0,0 +1,69 @@
1
+ import { LiteCheckout } from "../src/classes/liteCheckout";
2
+ import { CardOnFile } from "../src/helpers/card_on_file";
3
+
4
+ const CORE = "https://api-stage.tonder.io";
5
+ const LEGACY = "https://stage.tonder.io";
6
+
7
+ function reply(status: number, body: unknown) {
8
+ return { ok: status >= 200 && status < 300, status, json: async () => body, clone() { return this; } };
9
+ }
10
+
11
+ function installFetch(flag: boolean) {
12
+ (global as any).fetch = jest.fn(async (url: string, init?: RequestInit) => {
13
+ const route = `${init?.method ?? "GET"} ${url}`;
14
+ switch (route) {
15
+ case `GET ${CORE}/transactions/v1/business/config`:
16
+ return reply(200, {
17
+ business: { pk: 7 },
18
+ core_payments_enabled: flag,
19
+ cardonfile_keys: { public_key: "cof-public" },
20
+ });
21
+ case `POST ${CORE}/transactions/v1/customer`:
22
+ return reply(201, { customer_id: 9, auth_token: "eyJ.core.jwt", first_name: "Ana", last_name: "", email: "ana@example.com", auth_token_expires_at: "2026-11-20T12:00:00Z" });
23
+ case `POST ${LEGACY}/api/v1/customer/`:
24
+ return reply(200, { id: 9, auth_token: "legacy-customer-token", first_name: "Ana", email: "ana@example.com" });
25
+ case `POST ${CORE}/transactions/v1/cards`:
26
+ case `POST ${LEGACY}/api/v1/business/7/cards/`:
27
+ return reply(201, { id: "sf-2", customer_id: 9, subscription_id: null, card_bin: "411111" });
28
+ default:
29
+ throw new Error(`unexpected request ${route}`);
30
+ }
31
+ });
32
+ }
33
+
34
+ async function saveCardAndGetSubscriptionOwner(flag: boolean) {
35
+ installFetch(flag);
36
+ const checkout = new LiteCheckout({ mode: "stage", apiKey: "key" });
37
+ checkout.configureCheckout({ customer: { email: "ana@example.com" }, secureToken: "secure" } as any);
38
+ jest.spyOn(CardOnFile.prototype, "initialize").mockResolvedValue(undefined);
39
+ jest.spyOn(CardOnFile.prototype, "getJwt").mockResolvedValue("jwt");
40
+ jest.spyOn(CardOnFile.prototype, "generateToken").mockResolvedValue({ token: "tok", secureId: "sid", security: {} } as any);
41
+ jest.spyOn(CardOnFile.prototype, "validate3DS").mockResolvedValue(true as any);
42
+ const createSubscription = jest
43
+ .spyOn(CardOnFile.prototype, "createSubscription")
44
+ .mockResolvedValue({ subscriptionId: "sub-1" } as any);
45
+ jest.spyOn(checkout as any, "collectCreateCardTokens").mockResolvedValue({
46
+ skyflow_id: "sf-2",
47
+ card_number: "t1",
48
+ cvv: "t2",
49
+ expiration_month: "t3",
50
+ expiration_year: "t4",
51
+ cardholder_name: "t5",
52
+ });
53
+
54
+ await checkout.saveCustomerCard();
55
+
56
+ return (createSubscription.mock.calls[0][0] as any).metadata.customerId;
57
+ }
58
+
59
+ afterEach(() => jest.restoreAllMocks());
60
+
61
+ describe("Card On File subscription owner", () => {
62
+ it("is the customer's id with the flag ON, never the core's token", async () => {
63
+ expect(await saveCardAndGetSubscriptionOwner(true)).toBe("9");
64
+ });
65
+
66
+ it("is still the customer's token with the flag OFF", async () => {
67
+ expect(await saveCardAndGetSubscriptionOwner(false)).toBe("legacy-customer-token");
68
+ });
69
+ });
@@ -7,7 +7,7 @@ import type { CoreVerifyTransaction, ITransaction } from "../src/types/transacti
7
7
 
8
8
  const CORE_BASE = "https://api-stage.tonder.io";
9
9
  const CTX = { coreBaseUrl: CORE_BASE };
10
- const PUBLIC_ID = "0192b8a0-0000-7000-8000-000000000001";
10
+ const TRANSACTION_ID = "0192b8a0-0000-7000-8000-000000000001";
11
11
 
12
12
  const ITEMS = [
13
13
  {
@@ -118,7 +118,7 @@ describe("buildCoreProcessBody", () => {
118
118
  });
119
119
 
120
120
  const SUCCESS = {
121
- id: PUBLIC_ID,
121
+ id: TRANSACTION_ID,
122
122
  status: "Success",
123
123
  amount: 100,
124
124
  currency: "MXN",
@@ -129,22 +129,22 @@ const SUCCESS = {
129
129
  transaction_status: "Success",
130
130
  psp_response: { id: "psp-1" },
131
131
  routing: { checkout_id: "chk-1", is_route_finished: true },
132
- next_action: { verify_transaction_status_url: `/transactions/v1/${PUBLIC_ID}` },
132
+ next_action: { verify_transaction_status_url: `/transactions/v1/${TRANSACTION_ID}` },
133
133
  };
134
134
 
135
135
  const VERIFY_ACTION = {
136
136
  name: "verify_transaction_status",
137
- url: `${CORE_BASE}/transactions/v1/${PUBLIC_ID}`,
137
+ url: `${CORE_BASE}/transactions/v1/${TRANSACTION_ID}`,
138
138
  method: "GET",
139
139
  };
140
140
 
141
141
  describe("rebuildCheckoutResult", () => {
142
- it("points the verify action of a core payment at the core's GET by public id", () => {
142
+ it("points the verify action of a core payment at the core's GET by transaction id", () => {
143
143
  const { actions } = rebuildCheckoutResult(201, SUCCESS, CTX).body;
144
144
 
145
145
  expect(actions[0]).toEqual({
146
146
  name: "verify_transaction_status",
147
- url: `${CORE_BASE}/transactions/v1/${PUBLIC_ID}`,
147
+ url: `${CORE_BASE}/transactions/v1/${TRANSACTION_ID}`,
148
148
  method: "GET",
149
149
  });
150
150
  });
@@ -170,7 +170,7 @@ describe("rebuildCheckoutResult", () => {
170
170
  name: "refund_transaction",
171
171
  url: `${CORE_BASE}/transactions/v1/process`,
172
172
  method: "POST",
173
- body: { operation_type: "refund", original_transaction_id: PUBLIC_ID },
173
+ body: { operation_type: "refund", original_transaction_id: TRANSACTION_ID },
174
174
  },
175
175
  ],
176
176
  });
@@ -197,7 +197,7 @@ describe("rebuildCheckoutResult", () => {
197
197
  redirect_to_url: {
198
198
  url: "https://payflow.example.com/process?token=t#session=s",
199
199
  return_url: "https://shop.example.com/done",
200
- verify_transaction_status_url: `/transactions/v1/${PUBLIC_ID}`,
200
+ verify_transaction_status_url: `/transactions/v1/${TRANSACTION_ID}`,
201
201
  },
202
202
  };
203
203
 
@@ -252,7 +252,7 @@ describe("rebuildCheckoutResult", () => {
252
252
  name: "refund_transaction",
253
253
  url: `${CORE_BASE}/transactions/v1/process`,
254
254
  method: "POST",
255
- body: { operation_type: "refund", original_transaction_id: PUBLIC_ID },
255
+ body: { operation_type: "refund", original_transaction_id: TRANSACTION_ID },
256
256
  },
257
257
  ],
258
258
  });
@@ -413,7 +413,7 @@ describe("rebuildCheckoutResult", () => {
413
413
  describe("rebuildVerifyTransaction", () => {
414
414
  it("is typed as the reduced object, which is not an ITransaction", () => {
415
415
  const verified: CoreVerifyTransaction = rebuildVerifyTransaction({
416
- id: PUBLIC_ID,
416
+ id: TRANSACTION_ID,
417
417
  status: "Success",
418
418
  });
419
419
  // @ts-expect-error country, payment_method and the fees are absent, so it is not a full ITransaction
@@ -422,7 +422,7 @@ describe("rebuildVerifyTransaction", () => {
422
422
  });
423
423
 
424
424
  const CORE_GET = {
425
- id: PUBLIC_ID,
425
+ id: TRANSACTION_ID,
426
426
  operation_type: "payment",
427
427
  status: "Success",
428
428
  amount: "100.0000",
@@ -519,7 +519,7 @@ describe("rebuildVerifyTransaction", () => {
519
519
 
520
520
  it("keeps a null the core answers as null and omits only the keys it lacks", () => {
521
521
  const result = rebuildVerifyTransaction({
522
- id: PUBLIC_ID,
522
+ id: TRANSACTION_ID,
523
523
  operation_type: "payment",
524
524
  status: "Failed",
525
525
  metadata: null,
@@ -536,7 +536,7 @@ describe("rebuildVerifyTransaction", () => {
536
536
  checkout: null,
537
537
  checkout_id: null,
538
538
  });
539
- const lacking = rebuildVerifyTransaction({ id: PUBLIC_ID, status: "Failed" });
539
+ const lacking = rebuildVerifyTransaction({ id: TRANSACTION_ID, status: "Failed" });
540
540
  for (const key of ["metadata", "response", "id", "payment", "checkout", "checkout_id"]) {
541
541
  expect(lacking).not.toHaveProperty(key);
542
542
  }
@@ -544,7 +544,7 @@ describe("rebuildVerifyTransaction", () => {
544
544
 
545
545
  it("keeps a null currency, amount and dates null and leaves absent ones absent", () => {
546
546
  const nulls = rebuildVerifyTransaction({
547
- id: PUBLIC_ID,
547
+ id: TRANSACTION_ID,
548
548
  status: "Failed",
549
549
  currency: null,
550
550
  amount: null,
@@ -559,7 +559,7 @@ describe("rebuildVerifyTransaction", () => {
559
559
  modified: null,
560
560
  });
561
561
 
562
- const absent = rebuildVerifyTransaction({ id: PUBLIC_ID, status: "Failed" });
562
+ const absent = rebuildVerifyTransaction({ id: TRANSACTION_ID, status: "Failed" });
563
563
  for (const key of ["currency", "currency_code", "amount", "created", "modified"]) {
564
564
  expect(absent).not.toHaveProperty(key);
565
565
  }
@@ -575,7 +575,7 @@ describe("rebuildVerifyTransaction", () => {
575
575
 
576
576
  it("leaves out what the core does not hold instead of inventing it", () => {
577
577
  const result = rebuildVerifyTransaction({
578
- id: PUBLIC_ID,
578
+ id: TRANSACTION_ID,
579
579
  operation_type: "payment",
580
580
  status: "Failed",
581
581
  amount: "5.0000",
@@ -5,7 +5,7 @@ import { ErrorKeyEnum } from "../src/shared/enum/ErrorKeyEnum";
5
5
  const API_KEY = "merchant-api-key";
6
6
  const LEGACY = "https://stage.tonder.io";
7
7
  const CORE = "https://api-stage.tonder.io";
8
- const PUBLIC_ID = "0192b8a0-0000-7000-8000-000000000001";
8
+ const TRANSACTION_ID = "0192b8a0-0000-7000-8000-000000000001";
9
9
 
10
10
  const ITEMS = [
11
11
  {
@@ -35,7 +35,7 @@ function config(flag: boolean | undefined) {
35
35
  }
36
36
 
37
37
  const CORE_SUCCESS = {
38
- id: PUBLIC_ID,
38
+ id: TRANSACTION_ID,
39
39
  status: "Success",
40
40
  amount: 100,
41
41
  currency: "MXN",
@@ -46,7 +46,7 @@ const CORE_SUCCESS = {
46
46
  transaction_status: "Success",
47
47
  psp_response: { id: "psp-1" },
48
48
  routing: { checkout_id: "chk-1", is_route_finished: true },
49
- next_action: { verify_transaction_status_url: `/transactions/v1/${PUBLIC_ID}` },
49
+ next_action: { verify_transaction_status_url: `/transactions/v1/${TRANSACTION_ID}` },
50
50
  };
51
51
 
52
52
  const LEGACY_ROUTER_BODY = {
@@ -89,6 +89,9 @@ function installFetch({ flag, process, router }: Routes): jest.Mock {
89
89
  if (url === `${CORE}/transactions/v1/process`) {
90
90
  return reply(process ?? { status: 201, body: CORE_SUCCESS });
91
91
  }
92
+ if (url === `${CORE}/transactions/v1/customer`) {
93
+ return reply({ status: 201, body: { customer_id: 1, email: "ana@example.com", first_name: "Ana", last_name: "", auth_token: "core-cust-token", auth_token_expires_at: "2026-11-20T12:00:00Z" } });
94
+ }
92
95
  if (url === `${LEGACY}/api/v1/customer/`) {
93
96
  return reply({ status: 200, body: { id: 1, auth_token: "cust-token" } });
94
97
  }
@@ -109,6 +112,14 @@ function callsTo(mock: jest.Mock, url: string) {
109
112
  return mock.mock.calls.filter(([called]) => called === url);
110
113
  }
111
114
 
115
+ // A core customer's token is not valid on the monolith: the legacy order is placed by the
116
+ // customer the monolith registered, never by the one the core did.
117
+ function expectLegacyOrderOfLegacyCustomer(mock: jest.Mock) {
118
+ expect(callsTo(mock, `${LEGACY}/api/v1/customer/`)).toHaveLength(1);
119
+ const order = JSON.parse(callsTo(mock, `${LEGACY}/api/v1/orders/`)[0][1].body);
120
+ expect(order.client).toBe("cust-token");
121
+ }
122
+
112
123
  function paymentData(overrides: Record<string, unknown> = {}) {
113
124
  return {
114
125
  customer: CUSTOMER,
@@ -400,6 +411,7 @@ describe("card payment with the flag ON", () => {
400
411
  expect(callsTo(mock, `${CORE}/transactions/v1/process`)).toHaveLength(1);
401
412
  expect(callsTo(mock, `${LEGACY}/api/v1/orders/`)).toHaveLength(1);
402
413
  expect(callsTo(mock, `${LEGACY}/api/v1/checkout-router/`)).toHaveLength(1);
414
+ expectLegacyOrderOfLegacyCustomer(mock);
403
415
  });
404
416
 
405
417
  it("sends the customer's identification as the legacy SDK did", async () => {
@@ -486,6 +498,7 @@ describe("card payment with the flag ON", () => {
486
498
 
487
499
  expect(callsTo(mock, `${CORE}/transactions/v1/process`)).toHaveLength(0);
488
500
  expect(callsTo(mock, `${LEGACY}/api/v1/checkout-router/`)).toHaveLength(1);
501
+ expectLegacyOrderOfLegacyCustomer(mock);
489
502
  });
490
503
 
491
504
  it("keeps the engine of a payment with the 3DS state it stores", async () => {
@@ -502,7 +515,7 @@ describe("card payment with the flag ON", () => {
502
515
  redirect_to_url: {
503
516
  url: "https://payflow.example.com/process?token=t#session=s",
504
517
  return_url: "https://shop.example.com/done",
505
- verify_transaction_status_url: `/transactions/v1/${PUBLIC_ID}`,
518
+ verify_transaction_status_url: `/transactions/v1/${TRANSACTION_ID}`,
506
519
  },
507
520
  },
508
521
  },
@@ -521,7 +534,7 @@ describe("card payment with the flag ON", () => {
521
534
  await new Promise((resolve) => setTimeout(resolve, 0));
522
535
 
523
536
  expect(JSON.parse(localStorage.getItem("verify_transaction_status_url")!)).toMatchObject({
524
- url: `/transactions/v1/${PUBLIC_ID}`,
537
+ url: `/transactions/v1/${TRANSACTION_ID}`,
525
538
  engine: "core",
526
539
  });
527
540
  expect((window.location as any).href ?? window.location).toBe(
@@ -584,7 +597,7 @@ describe("card payment with the flag OFF", () => {
584
597
 
585
598
  describe("verify3dsTransaction of a core payment", () => {
586
599
  const STORAGE_KEY = "verify_transaction_status_url";
587
- const VERIFY_PATH = `/transactions/v1/${PUBLIC_ID}`;
600
+ const VERIFY_PATH = `/transactions/v1/${TRANSACTION_ID}`;
588
601
 
589
602
  function storeCoreState() {
590
603
  localStorage.setItem(
@@ -0,0 +1,378 @@
1
+ import Skyflow from "skyflow-js";
2
+ import { LiteCheckout } from "../src/classes/liteCheckout";
3
+ import { fetchCustomerCards, saveCustomerCard } from "../src/data/cardApi";
4
+ import { fetchCustomerPaymentMethods } from "../src/data/paymentMethodApi";
5
+ import { getVaultToken } from "../src/data/skyflowApi";
6
+ import { ErrorKeyEnum } from "../src/shared/enum/ErrorKeyEnum";
7
+
8
+ const API_KEY = "merchant-api-key";
9
+ const SECURE_TOKEN = "secure-token-value";
10
+ const LEGACY = "https://stage.tonder.io";
11
+ const CORE = "https://api-stage.tonder.io";
12
+ const CUSTOMER_TOKEN = "customer-token";
13
+
14
+ const CORE_CARDS = {
15
+ customer_id: 9,
16
+ data: [
17
+ {
18
+ id: "sf-1",
19
+ card_number: "XXXX-XXXX-XXXX-1111",
20
+ expiration_month: "12",
21
+ expiration_year: "30",
22
+ card_scheme: "VISA",
23
+ subscription_id: "sub-1",
24
+ },
25
+ ],
26
+ };
27
+
28
+ const CORE_PAYMENT_METHODS = {
29
+ data: [
30
+ {
31
+ id: "0192b8a0-0000-7000-8000-0000000000aa",
32
+ payment_method: "OXXO",
33
+ category: "Cash",
34
+ acquirer: "Kushki",
35
+ status: "active",
36
+ priority: 1,
37
+ unavailable_countries: [],
38
+ },
39
+ ],
40
+ };
41
+
42
+ const CARDS = { user_id: 9, cards: [{ fields: { skyflow_id: "sf-1", card_scheme: "VISA", subscription_id: "sub-1" } }] };
43
+
44
+ function config(flag: boolean | undefined) {
45
+ return {
46
+ business: { pk: 7, name: "Shop" },
47
+ openpay_keys: { merchant_id: "", public_key: "" },
48
+ mercado_pago: { active: false },
49
+ vault_id: "vault",
50
+ vault_url: "https://vault.example.com",
51
+ reference: "TNDR-1",
52
+ ...(flag === undefined ? {} : { core_payments_enabled: flag }),
53
+ };
54
+ }
55
+
56
+ function reply(status: number, body: unknown) {
57
+ return {
58
+ ok: status >= 200 && status < 300,
59
+ status,
60
+ json: async () => body,
61
+ clone() {
62
+ return this;
63
+ },
64
+ };
65
+ }
66
+
67
+ function installFetch(flag: boolean | undefined): jest.Mock {
68
+ const mock = jest.fn(async (url: string, init?: RequestInit) => {
69
+ const method = init?.method ?? "GET";
70
+ const route = `${method} ${url}`;
71
+ switch (route) {
72
+ case `GET ${CORE}/transactions/v1/business/config`:
73
+ return reply(200, config(flag));
74
+ case `POST ${CORE}/transactions/v1/customer`:
75
+ return reply(201, { customer_id: 9, email: "ana@example.com", first_name: "Ana", last_name: "", auth_token: "core-customer-token", auth_token_expires_at: "2026-11-20T12:00:00Z" });
76
+ case `POST ${LEGACY}/api/v1/customer/`:
77
+ return reply(200, { id: 9, auth_token: "legacy-customer-token", email: "ana@example.com" });
78
+ case `GET ${CORE}/transactions/v1/cards`:
79
+ return reply(200, CORE_CARDS);
80
+ case `GET ${LEGACY}/api/v1/business/7/cards/`:
81
+ return reply(200, CARDS);
82
+ case `DELETE ${CORE}/transactions/v1/cards/sf-1`:
83
+ return reply(204, undefined);
84
+ case `DELETE ${LEGACY}/api/v1/business/7/cards/sf-1`:
85
+ return reply(204, undefined);
86
+ case `POST ${CORE}/transactions/v1/cards`:
87
+ return reply(201, { id: "sf-2", customer_id: 9, subscription_id: "sub-2", card_scheme: "VISA", card_bin: "411111" });
88
+ case `POST ${LEGACY}/api/v1/business/7/cards/`:
89
+ return reply(201, { skyflow_id: "sf-2", user_id: 9 });
90
+ case `GET ${CORE}/transactions/v1/payment_methods?status=active&pagesize=10000`:
91
+ return reply(200, CORE_PAYMENT_METHODS);
92
+ case `GET ${CORE}/transactions/v1/vault-token`:
93
+ return reply(200, { token: "vault-bearer" });
94
+ default:
95
+ throw new Error(`unexpected request ${route}`);
96
+ }
97
+ });
98
+ (global as any).fetch = mock;
99
+ return mock;
100
+ }
101
+
102
+ function calls(mock: jest.Mock, route: string) {
103
+ return mock.mock.calls.filter(([url, init]) => `${init?.method ?? "GET"} ${url}` === route);
104
+ }
105
+
106
+ function headersOf(call: any[]): Record<string, string> {
107
+ const lower: Record<string, string> = {};
108
+ for (const [name, value] of Object.entries((call[1]?.headers ?? {}) as Record<string, string>)) {
109
+ lower[name.toLowerCase()] = value;
110
+ }
111
+ return lower;
112
+ }
113
+
114
+ async function ready() {
115
+ const checkout = new LiteCheckout({ mode: "stage", apiKey: API_KEY });
116
+ checkout.configureCheckout({ customer: { email: "ana@example.com" }, secureToken: SECURE_TOKEN } as any);
117
+ return checkout;
118
+ }
119
+
120
+ describe("support APIs with the core flag ON", () => {
121
+ it("registers the customer on the core with the key the payment uses", async () => {
122
+ const fetchMock = installFetch(true);
123
+ const checkout = await ready();
124
+
125
+ await checkout.getCustomerCards();
126
+
127
+ const [call] = calls(fetchMock, `POST ${CORE}/transactions/v1/customer`);
128
+ expect(headersOf(call).authorization).toBe(`Token ${API_KEY}`);
129
+ expect(JSON.parse(call[1].body)).toMatchObject({ email: "ana@example.com" });
130
+ expect(calls(fetchMock, `POST ${LEGACY}/api/v1/customer/`)).toHaveLength(0);
131
+ });
132
+
133
+ it("lists the saved cards on the core with only the secure token and the customer's token", async () => {
134
+ const fetchMock = installFetch(true);
135
+ const checkout = await ready();
136
+
137
+ const result = await checkout.getCustomerCards();
138
+
139
+ const [call] = calls(fetchMock, `GET ${CORE}/transactions/v1/cards`);
140
+ const headers = headersOf(call);
141
+ expect(headers.authorization).toBe(`Bearer ${SECURE_TOKEN}`);
142
+ expect(headers["user-token"]).toBe("core-customer-token");
143
+ expect(headers["x-app-origin"]).toBeUndefined();
144
+ expect(result).toMatchObject({
145
+ user_id: 9,
146
+ cards: [
147
+ {
148
+ fields: {
149
+ skyflow_id: "sf-1",
150
+ card_number: "XXXX-XXXX-XXXX-1111",
151
+ expiration_month: "12",
152
+ expiration_year: "30",
153
+ card_scheme: "VISA",
154
+ },
155
+ },
156
+ ],
157
+ });
158
+ expect(fetchMock.mock.calls.some(([url]) => String(url).startsWith(LEGACY))).toBe(false);
159
+ });
160
+
161
+ it("adds a card on the core without the business in the path", async () => {
162
+ const fetchMock = installFetch(true);
163
+
164
+ const answer = await saveCustomerCard(
165
+ { engine: "core", baseUrl: CORE },
166
+ "core-customer-token",
167
+ SECURE_TOKEN,
168
+ 7,
169
+ { skyflow_id: "sf-2", subscription_id: "sub-2" } as any,
170
+ true,
171
+ );
172
+
173
+ const [call] = calls(fetchMock, `POST ${CORE}/transactions/v1/cards`);
174
+ expect(headersOf(call)).toMatchObject({
175
+ authorization: `Bearer ${SECURE_TOKEN}`,
176
+ "user-token": "core-customer-token",
177
+ "x-app-origin": "sdk/ionic",
178
+ });
179
+ expect(JSON.parse(call[1].body)).toEqual({ skyflow_id: "sf-2", subscription_id: "sub-2" });
180
+ expect(answer).toEqual({ skyflow_id: "sf-2", user_id: 9, card_bin: "411111" });
181
+ });
182
+
183
+ it("removes a card on the core by its skyflow id", async () => {
184
+ const fetchMock = installFetch(true);
185
+ const checkout = await ready();
186
+
187
+ await checkout.removeCustomerCard("sf-1");
188
+
189
+ const [call] = calls(fetchMock, `DELETE ${CORE}/transactions/v1/cards/sf-1`);
190
+ expect(headersOf(call)).toMatchObject({
191
+ authorization: `Bearer ${SECURE_TOKEN}`,
192
+ "user-token": "core-customer-token",
193
+ });
194
+ expect(fetchMock.mock.calls.some(([url]) => String(url).startsWith(LEGACY))).toBe(false);
195
+ });
196
+
197
+ it("keeps answering an empty list when the core refuses the secure token", async () => {
198
+ const fetchMock = installFetch(true);
199
+ const original = fetchMock.getMockImplementation()!;
200
+ fetchMock.mockImplementation(async (url: string, init?: RequestInit) =>
201
+ url === `${CORE}/transactions/v1/cards` ? reply(401, {}) : original(url, init),
202
+ );
203
+ const checkout = await ready();
204
+
205
+ const result = await checkout.getCustomerCards();
206
+
207
+ expect(result).toEqual({ user_id: 0, cards: [] });
208
+ });
209
+ });
210
+
211
+ describe("what the core answers becomes what the SDK returned before", () => {
212
+ it("rebuilds the payment methods list the paged answer had", async () => {
213
+ installFetch(true);
214
+
215
+ const answer = await fetchCustomerPaymentMethods(CORE, API_KEY);
216
+
217
+ expect(answer).toMatchObject({
218
+ count: 1,
219
+ next: null,
220
+ previous: null,
221
+ results: [{ pk: "0192b8a0-0000-7000-8000-0000000000aa", payment_method: "OXXO", category: "Cash", priority: 1 }],
222
+ });
223
+ });
224
+
225
+ it("keeps the subscription id of a saved card", async () => {
226
+ installFetch(true);
227
+
228
+ const answer = await fetchCustomerCards({ engine: "core", baseUrl: CORE }, "t", SECURE_TOKEN, 7);
229
+
230
+ expect(answer.cards[0].fields.subscription_id).toBe("sub-1");
231
+ });
232
+
233
+ it("keeps the fields of the card add answer the SDK used", async () => {
234
+ installFetch(true);
235
+
236
+ const answer = await saveCustomerCard({ engine: "core", baseUrl: CORE }, "t", SECURE_TOKEN, 7, { skyflow_id: "sf-2" } as any);
237
+
238
+ expect(Object.keys(answer).sort()).toEqual(["card_bin", "skyflow_id", "user_id"]);
239
+ });
240
+
241
+ it.each([
242
+ [409, "card_limit_reached", { limit: 10 }],
243
+ [409, "customer_phone_required", undefined],
244
+ [503, "dependency_unavailable", undefined],
245
+ [404, "not_found", undefined],
246
+ ])("keeps SAVE_CARD_ERROR for a %s %s, with the core's code as the system error", async (status, code, details) => {
247
+ const fetchMock = installFetch(true);
248
+ const original = fetchMock.getMockImplementation()!;
249
+ fetchMock.mockImplementation(async (url: string, init?: RequestInit) =>
250
+ url === `${CORE}/transactions/v1/cards` && init?.method === "POST"
251
+ ? reply(status, { error: { code, message: "refused", type: "x", ...(details ? { details } : {}) }, request_id: "r-1" })
252
+ : original(url, init),
253
+ );
254
+
255
+ const failure = await saveCustomerCard({ engine: "core", baseUrl: CORE }, "t", SECURE_TOKEN, 7, { skyflow_id: "sf-2" } as any).catch((e) => e);
256
+
257
+ expect(failure.code).toBe(ErrorKeyEnum.SAVE_CARD_ERROR);
258
+ expect(failure.statusCode).toBe(status);
259
+ expect(failure.details.systemError).toBe(code);
260
+ });
261
+ });
262
+
263
+ describe("support APIs with the core flag OFF", () => {
264
+ it.each([false, undefined])("keeps customer and cards on the monolith (flag %s)", async (flag) => {
265
+ const fetchMock = installFetch(flag);
266
+ const checkout = await ready();
267
+
268
+ await checkout.getCustomerCards();
269
+ await checkout.removeCustomerCard("sf-1");
270
+
271
+ const [customerCall] = calls(fetchMock, `POST ${LEGACY}/api/v1/customer/`);
272
+ expect(headersOf(customerCall).authorization).toBe(`Token ${API_KEY}`);
273
+ const [listCall] = calls(fetchMock, `GET ${LEGACY}/api/v1/business/7/cards/`);
274
+ expect(headersOf(listCall)).toMatchObject({
275
+ authorization: `Bearer ${SECURE_TOKEN}`,
276
+ "user-token": "legacy-customer-token",
277
+ });
278
+ expect(calls(fetchMock, `DELETE ${LEGACY}/api/v1/business/7/cards/sf-1`)).toHaveLength(1);
279
+ expect(fetchMock.mock.calls.some(([url]) => String(url).startsWith(`${CORE}/transactions/v1/customer`))).toBe(false);
280
+ expect(fetchMock.mock.calls.some(([url]) => String(url).startsWith(`${CORE}/transactions/v1/cards`))).toBe(false);
281
+ });
282
+
283
+ it("still adds a card on the monolith with the business in the path", async () => {
284
+ const fetchMock = installFetch(false);
285
+
286
+ await saveCustomerCard(
287
+ { engine: "legacy", baseUrl: LEGACY },
288
+ "legacy-customer-token",
289
+ SECURE_TOKEN,
290
+ 7,
291
+ { skyflow_id: "sf-2" } as any,
292
+ );
293
+
294
+ const [call] = calls(fetchMock, `POST ${LEGACY}/api/v1/business/7/cards/`);
295
+ expect(headersOf(call)["user-token"]).toBe("legacy-customer-token");
296
+ });
297
+ });
298
+
299
+ describe.each([true, false, undefined])("support APIs that always go to the core (flag %s)", (flag) => {
300
+ it("lists the payment methods on the core with the same query and key", async () => {
301
+ const fetchMock = installFetch(flag);
302
+ const checkout = await ready();
303
+
304
+ const methods = await checkout.getCustomerPaymentMethods();
305
+
306
+ const [call] = calls(fetchMock, `GET ${CORE}/transactions/v1/payment_methods?status=active&pagesize=10000`);
307
+ expect(headersOf(call).authorization).toBe(`Token ${API_KEY}`);
308
+ expect(methods.map((m) => m.payment_method)).toEqual(["OXXO"]);
309
+ expect(fetchMock.mock.calls.some(([url]) => String(url).startsWith(LEGACY))).toBe(false);
310
+ });
311
+
312
+ it("asks the core for the vault token", async () => {
313
+ const fetchMock = installFetch(flag);
314
+
315
+ const token = await getVaultToken(CORE, API_KEY);
316
+
317
+ const [call] = calls(fetchMock, `GET ${CORE}/transactions/v1/vault-token`);
318
+ expect(headersOf(call).authorization).toBe(`Token ${API_KEY}`);
319
+ expect(token).toBe("vault-bearer");
320
+ });
321
+
322
+ it("hands the Skyflow instance a vault-token getter that reads the core", async () => {
323
+ const fetchMock = installFetch(flag);
324
+ const checkout = await ready();
325
+
326
+ const init = jest.spyOn(Skyflow, "init").mockImplementation((config: any) => config);
327
+ await (checkout as any).createSkyflowInstance();
328
+ const { getBearerToken } = init.mock.calls[0][0] as any;
329
+ init.mockRestore();
330
+
331
+ expect(await getBearerToken()).toBe("vault-bearer");
332
+ expect(calls(fetchMock, `GET ${CORE}/transactions/v1/vault-token`)).toHaveLength(1);
333
+ });
334
+ });
335
+
336
+ describe("the deprecated methods follow the same split", () => {
337
+ it("getActiveAPMs reads the core with the query it sent before", async () => {
338
+ const fetchMock = installFetch(false);
339
+ const original = fetchMock.getMockImplementation()!;
340
+ fetchMock.mockImplementation(async (url: string, init?: RequestInit) =>
341
+ String(url).startsWith(`${CORE}/transactions/v1/payment_methods?`)
342
+ ? reply(200, CORE_PAYMENT_METHODS)
343
+ : original(url, init),
344
+ );
345
+ const checkout = await ready();
346
+
347
+ const apms = await checkout.getActiveAPMs();
348
+
349
+ expect(apms).toHaveLength(1);
350
+ const urls = fetchMock.mock.calls.map(([url]) => String(url));
351
+ expect(urls).toContain(
352
+ `${CORE}/transactions/v1/payment_methods?status=active&page_size=10000&country=México`,
353
+ );
354
+ expect(urls.some((url) => url.startsWith(LEGACY))).toBe(false);
355
+ });
356
+
357
+ it("customerRegister follows the flag", async () => {
358
+ const fetchMock = installFetch(true);
359
+ const checkout = await ready();
360
+
361
+ const customer = await checkout.customerRegister("ana@example.com");
362
+
363
+ expect(customer).toMatchObject({ id: 9, email: "ana@example.com", auth_token: "core-customer-token", first_name: "Ana" });
364
+ expect(calls(fetchMock, `POST ${CORE}/transactions/v1/customer`)).toHaveLength(1);
365
+ expect(calls(fetchMock, `POST ${LEGACY}/api/v1/customer/`)).toHaveLength(0);
366
+ });
367
+
368
+ it("a failed customer call still rejects with CUSTOMER_OPERATION_ERROR", async () => {
369
+ const fetchMock = installFetch(true);
370
+ const original = fetchMock.getMockImplementation()!;
371
+ fetchMock.mockImplementation(async (url: string, init?: RequestInit) =>
372
+ url === `${CORE}/transactions/v1/customer` ? reply(500, {}) : original(url, init),
373
+ );
374
+ const checkout = await ready();
375
+
376
+ await expect(checkout.getCustomerCards()).rejects.toMatchObject({ code: ErrorKeyEnum.FETCH_CARDS_ERROR });
377
+ });
378
+ });