@paykit-sdk/gopay 1.1.3 → 1.1.4

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, OAuth2TokenManager, createCheckoutSchema, ValidationError, isEmailCustomer, InvalidTypeError, validateRequiredKeys, PAYKIT_METADATA_KEY, OperationFailedError, ProviderNotSupportedError, createSubscriptionSchema, ConfigurationError, createPaymentSchema, createRefundSchema, WebhookError, tryCatchAsync, paykitEvent$InboundSchema, omitInternalMetadata } from '@paykit-sdk/core';
1
+ import { schema, AbstractPayKitProvider, HTTPClient, OAuth2TokenManager, createCheckoutSchema, ValidationError, isEmailCustomer, InvalidTypeError, validateRequiredKeys, PAYKIT_METADATA_KEY, OperationFailedError, ProviderNotSupportedError, createSubscriptionSchema, isIdCustomer, createPaymentSchema, ConfigurationError, createRefundSchema, WebhookError, tryCatchAsync, paykitEvent$InboundSchema, omitInternalMetadata } from '@paykit-sdk/core';
2
2
  import * as crypto from 'crypto';
3
3
 
4
4
  var __defProp = Object.defineProperty;
@@ -4049,10 +4049,12 @@ var NEVER = INVALID;
4049
4049
  var decodeHtmlEntities = (str) => {
4050
4050
  return str.replace(/"/g, '"').replace(/'/g, "'").replace(/"/g, '"').replace(/'/g, "'");
4051
4051
  };
