@paykit-sdk/gopay 1.1.3 → 1.2.0

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.
package/dist/index.js CHANGED
@@ -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
@@ -4297,17 +4313,33 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4297
4313
  });
4298
4314
  }
4299
4315
  providerName = providerName;
4316
+ providerVersion = "1.2.0";
4300
4317
  _client;
4301
4318
  baseUrl;
4319
+ isSandbox;
4302
4320
  tokenManager;
4321
+ get _native() {
4322
+ return null;
4323
+ }
4303
4324
  createCheckout = async (params) => {
4304
4325
  const { error, data } = core.createCheckoutSchema.safeParse(params);
4305
- if (error) throw core.ValidationError.fromZodError(error, "gopay", "createCheckout");
4326
+ if (error) {
4327
+ throw core.ValidationError.fromZodError(
4328
+ error,
4329
+ "gopay",
4330
+ "createCheckout"
4331
+ );
4332
+ }
4306
4333
  if (!core.isEmailCustomer(data.customer)) {
4307
- throw new core.InvalidTypeError("customer", "object (customer) with email", "string", {
4308
- provider: this.providerName,
4309
- method: "createCheckout"
4310
- });
4334
+ throw new core.InvalidTypeError(
4335
+ "customer",
4336
+ "object (customer) with email",
4337
+ "string",
4338
+ {
4339
+ provider: this.providerName,
4340
+ method: "createCheckout"
4341
+ }
4342
+ );
4311
4343
  }
4312
4344
  const { amount, currency = "CZK" } = core.validateRequiredKeys(
4313
4345
  ["amount", "currency"],
@@ -4334,9 +4366,9 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4334
4366
  },
4335
4367
  target: { type: "ACCOUNT", goid: parseInt(this.opts.goId) },
4336
4368
  amount: Number(amount),
4337
- currency,
4369
+ currency: currency.toUpperCase(),
4338
4370
  order_number: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
4339
- order_description: data.metadata?.description || "Checkout",
4371
+ order_description: `Payment for ${data.item_id} by ${data.customer.email}`,
4340
4372
  items: [
4341
4373
  {
4342
4374
  name: data.item_id,
@@ -4346,7 +4378,10 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4346
4378
  }
4347
4379
  ],
4348
4380
  lang: data.provider_metadata?.language ? data.provider_metadata.language : "EN",
4349
- callback: { return_url: data.success_url, notification_url: this.opts.webhookUrl },
4381
+ callback: {
4382
+ return_url: data.success_url,
4383
+ notification_url: this.opts.webhookUrl
4384
+ },
4350
4385
  additional_params: Object.entries({
4351
4386
  ...data.metadata,
4352
4387
  [core.PAYKIT_METADATA_KEY]: JSON.stringify({
@@ -4367,11 +4402,15 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4367
4402
  }
4368
4403
  );
4369
4404
  if (!response.ok) {
4370
- throw new core.OperationFailedError("createCheckout", this.providerName, {
4371
- cause: new Error("Failed to create checkout")
4372
- });
4405
+ throw new core.OperationFailedError(
4406
+ "createCheckout",
4407
+ this.providerName,
4408
+ {
4409
+ cause: new Error("Failed to create checkout")
4410
+ }
4411
+ );
4373
4412
  }
4374
- return paykitCheckout$InboundSchema(response.value);
4413
+ return Checkout$inboundSchema(response.value);
4375
4414
  };
4376
4415
  retrieveCheckout = async (id) => {
4377
4416
  const response = await this._client.get(
@@ -4384,11 +4423,15 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4384
4423
  }
4385
4424
  );
4386
4425
  if (!response.ok) {
4387
- throw new core.OperationFailedError("retrieveCheckout", this.providerName, {
4388
- cause: new Error("Failed to retrieve checkout")
4389
- });
4426
+ throw new core.OperationFailedError(
4427
+ "retrieveCheckout",
4428
+ this.providerName,
4429
+ {
4430
+ cause: new Error("Failed to retrieve checkout")
4431
+ }
4432
+ );
4390
4433
  }
4391
- return paykitCheckout$InboundSchema(response.value);
4434
+ return Checkout$inboundSchema(response.value);
4392
4435
  };
4393
4436
  updateCheckout = async (id, params) => {
4394
4437
  if (this.opts.debug) {
@@ -4427,57 +4470,95 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4427
4470
  };
4428
4471
  createSubscription = async (params) => {
4429
4472
  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
- });
4473
+ if (error)
4474
+ throw core.ValidationError.fromZodError(
4475
+ error,
4476
+ "gopay",
4477
+ "createSubscription"
4478
+ );
4479
+ if (!core.isEmailCustomer(data.customer)) {
4480
+ throw new core.InvalidTypeError(
4481
+ "customer",
4482
+ "object with email",
4483
+ core.isIdCustomer(data.customer) ? "object with id" : typeof data.customer,
4484
+ {
4485
+ provider: this.providerName,
4486
+ method: "createSubscription"
4487
+ }
4488
+ );
4436
4489
  }
4437
4490
  const { success_url } = core.validateRequiredKeys(
4438
4491
  ["success_url"],
4439
4492
  data.provider_metadata,
4440
- "The following fields must be present in the provider_metadata of createCheckout: {keys}"
4493
+ "The following fields must be present in the provider_metadata of createSubscription: {keys}"
4441
4494
  );
4495
+ const billingInterval = data.billing_interval;
4496
+ const isCustom = typeof billingInterval === "object" && billingInterval.type === "custom";
4497
+ const isYear = billingInterval === "year";
4498
+ const isOnDemand = isCustom || isYear;
4499
+ const intervalMap = {
4500
+ day: "DAY",
4501
+ week: "WEEK",
4502
+ month: "MONTH",
4503
+ year: "ON_DEMAND"
4504
+ };
4505
+ const recurrenceCycle = isCustom ? "ON_DEMAND" : intervalMap[billingInterval];
4442
4506
  if (this.opts.debug) {
4443
- if (data.billing_interval === "year") {
4507
+ if (isYear) {
4508
+ console.info(
4509
+ "[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"
4510
+ );
4511
+ }
4512
+ if (isCustom) {
4513
+ const durationMs = billingInterval.durationMs;
4514
+ console.info(
4515
+ `[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`
4516
+ );
4517
+ }
4518
+ if (!isOnDemand) {
4519
+ console.info(
4520
+ `[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.`
4521
+ );
4522
+ } else {
4444
4523
  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"
4524
+ "[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
4525
  );
4447
4526
  }
4448
4527
  if (!data.provider_metadata?.description) {
4449
4528
  console.info(
4450
- `No description provided for the subscription \`provider_metadata.description\`, using default description \`Subscription by ${data.customer.email}\``
4529
+ `[PayKit/GoPay] No \`provider_metadata.description\` provided. Using default: "Subscription by ${data.customer.email}"`
4451
4530
  );
4452
4531
  }
4453
4532
  }
4454
- const intervalMap = {
4455
- day: "DAY",
4456
- week: "WEEK",
4457
- month: "MONTH",
4458
- year: "ON_DEMAND"
4533
+ const toDateString = (ms) => {
4534
+ const d = new Date(ms);
4535
+ return d.toISOString().split("T")[0];
4459
4536
  };
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();
4537
+ const GOPAY_MAX_DATE = "2099-12-30";
4538
+ const endDateOverride = data.provider_metadata?.end_date;
4539
+ const recurrenceDateTo = (() => {
4540
+ if (endDateOverride) {
4541
+ return endDateOverride < GOPAY_MAX_DATE ? endDateOverride : GOPAY_MAX_DATE;
4470
4542
  }
4471
4543
  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
- }
4544
+ if (isCustom) {
4545
+ return toDateString(Date.now() + 365 * 24 * 60 * 60 * 1e3);
4546
+ }
4547
+ return toDateString(
4548
+ Date.now() + 5 * 365 * 24 * 60 * 60 * 1e3
4477
4549
  );
4478
4550
  }
4479
- throw new Error("Invalid billing interval: " + data.billing_interval);
4551
+ return toDateString(Date.now() + 365 * 24 * 60 * 60 * 1e3);
4480
4552
  })();
