@paykit-sdk/medusajs 1.0.11 → 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,30 +53,49 @@ 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
+ );
75
79
  }
76
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
+ );
96
+ }
97
+ return result;
98
+ }
77
99
  initiatePayment = async ({
78
100
  context,
79
101
  amount,
@@ -83,325 +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
- if (typeof customer === "object" && "email" in customer) {
113
- const customerName = data?.name ? data.name : customer.email.split("@")[0];
114
- 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(
115
141
  this.paykit.customers.create({
116
142
  email: customer.email,
117
- phone: data?.phone ?? "",
118
- name: customerName,
143
+ name: fullName,
144
+ phone: data?.phone ?? null,
145
+ billing: billingInfo.data ?? null,
119
146
  metadata: {
120
- PAYKIT_METADATA_KEY: JSON.stringify({ source: "medusa-paykit-adapter" })
147
+ [core.PAYKIT_METADATA_KEY]: JSON.stringify({
148
+ source: "medusa-paykit-adapter"
149
+ })
121
150
  }
122
- })
151
+ }),
152
+ "Customer Creation",
153
+ { allowUnsupported: true }
123
154
  );
124
- if (createError) {
125
- if (createError.name === "ProviderNotSupportedError") {
126
- if (this.options.debug) {
127
- console.info(
128
- `[PayKit] Provider ${this.provider.providerName} doesn't support customer creation, using email object`
129
- );
130
- }
131
- } else {
132
- throw new utils.MedusaError(
133
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
134
- `Failed to create customer: ${createError.message}`
135
- );
136
- }
137
- } else {
138
- customer = createdCustomer.id;
155
+ if (created) {
156
+ customer = {
157
+ ..."id" in created ? { id: created.id } : {},
158
+ ..."email" in created ? { email: created.email } : {}
159
+ };
139
160
  }
140
- } else {
141
- customer = customer;
142
161
  }
143
- intent.customer = customer;
144
- const [paymentIntentResult, paymentIntentError] = await core.tryCatchAsync(
145
- 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"
146
177
  );
147
- if (paymentIntentError) {
148
- throw new utils.MedusaError(
149
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
150
- paymentIntentError.message
151
- );
152
- }
153
- if (paymentIntentResult.requires_action && paymentIntentResult.payment_url) {
154
- return {
155
- id: paymentIntentResult.id,
156
- status: utils.PaymentSessionStatus.REQUIRES_MORE,
157
- data: {
158
- payment_url: paymentIntentResult.payment_url
159
- }
160
- };
161
- }
162
178
  return {
163
- id: paymentIntentResult.id,
164
- 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 }
165
182
  };
166
183
  };
167
184
  capturePayment = async (input) => {
168
185
  if (this.options.debug) {
169
186
  console.info("[PayKit] Capturing payment", input);
170
187
  }
171
- const { id, amount } = core.validateRequiredKeys(
188
+ const { id: paymentId, amount } = core.validateRequiredKeys(
172
189
  ["id", "amount"],
173
- input?.data ?? {},
190
+ input.data ?? {},
174
191
  "Missing required fields: {keys}",
175
192
  (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
176
193
  );
177
- const [paymentIntentResult, paymentIntentError] = await core.tryCatchAsync(
178
- 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"
179
199
  );
180
- if (paymentIntentError)
181
- throw new utils.MedusaError(
182
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
183
- paymentIntentError.message
184
- );
185
- return { data: paymentIntentResult };
200
+ return {
201
+ data
202
+ };
186
203
  };
187
204
  authorizePayment = async (input) => {
188
- if (this.options.debug) {
189
- 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
+ );
190
220
  }
191
- 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
+ };
192
232
  };