4052
- var paykitPayment$InboundSchema = (data) => {
4052
+ var Payment$inboundSchema = (data) => {
4053
4053
  const { item } = JSON.parse(
4054
4054
  decodeHtmlEntities(
4055
- data.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4055
+ data.additional_params?.find(
4056
+ (param) => param.name === PAYKIT_METADATA_KEY
4057
+ )?.value ?? "{}"
4056
4058
  )
4057
4059
  );
4058
4060
  const metadata = omitInternalMetadata(
@@ -4079,7 +4081,7 @@ var paykitPayment$InboundSchema = (data) => {
4079
4081
  id: data.id.toString(),
4080
4082
  amount: data.amount,
4081
4083
  currency: data.currency,
4082
- customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4084
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : null,
4083
4085
  status: statusMap[data.state],
4084
4086
  item_id: item,
4085
4087
  metadata,
@@ -4087,10 +4089,12 @@ var paykitPayment$InboundSchema = (data) => {
4087
4089
  payment_url: data.gw_url ?? null
4088
4090
  };
4089
4091
  };
4090
- var paykitCheckout$InboundSchema = (data) => {
4092
+ var Checkout$inboundSchema = (data) => {
4091
4093
  const { item, qty, type } = JSON.parse(
4092
4094
  decodeHtmlEntities(
4093
- data.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4095
+ data.additional_params?.find(
4096
+ (param) => param.name === PAYKIT_METADATA_KEY
4097
+ )?.value ?? "{}"
4094
4098
  )
4095
4099
  );
4096
4100
  const metadata = omitInternalMetadata(
@@ -4106,24 +4110,28 @@ var paykitCheckout$InboundSchema = (data) => {
4106
4110
  id: data.id.toString(),
4107
4111
  amount: data.amount,
4108
4112
  currency: data.currency,
4109
- customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4113
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : null,
4110
4114
  payment_url: data.gw_url ?? "",
4111
4115
  metadata,
4112
4116
  session_type: type,
4113
4117
  products: [{ id: item, quantity: parseInt(qty) }]
4114
4118
  };
4115
4119
  };
4116
- var paykitInvoice$InboundSchema = (data, isSubscription) => {
4120
+ var Invoice$inboundSchema = (data, isSubscription) => {
4117
4121
  const { item, qty } = JSON.parse(
4118
4122
  decodeHtmlEntities(
4119
- data.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4123
+ data.additional_params?.find(
4124
+ (param) => param.name === PAYKIT_METADATA_KEY
4125
+ )?.value ?? "{}"
4120
4126
  )
4121
4127
  );
4122
4128
  const status = (() => {
4123
4129
  if (data.state === "PAID") return "paid";
4124
4130
  return "open";
4125
4131
  })();
4126
- const paidAt = isSubscription ? new Date(data.recurrence?.recurrence_date_to ?? "") : /* @__PURE__ */ new Date();
4132
+ const paidAt = isSubscription ? new Date(
4133
+ data.recurrence?.recurrence_date_to ?? ""
4134
+ ) : /* @__PURE__ */ new Date();
4127
4135
  const metadata = omitInternalMetadata(
4128
4136
  data.additional_params?.reduce(
4129
4137
  (acc, param) => {
@@ -4137,7 +4145,7 @@ var paykitInvoice$InboundSchema = (data, isSubscription) => {
4137
4145
  id: data.id.toString(),
4138
4146
  amount_paid: data.amount,
4139
4147
  currency: data.currency,
4140
- customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4148
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : null,
4141
4149
  status,
4142
4150
  paid_at: paidAt.toISOString(),
4143
4151
  metadata: metadata ?? {},
@@ -4147,10 +4155,12 @@ var paykitInvoice$InboundSchema = (data, isSubscription) => {
4147
4155
  line_items: [{ id: item, quantity: parseInt(qty) }]
4148
4156
  };
4149
4157
  };
4150
- var paykitSubscription$InboundSchema = (data) => {
4158
+ var Subscription$inboundSchema = (data) => {
4151
4159
  const { item } = JSON.parse(
4152
4160
  decodeHtmlEntities(
4153
- data.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4161
+ data.additional_params?.find(
4162
+ (param) => param.name === PAYKIT_METADATA_KEY
4163
+ )?.value ?? "{}"
4154
4164
  )
4155
4165
  );
4156
4166
  const billingIntervalMap = {
@@ -4162,7 +4172,9 @@ var paykitSubscription$InboundSchema = (data) => {
4162
4172
  const billingInterval = billingIntervalMap[data.recurrence?.recurrence_cycle ?? "ON_DEMAND"];
4163
4173
  const recurrencePeriod = data.recurrence?.recurrence_period ?? 1;
4164
4174
  const recurrenceCycle = data.recurrence?.recurrence_cycle;
4165
- const currentPeriodEnd = new Date(data.recurrence?.recurrence_date_to ?? "");
4175
+ const currentPeriodEnd = new Date(
4176
+ data.recurrence?.recurrence_date_to ?? ""
4177
+ );
4166
4178
  const currentPeriodStart = (() => {
4167
4179
  if (!currentPeriodEnd) return /* @__PURE__ */ new Date();
4168
4180
  const endDate = new Date(currentPeriodEnd);
@@ -4192,21 +4204,21 @@ var paykitSubscription$InboundSchema = (data) => {
4192
4204
  ) ?? {}
4193
4205
  );
4194
4206
  const requiresAction = data.state === "CREATED" ? true : false;
4195
- const status = (() => {
4196
- if (data.state === "CREATED") return "pending";
4197
- if (data.state === "PAID") return "active";
4198
- if (data.state === "CANCELED") return "canceled";
4199
- if (data.state === "TIMEOUTED") return "canceled";
4200
- if (data.state === "REFUNDED") return "canceled";
4201
- if (data.state === "PARTIALLY_REFUNDED") return "canceled";
4202
- if (data.state === "AUTHORIZED") return "active";
4203
- if (data.state === "PAYMENT_METHOD_CHOSEN") return "active";
4204
- return "pending";
4205
- })();
4207
+ const subscriptionStatusMap = {
4208
+ CREATED: "pending",
4209
+ PAID: "active",
4210
+ CANCELED: "canceled",
4211
+ TIMEOUTED: "canceled",
4212
+ REFUNDED: "canceled",
4213
+ PARTIALLY_REFUNDED: "canceled",
4214
+ AUTHORIZED: "active",
4215
+ PAYMENT_METHOD_CHOSEN: "active"
4216
+ };
4217
+ const status = subscriptionStatusMap[data.state] ?? "expired";
4206
4218
  return {
4207
4219
  id: data.id.toString(),
4208
4220
  status,
4209
- customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4221
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : null,
4210
4222
  item_id: item,
4211
4223
  billing_interval: billingInterval,
4212
4224
  currency: data.currency,
@@ -4219,7 +4231,7 @@ var paykitSubscription$InboundSchema = (data) => {
4219
4231
  payment_url: requiresAction ? data.gw_url ?? null : null
4220
4232
  };
4221
4233
  };
4222
- var paykitRefund$InboundSchema = (data) => {
4234
+ var Refund$inboundSchema = (data) => {
4223
4235
  return {
4224
4236
  id: data.id.toString(),
4225
4237
  amount: data.amount,
@@ -4245,6 +4257,7 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4245
4257
  constructor(opts) {
4246
4258
  super(gopayOptionsSchema, opts, providerName);
4247
4259
  this.opts = opts;
4260
+ this.isSandbox = opts.isSandbox;
4248
4261
  const debug = opts.debug ?? true;
4249
4262
  this.baseUrl = opts.isSandbox ? "https://gw.sandbox.gopay.com/api" : "https://gate.gopay.cz/api";
4250
4263
  this._client = new HTTPClient({
@@ -4256,7 +4269,10 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4256
4269
  client: this._client,
4257
4270
  provider: this.providerName,
4258
4271
  tokenEndpoint: "/oauth2/token",
4259
- credentials: { username: opts.clientId, password: opts.clientSecret },
4272
+ credentials: {
4273
+ username: opts.clientId,
4274
+ password: opts.clientSecret
4275
+ },
4260
4276
  responseAdapter: (response) => ({
4261
4277
  accessToken: response.access_token,
4262
4278
  expiresIn: response.expires_in
@@ -4277,15 +4293,30 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4277
4293
  providerName = providerName;
4278
4294
  _client;
4279
4295
  baseUrl;
4296
+ isSandbox;
4280
4297
  tokenManager;
4298
+ get _native() {
4299
+ return null;
4300
+ }
4281
4301
  createCheckout = async (params) => {
4282
4302
  const { error, data } = createCheckoutSchema.safeParse(params);
4283
- if (error) throw ValidationError.fromZodError(error, "gopay", "createCheckout");
4303
+ if (error) {
4304
+ throw ValidationError.fromZodError(
4305
+ error,
4306
+ "gopay",
4307
+ "createCheckout"
4308
+ );
4309
+ }
4284
4310
  if (!isEmailCustomer(data.customer)) {
4285
- throw new InvalidTypeError("customer", "object (customer) with email", "string", {
4286
- provider: this.providerName,
4287
- method: "createCheckout"
4288
- });
4311
+ throw new InvalidTypeError(
4312
+ "customer",
4313
+ "object (customer) with email",
4314
+ "string",
4315
+ {
4316
+ provider: this.providerName,
4317
+ method: "createCheckout"
4318
+ }
4319
+ );
4289
4320
  }
4290
4321
  const { amount, currency = "CZK" } = validateRequiredKeys(
4291
4322
  ["amount", "currency"],
@@ -4312,9 +4343,9 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4312
4343
  },
4313
4344
  target: { type: "ACCOUNT", goid: parseInt(this.opts.goId) },
4314
4345
  amount: Number(amount),
4315
- currency,
4346
+ currency: currency.toUpperCase(),
4316
4347
  order_number: crypto.randomBytes(8).toString("hex").slice(0, 15),
4317
- order_description: data.metadata?.description || "Checkout",
4348
+ order_description: `Payment for ${data.item_id} by ${data.customer.email}`,
4318
4349
  items: [
4319
4350
  {
4320
4351
  name: data.item_id,
@@ -4324,7 +4355,10 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4324
4355
  }
4325
4356
  ],
4326
4357
  lang: data.provider_metadata?.language ? data.provider_metadata.language : "EN",
4327
- callback: { return_url: data.success_url, notification_url: this.opts.webhookUrl },
4358
+ callback: {
4359
+ return_url: data.success_url,
4360
+ notification_url: this.opts.webhookUrl
4361
+ },
4328
4362
  additional_params: Object.entries({
4329
4363
  ...data.metadata,
4330
4364
  [PAYKIT_METADATA_KEY]: JSON.stringify({
@@ -4345,11 +4379,15 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4345
4379
  }
4346
4380
  );
4347
4381
  if (!response.ok) {
4348
- throw new OperationFailedError("createCheckout", this.providerName, {
4349
- cause: new Error("Failed to create checkout")
4350
- });
4382
+ throw new OperationFailedError(
4383
+ "createCheckout",
4384
+ this.providerName,
4385
+ {
4386
+ cause: new Error("Failed to create checkout")
4387
+ }
4388
+ );
4351
4389
  }
4352
- return paykitCheckout$InboundSchema(response.value);
4390
+ return Checkout$inboundSchema(response.value);
4353
4391
  };
4354
4392
  retrieveCheckout = async (id) => {
4355
4393
  const response = await this._client.get(
@@ -4362,11 +4400,15 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4362
4400
  }
4363
4401
  );
4364
4402
  if (!response.ok) {
4365
- throw new OperationFailedError("retrieveCheckout", this.providerName, {
4366
- cause: new Error("Failed to retrieve checkout")
4367
- });
4403
+ throw new OperationFailedError(
4404
+ "retrieveCheckout",
4405
+ this.providerName,
4406
+ {
4407
+ cause: new Error("Failed to retrieve checkout")
4408
+ }
4409
+ );
4368
4410
  }
4369
- return paykitCheckout$InboundSchema(response.value);
4411
+ return Checkout$inboundSchema(response.value);
4370
4412
  };
4371
4413
  updateCheckout = async (id, params) => {
4372
4414
  if (this.opts.debug) {
@@ -4405,57 +4447,95 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4405
4447
  };
4406
4448
  createSubscription = async (params) => {
4407
4449
  const { error, data } = createSubscriptionSchema.safeParse(params);
4408
- if (error) throw ValidationError.fromZodError(error, "gopay", "createSubscription");
4409
- if (typeof data.customer == "string" || typeof data.customer === "object" && !data.customer.email) {
4410
- throw new InvalidTypeError("customer", "object (customer) with email", "string", {
4411
- provider: this.providerName,
4412
- method: "createCheckout"
4413
- });
4450
+ if (error)
4451
+ throw ValidationError.fromZodError(
4452
+ error,
4453
+ "gopay",
4454
+ "createSubscription"
4455
+ );
4456
+ if (!isEmailCustomer(data.customer)) {
4457
+ throw new InvalidTypeError(
4458
+ "customer",
4459
+ "object with email",
4460
+ isIdCustomer(data.customer) ? "object with id" : typeof data.customer,
4461
+ {
4462
+ provider: this.providerName,
4463
+ method: "createSubscription"
4464
+ }
4465
+ );
4414
4466
  }
4415
4467
  const { success_url } = validateRequiredKeys(
4416
4468
  ["success_url"],
4417
4469
  data.provider_metadata,
4418
- "The following fields must be present in the provider_metadata of createCheckout: {keys}"
4470
+ "The following fields must be present in the provider_metadata of createSubscription: {keys}"
4419
4471
  );
4472
+ const billingInterval = data.billing_interval;
4473
+ const isCustom = typeof billingInterval === "object" && billingInterval.type === "custom";
4474
+ const isYear = billingInterval === "year";
4475
+ const isOnDemand = isCustom || isYear;
4476
+ const intervalMap = {
4477
+ day: "DAY",
4478
+ week: "WEEK",
4479
+ month: "MONTH",
4480
+ year: "ON_DEMAND"
4481
+ };
4482
+ const recurrenceCycle = isCustom ? "ON_DEMAND" : intervalMap[billingInterval];
4420
4483
  if (this.opts.debug) {
4421
- if (data.billing_interval === "year") {
4484
+ if (isYear) {
4485
+ console.info(
4486
+ "[PayKit/GoPay] GoPay does not support yearly recurrence. Falling back to ON_DEMAND \u2014 you must trigger each charge manually via createRecurrence(parentPaymentId, ...). See: https://doc.gopay.com/#recurring-on-demand"
4487
+ );
4488
+ }
4489
+ if (isCustom) {
4490
+ const durationMs = billingInterval.durationMs;
4491
+ console.info(
4492
+ `[PayKit/GoPay] Custom interval (${durationMs}ms) is not supported by GoPay. Falling back to ON_DEMAND \u2014 trigger charges manually via createRecurrence(parentPaymentId, ...). See: https://doc.gopay.com/#recurring-on-demand`
4493
+ );
4494
+ }
4495
+ if (!isOnDemand) {
4496
+ console.info(
4497
+ `[PayKit/GoPay] AUTO recurrence (${recurrenceCycle}) \u2014 GoPay charges automatically each cycle. No createRecurrence() call is needed. Set provider_metadata.end_date (ISO string, e.g. "2027-01-01") to control when the subscription ends. Defaults to 1 year from today.`
4498
+ );
4499
+ } else {
4422
4500
  console.info(
4423
- "GoPay does not support yearly subscriptions, the available options are `day`, `week`, `month` and `ON_DEMAND` \n raise an issue at https://github.com/usepaykit/paykit-sdk/issues if you need this feature"
4501
+ "[PayKit/GoPay] ON_DEMAND recurrence \u2014 you MUST call createRecurrence(parentPaymentId, ...) for each subsequent charge. GoPay will NOT charge automatically. Set provider_metadata.end_date (ISO string) to control the authorization window. Defaults to 1 year (custom interval) or 5 years (yearly interval)."
4424
4502
  );
4425
4503
  }
4426
4504
  if (!data.provider_metadata?.description) {
4427
4505
  console.info(
4428
- `No description provided for the subscription \`provider_metadata.description\`, using default description \`Subscription by ${data.customer.email}\``
4506
+ `[PayKit/GoPay] No \`provider_metadata.description\` provided. Using default: "Subscription by ${data.customer.email}"`
4429
4507
  );
4430
4508
  }
4431
4509
  }
4432
- const intervalMap = {
4433
- day: "DAY",
4434
- week: "WEEK",
4435
- month: "MONTH",
4436
- year: "ON_DEMAND"
4510
+ const toDateString = (ms) => {
4511
+ const d = new Date(ms);
4512
+ return d.toISOString().split("T")[0];
4437
4513
  };
4438
- const recurrenceCycle = intervalMap?.[data.billing_interval] ?? "ON_DEMAND";
4439
- const currentPeriodEnd = (() => {
4440
- if (recurrenceCycle === "DAY") {
4441
- return new Date(Date.now() + 1 * 24 * 60 * 60 * 1e3).toISOString();
4442
- }
4443
- if (recurrenceCycle === "WEEK") {
4444
- return new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3).toISOString();
4445
- }
4446
- if (recurrenceCycle === "MONTH") {
4447
- return new Date(Date.now() + 30 * 24 * 60 * 60 * 1e3).toISOString();
4514
+ const GOPAY_MAX_DATE = "2099-12-30";
4515
+ const endDateOverride = data.provider_metadata?.end_date;
4516
+ const recurrenceDateTo = (() => {
4517
+ if (endDateOverride) {
4518
+ return endDateOverride < GOPAY_MAX_DATE ? endDateOverride : GOPAY_MAX_DATE;
4448
4519
  }
4449
4520
  if (recurrenceCycle === "ON_DEMAND") {
4450
- throw new ConfigurationError(
4451
- "ON_DEMAND subscriptions is not yet implemented by PayKit, please open an issue at https://github.com/usepaykit/paykit-sdk/issues",
4452
- {
4453
- provider: this.providerName
4454
- }
4521
+ if (isCustom) {
4522
+ return toDateString(Date.now() + 365 * 24 * 60 * 60 * 1e3);
4523
+ }
4524
+ return toDateString(
4525
+ Date.now() + 5 * 365 * 24 * 60 * 60 * 1e3
4455
4526
  );
4456
4527
  }
4457
- throw new Error("Invalid billing interval: " + data.billing_interval);
4528
+ return toDateString(Date.now() + 365 * 24 * 60 * 60 * 1e3);
4458
4529
  })();
4530
+ const recurrencePeriod = data.provider_metadata?.recurrence_period ?? 1;
4531
+ const recurrence = isOnDemand ? {
4532
+ recurrence_cycle: recurrenceCycle,
4533
+ recurrence_date_to: recurrenceDateTo
4534
+ } : {
4535
+ recurrence_cycle: recurrenceCycle,
4536
+ recurrence_period: recurrencePeriod,
4537
+ recurrence_date_to: recurrenceDateTo
4538
+ };
4459
4539
  const goPaySubscriptionOptions = {
4460
4540
  payer: {
4461
4541
  allowed_payment_instruments: ["PAYMENT_CARD"],
@@ -4466,24 +4546,28 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4466
4546
  amount: Number(data.amount),
4467
4547
  currency: data.currency ?? "CZK",
4468
4548
  order_number: crypto.randomBytes(8).toString("hex").slice(0, 15),
4469
- order_description: data.provider_metadata?.description ? data.provider_metadata.description : "Subscription by " + data.customer.email,
4470
- items: [{ name: data.item_id, amount: Number(data.amount), count: data.quantity }],
4471
- recurrence: {
4472
- recurrence_cycle: recurrenceCycle,
4473
- recurrence_period: data.quantity,
4474
- recurrence_date_to: currentPeriodEnd
4549
+ order_description: data.provider_metadata?.description ? data.provider_metadata.description : `Subscription by ${data.customer.email}`,
4550
+ items: [
4551
+ {
4552
+ name: data.item_id,
4553
+ amount: Number(data.amount),
4554
+ count: data.quantity ?? 1
4555
+ }
4556
+ ],
4557
+ recurrence,
4558
+ callback: {
4559
+ return_url: success_url,
4560
+ notification_url: this.opts.webhookUrl
4475
4561
  },
4476
- callback: { return_url: success_url, notification_url: this.opts.webhookUrl },
4477
4562
  additional_params: Object.entries({
4478
4563
  ...data.metadata,
4479
4564
  [PAYKIT_METADATA_KEY]: JSON.stringify({
4480
4565
  item: data.item_id,
4481
- qty: data.quantity
4566
+ qty: data.quantity,
4567
+ // Store the original interval so createRecurrence callers know the intended cadence
4568
+ billing_interval: isCustom ? `custom:${billingInterval.durationMs}ms` : billingInterval
4482
4569
  })
4483
- }).map(([name, value]) => ({
4484
- name,
4485
- value: String(value)
4486
- }))
4570
+ }).map(([name, value]) => ({ name, value: String(value) }))
4487
4571
  };
4488
4572
  const response = await this._client.post(
4489
4573
  "/payments/payment",
@@ -4493,28 +4577,42 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4493
4577
  }
4494
4578
  );
4495
4579
  if (!response.ok) {
4496
- throw new OperationFailedError("createSubscription", this.providerName, {
4497
- cause: new Error("Failed to create subscription")
4498
- });
4580
+ throw new OperationFailedError(
4581
+ "createSubscription",
4582
+ this.providerName,
4583
+ {
4584
+ cause: new Error(
4585
+ `[PayKit/GoPay] Failed to create subscription. Error: ${response.error}`
4586
+ )
4587
+ }
4588
+ );
4499
4589
  }
4500
- return paykitSubscription$InboundSchema(response.value);
4590
+ return Subscription$inboundSchema(response.value);
4501
4591
  };
4502
4592
  updateSubscription = async (id, params) => {
4503
4593
  const subscription = await this.retrieveSubscription(id);
4504
4594
  if (!subscription) {
4505
- throw new ProviderNotSupportedError("updateSubscription", this.providerName, {
4506
- reason: "Gopay doesn't support updating subscriptions",
4507
- alternative: "Use the payment API instead and update the subscription manually"
4508
- });
4595
+ throw new ProviderNotSupportedError(
4596
+ "updateSubscription",
4597
+ this.providerName,
4598
+ {
4599
+ reason: "Gopay doesn't support updating subscriptions",
4600
+ alternative: "Use the payment API instead and update the subscription manually"
4601
+ }
4602
+ );
4509
4603
  }
4510
4604
  return subscription;
4511
4605
  };
4512
4606
  cancelSubscription = async (id) => {
4513
4607
  const existingSubscription = await this.retrieveSubscription(id);
4514
4608
  if (!existingSubscription) {
4515
- throw new OperationFailedError("cancelSubscription", this.providerName, {
4516
- cause: new Error("Failed to retrieve subscription")
4517
- });
4609
+ throw new OperationFailedError(
4610
+ "cancelSubscription",
4611
+ this.providerName,
4612
+ {
4613
+ cause: new Error("Failed to retrieve subscription")
4614
+ }
4615
+ );
4518
4616
  }
4519
4617
  const response = await this._client.post(`/payments/payment/${id}/void-recurrence`, {
4520
4618
  headers: {
@@ -4524,7 +4622,9 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4524
4622
  });
4525
4623
  return {
4526
4624
  ...existingSubscription,
4527
- ...response.value?.result == "FINISHED" && { status: "canceled" }
4625
+ ...response.value?.result == "FINISHED" && {
4626
+ status: "canceled"
4627
+ }
4528
4628
  };
4529
4629
  };
4530
4630
  deleteSubscription = async (id) => {
@@ -4539,21 +4639,35 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4539
4639
  }
4540
4640
  );
4541
4641
  if (!response.ok) {
4542
- throw new OperationFailedError("retrieveSubscription", this.providerName, {
4543
- cause: new Error("Failed to retrieve subscription")
4544
- });
4642
+ throw new OperationFailedError(
4643
+ "retrieveSubscription",
4644
+ this.providerName,
4645
+ {
4646
+ cause: new Error("Failed to retrieve subscription")
4647
+ }
4648
+ );
4545
4649
  }
4546
- return paykitSubscription$InboundSchema(response.value);
4650
+ return Subscription$inboundSchema(response.value);
4547
4651
  };
4548
4652
  createPayment = async (params) => {
4549
4653
  const { error, data } = createPaymentSchema.safeParse(params);
4550
- if (error)
4551
- throw ValidationError.fromZodError(error, this.providerName, "createPayment");
4552
- if (typeof data.customer == "string" || typeof data.customer === "object" && !data.customer?.email) {
4553
- throw new InvalidTypeError("customer", "object (customer) with email", "string", {
4554
- provider: this.providerName,
4555
- method: "createPayment"
4556
- });
4654
+ if (error) {
4655
+ throw ValidationError.fromZodError(
4656
+ error,
4657
+ this.providerName,
4658
+ "createPayment"
4659
+ );
4660
+ }
4661
+ if (!isEmailCustomer(data.customer)) {
4662
+ throw new InvalidTypeError(
4663
+ "customer",
4664
+ "object with email",
4665
+ isIdCustomer(data.customer) ? "object with id" : typeof data.customer,
4666
+ {
4667
+ provider: this.providerName,
4668
+ method: "createPayment"
4669
+ }
4670
+ );
4557
4671
  }
4558
4672
  if (!data.item_id) {
4559
4673
  throw new ConfigurationError(
@@ -4578,20 +4692,40 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4578
4692
  payer: {
4579
4693
  allowed_payment_instruments: ["PAYMENT_CARD", "BANK_ACCOUNT"],
4580
4694
  default_payment_instrument: "PAYMENT_CARD",
4581
- contact: { email: data.customer.email }
4695
+ contact: { email: data.customer.email },
4696
+ ...data.billing && {
4697
+ city: data.billing.address.city,
4698
+ postal_code: data.billing.address.postal_code,
4699
+ country_code: data.billing.address.country,
4700
+ phone_number: data.billing.address.phone
4701
+ }
4582
4702
  },
4583
- callback: { return_url: successUrl, notification_url: this.opts.webhookUrl },
4584
4703
  target: { type: "ACCOUNT", goid: parseInt(this.opts.goId) },
4585
- amount: data.amount,
4704
+ amount: Number(data.amount),
4586
4705
  currency: data.currency ?? "CZK",
4587
4706
  order_number: crypto.randomBytes(8).toString("hex").slice(0, 15),
4588
4707
  order_description: `Payment for ${data.item_id} by ${data.customer.email}`,
4589
- items: [{ name: data.item_id, amount: data.amount, count: 1 }],
4708
+ items: [
4709
+ {
4710
+ name: data.item_id,
4711
+ amount: data.amount,
4712
+ count: 1,
4713
+ type: "ITEM"
4714
+ }
4715
+ ],
4716
+ lang: data.provider_metadata?.language ? data.provider_metadata.language : "EN",
4717
+ callback: {
4718
+ return_url: successUrl,
4719
+ notification_url: this.opts.webhookUrl
4720
+ },
4590
4721
  preauthorization: false,
4591
4722
  // automatically captures the payment
4592
4723
  additional_params: Object.entries({
4593
4724
  ...data.metadata,
4594
- [PAYKIT_METADATA_KEY]: JSON.stringify({ itemId: data.item_id, qty: 1 })
4725
+ [PAYKIT_METADATA_KEY]: JSON.stringify({
4726
+ itemId: data.item_id,
4727
+ qty: 1
4728
+ })
4595
4729
  }).map(([name, value]) => ({
4596
4730
  name,
4597
4731
  value: String(value)
@@ -4605,11 +4739,17 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4605
4739
  }
4606
4740
  );
4607
4741
  if (!response.ok) {
4608
- throw new OperationFailedError("createPayment", this.providerName, {
4609
- cause: new Error("Failed to create payment")
4610
- });
4742
+ throw new OperationFailedError(
4743
+ "createPayment",
4744
+ this.providerName,
4745
+ {
4746
+ cause: new Error(
4747
+ `Failed to create payment: ${JSON.stringify(response.error ?? response)}`
4748
+ )
4749
+ }
4750
+ );
4611
4751
  }
4612
- return paykitPayment$InboundSchema(response.value);
4752
+ return Payment$inboundSchema(response.value);
4613
4753
  };
4614
4754
  retrievePayment = async (id) => {
4615
4755
  const response = await this._client.get(
@@ -4622,17 +4762,25 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4622
4762
  }
4623
4763
  );
4624
4764
  if (!response.ok) {
4625
- throw new OperationFailedError("retrievePayment", this.providerName, {
4626
- cause: new Error("Failed to retrieve payment")
4627
- });
4765
+ throw new OperationFailedError(
4766
+ "retrievePayment",
4767
+ this.providerName,
4768
+ {
4769
+ cause: new Error("Failed to retrieve payment")
4770
+ }
4771
+ );
4628
4772
  }
4629
- return paykitPayment$InboundSchema(response.value);
4773
+ return Payment$inboundSchema(response.value);
4630
4774
  };
4631
4775
  deletePayment = async (id) => {
4632
- throw new ProviderNotSupportedError("deletePayment", this.providerName, {
4633
- reason: "GoPay does not support deleting payments, use the",
4634
- alternative: "Use createRefund() instead to refund payments"
4635
- });
4776
+ throw new ProviderNotSupportedError(
4777
+ "deletePayment",
4778
+ this.providerName,
4779
+ {
4780
+ reason: "GoPay does not support deleting payments, use the",
4781
+ alternative: "Use createRefund() instead to refund payments"
4782
+ }
4783
+ );
4636
4784
  };
4637
4785
  capturePayment = async (id, params) => {
4638
4786
  const payment = await this._client.get(
@@ -4640,32 +4788,39 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4640
4788
  { headers: await this.tokenManager.getAuthHeaders() }
4641
4789
  );
4642
4790
  if (!payment.ok) {
4643
- throw new OperationFailedError("capturePayment", this.providerName, {
4644
- cause: new Error("Failed to retrieve payment")
4645
- });
4791
+ throw new OperationFailedError(
4792
+ "capturePayment",
4793
+ this.providerName,
4794
+ {
4795
+ cause: new Error("Failed to retrieve payment")
4796
+ }
4797
+ );
4646
4798
  }
4647
4799
  const { item, qty } = JSON.parse(
4648
4800
  decodeHtmlEntities(
4649
- payment.value.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4801
+ payment.value.additional_params?.find(
4802
+ (param) => param.name === PAYKIT_METADATA_KEY
4803
+ )?.value ?? "{}"
4650
4804
  )
4651
4805
  );
4652
4806
  if (!payment) {
4653
- throw new OperationFailedError("capturePayment", this.providerName, {
4654
- cause: new Error("Payment not found after capture")
4655
- });
4807
+ throw new OperationFailedError(
4808
+ "capturePayment",
4809
+ this.providerName,
4810
+ {
4811
+ cause: new Error("Payment not found after capture")
4812
+ }
4813
+ );
4656
4814
  }
4657
4815
  const captureBody = {
4658
4816
  amount: params.amount,
4659
4817
  items: [{ name: item, amount: params.amount, count: qty }]
4660
4818
  };
4661
- await this._client.post(
4662
- `/payments/payment/${id}/capture`,
4663
- {
4664
- body: JSON.stringify(captureBody),
4665
- headers: await this.tokenManager.getAuthHeaders()
4666
- }
4667
- );
4668
- return paykitPayment$InboundSchema(payment.value);
4819
+ await this._client.post(`/payments/payment/${id}/capture`, {
4820
+ body: JSON.stringify(captureBody),
4821
+ headers: await this.tokenManager.getAuthHeaders()
4822
+ });
4823
+ return Payment$inboundSchema(payment.value);
4669
4824
  };
4670
4825
  cancelPayment = async (id) => {
4671
4826
  await this._client.post(
@@ -4674,9 +4829,13 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4674
4829
  );
4675
4830
  const payment = await this.retrievePayment(id);
4676
4831
  if (!payment) {
4677
- throw new OperationFailedError("cancelPayment", this.providerName, {
4678
- cause: new Error("Payment not found after cancellation")
4679
- });
4832
+ throw new OperationFailedError(
4833
+ "cancelPayment",
4834
+ this.providerName,
4835
+ {
4836
+ cause: new Error("Payment not found after cancellation")
4837
+ }
4838
+ );
4680
4839
  }
4681
4840
  return payment;
4682
4841
  };
@@ -4687,34 +4846,52 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4687
4846
  console.info("Gopay doesn't support updating payments");
4688
4847
  const existing = await this.retrievePayment(id);
4689
4848
  if (!existing) {
4690
- throw new OperationFailedError("updatePayment", this.providerName, {
4691
- cause: new Error("Failed to retrieve payment")
4692
- });
4849
+ throw new OperationFailedError(
4850
+ "updatePayment",
4851
+ this.providerName,
4852
+ {
4853
+ cause: new Error("Failed to retrieve payment")
4854
+ }
4855
+ );
4693
4856
  }
4694
4857
  return existing;
4695
4858
  };
4696
4859
  async createRefund(params) {
4697
4860
  const { error, data } = createRefundSchema.safeParse(params);
4698
4861
  if (error) {
4699
- throw ValidationError.fromZodError(error, this.providerName, "createRefund");
4862
+ throw ValidationError.fromZodError(
4863
+ error,
4864
+ this.providerName,
4865
+ "createRefund"
4866
+ );
4700
4867
  }
4701
4868
  const payment = await this.retrievePayment(data.payment_id);
4702
4869
  if (!payment) {
4703
- throw new OperationFailedError("createRefund", this.providerName, {
4704
- cause: new Error("Failed to retrieve payment")
4705
- });
4870
+ throw new OperationFailedError(
4871
+ "createRefund",
4872
+ this.providerName,
4873
+ {
4874
+ cause: new Error("Failed to retrieve payment")
4875
+ }
4876
+ );
4706
4877
  }
4707
4878
  const response = await this._client.post(`/payments/payment/${data.payment_id}/refund`, {
4708
- body: new URLSearchParams({ amount: String(data.amount) }).toString(),
4879
+ body: new URLSearchParams({
4880
+ amount: String(data.amount)
4881
+ }).toString(),
4709
4882
  headers: {
4710
4883
  ...await this.tokenManager.getAuthHeaders(),
4711
4884
  "Content-Type": "application/x-www-form-urlencoded"
4712
4885
  }
4713
4886
  });
4714
4887
  if (!response.ok) {
4715
- throw new OperationFailedError("createRefund", this.providerName, {
4716
- cause: new Error("Failed to create refund")
4717
- });
4888
+ throw new OperationFailedError(
4889
+ "createRefund",
4890
+ this.providerName,
4891
+ {
4892
+ cause: new Error("Failed to create refund")
4893
+ }
4894
+ );
4718
4895
  }
4719
4896
  return {
4720
4897
  id: crypto.randomBytes(8).toString("hex").slice(0, 15),
@@ -4724,23 +4901,28 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4724
4901
  metadata: data.metadata
4725
4902
  };
4726
4903
  }
4727
- handleWebhook = async (payload) => {
4904
+ handleWebhook = async (payload, webhookSecret) => {
4728
4905
  const { fullUrl } = payload;
4729
4906
  const paymentId = new URL(fullUrl).searchParams.get("id");
4730
4907
  const parentId = new URL(fullUrl).searchParams.get("parent_id");
4731
4908
  if (!paymentId) {
4732
- throw new WebhookError("Payment ID is required", { provider: this.providerName });
4909
+ throw new WebhookError("Payment ID is required", {
4910
+ provider: this.providerName
4911
+ });
4733
4912
  }
4734
4913
  if (this.opts.debug) {
4735
4914
  console.info("Received GoPay webhook for payment:", paymentId);
4736
4915
  }
4737
4916
  const [payment, error] = await tryCatchAsync(
4738
- this._client.get(`/payments/payment/${paymentId}`, {
4739
- headers: {
4740
- ...await this.tokenManager.getAuthHeaders(),
4741
- "Content-Type": "application/x-www-form-urlencoded"
4917
+ this._client.get(
4918
+ `/payments/payment/${paymentId}`,
4919
+ {
4920
+ headers: {
4921
+ ...await this.tokenManager.getAuthHeaders(),
4922
+ "Content-Type": "application/x-www-form-urlencoded"
4923
+ }
4742
4924
  }
4743
- })
4925
+ )
4744
4926
  );
4745
4927
  if (error) {
4746
4928
  throw new WebhookError("Failed to retrieve payment", {
@@ -4748,10 +4930,15 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4748
4930
  });
4749
4931
  }
4750
4932
  if (!payment.value) {
4751
- throw new WebhookError("Payment not found", { provider: this.providerName });
4933
+ throw new WebhookError("Payment not found", {
4934
+ provider: this.providerName
4935
+ });
4752
4936
  }
4753
4937
  if (this.opts.debug) {
4754
- console.info("Webhook verified successfully, status:", payment.value.state);
4938
+ console.info(
4939
+ "Webhook verified successfully, status:",
4940
+ payment.value.state
4941
+ );
4755
4942
  }
4756
4943
  const statusMap = {
4757
4944
  CREATED: "pending",
@@ -4770,7 +4957,7 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4770
4957
  __INDETERMINATE: (data) => {
4771
4958
  const isRefundEvent = data.state === "REFUNDED" || data.state === "PARTIALLY_REFUNDED";
4772
4959
  if (isRefundEvent) {
4773
- const refund = paykitRefund$InboundSchema(data);
4960
+ const refund = Refund$inboundSchema(data);
4774
4961
  return [
4775
4962
  paykitEvent$InboundSchema({
4776
4963
  type: "refund.created",
@@ -4783,7 +4970,7 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4783
4970
  return [];
4784
4971
  },
4785
4972
  pending: (data) => {
4786
- const payment2 = paykitPayment$InboundSchema(data);
4973
+ const payment2 = Payment$inboundSchema(data);
4787
4974
  return [
4788
4975
  paykitEvent$InboundSchema({
4789
4976
  type: "payment.created",
@@ -4794,7 +4981,7 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4794
4981
  ];
4795
4982
  },
4796
4983
  processing: (data) => {
4797
- const payment2 = paykitPayment$InboundSchema(data);
4984
+ const payment2 = Payment$inboundSchema(data);
4798
4985
  return [
4799
4986
  paykitEvent$InboundSchema({
4800
4987
  type: "payment.updated",
@@ -4805,7 +4992,7 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4805
4992
  ];
4806
4993
  },
4807
4994
  requires_capture: (data) => {
4808
- const payment2 = paykitPayment$InboundSchema(data);
4995
+ const payment2 = Payment$inboundSchema(data);
4809
4996
  return [
4810
4997
  paykitEvent$InboundSchema({
4811
4998
  type: "payment.updated",
@@ -4816,9 +5003,9 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4816
5003
  ];
4817
5004
  },
4818
5005
  canceled: (data) => {
4819
- const payment2 = paykitPayment$InboundSchema(data);
5006
+ const payment2 = Payment$inboundSchema(data);
4820
5007
  const isCancellingSubscription = parentId && data.recurrence?.recurrence_state == "STOPPED";
4821
- const subscription = paykitSubscription$InboundSchema(
5008
+ const subscription = Subscription$inboundSchema(
4822
5009
  data
4823
5010
  );
4824
5011
  const subscriptionCanceledWebhookEvent = {
@@ -4828,9 +5015,13 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4828
5015
  data: subscription
4829
5016
  };
4830
5017
  return [
4831
- ...isCancellingSubscription ? [paykitEvent$InboundSchema(subscriptionCanceledWebhookEvent)] : [],
5018
+ ...isCancellingSubscription ? [
5019
+ paykitEvent$InboundSchema(
5020
+ subscriptionCanceledWebhookEvent
5021
+ )
5022
+ ] : [],
4832
5023
  paykitEvent$InboundSchema({
4833
- type: "payment.canceled",
5024
+ type: "payment.failed",
4834
5025
  created: (/* @__PURE__ */ new Date()).getTime(),
4835
5026
  id: crypto.randomBytes(8).toString("hex").slice(0, 15),
4836
5027
  data: payment2
@@ -4838,10 +5029,10 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4838
5029
  ];
4839
5030
  },
4840
5031
  failed: (data) => {
4841
- const payment2 = paykitPayment$InboundSchema(data);
5032
+ const payment2 = Payment$inboundSchema(data);
4842
5033
  return [
4843
5034
  paykitEvent$InboundSchema({
4844
- type: "payment.canceled",
5035
+ type: "payment.failed",
4845
5036
  created: (/* @__PURE__ */ new Date()).getTime(),
4846
5037
  id: crypto.randomBytes(8).toString("hex").slice(0, 15),
4847
5038
  data: payment2
@@ -4849,9 +5040,9 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4849
5040
  ];
4850
5041
  },
4851
5042
  succeeded: (data) => {
4852
- const payment2 = paykitPayment$InboundSchema(data);
4853
- const invoice = paykitInvoice$InboundSchema(data, !!parentId);
4854
- const subscription = paykitSubscription$InboundSchema(
5043
+ const payment2 = Payment$inboundSchema(data);
5044
+ const invoice = Invoice$inboundSchema(data, !!parentId);
5045
+ const subscription = Subscription$inboundSchema(
4855
5046
  data
4856
5047
  );
4857
5048
  const subscriptionCreatedWebhookEvent = {
@@ -4861,7 +5052,11 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4861
5052
  data: subscription
4862
5053
  };
4863
5054
  return [
4864
- ...parentId ? [paykitEvent$InboundSchema(subscriptionCreatedWebhookEvent)] : [],
5055
+ ...parentId ? [
5056
+ paykitEvent$InboundSchema(
5057
+ subscriptionCreatedWebhookEvent
5058
+ )
5059
+ ] : [],
4865
5060
  paykitEvent$InboundSchema({
4866
5061
  type: "invoice.generated",
4867
5062
  created: (/* @__PURE__ */ new Date()).getTime(),
@@ -4869,7 +5064,7 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4869
5064
  data: invoice
4870
5065
  }),
4871
5066
  paykitEvent$InboundSchema({
4872
- type: "payment.created",
5067
+ type: "payment.succeeded",
4873
5068
  created: (/* @__PURE__ */ new Date()).getTime(),
4874
5069
  id: crypto.randomBytes(8).toString("hex").slice(0, 15),
4875
5070
  data: payment2
@@ -4877,7 +5072,7 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4877
5072
  ];
4878
5073
  },
4879
5074
  requires_action: (data) => {
4880
- const payment2 = paykitPayment$InboundSchema(data);
5075
+ const payment2 = Payment$inboundSchema(data);
4881
5076
  return [
4882
5077
  paykitEvent$InboundSchema({
4883
5078
  type: "payment.updated",