4553
+ const recurrencePeriod = data.provider_metadata?.recurrence_period ?? 1;
4554
+ const recurrence = isOnDemand ? {
4555
+ recurrence_cycle: recurrenceCycle,
4556
+ recurrence_date_to: recurrenceDateTo
4557
+ } : {
4558
+ recurrence_cycle: recurrenceCycle,
4559
+ recurrence_period: recurrencePeriod,
4560
+ recurrence_date_to: recurrenceDateTo
4561
+ };
4481
4562
  const goPaySubscriptionOptions = {
4482
4563
  payer: {
4483
4564
  allowed_payment_instruments: ["PAYMENT_CARD"],
@@ -4488,24 +4569,28 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4488
4569
  amount: Number(data.amount),
4489
4570
  currency: data.currency ?? "CZK",
4490
4571
  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
4572
+ order_description: data.provider_metadata?.description ? data.provider_metadata.description : `Subscription by ${data.customer.email}`,
4573
+ items: [
4574
+ {
4575
+ name: data.item_id,
4576
+ amount: Number(data.amount),
4577
+ count: data.quantity ?? 1
4578
+ }
4579
+ ],
4580
+ recurrence,
4581
+ callback: {
4582
+ return_url: success_url,
4583
+ notification_url: this.opts.webhookUrl
4497
4584
  },
4498
- callback: { return_url: success_url, notification_url: this.opts.webhookUrl },
4499
4585
  additional_params: Object.entries({
4500
4586
  ...data.metadata,
4501
4587
  [core.PAYKIT_METADATA_KEY]: JSON.stringify({
4502
4588
  item: data.item_id,
4503
- qty: data.quantity
4589
+ qty: data.quantity,
4590
+ // Store the original interval so createRecurrence callers know the intended cadence
4591
+ billing_interval: isCustom ? `custom:${billingInterval.durationMs}ms` : billingInterval
4504
4592
  })
4505
- }).map(([name, value]) => ({
4506
- name,
4507
- value: String(value)
4508
- }))
4593
+ }).map(([name, value]) => ({ name, value: String(value) }))
4509
4594
  };
