@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.
@@ -4071,10 +4071,12 @@ var NEVER = INVALID;
4071
4071
  var decodeHtmlEntities = (str) => {
4072
4072
  return str.replace(/"/g, '"').replace(/'/g, "'").replace(/"/g, '"').replace(/'/g, "'");
4073
4073
  };
4074
- var paykitPayment$InboundSchema = (data) => {
4074
+ var Payment$inboundSchema = (data) => {
4075
4075
  const { item } = JSON.parse(
4076
4076
  decodeHtmlEntities(
4077
- data.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4077
+ data.additional_params?.find(
4078
+ (param) => param.name === core.PAYKIT_METADATA_KEY
4079
+ )?.value ?? "{}"
4078
4080
  )
4079
4081
  );
4080
4082
  const metadata = core.omitInternalMetadata(
@@ -4101,7 +4103,7 @@ var paykitPayment$InboundSchema = (data) => {
4101
4103
  id: data.id.toString(),
4102
4104
  amount: data.amount,
4103
4105
  currency: data.currency,
4104
- customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4106
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : null,
4105
4107
  status: statusMap[data.state],
4106
4108
  item_id: item,
4107
4109
  metadata,
@@ -4109,10 +4111,12 @@ var paykitPayment$InboundSchema = (data) => {
4109
4111
  payment_url: data.gw_url ?? null
4110
4112
  };
4111
4113
  };
4112
- var paykitCheckout$InboundSchema = (data) => {
4114
+ var Checkout$inboundSchema = (data) => {
4113
4115
  const { item, qty, type } = JSON.parse(
4114
4116
  decodeHtmlEntities(
4115
- data.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4117
+ data.additional_params?.find(
4118
+ (param) => param.name === core.PAYKIT_METADATA_KEY
4119
+ )?.value ?? "{}"
4116
4120
  )
4117
4121
  );
4118
4122
  const metadata = core.omitInternalMetadata(
@@ -4128,24 +4132,28 @@ var paykitCheckout$InboundSchema = (data) => {
4128
4132
  id: data.id.toString(),
4129
4133
  amount: data.amount,
4130
4134
  currency: data.currency,
4131
- customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4135
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : null,
4132
4136
  payment_url: data.gw_url ?? "",
4133
4137
  metadata,
4134
4138
  session_type: type,
4135
4139
  products: [{ id: item, quantity: parseInt(qty) }]
4136
4140
  };
4137
4141
  };
4138
- var paykitInvoice$InboundSchema = (data, isSubscription) => {
4142
+ var Invoice$inboundSchema = (data, isSubscription) => {
4139
4143
  const { item, qty } = JSON.parse(
4140
4144
  decodeHtmlEntities(
4141
- data.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4145
+ data.additional_params?.find(
4146
+ (param) => param.name === core.PAYKIT_METADATA_KEY
4147
+ )?.value ?? "{}"
4142
4148
  )
4143
4149
  );
4144
4150
  const status = (() => {
4145
4151
  if (data.state === "PAID") return "paid";
4146
4152
  return "open";
4147
4153
  })();
4148
- const paidAt = isSubscription ? new Date(data.recurrence?.recurrence_date_to ?? "") : /* @__PURE__ */ new Date();
4154
+ const paidAt = isSubscription ? new Date(
4155
+ data.recurrence?.recurrence_date_to ?? ""
4156
+ ) : /* @__PURE__ */ new Date();
4149
4157
  const metadata = core.omitInternalMetadata(
4150
4158
  data.additional_params?.reduce(
4151
4159
  (acc, param) => {
@@ -4159,7 +4167,7 @@ var paykitInvoice$InboundSchema = (data, isSubscription) => {
4159
4167
  id: data.id.toString(),
4160
4168
  amount_paid: data.amount,
4161
4169
  currency: data.currency,
4162
- customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4170
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : null,
4163
4171
  status,
4164
4172
  paid_at: paidAt.toISOString(),
4165
4173
  metadata: metadata ?? {},
@@ -4169,10 +4177,12 @@ var paykitInvoice$InboundSchema = (data, isSubscription) => {
4169
4177
  line_items: [{ id: item, quantity: parseInt(qty) }]
4170
4178
  };
4171
4179
  };
4172
- var paykitSubscription$InboundSchema = (data) => {
4180
+ var Subscription$inboundSchema = (data) => {
4173
4181
  const { item } = JSON.parse(
4174
4182
  decodeHtmlEntities(
4175
- data.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4183
+ data.additional_params?.find(
4184
+ (param) => param.name === core.PAYKIT_METADATA_KEY
4185
+ )?.value ?? "{}"
4176
4186
  )
4177
4187
  );
4178
4188
  const billingIntervalMap = {
@@ -4184,7 +4194,9 @@ var paykitSubscription$InboundSchema = (data) => {
4184
4194
  const billingInterval = billingIntervalMap[data.recurrence?.recurrence_cycle ?? "ON_DEMAND"];
4185
4195
  const recurrencePeriod = data.recurrence?.recurrence_period ?? 1;
4186
4196
  const recurrenceCycle = data.recurrence?.recurrence_cycle;
4187
- const currentPeriodEnd = new Date(data.recurrence?.recurrence_date_to ?? "");
4197
+ const currentPeriodEnd = new Date(
4198
+ data.recurrence?.recurrence_date_to ?? ""
4199
+ );
4188
4200
  const currentPeriodStart = (() => {
4189
4201
  if (!currentPeriodEnd) return /* @__PURE__ */ new Date();
4190
4202
  const endDate = new Date(currentPeriodEnd);
@@ -4214,21 +4226,21 @@ var paykitSubscription$InboundSchema = (data) => {
4214
4226
  ) ?? {}
4215
4227
  );
4216
4228
  const requiresAction = data.state === "CREATED" ? true : false;
4217
- const status = (() => {
4218
- if (data.state === "CREATED") return "pending";
4219
- if (data.state === "PAID") return "active";
4220
- if (data.state === "CANCELED") return "canceled";
4221
- if (data.state === "TIMEOUTED") return "canceled";
4222
- if (data.state === "REFUNDED") return "canceled";
4223
- if (data.state === "PARTIALLY_REFUNDED") return "canceled";
4224
- if (data.state === "AUTHORIZED") return "active";
4225
- if (data.state === "PAYMENT_METHOD_CHOSEN") return "active";
4226
- return "pending";
4227
- })();
4229
+ const subscriptionStatusMap = {
4230
+ CREATED: "pending",
4231
+ PAID: "active",
4232
+ CANCELED: "canceled",
4233
+ TIMEOUTED: "canceled",
4234
+ REFUNDED: "canceled",
4235
+ PARTIALLY_REFUNDED: "canceled",
4236
+ AUTHORIZED: "active",
4237
+ PAYMENT_METHOD_CHOSEN: "active"
4238
+ };
4239
+ const status = subscriptionStatusMap[data.state] ?? "expired";
4228
4240
  return {
4229
4241
  id: data.id.toString(),
4230
4242
  status,
4231
- customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4243
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : null,
4232
4244
  item_id: item,
4233
4245
  billing_interval: billingInterval,
4234
4246
  currency: data.currency,
@@ -4241,7 +4253,7 @@ var paykitSubscription$InboundSchema = (data) => {
4241
4253
  payment_url: requiresAction ? data.gw_url ?? null : null
4242
4254
  };
4243
4255
  };
4244
- var paykitRefund$InboundSchema = (data) => {
4256
+ var Refund$inboundSchema = (data) => {
4245
4257
  return {
4246
4258
  id: data.id.toString(),
4247
4259
  amount: data.amount,
@@ -4267,6 +4279,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4267
4279
  constructor(opts) {
4268
4280
  super(gopayOptionsSchema, opts, providerName);
4269
4281
  this.opts = opts;
4282
+ this.isSandbox = opts.isSandbox;
4270
4283
  const debug = opts.debug ?? true;
4271
4284
  this.baseUrl = opts.isSandbox ? "https://gw.sandbox.gopay.com/api" : "https://gate.gopay.cz/api";
4272
4285
  this._client = new core.HTTPClient({
@@ -4278,7 +4291,10 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4278
4291
  client: this._client,
4279
4292
  provider: this.providerName,
4280
4293
  tokenEndpoint: "/oauth2/token",
4281
- credentials: { username: opts.clientId, password: opts.clientSecret },
4294
+ credentials: {
4295
+ username: opts.clientId,
4296
+ password: opts.clientSecret
4297
+ },
4282
4298
  responseAdapter: (response) => ({
4283
4299
  accessToken: response.access_token,
4284
4300
  expiresIn: response.expires_in
@@ -4299,15 +4315,30 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4299
4315
  providerName = providerName;
4300
4316
  _client;
4301
4317
  baseUrl;
4318
+ isSandbox;
4302
4319
  tokenManager;
4320
+ get _native() {
4321
+ return null;
4322
+ }
4303
4323
  createCheckout = async (params) => {
4304
4324
  const { error, data } = core.createCheckoutSchema.safeParse(params);
4305
- if (error) throw core.ValidationError.fromZodError(error, "gopay", "createCheckout");
4325
+ if (error) {
4326
+ throw core.ValidationError.fromZodError(
4327
+ error,
4328
+ "gopay",
4329
+ "createCheckout"
4330
+ );
4331
+ }
4306
4332
  if (!core.isEmailCustomer(data.customer)) {
4307
- throw new core.InvalidTypeError("customer", "object (customer) with email", "string", {
4308
- provider: this.providerName,
4309
- method: "createCheckout"
4310
- });
4333
+ throw new core.InvalidTypeError(
4334
+ "customer",
4335
+ "object (customer) with email",
4336
+ "string",
4337
+ {
4338
+ provider: this.providerName,
4339
+ method: "createCheckout"
4340
+ }
4341
+ );
4311
4342
  }
4312
4343
  const { amount, currency = "CZK" } = core.validateRequiredKeys(
4313
4344
  ["amount", "currency"],
@@ -4334,9 +4365,9 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4334
4365
  },
4335
4366
  target: { type: "ACCOUNT", goid: parseInt(this.opts.goId) },
4336
4367
  amount: Number(amount),
4337
- currency,
4368
+ currency: currency.toUpperCase(),
4338
4369
  order_number: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
4339
- order_description: data.metadata?.description || "Checkout",
4370
+ order_description: `Payment for ${data.item_id} by ${data.customer.email}`,
4340
4371
  items: [
4341
4372
  {
4342
4373
  name: data.item_id,
@@ -4346,7 +4377,10 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4346
4377
  }
4347
4378
  ],
4348
4379
  lang: data.provider_metadata?.language ? data.provider_metadata.language : "EN",
4349
- callback: { return_url: data.success_url, notification_url: this.opts.webhookUrl },
4380
+ callback: {
4381
+ return_url: data.success_url,
4382
+ notification_url: this.opts.webhookUrl
4383
+ },
4350
4384
  additional_params: Object.entries({
4351
4385
  ...data.metadata,
4352
4386
  [core.PAYKIT_METADATA_KEY]: JSON.stringify({
@@ -4367,11 +4401,15 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4367
4401
  }
4368
4402
  );
4369
4403
  if (!response.ok) {
4370
- throw new core.OperationFailedError("createCheckout", this.providerName, {
4371
- cause: new Error("Failed to create checkout")
4372
- });
4404
+ throw new core.OperationFailedError(
4405
+ "createCheckout",
4406
+ this.providerName,
4407
+ {
4408
+ cause: new Error("Failed to create checkout")
4409
+ }
4410
+ );
4373
4411
  }
4374
- return paykitCheckout$InboundSchema(response.value);
4412
+ return Checkout$inboundSchema(response.value);
4375
4413
  };
4376
4414
  retrieveCheckout = async (id) => {
4377
4415
  const response = await this._client.get(
@@ -4384,11 +4422,15 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4384
4422
  }
4385
4423
  );
4386
4424
  if (!response.ok) {
4387
- throw new core.OperationFailedError("retrieveCheckout", this.providerName, {
4388
- cause: new Error("Failed to retrieve checkout")
4389
- });
4425
+ throw new core.OperationFailedError(
4426
+ "retrieveCheckout",
4427
+ this.providerName,
4428
+ {
4429
+ cause: new Error("Failed to retrieve checkout")
4430
+ }
4431
+ );
4390
4432
  }
4391
- return paykitCheckout$InboundSchema(response.value);
4433
+ return Checkout$inboundSchema(response.value);
4392
4434
  };
4393
4435
  updateCheckout = async (id, params) => {
4394
4436
  if (this.opts.debug) {
@@ -4427,57 +4469,95 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4427
4469
  };
4428
4470
  createSubscription = async (params) => {
4429
4471
  const { error, data } = core.createSubscriptionSchema.safeParse(params);
4430
- if (error) throw core.ValidationError.fromZodError(error, "gopay", "createSubscription");
4431
- if (typeof data.customer == "string" || typeof data.customer === "object" && !data.customer.email) {
4432
- throw new core.InvalidTypeError("customer", "object (customer) with email", "string", {
4433
- provider: this.providerName,
4434
- method: "createCheckout"
4435
- });
4472
+ if (error)
4473
+ throw core.ValidationError.fromZodError(
4474
+ error,
4475
+ "gopay",
4476
+ "createSubscription"
4477
+ );
4478
+ if (!core.isEmailCustomer(data.customer)) {
4479
+ throw new core.InvalidTypeError(
4480
+ "customer",
4481
+ "object with email",
4482
+ core.isIdCustomer(data.customer) ? "object with id" : typeof data.customer,
4483
+ {
4484
+ provider: this.providerName,
4485
+ method: "createSubscription"
4486
+ }
4487
+ );
4436
4488
  }
4437
4489
  const { success_url } = core.validateRequiredKeys(
4438
4490
  ["success_url"],
4439
4491
  data.provider_metadata,
4440
- "The following fields must be present in the provider_metadata of createCheckout: {keys}"
4492
+ "The following fields must be present in the provider_metadata of createSubscription: {keys}"
4441
4493
  );
4494
+ const billingInterval = data.billing_interval;
4495
+ const isCustom = typeof billingInterval === "object" && billingInterval.type === "custom";
4496
+ const isYear = billingInterval === "year";
4497
+ const isOnDemand = isCustom || isYear;
4498
+ const intervalMap = {
4499
+ day: "DAY",
4500
+ week: "WEEK",
4501
+ month: "MONTH",
4502
+ year: "ON_DEMAND"
4503
+ };
4504
+ const recurrenceCycle = isCustom ? "ON_DEMAND" : intervalMap[billingInterval];
4442
4505
  if (this.opts.debug) {
4443
- if (data.billing_interval === "year") {
4506
+ if (isYear) {
4507
+ console.info(
4508
+ "[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"
4509
+ );
4510
+ }
4511
+ if (isCustom) {
4512
+ const durationMs = billingInterval.durationMs;
4513
+ console.info(
4514
+ `[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`
4515
+ );
4516
+ }
4517
+ if (!isOnDemand) {
4518
+ console.info(
4519
+ `[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.`
4520
+ );
4521
+ } else {
4444
4522
  console.info(
4445
- "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"
4523
+ "[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)."
4446
4524
  );
4447
4525
  }
4448
4526
  if (!data.provider_metadata?.description) {
4449
4527
  console.info(
4450
- `No description provided for the subscription \`provider_metadata.description\`, using default description \`Subscription by ${data.customer.email}\``
4528
+ `[PayKit/GoPay] No \`provider_metadata.description\` provided. Using default: "Subscription by ${data.customer.email}"`
4451
4529
  );
4452
4530
  }
4453
4531
  }
4454
- const intervalMap = {
4455
- day: "DAY",
4456
- week: "WEEK",
4457
- month: "MONTH",
4458
- year: "ON_DEMAND"
4532
+ const toDateString = (ms) => {
4533
+ const d = new Date(ms);
4534
+ return d.toISOString().split("T")[0];
4459
4535
  };
4460
- const recurrenceCycle = intervalMap?.[data.billing_interval] ?? "ON_DEMAND";
4461
- const currentPeriodEnd = (() => {
4462
- if (recurrenceCycle === "DAY") {
4463
- return new Date(Date.now() + 1 * 24 * 60 * 60 * 1e3).toISOString();
4464
- }
4465
- if (recurrenceCycle === "WEEK") {
4466
- return new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3).toISOString();
4467
- }
4468
- if (recurrenceCycle === "MONTH") {
4469
- return new Date(Date.now() + 30 * 24 * 60 * 60 * 1e3).toISOString();
4536
+ const GOPAY_MAX_DATE = "2099-12-30";
4537
+ const endDateOverride = data.provider_metadata?.end_date;
4538
+ const recurrenceDateTo = (() => {
4539
+ if (endDateOverride) {
4540
+ return endDateOverride < GOPAY_MAX_DATE ? endDateOverride : GOPAY_MAX_DATE;
4470
4541
  }
4471
4542
  if (recurrenceCycle === "ON_DEMAND") {
4472
- throw new core.ConfigurationError(
4473
- "ON_DEMAND subscriptions is not yet implemented by PayKit, please open an issue at https://github.com/usepaykit/paykit-sdk/issues",
4474
- {
4475
- provider: this.providerName
4476
- }
4543
+ if (isCustom) {
4544
+ return toDateString(Date.now() + 365 * 24 * 60 * 60 * 1e3);
4545
+ }
4546
+ return toDateString(
4547
+ Date.now() + 5 * 365 * 24 * 60 * 60 * 1e3
4477
4548
  );
4478
4549
  }
4479
- throw new Error("Invalid billing interval: " + data.billing_interval);
4550
+ return toDateString(Date.now() + 365 * 24 * 60 * 60 * 1e3);
4480
4551
  })();
4552
+ const recurrencePeriod = data.provider_metadata?.recurrence_period ?? 1;
4553
+ const recurrence = isOnDemand ? {
4554
+ recurrence_cycle: recurrenceCycle,
4555
+ recurrence_date_to: recurrenceDateTo
4556
+ } : {
4557
+ recurrence_cycle: recurrenceCycle,
4558
+ recurrence_period: recurrencePeriod,
4559
+ recurrence_date_to: recurrenceDateTo
4560
+ };
4481
4561
  const goPaySubscriptionOptions = {
4482
4562
  payer: {
4483
4563
  allowed_payment_instruments: ["PAYMENT_CARD"],
@@ -4488,24 +4568,28 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4488
4568
  amount: Number(data.amount),
4489
4569
  currency: data.currency ?? "CZK",
4490
4570
  order_number: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
4491
- order_description: data.provider_metadata?.description ? data.provider_metadata.description : "Subscription by " + data.customer.email,
4492
- items: [{ name: data.item_id, amount: Number(data.amount), count: data.quantity }],
4493
- recurrence: {
4494
- recurrence_cycle: recurrenceCycle,
4495
- recurrence_period: data.quantity,
4496
- recurrence_date_to: currentPeriodEnd
4571
+ order_description: data.provider_metadata?.description ? data.provider_metadata.description : `Subscription by ${data.customer.email}`,
4572
+ items: [
4573
+ {
4574
+ name: data.item_id,
4575
+ amount: Number(data.amount),
4576
+ count: data.quantity ?? 1
4577
+ }
4578
+ ],
4579
+ recurrence,
4580
+ callback: {
4581
+ return_url: success_url,
4582
+ notification_url: this.opts.webhookUrl
4497
4583
  },
4498
- callback: { return_url: success_url, notification_url: this.opts.webhookUrl },
4499
4584
  additional_params: Object.entries({
4500
4585
  ...data.metadata,
4501
4586
  [core.PAYKIT_METADATA_KEY]: JSON.stringify({
4502
4587
  item: data.item_id,
4503
- qty: data.quantity
4588
+ qty: data.quantity,
4589
+ // Store the original interval so createRecurrence callers know the intended cadence
4590
+ billing_interval: isCustom ? `custom:${billingInterval.durationMs}ms` : billingInterval
4504
4591
  })
4505
- }).map(([name, value]) => ({
4506
- name,
4507
- value: String(value)
4508
- }))
4592
+ }).map(([name, value]) => ({ name, value: String(value) }))
4509
4593
  };
4510
4594
  const response = await this._client.post(
4511
4595
  "/payments/payment",
@@ -4515,28 +4599,42 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4515
4599
  }
4516
4600
  );
4517
4601
  if (!response.ok) {
4518
- throw new core.OperationFailedError("createSubscription", this.providerName, {
4519
- cause: new Error("Failed to create subscription")
4520
- });
4602
+ throw new core.OperationFailedError(
4603
+ "createSubscription",
4604
+ this.providerName,
4605
+ {
4606
+ cause: new Error(
4607
+ `[PayKit/GoPay] Failed to create subscription. Error: ${response.error}`
4608
+ )
4609
+ }
4610
+ );
4521
4611
  }
4522
- return paykitSubscription$InboundSchema(response.value);
4612
+ return Subscription$inboundSchema(response.value);
4523
4613
  };
4524
4614
  updateSubscription = async (id, params) => {
4525
4615
  const subscription = await this.retrieveSubscription(id);
4526
4616
  if (!subscription) {
4527
- throw new core.ProviderNotSupportedError("updateSubscription", this.providerName, {
4528
- reason: "Gopay doesn't support updating subscriptions",
4529
- alternative: "Use the payment API instead and update the subscription manually"
4530
- });
4617
+ throw new core.ProviderNotSupportedError(
4618
+ "updateSubscription",
4619
+ this.providerName,
4620
+ {
4621
+ reason: "Gopay doesn't support updating subscriptions",
4622
+ alternative: "Use the payment API instead and update the subscription manually"
4623
+ }
4624
+ );
4531
4625
  }
4532
4626
  return subscription;
4533
4627
  };
4534
4628
  cancelSubscription = async (id) => {
4535
4629
  const existingSubscription = await this.retrieveSubscription(id);
4536
4630
  if (!existingSubscription) {
4537
- throw new core.OperationFailedError("cancelSubscription", this.providerName, {
4538
- cause: new Error("Failed to retrieve subscription")
4539
- });
4631
+ throw new core.OperationFailedError(
4632
+ "cancelSubscription",
4633
+ this.providerName,
4634
+ {
4635
+ cause: new Error("Failed to retrieve subscription")
4636
+ }
4637
+ );
4540
4638
  }
4541
4639
  const response = await this._client.post(`/payments/payment/${id}/void-recurrence`, {
4542
4640
  headers: {
@@ -4546,7 +4644,9 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4546
4644
  });
4547
4645
  return {
4548
4646
  ...existingSubscription,
4549
- ...response.value?.result == "FINISHED" && { status: "canceled" }
4647
+ ...response.value?.result == "FINISHED" && {
4648
+ status: "canceled"
4649
+ }
4550
4650
  };
4551
4651
  };
4552
4652
  deleteSubscription = async (id) => {
@@ -4561,21 +4661,35 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4561
4661
  }
4562
4662
  );
4563
4663
  if (!response.ok) {
4564
- throw new core.OperationFailedError("retrieveSubscription", this.providerName, {
4565
- cause: new Error("Failed to retrieve subscription")
4566
- });
4664
+ throw new core.OperationFailedError(
4665
+ "retrieveSubscription",
4666
+ this.providerName,
4667
+ {
4668
+ cause: new Error("Failed to retrieve subscription")
4669
+ }
4670
+ );
4567
4671
  }
4568
- return paykitSubscription$InboundSchema(response.value);
4672
+ return Subscription$inboundSchema(response.value);
4569
4673
  };
4570
4674
  createPayment = async (params) => {
4571
4675
  const { error, data } = core.createPaymentSchema.safeParse(params);
4572
- if (error)
4573
- throw core.ValidationError.fromZodError(error, this.providerName, "createPayment");
4574
- if (typeof data.customer == "string" || typeof data.customer === "object" && !data.customer?.email) {
4575
- throw new core.InvalidTypeError("customer", "object (customer) with email", "string", {
4576
- provider: this.providerName,
4577
- method: "createPayment"
4578
- });
4676
+ if (error) {
4677
+ throw core.ValidationError.fromZodError(
4678
+ error,
4679
+ this.providerName,
4680
+ "createPayment"
4681
+ );
4682
+ }
4683
+ if (!core.isEmailCustomer(data.customer)) {
4684
+ throw new core.InvalidTypeError(
4685
+ "customer",
4686
+ "object with email",
4687
+ core.isIdCustomer(data.customer) ? "object with id" : typeof data.customer,
4688
+ {
4689
+ provider: this.providerName,
4690
+ method: "createPayment"
4691
+ }
4692
+ );
4579
4693
  }
4580
4694
  if (!data.item_id) {
4581
4695
  throw new core.ConfigurationError(
@@ -4600,20 +4714,40 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4600
4714
  payer: {
4601
4715
  allowed_payment_instruments: ["PAYMENT_CARD", "BANK_ACCOUNT"],
4602
4716
  default_payment_instrument: "PAYMENT_CARD",
4603
- contact: { email: data.customer.email }
4717
+ contact: { email: data.customer.email },
4718
+ ...data.billing && {
4719
+ city: data.billing.address.city,
4720
+ postal_code: data.billing.address.postal_code,
4721
+ country_code: data.billing.address.country,
4722
+ phone_number: data.billing.address.phone
4723
+ }
4604
4724
  },
4605
- callback: { return_url: successUrl, notification_url: this.opts.webhookUrl },
4606
4725
  target: { type: "ACCOUNT", goid: parseInt(this.opts.goId) },
4607
- amount: data.amount,
4726
+ amount: Number(data.amount),
4608
4727
  currency: data.currency ?? "CZK",
4609
4728
  order_number: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
4610
4729
  order_description: `Payment for ${data.item_id} by ${data.customer.email}`,
4611
- items: [{ name: data.item_id, amount: data.amount, count: 1 }],
4730
+ items: [
4731
+ {
4732
+ name: data.item_id,
4733
+ amount: data.amount,
4734
+ count: 1,
4735
+ type: "ITEM"
4736
+ }
4737
+ ],
4738
+ lang: data.provider_metadata?.language ? data.provider_metadata.language : "EN",
4739
+ callback: {
4740
+ return_url: successUrl,
4741
+ notification_url: this.opts.webhookUrl
4742
+ },
4612
4743
  preauthorization: false,
4613
4744
  // automatically captures the payment
4614
4745
  additional_params: Object.entries({
4615
4746
  ...data.metadata,
4616
- [core.PAYKIT_METADATA_KEY]: JSON.stringify({ itemId: data.item_id, qty: 1 })
4747
+ [core.PAYKIT_METADATA_KEY]: JSON.stringify({
4748
+ itemId: data.item_id,
4749
+ qty: 1
4750
+ })
4617
4751
  }).map(([name, value]) => ({
4618
4752
  name,
4619
4753
  value: String(value)
@@ -4627,11 +4761,17 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4627
4761
  }
4628
4762
  );
4629
4763
  if (!response.ok) {
4630
- throw new core.OperationFailedError("createPayment", this.providerName, {
4631
- cause: new Error("Failed to create payment")
4632
- });
4764
+ throw new core.OperationFailedError(
4765
+ "createPayment",
4766
+ this.providerName,
4767
+ {
4768
+ cause: new Error(
4769
+ `Failed to create payment: ${JSON.stringify(response.error ?? response)}`
4770
+ )
4771
+ }
4772
+ );
4633
4773
  }
4634
- return paykitPayment$InboundSchema(response.value);
4774
+ return Payment$inboundSchema(response.value);
4635
4775
  };
4636
4776
  retrievePayment = async (id) => {
4637
4777
  const response = await this._client.get(
@@ -4644,17 +4784,25 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4644
4784
  }
4645
4785
  );
4646
4786
  if (!response.ok) {
4647
- throw new core.OperationFailedError("retrievePayment", this.providerName, {
4648
- cause: new Error("Failed to retrieve payment")
4649
- });
4787
+ throw new core.OperationFailedError(
4788
+ "retrievePayment",
4789
+ this.providerName,
4790
+ {
4791
+ cause: new Error("Failed to retrieve payment")
4792
+ }
4793
+ );
4650
4794
  }
4651
- return paykitPayment$InboundSchema(response.value);
4795
+ return Payment$inboundSchema(response.value);
4652
4796
  };
4653
4797
  deletePayment = async (id) => {
4654
- throw new core.ProviderNotSupportedError("deletePayment", this.providerName, {
4655
- reason: "GoPay does not support deleting payments, use the",
4656
- alternative: "Use createRefund() instead to refund payments"
4657
- });
4798
+ throw new core.ProviderNotSupportedError(
4799
+ "deletePayment",
4800
+ this.providerName,
4801
+ {
4802
+ reason: "GoPay does not support deleting payments, use the",
4803
+ alternative: "Use createRefund() instead to refund payments"
4804
+ }
4805
+ );
4658
4806
  };
4659
4807
  capturePayment = async (id, params) => {
4660
4808
  const payment = await this._client.get(
@@ -4662,32 +4810,39 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4662
4810
  { headers: await this.tokenManager.getAuthHeaders() }
4663
4811
  );
4664
4812
  if (!payment.ok) {
4665
- throw new core.OperationFailedError("capturePayment", this.providerName, {
4666
- cause: new Error("Failed to retrieve payment")
4667
- });
4813
+ throw new core.OperationFailedError(
4814
+ "capturePayment",
4815
+ this.providerName,
4816
+ {
4817
+ cause: new Error("Failed to retrieve payment")
4818
+ }
4819
+ );
4668
4820
  }
4669
4821
  const { item, qty } = JSON.parse(
4670
4822
  decodeHtmlEntities(
4671
- payment.value.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4823
+ payment.value.additional_params?.find(
4824
+ (param) => param.name === core.PAYKIT_METADATA_KEY
4825
+ )?.value ?? "{}"
4672
4826
  )
4673
4827
  );
4674
4828
  if (!payment) {
4675
- throw new core.OperationFailedError("capturePayment", this.providerName, {
4676
- cause: new Error("Payment not found after capture")
4677
- });
4829
+ throw new core.OperationFailedError(
4830
+ "capturePayment",
4831
+ this.providerName,
4832
+ {
4833
+ cause: new Error("Payment not found after capture")
4834
+ }
4835
+ );
4678
4836
  }
4679
4837
  const captureBody = {
4680
4838
  amount: params.amount,
4681
4839
  items: [{ name: item, amount: params.amount, count: qty }]
4682
4840
  };
4683
- await this._client.post(
4684
- `/payments/payment/${id}/capture`,
4685
- {
4686
- body: JSON.stringify(captureBody),
4687
- headers: await this.tokenManager.getAuthHeaders()
4688
- }
4689
- );
4690
- return paykitPayment$InboundSchema(payment.value);
4841
+ await this._client.post(`/payments/payment/${id}/capture`, {
4842
+ body: JSON.stringify(captureBody),
4843
+ headers: await this.tokenManager.getAuthHeaders()
4844
+ });
4845
+ return Payment$inboundSchema(payment.value);
4691
4846
  };
4692
4847
  cancelPayment = async (id) => {
4693
4848
  await this._client.post(
@@ -4696,9 +4851,13 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4696
4851
  );
4697
4852
  const payment = await this.retrievePayment(id);
4698
4853
  if (!payment) {
4699
- throw new core.OperationFailedError("cancelPayment", this.providerName, {
4700
- cause: new Error("Payment not found after cancellation")
4701
- });
4854
+ throw new core.OperationFailedError(
4855
+ "cancelPayment",
4856
+ this.providerName,
4857
+ {
4858
+ cause: new Error("Payment not found after cancellation")
4859
+ }
4860
+ );
4702
4861
  }
4703
4862
  return payment;
4704
4863
  };
@@ -4709,34 +4868,52 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4709
4868
  console.info("Gopay doesn't support updating payments");
4710
4869
  const existing = await this.retrievePayment(id);
4711
4870
  if (!existing) {
4712
- throw new core.OperationFailedError("updatePayment", this.providerName, {
4713
- cause: new Error("Failed to retrieve payment")
4714
- });
4871
+ throw new core.OperationFailedError(
4872
+ "updatePayment",
4873
+ this.providerName,
4874
+ {
4875
+ cause: new Error("Failed to retrieve payment")
4876
+ }
4877
+ );
4715
4878
  }
4716
4879
  return existing;
4717
4880
  };
4718
4881
  async createRefund(params) {
4719
4882
  const { error, data } = core.createRefundSchema.safeParse(params);
4720
4883
  if (error) {
4721
- throw core.ValidationError.fromZodError(error, this.providerName, "createRefund");
4884
+ throw core.ValidationError.fromZodError(
4885
+ error,
4886
+ this.providerName,
4887
+ "createRefund"
4888
+ );
4722
4889
  }
4723
4890
  const payment = await this.retrievePayment(data.payment_id);
4724
4891
  if (!payment) {
4725
- throw new core.OperationFailedError("createRefund", this.providerName, {
4726
- cause: new Error("Failed to retrieve payment")
4727
- });
4892
+ throw new core.OperationFailedError(
4893
+ "createRefund",
4894
+ this.providerName,
4895
+ {
4896
+ cause: new Error("Failed to retrieve payment")
4897
+ }
4898
+ );
4728
4899
  }
4729
4900
  const response = await this._client.post(`/payments/payment/${data.payment_id}/refund`, {
4730
- body: new URLSearchParams({ amount: String(data.amount) }).toString(),
4901
+ body: new URLSearchParams({
4902
+ amount: String(data.amount)
4903
+ }).toString(),
4731
4904
  headers: {
4732
4905
  ...await this.tokenManager.getAuthHeaders(),
4733
4906
  "Content-Type": "application/x-www-form-urlencoded"
4734
4907
  }
4735
4908
  });
4736
4909
  if (!response.ok) {
4737
- throw new core.OperationFailedError("createRefund", this.providerName, {
4738
- cause: new Error("Failed to create refund")
4739
- });
4910
+ throw new core.OperationFailedError(
4911
+ "createRefund",
4912
+ this.providerName,
4913
+ {
4914
+ cause: new Error("Failed to create refund")
4915
+ }
4916
+ );
4740
4917
  }
4741
4918
  return {
4742
4919
  id: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
@@ -4746,23 +4923,28 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4746
4923
  metadata: data.metadata
4747
4924
  };
4748
4925
  }
4749
- handleWebhook = async (payload) => {
4926
+ handleWebhook = async (payload, webhookSecret) => {
4750
4927
  const { fullUrl } = payload;
4751
4928
  const paymentId = new URL(fullUrl).searchParams.get("id");
4752
4929
  const parentId = new URL(fullUrl).searchParams.get("parent_id");
4753
4930
  if (!paymentId) {
4754
- throw new core.WebhookError("Payment ID is required", { provider: this.providerName });
4931
+ throw new core.WebhookError("Payment ID is required", {
4932
+ provider: this.providerName
4933
+ });
4755
4934
  }
4756
4935
  if (this.opts.debug) {
4757
4936
  console.info("Received GoPay webhook for payment:", paymentId);
4758
4937
  }
4759
4938
  const [payment, error] = await core.tryCatchAsync(
4760
- this._client.get(`/payments/payment/${paymentId}`, {
4761
- headers: {
4762
- ...await this.tokenManager.getAuthHeaders(),
4763
- "Content-Type": "application/x-www-form-urlencoded"
4939
+ this._client.get(
4940
+ `/payments/payment/${paymentId}`,
4941
+ {
4942
+ headers: {
4943
+ ...await this.tokenManager.getAuthHeaders(),
4944
+ "Content-Type": "application/x-www-form-urlencoded"
4945
+ }
4764
4946
  }
4765
- })
4947
+ )
4766
4948
  );
4767
4949
  if (error) {
4768
4950
  throw new core.WebhookError("Failed to retrieve payment", {
@@ -4770,10 +4952,15 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4770
4952
  });
4771
4953
  }
4772
4954
  if (!payment.value) {
4773
- throw new core.WebhookError("Payment not found", { provider: this.providerName });
4955
+ throw new core.WebhookError("Payment not found", {
4956
+ provider: this.providerName
4957
+ });
4774
4958
  }
4775
4959
  if (this.opts.debug) {
4776
- console.info("Webhook verified successfully, status:", payment.value.state);
4960
+ console.info(
4961
+ "Webhook verified successfully, status:",
4962
+ payment.value.state
4963
+ );
4777
4964
  }
4778
4965
  const statusMap = {
4779
4966
  CREATED: "pending",
@@ -4792,7 +4979,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4792
4979
  __INDETERMINATE: (data) => {
4793
4980
  const isRefundEvent = data.state === "REFUNDED" || data.state === "PARTIALLY_REFUNDED";
4794
4981
  if (isRefundEvent) {
4795
- const refund = paykitRefund$InboundSchema(data);
4982
+ const refund = Refund$inboundSchema(data);
4796
4983
  return [
4797
4984
  core.paykitEvent$InboundSchema({
4798
4985
  type: "refund.created",
@@ -4805,7 +4992,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4805
4992
  return [];
4806
4993
  },
4807
4994
  pending: (data) => {
4808
- const payment2 = paykitPayment$InboundSchema(data);
4995
+ const payment2 = Payment$inboundSchema(data);
4809
4996
  return [
4810
4997
  core.paykitEvent$InboundSchema({
4811
4998
  type: "payment.created",
@@ -4816,7 +5003,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4816
5003
  ];
4817
5004
  },
4818
5005
  processing: (data) => {
4819
- const payment2 = paykitPayment$InboundSchema(data);
5006
+ const payment2 = Payment$inboundSchema(data);
4820
5007
  return [
4821
5008
  core.paykitEvent$InboundSchema({
4822
5009
  type: "payment.updated",
@@ -4827,7 +5014,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4827
5014
  ];
4828
5015
  },
4829
5016
  requires_capture: (data) => {
4830
- const payment2 = paykitPayment$InboundSchema(data);
5017
+ const payment2 = Payment$inboundSchema(data);
4831
5018
  return [
4832
5019
  core.paykitEvent$InboundSchema({
4833
5020
  type: "payment.updated",
@@ -4838,9 +5025,9 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4838
5025
  ];
4839
5026
  },
4840
5027
  canceled: (data) => {
4841
- const payment2 = paykitPayment$InboundSchema(data);
5028
+ const payment2 = Payment$inboundSchema(data);
4842
5029
  const isCancellingSubscription = parentId && data.recurrence?.recurrence_state == "STOPPED";
4843
- const subscription = paykitSubscription$InboundSchema(
5030
+ const subscription = Subscription$inboundSchema(
4844
5031
  data
4845
5032
  );
4846
5033
  const subscriptionCanceledWebhookEvent = {
@@ -4850,9 +5037,13 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4850
5037
  data: subscription
4851
5038
  };
4852
5039
  return [
4853
- ...isCancellingSubscription ? [core.paykitEvent$InboundSchema(subscriptionCanceledWebhookEvent)] : [],
5040
+ ...isCancellingSubscription ? [
5041
+ core.paykitEvent$InboundSchema(
5042
+ subscriptionCanceledWebhookEvent
5043
+ )
5044
+ ] : [],
4854
5045
  core.paykitEvent$InboundSchema({
4855
- type: "payment.canceled",
5046
+ type: "payment.failed",
4856
5047
  created: (/* @__PURE__ */ new Date()).getTime(),
4857
5048
  id: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
4858
5049
  data: payment2
@@ -4860,10 +5051,10 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4860
5051
  ];
4861
5052
  },
4862
5053
  failed: (data) => {
4863
- const payment2 = paykitPayment$InboundSchema(data);
5054
+ const payment2 = Payment$inboundSchema(data);
4864
5055
  return [
4865
5056
  core.paykitEvent$InboundSchema({
4866
- type: "payment.canceled",
5057
+ type: "payment.failed",
4867
5058
  created: (/* @__PURE__ */ new Date()).getTime(),
4868
5059
  id: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
4869
5060
  data: payment2
@@ -4871,9 +5062,9 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4871
5062
  ];
4872
5063
  },
4873
5064
  succeeded: (data) => {
4874
- const payment2 = paykitPayment$InboundSchema(data);
4875
- const invoice = paykitInvoice$InboundSchema(data, !!parentId);
4876
- const subscription = paykitSubscription$InboundSchema(
5065
+ const payment2 = Payment$inboundSchema(data);
5066
+ const invoice = Invoice$inboundSchema(data, !!parentId);
5067
+ const subscription = Subscription$inboundSchema(
4877
5068
  data
4878
5069
  );
4879
5070
  const subscriptionCreatedWebhookEvent = {
@@ -4883,7 +5074,11 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4883
5074
  data: subscription
4884
5075
  };
4885
5076
  return [
4886
- ...parentId ? [core.paykitEvent$InboundSchema(subscriptionCreatedWebhookEvent)] : [],
5077
+ ...parentId ? [
5078
+ core.paykitEvent$InboundSchema(
5079
+ subscriptionCreatedWebhookEvent
5080
+ )
5081
+ ] : [],
4887
5082
  core.paykitEvent$InboundSchema({
4888
5083
  type: "invoice.generated",
4889
5084
  created: (/* @__PURE__ */ new Date()).getTime(),
@@ -4891,7 +5086,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4891
5086
  data: invoice
4892
5087
  }),
4893
5088
  core.paykitEvent$InboundSchema({
4894
- type: "payment.created",
5089
+ type: "payment.succeeded",
4895
5090
  created: (/* @__PURE__ */ new Date()).getTime(),
4896
5091
  id: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
4897
5092
  data: payment2
@@ -4899,7 +5094,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4899
5094
  ];
4900
5095
  },
4901
5096
  requires_action: (data) => {
4902
- const payment2 = paykitPayment$InboundSchema(data);
5097
+ const payment2 = Payment$inboundSchema(data);
4903
5098
  return [
4904
5099
  core.paykitEvent$InboundSchema({
4905
5100
  type: "payment.updated",