@paykit-sdk/comgate 1.0.8 → 1.0.9

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.
@@ -1,4 +1,4 @@
1
- import { schema, AbstractPayKitProvider, HTTPClient, OperationFailedError, createPaymentSchema, isIdCustomer, InvalidTypeError, ProviderNotSupportedError, ValidationError, validateRequiredKeys, capturePaymentSchema, createRefundSchema, WebhookError, paykitEvent$InboundSchema, omitInternalMetadata } from '@paykit-sdk/core';
1
+ import { schema, AbstractPayKitProvider, HTTPClient, OperationFailedError, createPaymentSchema, isEmailCustomer, InvalidTypeError, ProviderNotSupportedError, ValidationError, isIdCustomer, validateRequiredKeys, capturePaymentSchema, createRefundSchema, WebhookError, paykitEvent$InboundSchema, omitInternalMetadata } from '@paykit-sdk/core';
2
2
 
3
3
  var __defProp = Object.defineProperty;
4
4
  var __export = (target, all) => {
@@ -4045,12 +4045,12 @@ var coerce = {
4045
4045
  date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
4046
4046
  };
4047
4047
  var NEVER = INVALID;
4048
- var paykitPayment$InboundSchema = (webhookResponse, status) => {
4048
+ var Payment$inboundSchema = (webhookResponse, status) => {
4049
4049
  return {
4050
4050
  id: webhookResponse.transId,
4051
4051
  amount: webhookResponse.price,
4052
4052
  currency: webhookResponse.curr,
4053
- customer: webhookResponse.payerId ?? { email: webhookResponse.email },
4053
+ customer: webhookResponse.payerId ? { id: webhookResponse.payerId } : { email: webhookResponse.email },
4054
4054
  status,
4055
4055
  metadata: omitInternalMetadata(
4056
4056
  JSON.parse(webhookResponse.refId)
@@ -4060,7 +4060,7 @@ var paykitPayment$InboundSchema = (webhookResponse, status) => {
4060
4060
  payment_url: ""
4061
4061
  };
4062
4062
  };
4063
- var paykitInvoice$InboundSchema = (webhookResponse) => {
4063
+ var Invoice$inboundSchema = (webhookResponse) => {
4064
4064
  const status = (() => {
4065
4065
  if (webhookResponse.status == "PAID") return "paid";
4066
4066
  return "open";
@@ -4071,11 +4071,10 @@ var paykitInvoice$InboundSchema = (webhookResponse) => {
4071
4071
  paid_at: (/* @__PURE__ */ new Date()).toISOString(),
4072
4072
  amount_paid: webhookResponse.price,
4073
4073
  currency: webhookResponse.curr,
4074
- customer: webhookResponse.payerId ?? { email: webhookResponse.email },
4074
+ customer: webhookResponse.payerId ? { id: webhookResponse.payerId } : { email: webhookResponse.email },
4075
4075
  custom_fields: null,
4076
4076
  subscription_id: null,
4077
4077
  billing_mode: "one_time",
4078
- // comgate does not support recurring payments
4079
4078
  line_items: webhookResponse.name ? [{ id: webhookResponse.name, quantity: 1 }] : [],
4080
4079
  metadata: omitInternalMetadata(
4081
4080
  JSON.parse(webhookResponse.refId)
@@ -4107,45 +4106,66 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4107
4106
  },
4108
4107
  retryOptions: { max: 3, baseDelay: 1e3, debug }
4109
4108
  });
4109
+ this.isSandbox = opts.isSandbox;
4110
4110
  }
4111
4111
  providerName = providerName;
4112
4112
  baseUrl;
4113
+ isSandbox;
4113
4114
  _client;
4115
+ get _native() {
4116
+ return null;
4117
+ }
4114
4118
  _throwOnError = (req, message) => {
4115
4119
  if (!req.ok)
4116
4120
  throw new OperationFailedError(message, this.providerName, {
4117
4121
  cause: new Error(req.error)
4118
4122
  });
4119
4123
  if (req.value.code == 1100) {
4120
- throw new OperationFailedError("Unknown error", this.providerName, {
4121
- cause: new Error("Unknown error")
4122
- });
4124
+ throw new OperationFailedError(
4125
+ "Unknown error",
4126
+ this.providerName,
4127
+ {
4128
+ cause: new Error("Unknown error")
4129
+ }
4130
+ );
4123
4131
  }
4124
4132
  if (req.value.code == 1200) {
4125
- throw new OperationFailedError("Database error", this.providerName, {
4126
- cause: new Error("Database error")
4127
- });
4133
+ throw new OperationFailedError(
4134
+ "Database error",
4135
+ this.providerName,
4136
+ {
4137
+ cause: new Error("Database error")
4138
+ }
4139
+ );
4128
4140
  }
4129
4141
  if (req.value.code == 1400) {
4130
- throw new OperationFailedError("Wrong query error", this.providerName, {
4131
- cause: new Error("Wrong query error")
4132
- });
4142
+ throw new OperationFailedError(
4143
+ "Wrong query error",
4144
+ this.providerName,
4145
+ {
4146
+ cause: new Error("Wrong query error")
4147
+ }
4148
+ );
4133
4149
  }
4134
4150
  if (req.value.code == 1500) {
4135
- throw new OperationFailedError("Unexpected error", this.providerName, {
4136
- cause: new Error("Unexpected error")
4137
- });
4151
+ throw new OperationFailedError(
4152
+ "Unexpected error",
4153
+ this.providerName,
4154
+ {
4155
+ cause: new Error("Unexpected error")
4156
+ }
4157
+ );
4138
4158
  }
4139
4159
  return req.value;
4140
4160
  };
4141
4161
  createCheckout = async (params) => {
4142
4162
  const { error, data } = createPaymentSchema.safeParse(params);
4143
4163
  if (error) throw new Error(error.message.split("\n").join(" "));
4144
- if (isIdCustomer(data.customer)) {
4164
+ if (!isEmailCustomer(data.customer)) {
4145
4165
  throw new InvalidTypeError(
4146
4166
  "customer",
4147
- "object (customer) with email",
4148
- "string (customer ID)",
4167
+ "object with email",
4168
+ data.customer === null ? "null" : "object with id",
4149
4169
  {
4150
4170
  provider: this.providerName,
4151
4171
  method: "createCheckout"
@@ -4163,7 +4183,10 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4163
4183
  label: data.provider_metadata?.label ? String(data.provider_metadata.label) : "Order from Eshop"
4164
4184
  });
4165
4185
  if (this.opts.debug) {
4166
- console.log("Creating payment with data:", requestBody.toString());
4186
+ console.log(
4187
+ "Creating payment with data:",
4188
+ requestBody.toString()
4189
+ );
4167
4190
  }
4168
4191
  const response = await this._client.post(
4169
4192
  `/v2.0/paymentRedirect/merchant/${this.opts.merchant}`,
@@ -4172,9 +4195,13 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4172
4195
  }
4173
4196
  );
4174
4197
  if (!response.ok) {
4175
- throw new OperationFailedError(`Failed to create payment`, this.providerName, {
4176
- cause: new Error("Unknown error")
4177
- });
4198
+ throw new OperationFailedError(
4199
+ `Failed to create payment`,
4200
+ this.providerName,
4201
+ {
4202
+ cause: new Error("Unknown error")
4203
+ }
4204
+ );
4178
4205
  }
4179
4206
  this._throwOnError(response, "Failed to create payment");
4180
4207
  return null;
@@ -4192,10 +4219,14 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4192
4219
  });
4193
4220
  };
4194
4221
  retrieveCheckout = async (id) => {
4195
- throw new ProviderNotSupportedError("retrieveCheckout", "Comgate", {
4196
- reason: "Comgate does not support retrieving checkouts, use the payment API instead",
4197
- alternative: "Use the payment API instead"
4198
- });
4222
+ throw new ProviderNotSupportedError(
4223
+ "retrieveCheckout",
4224
+ "Comgate",
4225
+ {
4226
+ reason: "Comgate does not support retrieving checkouts, use the payment API instead",
4227
+ alternative: "Use the payment API instead"
4228
+ }
4229
+ );
4199
4230
  };
4200
4231
  createCustomer = async (params) => {
4201
4232
  throw new ProviderNotSupportedError("createCustomer", "Comgate", {
@@ -4204,10 +4235,14 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4204
4235
  });
4205
4236
  };
4206
4237
  retrieveCustomer = async (id) => {
4207
- throw new ProviderNotSupportedError("retrieveCustomer", "Comgate", {
4208
- reason: "Comgate does not support retrieving customers",
4209
- alternative: "Use the payment API instead"
4210
- });
4238
+ throw new ProviderNotSupportedError(
4239
+ "retrieveCustomer",
4240
+ "Comgate",
4241
+ {
4242
+ reason: "Comgate does not support retrieving customers",
4243
+ alternative: "Use the payment API instead"
4244
+ }
4245
+ );
4211
4246
  };
4212
4247
  updateCustomer = async (id, params) => {
4213
4248
  throw new ProviderNotSupportedError("updateCustomer", "Comgate", {
@@ -4224,28 +4259,41 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4224
4259
  createPayment = async (params) => {
4225
4260
  const { error, data } = createPaymentSchema.safeParse(params);
4226
4261
  if (error) {
4227
- throw ValidationError.fromZodError(error, this.providerName, "createPayment");
4262
+ throw ValidationError.fromZodError(
4263
+ error,
4264
+ this.providerName,
4265
+ "createPayment"
4266
+ );
4228
4267
  }
4229
4268
  const { customer } = data;
4230
- if (typeof customer === "object") {
4231
- throw new InvalidTypeError("customer", "string (customer ID)", "object", {
4232
- provider: this.providerName,
4233
- method: "createPayment"
4234
- });
4269
+ if (!isIdCustomer(customer)) {
4270
+ throw new InvalidTypeError(
4271
+ "customer",
4272
+ "object with id",
4273
+ customer === null ? "null" : "object with email",
4274
+ {
4275
+ provider: this.providerName,
4276
+ method: "createPayment"
4277
+ }
4278
+ );
4235
4279
  }
4280
+ const payerId = String(customer.id);
4236
4281
  const { email, paymentLabel = "Order from Eshop" } = validateRequiredKeys(
4237
4282
  ["email", "paymentLabel"],
4238
4283
  data.provider_metadata ?? {},
4239
4284
  "Missing required provider metadata: {keys}"
4240
4285
  );
4241
4286
  if (this.opts.debug) {
4242
- console.log("Creating payment with metadata:", { email, paymentLabel });
4287
+ console.log("Creating payment with metadata:", {
4288
+ email,
4289
+ paymentLabel
4290
+ });
4243
4291
  }
4244
4292
  const requestBody = new URLSearchParams({
4245
4293
  code: "0",
4246
4294
  test: this.opts.isSandbox ? "true" : "false",
4247
4295
  refId: JSON.stringify(data.metadata ?? {}),
4248
- payerId: customer,
4296
+ payerId,
4249
4297
  price: String(data.amount),
4250
4298
  email,
4251
4299
  curr: String(data.currency),
@@ -4264,9 +4312,12 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4264
4312
  currency: data.currency,
4265
4313
  status: "pending",
4266
4314
  metadata: Object.fromEntries(
4267
- Object.entries(data.metadata ?? {}).map(([key, value]) => [key, String(value)])
4315
+ Object.entries(data.metadata ?? {}).map(([key, value]) => [
4316
+ key,
4317
+ String(value)
4318
+ ])
4268
4319
  ),
4269
- customer,
4320
+ customer: isIdCustomer(customer) ? customer : null,
4270
4321
  item_id: data.item_id ?? null,
4271
4322
  requires_action: false,
4272
4323
  payment_url: response.value.redirect ?? null
@@ -4280,36 +4331,55 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4280
4331
  });
4281
4332
  };
4282
4333
  deletePayment = async (id) => {
4283
- const response = await this._client.delete(`/v2.0/payment/${id}.json`);
4334
+ const response = await this._client.delete(
4335
+ `/v2.0/payment/${id}.json`
4336
+ );
4284
4337
  if (!response.ok) {
4285
- throw new OperationFailedError(`Failed to delete payment`, this.providerName, {
4286
- cause: new Error("Unknown error")
4287
- });
4338
+ throw new OperationFailedError(
4339
+ `Failed to delete payment`,
4340
+ this.providerName,
4341
+ {
4342
+ cause: new Error("Unknown error")
4343
+ }
4344
+ );
4288
4345
  }
4289
4346
  return null;
4290
4347
  };
4291
4348
  retrievePayment = async (id) => {
4292
4349
  const { error } = createPaymentSchema.safeParse({ id });
4293
- if (error) throw new Error(`Payment retrieval validation failed: ${error.message}`);
4350
+ if (error)
4351
+ throw new Error(
4352
+ `Payment retrieval validation failed: ${error.message}`
4353
+ );
4294
4354
  const response = await this._client.get(
4295
4355
  `/v2.0/payment/${id}.json`
4296
4356
  );
4297
4357
  if (!response.ok) {
4298
- throw new OperationFailedError(`Failed to retrieve payment`, this.providerName, {
4299
- cause: new Error("Unknown error")
4300
- });
4358
+ throw new OperationFailedError(
4359
+ `Failed to retrieve payment`,
4360
+ this.providerName,
4361
+ {
4362
+ cause: new Error("Unknown error")
4363
+ }
4364
+ );
4301
4365
  }
4302
4366
  return response.value;
4303
4367
  };
4304
4368
  capturePayment = async (id, params) => {
4305
4369
  const { error, data } = capturePaymentSchema.safeParse(params);
4306
4370
  if (error) {
4307
- throw ValidationError.fromZodError(error, this.providerName, "capturePayment");
4371
+ throw ValidationError.fromZodError(
4372
+ error,
4373
+ this.providerName,
4374
+ "capturePayment"
4375
+ );
4308
4376
  }
4309
4377
  const response = await this._client.post(
4310
4378
  `/v2.0/preauth/${id}/confirm.json`,
4311
4379
  {
4312
- body: new URLSearchParams({ amount: String(data.amount) }).toString()
4380
+ body: new URLSearchParams({
4381
+ amount: String(data.amount)
4382
+ }).toString()
4313
4383
  }
4314
4384
  );
4315
4385
  this._throwOnError(response, "Failed to capture payment");
@@ -4319,7 +4389,7 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4319
4389
  currency: "CZK",
4320
4390
  status: "succeeded",
4321
4391
  metadata: {},
4322
- customer: "",
4392
+ customer: null,
4323
4393
  item_id: null,
4324
4394
  requires_action: false,
4325
4395
  payment_url: response.value.redirect ?? null
@@ -4346,9 +4416,12 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4346
4416
  test: this.opts.isSandbox ? "true" : "false",
4347
4417
  refId: JSON.stringify(data.metadata ?? {})
4348
4418
  });
4349
- const response = await this._client.post("/v2.0/refund.json", {
4350
- body: requestBody.toString()
4351
- });
4419
+ const response = await this._client.post(
4420
+ "/v2.0/refund.json",
4421
+ {
4422
+ body: requestBody.toString()
4423
+ }
4424
+ );
4352
4425
  this._throwOnError(response, "Failed to create refund");
4353
4426
  const refundObject = {
4354
4427
  id: `paykit:refund:${Math.random().toString(36).substring(2, 15)}`,
@@ -4357,7 +4430,10 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4357
4430
  reason: data.reason,
4358
4431
  metadata: {
4359
4432
  ...Object.fromEntries(
4360
- Object.entries(data.metadata ?? {}).map(([key, value]) => [key, String(value)])
4433
+ Object.entries(data.metadata ?? {}).map(([key, value]) => [
4434
+ key,
4435
+ String(value)
4436
+ ])
4361
4437
  ),
4362
4438
  ...response.value?.code ? { __comgate_refund_code: String(response.value.code) } : {},
4363
4439
  ...response.value?.message && {
@@ -4368,48 +4444,68 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4368
4444
  return refundObject;
4369
4445
  };
4370
4446
  createSubscription = async (params) => {
4371
- throw new ProviderNotSupportedError("createSubscription", "Comgate", {
4372
- reason: "Comgate does not support creating subscriptions",
4373
- alternative: "Use the payment API instead and create a subscription manually"
4374
- });
4447
+ throw new ProviderNotSupportedError(
4448
+ "createSubscription",
4449
+ "Comgate",
4450
+ {
4451
+ reason: "Comgate does not support creating subscriptions",
4452
+ alternative: "Use the payment API instead and create a subscription manually"
4453
+ }
4454
+ );
4375
4455
  };
4376
4456
  deleteSubscription = async (id) => {
4377
- throw new ProviderNotSupportedError("deleteSubscription", "Comgate", {
4378
- reason: "Comgate does not support deleting subscriptions",
4379
- alternative: "Use the payment API instead and delete the subscription manually"
4380
- });
4457
+ throw new ProviderNotSupportedError(
4458
+ "deleteSubscription",
4459
+ "Comgate",
4460
+ {
4461
+ reason: "Comgate does not support deleting subscriptions",
4462
+ alternative: "Use the payment API instead and delete the subscription manually"
4463
+ }
4464
+ );
4381
4465
  };
4382
4466
  updateSubscription = async (id, params) => {
4383
- throw new ProviderNotSupportedError("updateSubscription", "Comgate", {
4384
- reason: "Comgate does not support updating subscriptions",
4385
- alternative: "Use the payment API instead and update the subscription manually"
4386
- });
4467
+ throw new ProviderNotSupportedError(
4468
+ "updateSubscription",
4469
+ "Comgate",
4470
+ {
4471
+ reason: "Comgate does not support updating subscriptions",
4472
+ alternative: "Use the payment API instead and update the subscription manually"
4473
+ }
4474
+ );
4387
4475
  };
4388
4476
  retrieveSubscription = async (id) => {
4389
- throw new ProviderNotSupportedError("retrieveSubscription", "Comgate", {
4390
- reason: "Comgate does not support retrieving subscriptions",
4391
- alternative: "Use the payment API instead and retrieve the subscription manually"
4392
- });
4477
+ throw new ProviderNotSupportedError(
4478
+ "retrieveSubscription",
4479
+ "Comgate",
4480
+ {
4481
+ reason: "Comgate does not support retrieving subscriptions",
4482
+ alternative: "Use the payment API instead and retrieve the subscription manually"
4483
+ }
4484
+ );
4393
4485
  };
4394
4486
  cancelSubscription = async (id) => {
4395
- throw new ProviderNotSupportedError("cancelSubscription", "Comgate", {
4396
- reason: "Comgate does not support canceling subscriptions",
4397
- alternative: "Use the payment API instead and cancel the subscription manually"
4398
- });
4487
+ throw new ProviderNotSupportedError(
4488
+ "cancelSubscription",
4489
+ "Comgate",
4490
+ {
4491
+ reason: "Comgate does not support canceling subscriptions",
4492
+ alternative: "Use the payment API instead and cancel the subscription manually"
4493
+ }
4494
+ );
4399
4495
  };
4400
- handleWebhook = async ({
4401
- body: rawBody,
4402
- headers
4403
- }) => {
4496
+ handleWebhook = async (payload, webhookSecret) => {
4497
+ const { body: rawBody, headersAsObject } = payload;
4404
4498
  let body;
4405
- const contentType = headers.get("content-type");
4499
+ const contentType = headersAsObject["content-type"];
4406
4500
  if (contentType === "application/json") {
4407
4501
  body = JSON.parse(rawBody);
4408
4502
  } else {
4409
4503
  body = Object.fromEntries(new URLSearchParams(rawBody));
4410
4504
  }
4411
4505
  if (!body || typeof body !== "object") {
4412
- throw new WebhookError("Invalid webhook payload", { provider: this.providerName });
4506
+ throw new WebhookError("Invalid webhook payload", {
4507
+ provider: this.providerName
4508
+ });
4413
4509
  }
4414
4510
  if (this.opts.debug) {
4415
4511
  console.info("Verifying webhook...");
@@ -4425,7 +4521,9 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4425
4521
  "Missing required webhook parameters: {keys}"
4426
4522
  );
4427
4523
  if (secret !== this.opts.secret) {
4428
- throw new WebhookError("Webhook secret mismatch", { provider: this.providerName });
4524
+ throw new WebhookError("Webhook secret mismatch", {
4525
+ provider: this.providerName
4526
+ });
4429
4527
  }
4430
4528
  if (merchant !== this.opts.merchant) {
4431
4529
  throw new WebhookError("Webhook merchant mismatch", {
@@ -4451,7 +4549,9 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4451
4549
  );
4452
4550
  }
4453
4551
  if (!comgateWebhookApiResponse.status) {
4454
- throw new WebhookError("Failed to verify webhook: no status returned");
4552
+ throw new WebhookError(
4553
+ "Failed to verify webhook: no status returned"
4554
+ );
4455
4555
  }
4456
4556
  if (comgateWebhookApiResponse.status !== webhookStatusOut) {
4457
4557
  throw new WebhookError(
@@ -4467,7 +4567,7 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4467
4567
  const status = statusMap[comgateWebhookApiResponse.status];
4468
4568
  const webhookHandlers = {
4469
4569
  pending: (data) => {
4470
- const payment = paykitPayment$InboundSchema(data, "pending");
4570
+ const payment = Payment$inboundSchema(data, "pending");
4471
4571
  return [
4472
4572
  paykitEvent$InboundSchema({
4473
4573
  type: "payment.created",
@@ -4478,7 +4578,10 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4478
4578
  ];
4479
4579
  },
4480
4580
  requires_capture: (data) => {
4481
- const payment = paykitPayment$InboundSchema(data, "requires_capture");
4581
+ const payment = Payment$inboundSchema(
4582
+ data,
4583
+ "requires_capture"
4584
+ );
4482
4585
  return [
4483
4586
  paykitEvent$InboundSchema({
4484
4587
  type: "payment.updated",
@@ -4489,10 +4592,10 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4489
4592
  ];
4490
4593
  },
4491
4594
  canceled: (data) => {
4492
- const payment = paykitPayment$InboundSchema(data, "canceled");
4595
+ const payment = Payment$inboundSchema(data, "canceled");
4493
4596
  return [
4494
4597
  paykitEvent$InboundSchema({
4495
- type: "payment.canceled",
4598
+ type: "payment.failed",
4496
4599
  created: (/* @__PURE__ */ new Date()).getTime(),
4497
4600
  id: `paykit:payment:${Math.random().toString(36).substring(2, 15)}`,
4498
4601
  data: payment
@@ -4500,11 +4603,11 @@ var ComgateProvider = class extends AbstractPayKitProvider {
4500
4603
  ];
4501
4604
  },
4502
4605
  succeeded: (data) => {
4503
- const invoice = paykitInvoice$InboundSchema(data);
4504
- const payment = paykitPayment$InboundSchema(data, "succeeded");
4606
+ const invoice = Invoice$inboundSchema(data);
4607
+ const payment = Payment$inboundSchema(data, "succeeded");
4505
4608
  return [
4506
4609
  paykitEvent$InboundSchema({
4507
- type: "payment.created",
4610
+ type: "payment.succeeded",
4508
4611
  created: (/* @__PURE__ */ new Date()).getTime(),
4509
4612
  id: `paykit:payment:${Math.random().toString(36).substring(2, 15)}`,
4510
4613
  data: payment