4510
4595
  const response = await this._client.post(
4511
4596
  "/payments/payment",
@@ -4515,28 +4600,42 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4515
4600
  }
4516
4601
  );
4517
4602
  if (!response.ok) {
4518
- throw new core.OperationFailedError("createSubscription", this.providerName, {
4519
- cause: new Error("Failed to create subscription")
4520
- });
4603
+ throw new core.OperationFailedError(
4604
+ "createSubscription",
4605
+ this.providerName,
4606
+ {
4607
+ cause: new Error(
4608
+ `[PayKit/GoPay] Failed to create subscription. Error: ${response.error}`
4609
+ )
4610
+ }
4611
+ );
4521
4612
  }
4522
- return paykitSubscription$InboundSchema(response.value);
4613
+ return Subscription$inboundSchema(response.value);
4523
4614
  };
4524
4615
  updateSubscription = async (id, params) => {
4525
4616
  const subscription = await this.retrieveSubscription(id);
4526
4617
  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
- });
4618
+ throw new core.ProviderNotSupportedError(
4619
+ "updateSubscription",
4620
+ this.providerName,
4621
+ {
4622
+ reason: "Gopay doesn't support updating subscriptions",
4623
+ alternative: "Use the payment API instead and update the subscription manually"
4624
+ }
4625
+ );
4531
4626
  }
4532
4627
  return subscription;
4533
4628
  };
