@paykit-sdk/gopay 1.0.5 → 1.1.2

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.
@@ -4058,70 +4058,63 @@ var ostring = () => stringType().optional();
4058
4058
  var onumber = () => numberType().optional();
4059
4059
  var oboolean = () => booleanType().optional();
4060
4060
  var coerce = {
4061
- string: (arg) => ZodString.create({ ...arg, coerce: true }),
4062
- number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
4063
- boolean: (arg) => ZodBoolean.create({
4061
+ string: ((arg) => ZodString.create({ ...arg, coerce: true })),
4062
+ number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
4063
+ boolean: ((arg) => ZodBoolean.create({
4064
4064
  ...arg,
4065
4065
  coerce: true
4066
- }),
4067
- bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
4068
- date: (arg) => ZodDate.create({ ...arg, coerce: true })
4066
+ })),
4067
+ bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
4068
+ date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
4069
4069
  };
4070
4070
  var NEVER = INVALID;
4071
- var AuthController = class {
4072
- constructor(opts) {
4073
- this.opts = opts;
4074
- const debug = opts.debug ?? true;
4075
- this._client = new core.HTTPClient({
4076
- baseUrl: this.opts.baseUrl,
4077
- headers: {},
4078
- retryOptions: { max: 3, baseDelay: 1e3, debug }
4079
- });
4080
- }
4081
- _client;
4082
- _accessToken = null;
4083
- getAccessToken = async () => {
4084
- if (this._accessToken) {
4085
- const [token, , expiryStr] = this._accessToken.split("::paykit::");
4086
- const expiry = parseInt(expiryStr || "0", 10);
4087
- if (expiry > Date.now()) return token;
4088
- }
4089
- const credentials = Buffer.from(
4090
- `${this.opts.clientId}:${this.opts.clientSecret}`
4091
- ).toString("base64");
4092
- const response = await this._client.post("/oauth2/token", {
4093
- headers: {
4094
- Authorization: `Basic ${credentials}`,
4095
- "Content-Type": "application/x-www-form-urlencoded"
4071
+ var decodeHtmlEntities = (str) => {
4072
+ return str.replace(/"/g, '"').replace(/'/g, "'").replace(/"/g, '"').replace(/'/g, "'");
4073
+ };
4074
+ var paykitPayment$InboundSchema = (data) => {
4075
+ const { item } = JSON.parse(
4076
+ decodeHtmlEntities(
4077
+ data.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4078
+ )
4079
+ );
4080
+ const metadata = core.omitInternalMetadata(
4081
+ data.additional_params?.reduce(
4082
+ (acc, param) => {
4083
+ acc[param.name] = String(param.value);
4084
+ return acc;
4096
4085
  },
4097
- body: new URLSearchParams({
4098
- grant_type: "client_credentials",
4099
- scope: "payment-all"
4100
- }).toString()
4101
- });
4102
- if (!response.ok || !response.value.access_token) {
4103
- throw new core.OperationFailedError("getAccessToken", "gopay", {
4104
- cause: new Error("Failed to obtain GoPay access token")
4105
- });
4106
- }
4107
- const expiryTime = Date.now() + (response.value.expires_in - 300) * 1e3;
4108
- const accessToken = `${response.value.access_token}::paykit::${expiryTime}`;
4109
- this._accessToken = accessToken;
4110
- return accessToken;
4086
+ {}
4087
+ ) ?? {}
4088
+ );
4089
+ const statusMap = {
4090
+ CREATED: "pending",
4091
+ PAYMENT_METHOD_CHOSEN: "processing",
4092
+ PAID: "succeeded",
4093
+ AUTHORIZED: "requires_capture",
4094
+ CANCELED: "canceled",
4095
+ TIMEOUTED: "canceled",
4096
+ REFUNDED: "canceled",
4097
+ PARTIALLY_REFUNDED: "canceled"
4111
4098
  };
4112
- getAuthHeaders = async () => {
4113
- const token = await this.getAccessToken();
4114
- return {
4115
- Authorization: `Bearer ${token}`,
4116
- "Content-Type": "application/json",
4117
- Accept: "application/json"
4118
- };
4099
+ const requiresAction = data.state === "CREATED" || data.state === "AUTHORIZED" ? true : false;
4100
+ return {
4101
+ id: data.id.toString(),
4102
+ amount: data.amount,
4103
+ currency: data.currency,
4104
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4105
+ status: statusMap[data.state],
4106
+ item_id: item,
4107
+ metadata,
4108
+ requires_action: requiresAction,
4109
+ payment_url: data.gw_url ?? null
4119
4110
  };
4120
4111
  };
4121
- var paykitPayment$InboundSchema = (data) => {
4122
- const itemId = JSON.parse(
4123
- data.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4124
- ).itemId;
4112
+ var paykitCheckout$InboundSchema = (data) => {
4113
+ const { item, qty, type } = JSON.parse(
4114
+ decodeHtmlEntities(
4115
+ data.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4116
+ )
4117
+ );
4125
4118
  const metadata = core.omitInternalMetadata(
4126
4119
  data.additional_params?.reduce(
4127
4120
  (acc, param) => {
@@ -4135,24 +4128,24 @@ var paykitPayment$InboundSchema = (data) => {
4135
4128
  id: data.id.toString(),
4136
4129
  amount: data.amount,
4137
4130
  currency: data.currency,
4138
- customer: data.payer ?? { email: data.payer?.email ?? "" },
4139
- status: data.state,
4140
- item_id: itemId,
4141
- metadata
4131
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4132
+ payment_url: data.gw_url ?? "",
4133
+ metadata,
4134
+ session_type: type,
4135
+ products: [{ id: item, quantity: parseInt(qty) }]
4142
4136
  };
4143
4137
  };
4144
4138
  var paykitInvoice$InboundSchema = (data, isSubscription) => {
4145
- const quantity = JSON.parse(
4146
- data.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4147
- ).qty;
4148
- const itemId = JSON.parse(
4149
- data.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4150
- ).itemId;
4139
+ const { item, qty } = JSON.parse(
4140
+ decodeHtmlEntities(
4141
+ data.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4142
+ )
4143
+ );
4151
4144
  const status = (() => {
4152
4145
  if (data.state === "PAID") return "paid";
4153
4146
  return "open";
4154
4147
  })();
4155
- const paidAt = isSubscription ? new Date(data.recurrence?.recurrence_date_from ?? "") : /* @__PURE__ */ new Date();
4148
+ const paidAt = isSubscription ? new Date(data.recurrence?.recurrence_date_to ?? "") : /* @__PURE__ */ new Date();
4156
4149
  const metadata = core.omitInternalMetadata(
4157
4150
  data.additional_params?.reduce(
4158
4151
  (acc, param) => {
@@ -4166,20 +4159,22 @@ var paykitInvoice$InboundSchema = (data, isSubscription) => {
4166
4159
  id: data.id.toString(),
4167
4160
  amount_paid: data.amount,
4168
4161
  currency: data.currency,
4169
- customer: data.payer ?? { email: data.payer?.email ?? "" },
4162
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4170
4163
  status,
4171
4164
  paid_at: paidAt.toISOString(),
4172
4165
  metadata: metadata ?? {},
4173
4166
  custom_fields: null,
4174
4167
  subscription_id: isSubscription ? data.id.toString() : null,
4175
4168
  billing_mode: isSubscription ? "recurring" : "one_time",
4176
- line_items: [{ id: itemId, quantity: parseInt(quantity) }]
4169
+ line_items: [{ id: item, quantity: parseInt(qty) }]
4177
4170
  };
4178
4171
  };
4179
4172
  var paykitSubscription$InboundSchema = (data) => {
4180
- const itemId = JSON.parse(
4181
- data.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4182
- ).itemId;
4173
+ const { item } = JSON.parse(
4174
+ decodeHtmlEntities(
4175
+ data.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4176
+ )
4177
+ );
4183
4178
  const billingIntervalMap = {
4184
4179
  DAY: "day",
4185
4180
  WEEK: "week",
@@ -4187,8 +4182,28 @@ var paykitSubscription$InboundSchema = (data) => {
4187
4182
  ON_DEMAND: "month"
4188
4183
  };
4189
4184
  const billingInterval = billingIntervalMap[data.recurrence?.recurrence_cycle ?? "ON_DEMAND"];
4190
- const currentPeriodStart = new Date(data.recurrence?.recurrence_date_from ?? "");
4185
+ const recurrencePeriod = data.recurrence?.recurrence_period ?? 1;
4186
+ const recurrenceCycle = data.recurrence?.recurrence_cycle;
4191
4187
  const currentPeriodEnd = new Date(data.recurrence?.recurrence_date_to ?? "");
4188
+ const currentPeriodStart = (() => {
4189
+ if (!currentPeriodEnd) return /* @__PURE__ */ new Date();
4190
+ const endDate = new Date(currentPeriodEnd);
4191
+ const startDate = new Date(endDate);
4192
+ switch (recurrenceCycle) {
4193
+ case "DAY":
4194
+ startDate.setDate(startDate.getDate() - recurrencePeriod);
4195
+ break;
4196
+ case "WEEK":
4197
+ startDate.setDate(startDate.getDate() - recurrencePeriod * 7);
4198
+ break;
4199
+ case "MONTH":
4200
+ startDate.setMonth(startDate.getMonth() - recurrencePeriod);
4201
+ break;
4202
+ default:
4203
+ startDate.setDate(startDate.getDate() - recurrencePeriod);
4204
+ }
4205
+ return startDate;
4206
+ })();
4192
4207
  const metadata = core.omitInternalMetadata(
4193
4208
  data.additional_params?.reduce(
4194
4209
  (acc, param) => {
@@ -4198,18 +4213,32 @@ var paykitSubscription$InboundSchema = (data) => {
4198
4213
  {}
4199
4214
  ) ?? {}
4200
4215
  );
4216
+ 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
+ })();
4201
4228
  return {
4202
4229
  id: data.id.toString(),
4203
- status: "active",
4204
- customer: data.payer ?? { email: data.payer?.email ?? "" },
4205
- item_id: itemId,
4230
+ status,
4231
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4232
+ item_id: item,
4206
4233
  billing_interval: billingInterval,
4207
4234
  currency: data.currency,
4208
4235
  amount: data.amount,
4209
- metadata: metadata ?? {},
4236
+ metadata,
4210
4237
  custom_fields: null,
4211
4238
  current_period_start: currentPeriodStart,
4212
- current_period_end: currentPeriodEnd
4239
+ current_period_end: currentPeriodEnd,
4240
+ requires_action: requiresAction,
4241
+ payment_url: requiresAction ? data.gw_url ?? null : null
4213
4242
  };
4214
4243
  };
4215
4244
  var paykitRefund$InboundSchema = (data) => {
@@ -4239,22 +4268,42 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4239
4268
  super(gopayOptionsSchema, opts, providerName);
4240
4269
  this.opts = opts;
4241
4270
  const debug = opts.debug ?? true;
4242
- this.baseUrl = opts.isSandbox ? "https://gate.gopay.cz/api" : "https://gw.sandbox.gopay.com/api";
4271
+ this.baseUrl = opts.isSandbox ? "https://gw.sandbox.gopay.com/api" : "https://gate.gopay.cz/api";
4243
4272
  this._client = new core.HTTPClient({
4244
4273
  baseUrl: this.baseUrl,
4245
4274
  headers: {},
4246
4275
  retryOptions: { max: 3, baseDelay: 1e3, debug }
4247
4276
  });
4248
- this.authController = new AuthController({ ...opts, baseUrl: this.baseUrl });
4277
+ this.tokenManager = new core.OAuth2TokenManager({
4278
+ client: this._client,
4279
+ provider: this.providerName,
4280
+ tokenEndpoint: "/oauth2/token",
4281
+ credentials: { username: opts.clientId, password: opts.clientSecret },
4282
+ responseAdapter: (response) => ({
4283
+ accessToken: response.access_token,
4284
+ expiresIn: response.expires_in
4285
+ }),
4286
+ expiryBuffer: 5 * 60,
4287
+ // 5 minutes
4288
+ requestBody: "grant_type=client_credentials&scope=payment-all",
4289
+ requestHeaders: {
4290
+ "Content-Type": "application/x-www-form-urlencoded",
4291
+ Accept: "application/json"
4292
+ },
4293
+ authHeaders: {
4294
+ "Content-Type": "application/json",
4295
+ Accept: "application/json"
4296
+ }
4297
+ });
4249
4298
  }
4250
4299
  providerName = providerName;
4251
4300
  _client;
4252
4301
  baseUrl;
4253
- authController;
4302
+ tokenManager;
4254
4303
  createCheckout = async (params) => {
4255
4304
  const { error, data } = core.createCheckoutSchema.safeParse(params);
4256
4305
  if (error) throw core.ValidationError.fromZodError(error, "gopay", "createCheckout");
4257
- if (typeof data.customer == "string" || typeof data.customer === "object" && !data.customer.email) {
4306
+ if (!core.isEmailCustomer(data.customer)) {
4258
4307
  throw new core.InvalidTypeError("customer", "object (customer) with email", "string", {
4259
4308
  provider: this.providerName,
4260
4309
  method: "createCheckout"
@@ -4267,7 +4316,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4267
4316
  );
4268
4317
  if (this.opts.debug) {
4269
4318
  console.info(
4270
- "Specify `lang` in the provider_metadata of createCheckout to set the language of the checkout, default is `EN`"
4319
+ "Specify `language` in the `provider_metadata` of createCheckout to set the language of the checkout, default is `EN`"
4271
4320
  );
4272
4321
  console.info("Creating checkout with metadata:", data.metadata);
4273
4322
  }
@@ -4296,31 +4345,42 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4296
4345
  type: "ITEM"
4297
4346
  }
4298
4347
  ],
4299
- lang: data.provider_metadata?.lang ? data.provider_metadata.lang : "EN",
4348
+ lang: data.provider_metadata?.language ? data.provider_metadata.language : "EN",
4300
4349
  callback: { return_url: data.success_url, notification_url: this.opts.webhookUrl },
4301
4350
  additional_params: Object.entries({
4302
4351
  ...data.metadata,
4303
4352
  [core.PAYKIT_METADATA_KEY]: JSON.stringify({
4304
- itemId: data.item_id,
4305
- qty: data.quantity
4353
+ item: data.item_id,
4354
+ qty: data.quantity,
4355
+ type: data.session_type
4306
4356
  })
4307
4357
  }).map(([name, value]) => ({
4308
4358
  name,
4309
4359
  value: String(value)
4310
4360
  }))
4311
4361
  };
4312
- const response = await this._client.post("/payments/payment", {
4313
- body: JSON.stringify(goPayRequest),
4314
- headers: await this.authController.getAuthHeaders()
4315
- });
4316
- console.dir({ response }, { depth: null });
4317
- return response.value;
4362
+ const response = await this._client.post(
4363
+ "/payments/payment",
4364
+ {
4365
+ body: JSON.stringify(goPayRequest),
4366
+ headers: await this.tokenManager.getAuthHeaders()
4367
+ }
4368
+ );
4369
+ if (!response.ok) {
4370
+ throw new core.OperationFailedError("createCheckout", this.providerName, {
4371
+ cause: new Error("Failed to create checkout")
4372
+ });
4373
+ }
4374
+ return paykitCheckout$InboundSchema(response.value);
4318
4375
  };
4319
4376
  retrieveCheckout = async (id) => {
4320
4377
  const response = await this._client.get(
4321
4378
  `/payments/payment/${id}`,
4322
4379
  {
4323
- headers: await this.authController.getAuthHeaders()
4380
+ headers: {
4381
+ ...await this.tokenManager.getAuthHeaders(),
4382
+ "Content-Type": "application/x-www-form-urlencoded"
4383
+ }
4324
4384
  }
4325
4385
  );
4326
4386
  if (!response.ok) {
@@ -4328,12 +4388,13 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4328
4388
  cause: new Error("Failed to retrieve checkout")
4329
4389
  });
4330
4390
  }
4331
- console.dir({ response }, { depth: null });
4332
- return response.value;
4391
+ return paykitCheckout$InboundSchema(response.value);
4333
4392
  };
4334
4393
  updateCheckout = async (id, params) => {
4335
4394
  if (this.opts.debug) {
4336
- console.info("Gopay doesn't support updating checkouts");
4395
+ console.info(
4396
+ "Gopay doesn't support updating checkouts, returning existing checkout"
4397
+ );
4337
4398
  }
4338
4399
  const existing = await this.retrieveCheckout(id);
4339
4400
  return existing;
@@ -4345,23 +4406,36 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4345
4406
  });
4346
4407
  };
4347
4408
  createCustomer = async (params) => {
4409
+ if (this.cloudClient) {
4410
+ return this.cloudClient.customers.create(params);
4411
+ }
4348
4412
  throw new core.ProviderNotSupportedError("createCustomer", "gopay", {
4349
- reason: "Gopay doesn't support creating customers"
4413
+ reason: "Gopay doesn't support creating customers, use the cloud API instead by setting `cloudApiKey` in the options"
4350
4414
  });
4351
4415
  };
4352
4416
  updateCustomer = async (id, params) => {
4417
+ if (this.cloudClient) {
4418
+ return this.cloudClient.customers.update(id, params);
4419
+ }
4353
4420
  throw new core.ProviderNotSupportedError("updateCustomer", "gopay", {
4354
- reason: "Gopay doesn't support updating customers"
4421
+ reason: "Gopay doesn't support updating customers, use the cloud API instead by setting `cloudApiKey` in the options"
4355
4422
  });
4356
4423
  };
4357
4424
  deleteCustomer = async (id) => {
4425
+ if (this.cloudClient) {
4426
+ this.cloudClient.customers.delete(id);
4427
+ return null;
4428
+ }
4358
4429
  throw new core.ProviderNotSupportedError("deleteCustomer", "gopay", {
4359
- reason: "Gopay doesn't support deleting customers"
4430
+ reason: "Gopay doesn't support deleting customers, use the cloud API instead by setting `cloudApiKey` in the options"
4360
4431
  });
4361
4432
  };
4362
4433
  retrieveCustomer = async (id) => {
4434
+ if (this.cloudClient) {
4435
+ return this.cloudClient.customers.retrieve(id);
4436
+ }
4363
4437
  throw new core.ProviderNotSupportedError("retrieveCustomer", "gopay", {
4364
- reason: "Gopay doesn't support retrieving customers"
4438
+ reason: "Gopay doesn't support retrieving customers, use the cloud API instead by setting `cloudApiKey` in the options"
4365
4439
  });
4366
4440
  };
4367
4441
  createSubscription = async (params) => {
@@ -4373,30 +4447,50 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4373
4447
  method: "createCheckout"
4374
4448
  });
4375
4449
  }
4376
- const { quantity, success_url } = core.validateRequiredKeys(
4377
- ["quantity", "success_url"],
4450
+ const { success_url } = core.validateRequiredKeys(
4451
+ ["success_url"],
4378
4452
  data.provider_metadata,
4379
4453
  "The following fields must be present in the provider_metadata of createCheckout: {keys}"
4380
4454
  );
4455
+ if (this.opts.debug) {
4456
+ if (data.billing_interval === "year") {
4457
+ console.info(
4458
+ "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"
4459
+ );
4460
+ }
4461
+ if (!data.provider_metadata?.description) {
4462
+ console.info(
4463
+ `No description provided for the subscription \`provider_metadata.description\`, using default description \`Subscription by ${data.customer.email}\``
4464
+ );
4465
+ }
4466
+ }
4381
4467
  const intervalMap = {
4382
4468
  day: "DAY",
4383
4469
  week: "WEEK",
4384
4470
  month: "MONTH",
4385
- year: "MONTH"
4471
+ year: "ON_DEMAND"
4386
4472
  };
4473
+ const recurrenceCycle = intervalMap?.[data.billing_interval] ?? "ON_DEMAND";
4387
4474
  const currentPeriodEnd = (() => {
4388
- if (data.billing_interval === "day") {
4475
+ if (recurrenceCycle === "DAY") {
4389
4476
  return new Date(Date.now() + 1 * 24 * 60 * 60 * 1e3).toISOString();
4390
4477
  }
4391
- if (data.billing_interval === "week") {
4478
+ if (recurrenceCycle === "WEEK") {
4392
4479
  return new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3).toISOString();
4393
4480
  }
4394
- if (data.billing_interval === "month") {
4481
+ if (recurrenceCycle === "MONTH") {
4395
4482
  return new Date(Date.now() + 30 * 24 * 60 * 60 * 1e3).toISOString();
4396
4483
  }
4397
- return new Date(Date.now() + 365 * 24 * 60 * 60 * 1e3).toISOString();
4484
+ if (recurrenceCycle === "ON_DEMAND") {
4485
+ throw new core.ConfigurationError(
4486
+ "ON_DEMAND subscriptions is not yet implemented by PayKit, please open an issue at https://github.com/usepaykit/paykit-sdk/issues",
4487
+ {
4488
+ provider: this.providerName
4489
+ }
4490
+ );
4491
+ }
4492
+ throw new Error("Invalid billing interval: " + data.billing_interval);
4398
4493
  })();
4399
- const recurrenceCycle = intervalMap[data.billing_interval] ?? "ON_DEMAND";
4400
4494
  const goPaySubscriptionOptions = {
4401
4495
  payer: {
4402
4496
  allowed_payment_instruments: ["PAYMENT_CARD"],
@@ -4407,54 +4501,66 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4407
4501
  amount: Number(data.amount),
4408
4502
  currency: data.currency ?? "CZK",
4409
4503
  order_number: crypto__namespace.randomBytes(8).toString("hex").slice(0, 15),
4410
- order_description: data.metadata?.description || "Subscription",
4411
- items: [
4412
- { name: data.item_id, amount: Number(data.amount), count: parseInt(quantity) }
4413
- ],
4504
+ order_description: data.provider_metadata?.description ? data.provider_metadata.description : "Subscription by " + data.customer.email,
4505
+ items: [{ name: data.item_id, amount: Number(data.amount), count: data.quantity }],
4414
4506
  recurrence: {
4415
4507
  recurrence_cycle: recurrenceCycle,
4416
- recurrence_period: parseInt(quantity),
4508
+ recurrence_period: data.quantity,
4417
4509
  recurrence_date_to: currentPeriodEnd
4418
4510
  },
4419
- callback: { return_url: success_url, notification_url: this.opts.webhookUrl }
4511
+ callback: { return_url: success_url, notification_url: this.opts.webhookUrl },
4512
+ additional_params: Object.entries({
4513
+ ...data.metadata,
4514
+ [core.PAYKIT_METADATA_KEY]: JSON.stringify({
4515
+ item: data.item_id,
4516
+ qty: data.quantity
4517
+ })
4518
+ }).map(([name, value]) => ({
4519
+ name,
4520
+ value: String(value)
4521
+ }))
4420
4522
  };
4421
- const response = await this._client.post("/payments/payment", {
4422
- body: JSON.stringify(goPaySubscriptionOptions),
4423
- headers: await this.authController.getAuthHeaders()
4424
- });
4523
+ const response = await this._client.post(
4524
+ "/payments/payment",
4525
+ {
4526
+ body: JSON.stringify(goPaySubscriptionOptions),
4527
+ headers: await this.tokenManager.getAuthHeaders()
4528
+ }
4529
+ );
4425
4530
  if (!response.ok) {
4426
4531
  throw new core.OperationFailedError("createSubscription", this.providerName, {
4427
4532
  cause: new Error("Failed to create subscription")
4428
4533
  });
4429
4534
  }
4430
- console.dir({ response }, { depth: 100 });
4431
- return response.value;
4535
+ return paykitSubscription$InboundSchema(response.value);
4432
4536
  };
4433
4537
  updateSubscription = async (id, params) => {
4434
- console.info("Gopay doesn't support updating subscriptions");
4435
4538
  const subscription = await this.retrieveSubscription(id);
4436
4539
  if (!subscription) {
4437
- throw new core.OperationFailedError("updateSubscription", this.providerName, {
4438
- cause: new Error("Failed to retrieve subscription")
4540
+ throw new core.ProviderNotSupportedError("updateSubscription", this.providerName, {
4541
+ reason: "Gopay doesn't support updating subscriptions",
4542
+ alternative: "Use the payment API instead and update the subscription manually"
4439
4543
  });
4440
4544
  }
4441
4545
  return subscription;
4442
4546
  };
4443
4547
  cancelSubscription = async (id) => {
4444
- const response = await this._client.post(
4445
- `/payments/payment/${id}/void-recurrence`,
4446
- {
4447
- headers: await this.authController.getAuthHeaders()
4448
- }
4449
- );
4450
- console.dir({ response }, { depth: 100 });
4451
- const subscription = await this.retrieveSubscription(id);
4452
- if (!subscription) {
4548
+ const existingSubscription = await this.retrieveSubscription(id);
4549
+ if (!existingSubscription) {
4453
4550
  throw new core.OperationFailedError("cancelSubscription", this.providerName, {
4454
4551
  cause: new Error("Failed to retrieve subscription")
4455
4552
  });
4456
4553
  }
4457
- return { ...subscription, status: "canceled" };
4554
+ const response = await this._client.post(`/payments/payment/${id}/void-recurrence`, {
4555
+ headers: {
4556
+ ...await this.tokenManager.getAuthHeaders(),
4557
+ "Content-Type": "application/x-www-form-urlencoded"
4558
+ }
4559
+ });
4560
+ return {
4561
+ ...existingSubscription,
4562
+ ...response.value?.result == "FINISHED" && { status: "canceled" }
4563
+ };
4458
4564
  };
4459
4565
  deleteSubscription = async (id) => {
4460
4566
  await this.cancelSubscription(id);
@@ -4464,7 +4570,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4464
4570
  const response = await this._client.get(
4465
4571
  `/payments/payment/${id}`,
4466
4572
  {
4467
- headers: await this.authController.getAuthHeaders()
4573
+ headers: await this.tokenManager.getAuthHeaders()
4468
4574
  }
4469
4575
  );
4470
4576
  if (!response.ok) {
@@ -4472,14 +4578,13 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4472
4578
  cause: new Error("Failed to retrieve subscription")
4473
4579
  });
4474
4580
  }
4475
- console.dir({ response }, { depth: 100 });
4476
- return response.value;
4581
+ return paykitSubscription$InboundSchema(response.value);
4477
4582
  };
4478
4583
  createPayment = async (params) => {
4479
4584
  const { error, data } = core.createPaymentSchema.safeParse(params);
4480
4585
  if (error)
4481
4586
  throw core.ValidationError.fromZodError(error, this.providerName, "createPayment");
4482
- if (typeof data.customer == "string" || typeof data.customer === "object" && !data.customer.email) {
4587
+ if (typeof data.customer == "string" || typeof data.customer === "object" && !data.customer?.email) {
4483
4588
  throw new core.InvalidTypeError("customer", "object (customer) with email", "string", {
4484
4589
  provider: this.providerName,
4485
4590
  method: "createPayment"
@@ -4516,23 +4621,28 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4516
4621
  value: String(value)
4517
4622
  }))
4518
4623
  };
4519
- const response = await this._client.post("/payments/payment", {
4520
- body: JSON.stringify(goPayRequest),
4521
- headers: await this.authController.getAuthHeaders()
4522
- });
4624
+ const response = await this._client.post(
4625
+ "/payments/payment",
4626
+ {
4627
+ body: JSON.stringify(goPayRequest),
4628
+ headers: await this.tokenManager.getAuthHeaders()
4629
+ }
4630
+ );
4523
4631
  if (!response.ok) {
4524
4632
  throw new core.OperationFailedError("createPayment", this.providerName, {
4525
4633
  cause: new Error("Failed to create payment")
4526
4634
  });
4527
4635
  }
4528
- console.dir({ response }, { depth: 100 });
4529
- return response.value;
4636
+ return paykitPayment$InboundSchema(response.value);
4530
4637
  };
4531
4638
  retrievePayment = async (id) => {
4532
4639
  const response = await this._client.get(
4533
4640
  `/payments/payment/${id}`,
4534
4641
  {
4535
- headers: await this.authController.getAuthHeaders()
4642
+ headers: {
4643
+ ...await this.tokenManager.getAuthHeaders(),
4644
+ "Content-Type": "application/x-www-form-urlencoded"
4645
+ }
4536
4646
  }
4537
4647
  );
4538
4648
  if (!response.ok) {
@@ -4540,8 +4650,7 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4540
4650
  cause: new Error("Failed to retrieve payment")
4541
4651
  });
4542
4652
  }
4543
- console.dir({ response }, { depth: 100 });
4544
- return response.value;
4653
+ return paykitPayment$InboundSchema(response.value);
4545
4654
  };
4546
4655
  deletePayment = async (id) => {
4547
4656
  throw new core.ProviderNotSupportedError("deletePayment", this.providerName, {
@@ -4551,22 +4660,19 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4551
4660
  };
4552
4661
  capturePayment = async (id, params) => {
4553
4662
  const payment = await this._client.get(
4554
- `/payments/payment/${id}`,
4555
- {
4556
- headers: await this.authController.getAuthHeaders()
4557
- }
4663
+ `/payments/payment/${id}/capture`,
4664
+ { headers: await this.tokenManager.getAuthHeaders() }
4558
4665
  );
4559
4666
  if (!payment.ok) {
4560
4667
  throw new core.OperationFailedError("capturePayment", this.providerName, {
4561
4668
  cause: new Error("Failed to retrieve payment")
4562
4669
  });
4563
4670
  }
4564
- const productId = JSON.parse(
4565
- payment.value.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4566
- ).itemId;
4567
- const quantity = JSON.parse(
4568
- payment.value.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4569
- ).qty;
4671
+ const { item, qty } = JSON.parse(
4672
+ decodeHtmlEntities(
4673
+ payment.value.additional_params?.find((param) => param.name === core.PAYKIT_METADATA_KEY)?.value ?? "{}"
4674
+ )
4675
+ );
4570
4676
  if (!payment) {
4571
4677
  throw new core.OperationFailedError("capturePayment", this.providerName, {
4572
4678
  cause: new Error("Payment not found after capture")
@@ -4574,22 +4680,22 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4574
4680
  }
4575
4681
  const captureBody = {
4576
4682
  amount: params.amount,
4577
- items: [{ name: productId, amount: params.amount, count: quantity }]
4683
+ items: [{ name: item, amount: params.amount, count: qty }]
4578
4684
  };
4579
- await this._client.post(`/payments/payment/${id}/capture`, {
4580
- body: JSON.stringify(captureBody),
4581
- headers: await this.authController.getAuthHeaders()
4582
- });
4685
+ await this._client.post(
4686
+ `/payments/payment/${id}/capture`,
4687
+ {
4688
+ body: JSON.stringify(captureBody),
4689
+ headers: await this.tokenManager.getAuthHeaders()
4690
+ }
4691
+ );
4583
4692
  return paykitPayment$InboundSchema(payment.value);
4584
4693
  };
4585
4694
  cancelPayment = async (id) => {
4586
- const response = await this._client.post(
4695
+ await this._client.post(
4587
4696
  `/payments/payment/${id}/void-authorization`,
4588
- {
4589
- headers: await this.authController.getAuthHeaders()
4590
- }
4697
+ { headers: await this.tokenManager.getAuthHeaders() }
4591
4698
  );
4592
- console.dir({ response }, { depth: 100 });
4593
4699
  const payment = await this.retrievePayment(id);
4594
4700
  if (!payment) {
4595
4701
  throw new core.OperationFailedError("cancelPayment", this.providerName, {
@@ -4613,24 +4719,22 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4613
4719
  };
4614
4720
  async createRefund(params) {
4615
4721
  const { error, data } = core.createRefundSchema.safeParse(params);
4616
- if (error)
4722
+ if (error) {
4617
4723
  throw core.ValidationError.fromZodError(error, this.providerName, "createRefund");
4724
+ }
4618
4725
  const payment = await this.retrievePayment(data.payment_id);
4619
4726
  if (!payment) {
4620
4727
  throw new core.OperationFailedError("createRefund", this.providerName, {
4621
4728
  cause: new Error("Failed to retrieve payment")
4622
4729
  });
4623
4730
  }
4624
- const response = await this._client.post(
4625
- `/payments/payment/${data.payment_id}/refund`,
4626
- {
4627
- body: new URLSearchParams({ amount: String(data.amount) }).toString(),
4628
- headers: {
4629
- ...await this.authController.getAuthHeaders(),
4630
- "Content-Type": "application/x-www-form-urlencoded"
4631
- }
4731
+ const response = await this._client.post(`/payments/payment/${data.payment_id}/refund`, {
4732
+ body: new URLSearchParams({ amount: String(data.amount) }).toString(),
4733
+ headers: {
4734
+ ...await this.tokenManager.getAuthHeaders(),
4735
+ "Content-Type": "application/x-www-form-urlencoded"
4632
4736
  }
4633
- );
4737
+ });
4634
4738
  if (!response.ok) {
4635
4739
  throw new core.OperationFailedError("createRefund", this.providerName, {
4636
4740
  cause: new Error("Failed to create refund")
@@ -4656,7 +4760,10 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4656
4760
  }
4657
4761
  const [payment, error] = await core.tryCatchAsync(
4658
4762
  this._client.get(`/payments/payment/${paymentId}`, {
4659
- headers: await this.authController.getAuthHeaders()
4763
+ headers: {
4764
+ ...await this.tokenManager.getAuthHeaders(),
4765
+ "Content-Type": "application/x-www-form-urlencoded"
4766
+ }
4660
4767
  })
4661
4768
  );
4662
4769
  if (error) {
@@ -4735,7 +4842,9 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4735
4842
  canceled: (data) => {
4736
4843
  const payment2 = paykitPayment$InboundSchema(data);
4737
4844
  const isCancellingSubscription = parentId && data.recurrence?.recurrence_state == "STOPPED";
4738
- const subscription = paykitSubscription$InboundSchema(data);
4845
+ const subscription = paykitSubscription$InboundSchema(
4846
+ data
4847
+ );
4739
4848
  const subscriptionCanceledWebhookEvent = {
4740
4849
  type: "subscription.canceled",
4741
4850
  created: (/* @__PURE__ */ new Date()).getTime(),
@@ -4766,7 +4875,9 @@ var GoPayProvider = class extends core.AbstractPayKitProvider {
4766
4875
  succeeded: (data) => {
4767
4876
  const payment2 = paykitPayment$InboundSchema(data);
4768
4877
  const invoice = paykitInvoice$InboundSchema(data, !!parentId);
4769
- const subscription = paykitSubscription$InboundSchema(data);
4878
+ const subscription = paykitSubscription$InboundSchema(
4879
+ data
4880
+ );
4770
4881
  const subscriptionCreatedWebhookEvent = {
4771
4882
  type: "subscription.created",
4772
4883
  created: (/* @__PURE__ */ new Date()).getTime(),