@paykit-sdk/medusajs 1.0.12 → 1.0.13

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.
@@ -5,7 +5,7 @@ var core = require('@paykit-sdk/core');
5
5
  var zod = require('zod');
6
6
 
7
7
  // src/providers/paykit-provider.ts
8
- var medusaStatus$InboundSchema = (status) => {
8
+ var PaymentStatus$inboundSchema = (status) => {
9
9
  switch (status) {
10
10
  case "pending":
11
11
  case "processing":
@@ -29,17 +29,20 @@ var medusaStatus$InboundSchema = (status) => {
29
29
  var optionsSchema = zod.z.object({
30
30
  /**
31
31
  * The underlying PayKit provider instance (Stripe, PayPal, etc.)
32
- * This is required and must be a valid PayKit provider instance
33
32
  */
34
33
  provider: core.providerSchema,
35
34
  /**
36
- * The webhook secret for the provider
37
- * This is required and must be a valid webhook secret
35
+ * The webhook secret for the provider.
38
36
  */
39
- webhookSecret: zod.z.string(),
37
+ webhookSecret: zod.z.string().nullable().default(null),
38
+ /**
39
+ * Multiplier applied to the amount before sending to the payment provider.
40
+ * Use this when your provider expects amounts in the smallest currency unit (e.g. cents)
41
+ * but Medusa is passing amounts in the major unit (e.g. euros).
42
+ */
43
+ amountToCentsMultiplier: zod.z.number().min(1).default(1),
40
44
  /**
41
45
  * Whether to enable debug mode
42
- * If enabled, the adapter will log debug information to the console
43
46
  */
44
47
  debug: zod.z.boolean().optional()
45
48
  });
@@ -50,29 +53,48 @@ var PaykitMedusaJSAdapter = class extends utils.AbstractPaymentProvider {
50
53
  */
51
54
  static identifier = "paykit";
52
55
  paykit;
53
- provider;
54
56
  options;
55
57
  static validateOptions(options) {
56
58
  const { error } = optionsSchema.safeParse(options);
57
59
  if (error) {
58
- throw new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, error.message);
60
+ throw new utils.MedusaError(
61
+ utils.MedusaError.Types.INVALID_DATA,
62
+ error.message
63
+ );
59
64
  }
60
65
  return;
61
66
  }
62
67
  /**
63
- * Constructor receives Medusa's container and provider options
64
- *
65
68
  * @param cradle - Medusa's dependency injection container
66
69
  * @param options - PayKit provider configuration
67
70
  */
68
71
  constructor(cradle, options) {
69
72
  super(cradle, options);
70
73
  this.options = options;
71
- this.provider = options.provider;
72
- this.paykit = new core.PayKit(this.provider);
74
+ this.paykit = new core.PayKit(options.provider);
73
75
  if (this.options.debug) {
74
- console.info(`[PayKit] Initialized with provider: ${this.provider.providerName}`);
76
+ console.info(
77
+ `[PayKit] Initialized with provider: ${this.paykit.providerName}`
78
+ );
79
+ }
80
+ }
81
+ async exec(promise, context, options) {
82
+ const [result, error] = await core.tryCatchAsync(promise);
83
+ if (error) {
84
+ if (options?.allowUnsupported && error.name === "ProviderNotSupportedError") {
85
+ if (this.options.debug) {
86
+ console.warn(
87
+ `[PayKit ${context}] Operation not supported by ${this.paykit.providerName}.`
88
+ );
89
+ }
90
+ return null;
91
+ }
92
+ throw new utils.MedusaError(
93
+ utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
94
+ `[PayKit ${context}] ${error.message}`
95
+ );
75
96
  }
97
+ return result;
76
98
  }
77
99
  initiatePayment = async ({
78
100
  context,
@@ -83,341 +105,338 @@ var PaykitMedusaJSAdapter = class extends utils.AbstractPaymentProvider {
83
105
  if (this.options.debug) {
84
106
  console.info("[PayKit] Initiating payment", {
85
107
  context,
86
- amount,
108
+ amount: Number(amount) * this.options.amountToCentsMultiplier,
87
109
  currency_code,
88
110
  data
89
111
  });
90
112
  }
91
- const intent = {
92
- amount: Number(amount),
93
- currency: currency_code,
94
- metadata: { ...data?.metadata ?? {}, session_id: data?.session_id ?? null },
95
- provider_metadata: data?.provider_metadata,
96
- capture_method: "manual",
97
- item_id: data?.item_id
98
- };
99
- let customer;
113
+ const hasProviderCustomer = !!context?.account_holder?.data?.id;
114
+ let customer = null;
100
115
  if (context?.account_holder?.data?.id) {
101
- customer = context.account_holder.data.id;
102
- }
103
- if (data?.email) {
116
+ customer = { id: context.account_holder.data.id };
117
+ } else if (context?.customer?.email) {
118
+ customer = { email: context.customer.email };
119
+ } else if (data?.email) {
104
120
  customer = { email: data.email };
105
121
  }
106
- if (!customer) {
122
+ if (!customer || !core.isIdCustomer(customer) && !core.isEmailCustomer(customer)) {
107
123
  throw new utils.MedusaError(
108
124
  utils.MedusaError.Types.INVALID_DATA,
109
- "Required: customer ID (account_holder) or email (data)"
125
+ "Customer ID (account_holder) or Email (context.customer or data.email) required"
110
126
  );
111
127
  }
112
- const billingInfoParsed = core.billingSchema.safeParse(data?.billing);
113
- if (data?.billing && !billingInfoParsed.success) {
114
- throw new utils.MedusaError(
115
- utils.MedusaError.Types.INVALID_DATA,
116
- `Invalid billing information, ${billingInfoParsed.error.message} `
117
- );
118
- }
119
- if (typeof customer === "object" && "email" in customer) {
120
- const customerName = data?.name ? data.name : customer.email.split("@")[0];
121
- const [createdCustomer, createError] = await core.tryCatchAsync(
128
+ if (!hasProviderCustomer && core.isEmailCustomer(customer)) {
129
+ const { fullName } = core.parseCustomerName({
130
+ name: `${context?.customer?.first_name ?? ""} ${context?.customer?.last_name ?? ""}`.trim(),
131
+ email: customer.email
132
+ });
133
+ const billingInfo = core.billingSchema.safeParse(data?.billing);
134
+ if (data?.billing && !billingInfo.success) {
135
+ throw new utils.MedusaError(
136
+ utils.MedusaError.Types.INVALID_DATA,
137
+ `Invalid billing information, ${billingInfo.error.message} `
138
+ );
139
+ }
140
+ const created = await this.exec(
122
141
  this.paykit.customers.create({
123
142
  email: customer.email,
124
- phone: data?.phone ?? "",
125
- name: customerName,
143
+ name: fullName,
144
+ phone: data?.phone ?? null,
145
+ billing: billingInfo.data ?? null,
126
146
  metadata: {
127
- PAYKIT_METADATA_KEY: JSON.stringify({ source: "medusa-paykit-adapter" })
128
- },
129
- billing: billingInfoParsed.data ?? null
130
- })
131
- );
132
- if (createError) {
133
- if (createError.name === "ProviderNotSupportedError") {
134
- if (this.options.debug) {
135
- console.info(
136
- `[PayKit] Provider ${this.provider.providerName} doesn't support customer creation, using email object`
137
- );
147
+ [core.PAYKIT_METADATA_KEY]: JSON.stringify({
148
+ source: "medusa-paykit-adapter"
149
+ })
138
150
  }
139
- } else {
140
- throw new utils.MedusaError(
141
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
142
- `Failed to create customer: ${createError.message}`
143
- );
144
- }
145
- } else {
146
- customer = createdCustomer.id;
151
+ }),
152
+ "Customer Creation",
153
+ { allowUnsupported: true }
154
+ );
155
+ if (created) {
156
+ customer = {
157
+ ..."id" in created ? { id: created.id } : {},
158
+ ..."email" in created ? { email: created.email } : {}
159
+ };
147
160
  }
148
- } else {
149
- customer = customer;
150
161
  }
151
- intent.customer = customer;
152
- const [paymentIntentResult, paymentIntentError] = await core.tryCatchAsync(
153
- this.paykit.payments.create(intent)
162
+ const payment = await this.exec(
163
+ this.paykit.payments.create({
164
+ amount: Number(amount) * this.options.amountToCentsMultiplier,
165
+ currency: currency_code.toUpperCase(),
166
+ customer,
167
+ item_id: data?.item_id ?? null,
168
+ capture_method: "manual",
169
+ metadata: {
170
+ ...data?.metadata,
171
+ session_id: data?.session_id
172
+ },
173
+ ...data?.billing ? { billing: data.billing } : {},
174
+ provider_metadata: data?.provider_metadata
175
+ }),
176
+ "Initiate"
154
177
  );
155
- if (paymentIntentError) {
156
- throw new utils.MedusaError(
157
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
158
- paymentIntentError.message
159
- );
160
- }
161
- if (paymentIntentResult.requires_action && paymentIntentResult.payment_url) {
162
- return {
163
- id: paymentIntentResult.id,
164
- status: utils.PaymentSessionStatus.REQUIRES_MORE,
165
- data: {
166
- payment_url: paymentIntentResult.payment_url
167
- }
168
- };
169
- }
170
178
  return {
171
- id: paymentIntentResult.id,
172
- status: medusaStatus$InboundSchema(paymentIntentResult.status)
179
+ id: payment.id,
180
+ status: payment.requires_action ? utils.PaymentSessionStatus.REQUIRES_MORE : PaymentStatus$inboundSchema(payment.status),
181
+ data: { ...payment, payment_url: payment.payment_url }
173
182
  };
174
183
  };
175
184
  capturePayment = async (input) => {
176
185
  if (this.options.debug) {
177
186
  console.info("[PayKit] Capturing payment", input);
178
187
  }
179
- const { id, amount } = core.validateRequiredKeys(
188
+ const { id: paymentId, amount } = core.validateRequiredKeys(
180
189
  ["id", "amount"],
181
- input?.data ?? {},
190
+ input.data ?? {},
182
191
  "Missing required fields: {keys}",
183
192
  (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
184
193
  );
185
- const [paymentIntentResult, paymentIntentError] = await core.tryCatchAsync(
186
- this.paykit.payments.capture(id, { amount: Number(amount) })
194
+ const data = await this.exec(
195
+ this.paykit.payments.capture(paymentId, {
196
+ amount: Number(amount) * this.options.amountToCentsMultiplier
197
+ }),
198
+ "Capture"
187
199
  );
188
- if (paymentIntentError)
189
- throw new utils.MedusaError(
190
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
191
- paymentIntentError.message
192
- );
193
- return { data: paymentIntentResult };
200
+ return {
201
+ data
202
+ };
194
203
  };
195
204
  authorizePayment = async (input) => {
196
- if (this.options.debug) {
197
- console.info("[PayKit] Authorizing payment", input);
205
+ const { id: paymentId } = core.validateRequiredKeys(
206
+ ["id"],
207
+ input.data ?? {},
208
+ "Missing required fields: {keys}",
209
+ (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
210
+ );
211
+ const payment = await this.exec(
212
+ this.paykit.payments.retrieve(paymentId),
213
+ "Authorize"
214
+ );
215
+ if (!payment) {
216
+ throw new utils.MedusaError(
217
+ utils.MedusaError.Types.NOT_FOUND,
218
+ "Payment not found"
219
+ );
198
220
  }
199
- return this.getPaymentStatus(input);
221
+ const resolvedStatus = (() => {
222
+ if (payment.requires_action)
223
+ return utils.PaymentSessionStatus.REQUIRES_MORE;
224
+ if (payment.status === "succeeded")
225
+ return utils.PaymentSessionStatus.AUTHORIZED;
226
+ return PaymentStatus$inboundSchema(payment.status);
227
+ })();
228
+ return {
229
+ status: resolvedStatus,
230
+ data: payment
231
+ };
200
232
  };
201
233
  cancelPayment = async (input) => {
202
234
  if (this.options.debug) {
203
235
  console.info("[PayKit] Canceling payment", input);
204
236
  }
205
- const { id } = core.validateRequiredKeys(
237
+ const { id: paymentId } = core.validateRequiredKeys(
206
238
  ["id"],
207
- input?.data ?? {},
239
+ input.data ?? {},
208
240
  "Missing required fields: {keys}",
209
241
  (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
210
242
  );
211
- const [paymentIntentResult, paymentIntentError] = await core.tryCatchAsync(
212
- this.paykit.payments.cancel(id)
243
+ const data = await this.exec(
244
+ this.paykit.payments.cancel(paymentId),
245
+ "Cancel"
213
246
  );
214
- if (paymentIntentError)
215
- throw new utils.MedusaError(
216
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
217
- paymentIntentError.message
218
- );
219
- return { data: paymentIntentResult };
247
+ return { data };
220
248
  };
221
249
  deletePayment = async (input) => {
222
- return this.cancelPayment(input);
250
+ if (this.options.debug) {
251
+ console.info(
252
+ "[PayKit] Deleting payment (attempting cancel)",
253
+ input
254
+ );
255
+ }
256
+ const paymentId = input.data?.id;
257
+ if (!paymentId) {
258
+ return {};
259
+ }
260
+ const data = await this.exec(
261
+ this.paykit.payments.cancel(paymentId),
262
+ "Cancel",
263
+ { allowUnsupported: true }
264
+ );
265
+ return { data };
223
266
  };
224
267
  getPaymentStatus = async (input) => {
225
- const { id } = core.validateRequiredKeys(
268
+ const { id: paymentId } = core.validateRequiredKeys(
226
269
  ["id"],
227
- input?.data ?? {},
270
+ input.data ?? {},
228
271
  "Missing required fields: {keys}",
229
272
  (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
230
273
  );
231
- const [paymentIntentResult, paymentIntentError] = await core.tryCatchAsync(
232
- this.paykit.payments.retrieve(id)
274
+ const payment = await this.exec(
275
+ this.paykit.payments.retrieve(paymentId),
276
+ "Status"
233
277
  );
234
- if (paymentIntentError)
278
+ if (!payment)
235
279
  throw new utils.MedusaError(
236
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
237
- paymentIntentError.message
238
- );
239
- if (!paymentIntentResult)
240
- throw new utils.MedusaError(
241
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
280
+ utils.MedusaError.Types.NOT_FOUND,
242
281
  "Payment not found"
243
282
  );
244
283
  return {
245
- status: medusaStatus$InboundSchema(paymentIntentResult.status),
246
- data: paymentIntentResult
284
+ status: PaymentStatus$inboundSchema(payment.status),
285
+ data: payment
247
286
  };
248
287
  };
249
288
  refundPayment = async (input) => {
250
289
  if (this.options.debug) {
251
290
  console.info("[PayKit] Refunding payment", input);
252
291
  }
253
- const { id: paymentId } = core.validateRequiredKeys(
254
- ["id"],
255
- input?.data ?? {},
292
+ const { id: paymentId, reason = "customer_request" } = core.validateRequiredKeys(
293
+ ["id", "reason"],
294
+ input.data ?? {},
256
295
  "Missing required fields: {keys}",
257
296
  (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
258
297
  );
259
- const [refundResult, refundError] = await core.tryCatchAsync(
298
+ const refund = await this.exec(
260
299
  this.paykit.refunds.create({
261
300
  payment_id: paymentId,
262
- amount: Number(input.amount),
263
- reason: null,
264
- metadata: input.data?.metadata ? input.data.metadata : null,
265
- provider_metadata: input.data?.provider_metadata ? input.data.provider_metadata : void 0
266
- })
301
+ amount: Number(input.amount) * this.options.amountToCentsMultiplier,
302
+ reason,
303
+ metadata: input.data?.metadata ?? null,
304
+ provider_metadata: input.data?.provider_metadata ?? void 0
305
+ }),
306
+ "Refund"
267
307
  );
268
- if (refundError)
269
- throw new utils.MedusaError(
270
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
271
- refundError.message
272
- );
273
- return { data: refundResult };
308
+ return { data: refund };
274
309
  };
275
310
  retrievePayment = async (input) => {
276
311
  if (this.options.debug) {
277
312
  console.info("[PayKit] Retrieving payment", input);
278
313
  }
279
- const { id } = core.validateRequiredKeys(
314
+ const { id: paymentId } = core.validateRequiredKeys(
280
315
  ["id"],
281
- input?.data ?? {},
316
+ input.data ?? {},
282
317
  "Missing required fields: {keys}",
283
318
  (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
284
319
  );
285
- const [paymentIntentResult, paymentIntentError] = await core.tryCatchAsync(
286
- this.paykit.payments.retrieve(id)
320
+ const payment = await this.exec(
321
+ this.paykit.payments.retrieve(paymentId),
322
+ "Retrieve"
287
323
  );
288
- if (paymentIntentError)
289
- throw new utils.MedusaError(
290
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
291
- paymentIntentError.message
292
- );
293
- return { data: paymentIntentResult };
324
+ return { data: payment };
294
325
  };
295
326
  updatePayment = async (input) => {
296
327
  if (this.options.debug) {
297
328
  console.info("[PayKit] Updating payment", input);
298
329
  }
299
- const { amount, currency_code } = core.validateRequiredKeys(
300
- ["amount", "currency_code"],
301
- input,
302
- "Missing required fields: {keys}",
303
- (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
304
- );
305
- const { id: paymentId } = core.validateRequiredKeys(
306
- ["id"],
307
- input.data,
330
+ const {
331
+ amount,
332
+ id: paymentId,
333
+ currency_code: currencyCode
334
+ } = core.validateRequiredKeys(
335
+ ["amount", "currency_code", "id"],
336
+ input.data ?? {},
308
337
  "Missing required fields: {keys}",
309
338
  (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
310
339
  );
311
- const metadata = input.data?.metadata ?? {};
312
- const [paymentIntentResult, paymentIntentError] = await core.tryCatchAsync(
340
+ const data = await this.exec(
313
341
  this.paykit.payments.update(paymentId, {
314
- amount: Number(amount),
315
- currency: currency_code,
316
- metadata: core.stringifyMetadataValues(metadata),
317
- provider_metadata: input.data?.provider_metadata ? input.data.provider_metadata : void 0
318
- })
342
+ amount: Number(amount) * this.options.amountToCentsMultiplier,
343
+ currency: currencyCode.toUpperCase(),
344
+ provider_metadata: input.data?.provider_metadata
345
+ }),
346
+ "Update"
319
347
  );
320
- if (paymentIntentError)
321
- throw new utils.MedusaError(
322
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
323
- paymentIntentError.message
324
- );
325
- return { data: paymentIntentResult };
348
+ return { data };
326
349
  };
327
350
  getWebhookActionAndData = async (payload) => {
328
351
  if (this.options.debug) {
329
- console.info("[PayKit] Getting webhook action and data", payload);
352
+ console.info(
353
+ "[PayKit] Resolving webhook action and data",
354
+ payload
355
+ );
330
356
  }
331
357
  const { rawData, headers } = payload;
332
- const bodyString = Buffer.isBuffer(rawData) ? rawData.toString("utf8") : rawData;
358
+ const body = Buffer.isBuffer(rawData) ? rawData.toString("utf8") : rawData;
359
+ const headersMap = Object.fromEntries(
360
+ Object.entries(headers).map(([k, v]) => [k, String(v)])
361
+ );
362
+ let result = {
363
+ action: utils.PaymentActions.NOT_SUPPORTED
364
+ };
365
+ const statusMap = {
366
+ pending: utils.PaymentActions.PENDING,
367
+ processing: utils.PaymentActions.PENDING,
368
+ requires_action: utils.PaymentActions.REQUIRES_MORE,
369
+ requires_capture: utils.PaymentActions.AUTHORIZED,
370
+ succeeded: utils.PaymentActions.SUCCESSFUL,
371
+ failed: utils.PaymentActions.FAILED,
372
+ canceled: utils.PaymentActions.CANCELED
373
+ };
333
374
  const webhook = this.paykit.webhooks.setup({ webhookSecret: this.options.webhookSecret }).on("payment.created", async (event) => {
334
- return {
335
- action: utils.PaymentActions.PENDING,
375
+ result = {
376
+ action: statusMap[event?.data?.status ?? "pending"],
336
377
  data: {
337
378
  session_id: event.data?.metadata?.session_id,
338
- amount: event.data?.amount
379
+ amount: event.data?.amount ? event.data?.amount * this.options.amountToCentsMultiplier : 0
339
380
  }
340
381
  };
341
382
  }).on("payment.updated", async (event) => {
342
- const statusActionMap = {
343
- pending: utils.PaymentActions.PENDING,
344
- processing: utils.PaymentActions.PENDING,
345
- requires_action: utils.PaymentActions.REQUIRES_MORE,
346
- requires_capture: utils.PaymentActions.AUTHORIZED,
347
- succeeded: utils.PaymentActions.SUCCESSFUL,
348
- failed: utils.PaymentActions.FAILED,
349
- canceled: utils.PaymentActions.CANCELED
350
- };
351
- return {
352
- action: event.data?.status ? statusActionMap[event.data.status] : utils.PaymentActions.PENDING,
383
+ result = {
384
+ action: statusMap[event?.data?.status ?? "pending"],
353
385
  data: {
354
386
  session_id: event.data?.metadata?.session_id,
355
- amount: event.data?.amount
387
+ amount: event.data?.amount ? event.data?.amount * this.options.amountToCentsMultiplier : 0
356
388
  }
357
389
  };
358
- }).on("payment.canceled", async (event) => {
359
- return {
390
+ }).on("payment.failed", async (event) => {
391
+ result = {
360
392
  action: utils.PaymentActions.CANCELED,
361
393
  data: {
362
- session_id: event.data?.metadata?.session_id,
363
- amount: event.data?.amount
394
+ amount: event.data?.amount ? event.data?.amount * this.options.amountToCentsMultiplier : 0,
395
+ session_id: event.data?.metadata?.session_id
364
396
  }
365
397
  };
366
398
  });
367
- const stringifiedHeaders = Object.fromEntries(
368
- Object.entries(headers).map(([key, value]) => [key, String(value)])
369
- );
370
- const webhookEvents = await webhook.handle({
371
- body: bodyString,
372
- headers: new Headers(stringifiedHeaders),
373
- fullUrl: core.getURLFromHeaders(stringifiedHeaders)
399
+ await webhook.handle({
400
+ body,
401
+ headersAsObject: headersMap,
402
+ fullUrl: core.getURLFromHeaders(headersMap)
374
403
  });
375
- return webhookEvents;
404
+ return result;
376
405
  };
377
406
  createAccountHolder = async ({
378
407
  context,
379
408
  data
380
409
  }) => {
410
+ if (context.account_holder?.data?.id) {
411
+ return { id: context.account_holder.data.id };
412
+ }
381
413
  if (this.options.debug) {
382
414
  console.info("[PayKit] Creating account holder", context, data);
383
415
  }
384
- const { customer, account_holder } = context;
385
- if (account_holder?.data?.id) {
386
- return { id: account_holder.data.id };
387
- }
388
- if (!customer) {
389
- throw new utils.MedusaError(
390
- utils.MedusaError.Types.INVALID_DATA,
391
- "Customer not found in context"
392
- );
393
- }
394
- const billingInfoParsed = core.billingSchema.safeParse(data?.billing);
395
- if (data?.billing && !billingInfoParsed.success) {
416
+ const { fullName } = core.parseCustomerName({
417
+ email: context.customer?.email
418
+ });
419
+ const billingInfo = core.billingSchema.safeParse(data?.billing);
420
+ if (data?.billing && !billingInfo.success) {
396
421
  throw new utils.MedusaError(
397
422
  utils.MedusaError.Types.INVALID_DATA,
398
- `Invalid billing information, ${billingInfoParsed.error.message} `
423
+ `Invalid billing information, ${billingInfo.error.message} `
399
424
  );
400
425
  }
401
- const [accountHolderResult, accountHolderError] = await core.tryCatchAsync(
426
+ const res = await this.exec(
402
427
  this.paykit.customers.create({
403
- email: customer.email,
404
- name: customer.email.split("@")[0],
405
- phone: customer.phone,
406
- metadata: {
407
- PAYKIT_METADATA_KEY: JSON.stringify({ source: "medusa-paykit-adapter" })
408
- },
409
- billing: billingInfoParsed.data ?? null
410
- })
428
+ email: context.customer?.email,
429
+ name: fullName,
430
+ phone: context.customer?.phone ?? null,
431
+ billing: billingInfo.data ?? null
432
+ }),
433
+ "Create Account Holder",
434
+ { allowUnsupported: true }
411
435
  );
412
- if (accountHolderError) {
413
- throw new utils.MedusaError(
414
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
415
- accountHolderError.message
416
- );
417
- }
436
+ if (!res) return {};
418
437
  return {
419
- id: accountHolderResult.id,
420
- data: accountHolderResult
438
+ id: res.id,
439
+ data: res
421
440
  };
422
441
  };
423
442
  updateAccountHolder = async ({
@@ -435,27 +454,24 @@ var PaykitMedusaJSAdapter = class extends utils.AbstractPaymentProvider {
435
454
  );
436
455
  }
437
456
  if (!customer) return {};
438
- const accountHolderId = account_holder.data.id;
439
- const [accountHolderResult, accountHolderError] = await core.tryCatchAsync(
440
- this.paykit.customers.update(accountHolderId, {
441
- email: customer.email,
442
- name: customer.email.split("@")[0],
443
- phone: customer.phone,
444
- ...data?.metadata && {
445
- metadata: core.stringifyMetadataValues(
446
- data?.metadata ?? {}
447
- )
448
- },
449
- billing: data?.billing ? core.billingSchema.safeParse(data.billing).data : void 0
450
- })
457
+ const res = await this.exec(
458
+ this.paykit.customers.update(account_holder.data.id, {
459
+ ...data?.billing != null ? {
460
+ billing: core.billingSchema.safeParse(data.billing).data ?? null
461
+ } : {},
462
+ ...data?.email != null ? { email: data.email } : {},
463
+ ...data?.name != null ? { name: data.name } : {},
464
+ ...data?.phone != null ? { phone: data.phone } : {},
465
+ ...data?.metadata != null ? {
466
+ metadata: data.metadata
467
+ } : {},
468
+ ...data?.provider_metadata != null ? {
469
+ provider_metadata: data.provider_metadata
470
+ } : {}
471
+ }),
472
+ "Update Account Holder"
451
473
  );
452
- if (accountHolderError) {
453
- throw new utils.MedusaError(
454
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
455
- accountHolderError.message
456
- );
457
- }
458
- return { data: accountHolderResult };
474
+ return { data: res };
459
475
  };
460
476
  deleteAccountHolder = async ({
461
477
  context,
@@ -471,17 +487,11 @@ var PaykitMedusaJSAdapter = class extends utils.AbstractPaymentProvider {
471
487
  "Account holder not found in context"
472
488
  );
473
489
  }
474
- const accountHolderId = account_holder.data.id;
475
- const [accountHolderResult, accountHolderError] = await core.tryCatchAsync(
476
- this.paykit.customers.delete(accountHolderId)
490
+ const res = await this.exec(
491
+ this.paykit.customers.delete(account_holder.data.id),
492
+ "Delete Account Holder"
477
493
  );
478
- if (accountHolderError) {
479
- throw new utils.MedusaError(
480
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
481
- accountHolderError.message
482
- );
483
- }
484
- return { data: accountHolderResult };
494
+ return { data: res };
485
495
  };
486
496
  };
487
497