4534
4629
  cancelSubscription = async (id) => {
4535
4630
  const existingSubscription = await this.retrieveSubscription(id);
4536
4631
  if (!existingSubscription) {
4537
- throw new core.OperationFailedError("cancelSubscription", this.providerName, {
4538
- cause: new Error("Failed to retrieve subscription")
4539
- });
4632
+ throw new core.OperationFailedError(
4633
+ "cancelSubscription",
4634
+ this.providerName,
4635
+ {
4636
+ cause: new Error("Failed to retrieve subscription")
4637
+ }
4638
+ );
4540
4639
  }
4541
4640
  const response = await this._client.post(`/payments/payment/${id}/void-recurrence`, {
4542
4641
  headers: {
@@ -4546,7 +4645,9 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4546
4645
  });
4547
4646
  return {
4548
4647
  ...existingSubscription,
4549
- ...response.value?.result == "FINISHED" && { status: "canceled" }
4648
+ ...response.value?.result == "FINISHED" && {
4649
+ status: "canceled"
4650
+ }
4550
4651
  };
4551
4652
  };
4552
4653
  deleteSubscription = async (id) => {
@@ -4561,21 +4662,35 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4561
4662
  }
4562
4663
  );
4563
4664
  if (!response.ok) {
4564
- throw new core.OperationFailedError("retrieveSubscription", this.providerName, {
4565
- cause: new Error("Failed to retrieve subscription")
4566
- });
4665
+ throw new core.OperationFailedError(
4666
+ "retrieveSubscription",
4667
+ this.providerName,
4668
+ {
4669
+ cause: new Error("Failed to retrieve subscription")
4670
+ }
4671
+ );
4567
4672
  }
4568
- return paykitSubscription$InboundSchema(response.value);
4673
+ return Subscription$inboundSchema(response.value);
4569
4674
  };
4570
4675
  createPayment = async (params) => {
4571
4676
  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
- });
4677
+ if (error) {
4678
+ throw core.ValidationError.fromZodError(
4679
+ error,
4680
+ this.providerName,
4681
+ "createPayment"
4682
+ );
4683
+ }
4684
+ if (!core.isEmailCustomer(data.customer)) {
4685
+ throw new core.InvalidTypeError(
4686
+ "customer",
4687
+ "object with email",
4688
+ core.isIdCustomer(data.customer) ? "object with id" : typeof data.customer,
4689
+ {
4690
+ provider: this.providerName,
4691
+ method: "createPayment"
4692
+ }
4693
+ );
4579
4694
  }