193
233
  cancelPayment = async (input) => {
194
234
  if (this.options.debug) {
195
235
  console.info("[PayKit] Canceling payment", input);
196
236
  }
197
- const { id } = core.validateRequiredKeys(
237
+ const { id: paymentId } = core.validateRequiredKeys(
198
238
  ["id"],
199
- input?.data ?? {},
239
+ input.data ?? {},
200
240
  "Missing required fields: {keys}",
201
241
  (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
202
242
  );
203
- const [paymentIntentResult, paymentIntentError] = await core.tryCatchAsync(
204
- this.paykit.payments.cancel(id)
243
+ const data = await this.exec(
244
+ this.paykit.payments.cancel(paymentId),
245
+ "Cancel"
205
246
  );
206
- if (paymentIntentError)
207
- throw new utils.MedusaError(
208
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
209
- paymentIntentError.message
210
- );
211
- return { data: paymentIntentResult };
247
+ return { data };
212
248
  };
213
249
  deletePayment = async (input) => {
214
- 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 };
215
266
  };
216
267
  getPaymentStatus = async (input) => {
217
- const { id } = core.validateRequiredKeys(
268
+ const { id: paymentId } = core.validateRequiredKeys(
218
269
  ["id"],
219
- input?.data ?? {},
270
+ input.data ?? {},
220
271
  "Missing required fields: {keys}",
221
272
  (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
222
273
  );
223
- const [paymentIntentResult, paymentIntentError] = await core.tryCatchAsync(
224
- this.paykit.payments.retrieve(id)
274
+ const payment = await this.exec(
275
+ this.paykit.payments.retrieve(paymentId),
276
+ "Status"
225
277
  );
226
- if (paymentIntentError)
227
- throw new utils.MedusaError(
228
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
229
- paymentIntentError.message
230
- );
231
- if (!paymentIntentResult)
278
+ if (!payment)
232
279
  throw new utils.MedusaError(
233
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
280
+ utils.MedusaError.Types.NOT_FOUND,
234
281
  "Payment not found"
235
282
  );
236
283
  return {
237
- status: medusaStatus$InboundSchema(paymentIntentResult.status),
238
- data: paymentIntentResult
284
+ status: PaymentStatus$inboundSchema(payment.status),
285
+ data: payment
239
286
  };
240
287
  };
241
288
  refundPayment = async (input) => {
242
289
  if (this.options.debug) {
243
290
  console.info("[PayKit] Refunding payment", input);
244
291
  }
245
- const { id: paymentId } = core.validateRequiredKeys(
246
- ["id"],
247
- input?.data ?? {},
292
+ const { id: paymentId, reason = "customer_request" } = core.validateRequiredKeys(
293
+ ["id", "reason"],
294
+ input.data ?? {},
248
295
  "Missing required fields: {keys}",
249
296
  (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
250
297
  );
251
- const [refundResult, refundError] = await core.tryCatchAsync(
298
+ const refund = await this.exec(
252
299
  this.paykit.refunds.create({
253
300
  payment_id: paymentId,
254
- amount: Number(input.amount),
255
- reason: null,
256
- metadata: input.data?.metadata ? input.data.metadata : null,
257
- provider_metadata: input.data?.provider_metadata ? input.data.provider_metadata : void 0
258
- })
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"
259
307
  );
260
- if (refundError)
261
- throw new utils.MedusaError(
262
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
263
- refundError.message
264
- );
265
- return { data: refundResult };
308
+ return { data: refund };
266
309
  };
267
310
  retrievePayment = async (input) => {
268
311
  if (this.options.debug) {
269
312
  console.info("[PayKit] Retrieving payment", input);
270
313
  }
271
- const { id } = core.validateRequiredKeys(
314
+ const { id: paymentId } = core.validateRequiredKeys(
272
315
  ["id"],
273
- input?.data ?? {},
316
+ input.data ?? {},
274
317
  "Missing required fields: {keys}",
275
318
  (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
276
319
  );
277
- const [paymentIntentResult, paymentIntentError] = await core.tryCatchAsync(
278
- this.paykit.payments.retrieve(id)
320
+ const payment = await this.exec(
321
+ this.paykit.payments.retrieve(paymentId),
322
+ "Retrieve"
279
323
  );
280
- if (paymentIntentError)
281
- throw new utils.MedusaError(
282
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
283
- paymentIntentError.message
284
- );
285
- return { data: paymentIntentResult };
324
+ return { data: payment };
286
325
  };
287
326
  updatePayment = async (input) => {
288
327
  if (this.options.debug) {
289
328
  console.info("[PayKit] Updating payment", input);
290
329
  }
291
- const { amount, currency_code } = core.validateRequiredKeys(
292
- ["amount", "currency_code"],
293
- input,
330
+ const {
331
+ amount,
332
+ id: paymentId,
333
+ currency_code: currencyCode
334
+ } = core.validateRequiredKeys(
335
+ ["amount", "currency_code", "id"],
336
+ input.data ?? {},
294
337
  "Missing required fields: {keys}",
295
338
  (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
296
339
  );
297
- const { id: paymentId } = core.validateRequiredKeys(
298
- ["id"],
299
- input.data,
300
- "Missing required fields: {keys}",
301
- (message) => new utils.MedusaError(utils.MedusaError.Types.INVALID_DATA, message)
302
- );
303
- const metadata = input.data?.metadata ?? {};
304
- const [paymentIntentResult, paymentIntentError] = await core.tryCatchAsync(
340
+ const data = await this.exec(
305
341
  this.paykit.payments.update(paymentId, {
306
- amount: Number(amount),
307
- currency: currency_code,
308
- metadata: core.stringifyMetadataValues(metadata),
309
- provider_metadata: input.data?.provider_metadata ? input.data.provider_metadata : void 0
310
- })
342
+ amount: Number(amount) * this.options.amountToCentsMultiplier,
343
+ currency: currencyCode.toUpperCase(),
344
+ provider_metadata: input.data?.provider_metadata
345
+ }),
346
+ "Update"
311
347
  );
312
- if (paymentIntentError)
313
- throw new utils.MedusaError(
314
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
315
- paymentIntentError.message
316
- );
317
- return { data: paymentIntentResult };
348
+ return { data };
318
349
  };
319
350
  getWebhookActionAndData = async (payload) => {
320
351
  if (this.options.debug) {
321
- console.info("[PayKit] Getting webhook action and data", payload);
352
+ console.info(
353
+ "[PayKit] Resolving webhook action and data",
354
+ payload
355
+ );
322
356
  }
323
357
  const { rawData, headers } = payload;
324
- 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
+ };
325
374
  const webhook = this.paykit.webhooks.setup({ webhookSecret: this.options.webhookSecret }).on("payment.created", async (event) => {
326
- return {
327
- action: utils.PaymentActions.PENDING,
375
+ result = {
376
+ action: statusMap[event?.data?.status ?? "pending"],
328
377
  data: {
329
378
  session_id: event.data?.metadata?.session_id,
330
- amount: event.data?.amount
379
+ amount: event.data?.amount ? event.data?.amount * this.options.amountToCentsMultiplier : 0
331
380
  }
332
381
  };
333
382
  }).on("payment.updated", async (event) => {
334
- const statusActionMap = {
335
- pending: utils.PaymentActions.PENDING,
336
- processing: utils.PaymentActions.PENDING,
337
- requires_action: utils.PaymentActions.REQUIRES_MORE,
338
- requires_capture: utils.PaymentActions.AUTHORIZED,
339
- succeeded: utils.PaymentActions.SUCCESSFUL,
340
- failed: utils.PaymentActions.FAILED,
341
- canceled: utils.PaymentActions.CANCELED
342
- };
343
- return {
344
- action: event.data?.status ? statusActionMap[event.data.status] : utils.PaymentActions.PENDING,
383
+ result = {
384
+ action: statusMap[event?.data?.status ?? "pending"],
345
385
  data: {
346
386
  session_id: event.data?.metadata?.session_id,
347
- amount: event.data?.amount
387
+ amount: event.data?.amount ? event.data?.amount * this.options.amountToCentsMultiplier : 0
348
388
  }
349
389
  };
350
- }).on("payment.canceled", async (event) => {
351
- return {
390
+ }).on("payment.failed", async (event) => {
391
+ result = {
352
392
  action: utils.PaymentActions.CANCELED,
353
393
  data: {
354
- session_id: event.data?.metadata?.session_id,
355
- amount: event.data?.amount
394
+ amount: event.data?.amount ? event.data?.amount * this.options.amountToCentsMultiplier : 0,
395
+ session_id: event.data?.metadata?.session_id
356
396
  }
357
397
  };
358
398
  });
359
- const stringifiedHeaders = Object.fromEntries(
360
- Object.entries(headers).map(([key, value]) => [key, String(value)])
361
- );
362
- const webhookEvents = await webhook.handle({
363
- body: bodyString,
364
- headers: new Headers(stringifiedHeaders),
365
- fullUrl: core.getURLFromHeaders(stringifiedHeaders)
399
+ await webhook.handle({
400
+ body,
401
+ headersAsObject: headersMap,
402
+ fullUrl: core.getURLFromHeaders(headersMap)
366
403
  });
367
- return webhookEvents;
404
+ return result;
368
405
  };
369
406
  createAccountHolder = async ({
370
407
  context,
371
408
  data
372
409
  }) => {
410
+ if (context.account_holder?.data?.id) {
411
+ return { id: context.account_holder.data.id };
412
+ }
373
413
  if (this.options.debug) {
374
414
  console.info("[PayKit] Creating account holder", context, data);
375
415
  }
376
- const { customer, account_holder } = context;
377
- if (account_holder?.data?.id) {
378
- return { id: account_holder.data.id };
379
- }
380
- if (!customer) {
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) {
381
421
  throw new utils.MedusaError(
382
422
  utils.MedusaError.Types.INVALID_DATA,
383
- "Customer not found in context"
423
+ `Invalid billing information, ${billingInfo.error.message} `
384
424
  );
385
425
  }
386
- const [accountHolderResult, accountHolderError] = await core.tryCatchAsync(
426
+ const res = await this.exec(
387
427
  this.paykit.customers.create({
388
- email: customer.email,
389
- name: customer.email.split("@")[0],
390
- phone: customer.phone,
391
- metadata: {
392
- PAYKIT_METADATA_KEY: JSON.stringify({ source: "medusa-paykit-adapter" })
393
- }
394
- })
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 }
395
435
  );
396
- if (accountHolderError) {
397
- throw new utils.MedusaError(
398
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
399
- accountHolderError.message
400
- );
401
- }
436
+ if (!res) return {};
402
437
  return {
403
- id: accountHolderResult.id,
404
- data: accountHolderResult
438
+ id: res.id,
439
+ data: res
405
440
  };
406
441
  };
407
442
  updateAccountHolder = async ({
@@ -411,36 +446,32 @@ var PaykitMedusaJSAdapter = class extends utils.AbstractPaymentProvider {
411
446
  if (this.options.debug) {
412
447
  console.info("[PayKit] Updating account holder", context, data);
413
448
  }
414
- const { account_holder, customer, idempotency_key } = context;
449
+ const { account_holder, customer } = context;
415
450
  if (!account_holder.data?.id) {
416
451
  throw new utils.MedusaError(
417
452
  utils.MedusaError.Types.INVALID_DATA,
418
453
  "Account holder not found in context"
419
454
  );
420
455
  }
421
- if (!customer) {
422
- return {};
423
- }
424
- const accountHolderId = account_holder.data.id;
425
- const [accountHolderResult, accountHolderError] = await core.tryCatchAsync(
426
- this.paykit.customers.update(accountHolderId, {
427
- email: customer.email,
428
- name: customer.email.split("@")[0],
429
- phone: customer.phone,
430
- ...data?.metadata && {
431
- metadata: core.stringifyMetadataValues(
432
- data?.metadata ?? {}
433
- )
434
- }
435
- })
456
+ if (!customer) return {};
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"
436
473
  );
437
- if (accountHolderError) {
438
- throw new utils.MedusaError(
439
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
440
- accountHolderError.message
441
- );
442
- }
443
- return { data: accountHolderResult };
474
+ return { data: res };
444
475
  };
445
476
  deleteAccountHolder = async ({
446
477
  context,
@@ -456,17 +487,11 @@ var PaykitMedusaJSAdapter = class extends utils.AbstractPaymentProvider {
456
487
  "Account holder not found in context"
457
488
  );
458
489
  }
459
- const accountHolderId = account_holder.data.id;
460
- const [accountHolderResult, accountHolderError] = await core.tryCatchAsync(
461
- this.paykit.customers.delete(accountHolderId)
490
+ const res = await this.exec(
491
+ this.paykit.customers.delete(account_holder.data.id),
492
+ "Delete Account Holder"
462
493
  );
463
- if (accountHolderError) {
464
- throw new utils.MedusaError(
465
- utils.MedusaError.Types.PAYMENT_AUTHORIZATION_ERROR,
466
- accountHolderError.message
467
- );
468
- }
469
- return { data: accountHolderResult };
494
+ return { data: res };
470
495
  };
471
496
  };
472
497