4580
4695
  if (!data.item_id) {
4581
4696
  throw new core.ConfigurationError(
@@ -4600,20 +4715,40 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4600
4715
  payer: {
4601
4716
  allowed_payment_instruments: ["PAYMENT_CARD", "BANK_ACCOUNT"],
4602
4717
  default_payment_instrument: "PAYMENT_CARD",
4603
- contact: { email: data.customer.email }
4718
+ contact: { email: data.customer.email },
4719
+ ...data.billing && {
4720
+ city: data.billing.address.city,
4721
+ postal_code: data.billing.address.postal_code,
4722
+ country_code: data.billing.address.country,
4723
+ phone_number: data.billing.address.phone
4724
+ }
4604
4725
  },
4605
- callback: { return_url: successUrl, notification_url: this.opts.webhookUrl },
4606
4726
  target: { type: "ACCOUNT", goid: parseInt(this.opts.goId) },
4607
- amount: data.amount,
4727
+ amount: Number(data.amount),
4608
4728
  currency: data.currency ?? "CZK",
4609
4729
  order_number: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
4610
4730
  order_description: `Payment for ${data.item_id} by ${data.customer.email}`,
4611
- items: [{ name: data.item_id, amount: data.amount, count: 1 }],
4731
+ items: [
4732
+ {
4733
+ name: data.item_id,
4734
+ amount: data.amount,
4735
+ count: 1,
4736
+ type: "ITEM"
4737
+ }
4738
+ ],
4739
+ lang: data.provider_metadata?.language ? data.provider_metadata.language : "EN",
4740
+ callback: {
4741
+ return_url: successUrl,
4742
+ notification_url: this.opts.webhookUrl
4743
+ },
4612
4744
  preauthorization: false,
4613
4745
  // automatically captures the payment
4614
4746
  additional_params: Object.entries({
4615
4747
  ...data.metadata,
4616
- [core.PAYKIT_METADATA_KEY]: JSON.stringify({ itemId: data.item_id, qty: 1 })
4748
+ [core.PAYKIT_METADATA_KEY]: JSON.stringify({
4749
+ itemId: data.item_id,
4750
+ qty: 1
4751
+ })
4617
4752
  }).map(([name, value]) => ({
4618
4753
  name,
4619
4754
  value: String(value)
@@ -4627,11 +4762,17 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4627
4762
  }
4628
4763
  );
4629
4764
  if (!response.ok) {
4630
- throw new core.OperationFailedError("createPayment", this.providerName, {
4631
- cause: new Error("Failed to create payment")
4632
- });
4765
+ throw new core.OperationFailedError(
4766
+ "createPayment",
4767
+ this.providerName,
4768
+ {
4769
+ cause: new Error(
4770
+ `Failed to create payment: ${JSON.stringify(response.error ?? response)}`
4771
+ )
4772
+ }
4773
+ );
4633
4774
  }
4634
- return paykitPayment$InboundSchema(response.value);
4775
+ return Payment$inboundSchema(response.value);
4635
4776
  };
4636
4777
  retrievePayment = async (id) => {
4637
4778
  const response = await this._client.get(
@@ -4644,17 +4785,25 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4644
4785
  }
4645
4786
  );
4646
4787
  if (!response.ok) {
4647
- throw new core.OperationFailedError("retrievePayment", this.providerName, {
4648
- cause: new Error("Failed to retrieve payment")
4649
- });
4788
+ throw new core.OperationFailedError(
4789
+ "retrievePayment",
4790
+ this.providerName,
4791
+ {
4792
+ cause: new Error("Failed to retrieve payment")
4793
+ }
4794
+ );
4650
4795
  }
4651
- return paykitPayment$InboundSchema(response.value);
4796
+ return Payment$inboundSchema(response.value);
4652
4797
  };
4653
4798
  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
- });
4799
+ throw new core.ProviderNotSupportedError(
4800
+ "deletePayment",
4801
+ this.providerName,
4802
+ {
4803
+ reason: "GoPay does not support deleting payments, use the",
4804
+ alternative: "Use createRefund() instead to refund payments"
4805
+ }
4806
+ );
4658
4807
  };
4659
4808
  capturePayment = async (id, params) => {
4660
4809
  const payment = await this._client.get(
@@ -4662,32 +4811,39 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4662
4811
  { headers: await this.tokenManager.getAuthHeaders() }
4663
4812
  );
4664
4813
  if (!payment.ok) {
4665
- throw new core.OperationFailedError("capturePayment", this.providerName, {
4666
- cause: new Error("Failed to retrieve payment")
4667
- });
4814
+ throw new core.OperationFailedError(
4815
+ "capturePayment",
4816
+ this.providerName,
4817
+ {
4818
+ cause: new Error("Failed to retrieve payment")
4819
+ }
4820
+ );
4668
4821
  }
4669
4822
  const { item, qty } = JSON.parse(
4670
4823
  decodeHtmlEntities(
4671
- payment.value.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4824
+ payment.value.additional_params?.find(
4825
+ (param) => param.name === core.PAYKIT_METADATA_KEY
4826
+ )?.value ?? "{}"
4672
4827
  )
4673
4828
  );
4674
4829
  if (!payment) {
4675
- throw new core.OperationFailedError("capturePayment", this.providerName, {
4676
- cause: new Error("Payment not found after capture")
4677
- });
4830
+ throw new core.OperationFailedError(
4831
+ "capturePayment",
4832
+ this.providerName,
4833
+ {
4834
+ cause: new Error("Payment not found after capture")
4835
+ }
4836
+ );
4678
4837
  }
4679
4838
  const captureBody = {
4680
4839
  amount: params.amount,
4681
4840
  items: [{ name: item, amount: params.amount, count: qty }]
4682
4841
  };
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);
4842
+ await this._client.post(`/payments/payment/${id}/capture`, {
4843
+ body: JSON.stringify(captureBody),
4844
+ headers: await this.tokenManager.getAuthHeaders()
4845
+ });
4846
+ return Payment$inboundSchema(payment.value);
4691
4847
  };
4692
4848
  cancelPayment = async (id) => {
4693
4849
  await this._client.post(
@@ -4696,9 +4852,13 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4696
4852
  );
4697
4853
  const payment = await this.retrievePayment(id);
4698
4854
  if (!payment) {
4699
- throw new core.OperationFailedError("cancelPayment", this.providerName, {
4700
- cause: new Error("Payment not found after cancellation")
4701
- });
4855
+ throw new core.OperationFailedError(
4856
+ "cancelPayment",
4857
+ this.providerName,
4858
+ {
4859
+ cause: new Error("Payment not found after cancellation")
4860
+ }
4861
+ );
4702
4862
  }
4703
4863
  return payment;
4704
4864
  };
@@ -4709,34 +4869,52 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4709
4869
  console.info("Gopay doesn't support updating payments");
4710
4870
  const existing = await this.retrievePayment(id);
4711
4871
  if (!existing) {
4712
- throw new core.OperationFailedError("updatePayment", this.providerName, {
4713
- cause: new Error("Failed to retrieve payment")
4714
- });
4872
+ throw new core.OperationFailedError(
4873
+ "updatePayment",
4874
+ this.providerName,
4875
+ {
4876
+ cause: new Error("Failed to retrieve payment")
4877
+ }
4878
+ );
4715
4879
  }
4716
4880
  return existing;
4717
4881
  };
4718
4882
  async createRefund(params) {
4719
4883
  const { error, data } = core.createRefundSchema.safeParse(params);
4720
4884
  if (error) {
4721
- throw core.ValidationError.fromZodError(error, this.providerName, "createRefund");
4885
+ throw core.ValidationError.fromZodError(
4886
+ error,
4887
+ this.providerName,
4888
+ "createRefund"
4889
+ );
4722
4890
  }
4723
4891
  const payment = await this.retrievePayment(data.payment_id);
4724
4892
  if (!payment) {
4725
- throw new core.OperationFailedError("createRefund", this.providerName, {
4726
- cause: new Error("Failed to retrieve payment")
4727
- });
4893
+ throw new core.OperationFailedError(
4894
+ "createRefund",
4895
+ this.providerName,
4896
+ {
4897
+ cause: new Error("Failed to retrieve payment")
4898
+ }
4899
+ );
4728
4900
  }
4729
4901
  const response = await this._client.post(`/payments/payment/${data.payment_id}/refund`, {
4730
- body: new URLSearchParams({ amount: String(data.amount) }).toString(),
4902
+ body: new URLSearchParams({
4903
+ amount: String(data.amount)
4904
+ }).toString(),
4731
4905
  headers: {
4732
4906
  ...await this.tokenManager.getAuthHeaders(),
4733
4907
  "Content-Type": "application/x-www-form-urlencoded"
4734
4908
  }
4735
4909
  });
4736
4910
  if (!response.ok) {
4737
- throw new core.OperationFailedError("createRefund", this.providerName, {
4738
- cause: new Error("Failed to create refund")
4739
- });
4911
+ throw new core.OperationFailedError(
4912
+ "createRefund",
4913
+ this.providerName,
4914
+ {
4915
+ cause: new Error("Failed to create refund")
4916
+ }
4917
+ );
4740
4918
  }
4741
4919
  return {
4742
4920
  id: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
@@ -4746,23 +4924,28 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4746
4924
  metadata: data.metadata
4747
4925
  };
4748
4926
  }
4749
- handleWebhook = async (payload) => {
4927
+ handleWebhook = async (payload, webhookSecret) => {
4750
4928
  const { fullUrl } = payload;
4751
4929
  const paymentId = new URL(fullUrl).searchParams.get("id");
4752
4930
  const parentId = new URL(fullUrl).searchParams.get("parent_id");
4753
4931
  if (!paymentId) {
4754
- throw new core.WebhookError("Payment ID is required", { provider: this.providerName });
4932
+ throw new core.WebhookError("Payment ID is required", {
4933
+ provider: this.providerName
4934
+ });
4755
4935
  }
4756
4936
  if (this.opts.debug) {
4757
4937
  console.info("Received GoPay webhook for payment:", paymentId);
4758
4938
  }
4759
4939
  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"
4940
+ this._client.get(
4941
+ `/payments/payment/${paymentId}`,
4942
+ {
4943
+ headers: {
4944
+ ...await this.tokenManager.getAuthHeaders(),
4945
+ "Content-Type": "application/x-www-form-urlencoded"
4946
+ }
4764
4947
  }
4765
- })
4948
+ )
4766
4949
  );
4767
4950
  if (error) {
4768
4951
  throw new core.WebhookError("Failed to retrieve payment", {
@@ -4770,10 +4953,15 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4770
4953
  });
4771
4954
  }
4772
4955
  if (!payment.value) {
4773
- throw new core.WebhookError("Payment not found", { provider: this.providerName });
4956
+ throw new core.WebhookError("Payment not found", {
4957
+ provider: this.providerName
4958
+ });
4774
4959
  }
4775
4960
  if (this.opts.debug) {
4776
- console.info("Webhook verified successfully, status:", payment.value.state);
4961
+ console.info(
4962
+ "Webhook verified successfully, status:",
4963
+ payment.value.state
4964
+ );
4777
4965
  }
4778
4966
  const statusMap = {
4779
4967
  CREATED: "pending",
@@ -4792,7 +4980,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4792
4980
  __INDETERMINATE: (data) => {
4793
4981
  const isRefundEvent = data.state === "REFUNDED" || data.state === "PARTIALLY_REFUNDED";
4794
4982
  if (isRefundEvent) {
4795
- const refund = paykitRefund$InboundSchema(data);
4983
+ const refund = Refund$inboundSchema(data);
4796
4984
  return [
4797
4985
  core.paykitEvent$InboundSchema({
4798
4986
  type: "refund.created",
@@ -4805,7 +4993,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4805
4993
  return [];
4806
4994
  },
4807
4995
  pending: (data) => {
4808
- const payment2 = paykitPayment$InboundSchema(data);
4996
+ const payment2 = Payment$inboundSchema(data);
4809
4997
  return [
4810
4998
  core.paykitEvent$InboundSchema({
4811
4999
  type: "payment.created",
@@ -4816,7 +5004,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4816
5004
  ];
4817
5005
  },
4818
5006
  processing: (data) => {
4819
- const payment2 = paykitPayment$InboundSchema(data);
5007
+ const payment2 = Payment$inboundSchema(data);
4820
5008
  return [
4821
5009
  core.paykitEvent$InboundSchema({
4822
5010
  type: "payment.updated",
@@ -4827,7 +5015,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4827
5015
  ];
4828
5016
  },
4829
5017
  requires_capture: (data) => {
4830
- const payment2 = paykitPayment$InboundSchema(data);
5018
+ const payment2 = Payment$inboundSchema(data);
4831
5019
  return [
4832
5020
  core.paykitEvent$InboundSchema({
4833
5021
  type: "payment.updated",
@@ -4838,9 +5026,9 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4838
5026
  ];
4839
5027
  },
4840
5028
  canceled: (data) => {
4841
- const payment2 = paykitPayment$InboundSchema(data);
5029
+ const payment2 = Payment$inboundSchema(data);
4842
5030
  const isCancellingSubscription = parentId && data.recurrence?.recurrence_state == "STOPPED";
4843
- const subscription = paykitSubscription$InboundSchema(
5031
+ const subscription = Subscription$inboundSchema(
4844
5032
  data
4845
5033
  );
4846
5034
  const subscriptionCanceledWebhookEvent = {
@@ -4850,9 +5038,13 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4850
5038
  data: subscription
4851
5039
  };
4852
5040
  return [
4853
- ...isCancellingSubscription ? [core.paykitEvent$InboundSchema(subscriptionCanceledWebhookEvent)] : [],
5041
+ ...isCancellingSubscription ? [
5042
+ core.paykitEvent$InboundSchema(
5043
+ subscriptionCanceledWebhookEvent
5044
+ )
5045
+ ] : [],
4854
5046
  core.paykitEvent$InboundSchema({
4855
- type: "payment.canceled",
5047
+ type: "payment.failed",
4856
5048
  created: (/* @__PURE__ */ new Date()).getTime(),
4857
5049
  id: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
4858
5050
  data: payment2
@@ -4860,10 +5052,10 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4860
5052
  ];
4861
5053
  },
4862
5054
  failed: (data) => {
4863
- const payment2 = paykitPayment$InboundSchema(data);
5055
+ const payment2 = Payment$inboundSchema(data);
4864
5056
  return [
4865
5057
  core.paykitEvent$InboundSchema({
4866
- type: "payment.canceled",
5058
+ type: "payment.failed",
4867
5059
  created: (/* @__PURE__ */ new Date()).getTime(),
4868
5060
  id: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
4869
5061
  data: payment2
@@ -4871,9 +5063,9 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4871
5063
  ];
4872
5064
  },
4873
5065
  succeeded: (data) => {
4874
- const payment2 = paykitPayment$InboundSchema(data);
4875
- const invoice = paykitInvoice$InboundSchema(data, !!parentId);
4876
- const subscription = paykitSubscription$InboundSchema(
5066
+ const payment2 = Payment$inboundSchema(data);
5067
+ const invoice = Invoice$inboundSchema(data, !!parentId);
5068
+ const subscription = Subscription$inboundSchema(
4877
5069
  data
4878
5070
  );
4879
5071
  const subscriptionCreatedWebhookEvent = {
@@ -4883,7 +5075,11 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4883
5075
  data: subscription
4884
5076
  };
4885
5077
  return [
4886
- ...parentId ? [core.paykitEvent$InboundSchema(subscriptionCreatedWebhookEvent)] : [],
5078
+ ...parentId ? [
5079
+ core.paykitEvent$InboundSchema(
5080
+ subscriptionCreatedWebhookEvent
5081
+ )
5082
+ ] : [],
4887
5083
  core.paykitEvent$InboundSchema({
4888
5084
  type: "invoice.generated",
4889
5085
  created: (/* @__PURE__ */ new Date()).getTime(),
@@ -4891,7 +5087,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4891
5087
  data: invoice
4892
5088
  }),
4893
5089
  core.paykitEvent$InboundSchema({
4894
- type: "payment.created",
5090
+ type: "payment.succeeded",
4895
5091
  created: (/* @__PURE__ */ new Date()).getTime(),
4896
5092
  id: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
4897
5093
  data: payment2
@@ -4899,7 +5095,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4899
5095
  ];
4900
5096
  },
4901
5097
  requires_action: (data) => {
4902
- const payment2 = paykitPayment$InboundSchema(data);
5098
+ const payment2 = Payment$inboundSchema(data);
4903
5099
  return [
4904
5100
  core.paykitEvent$InboundSchema({
4905
5101
  type: "payment.updated",