@paykit-sdk/gopay 1.0.5 → 1.1.1

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.mjs CHANGED
@@ -4036,14 +4036,14 @@ var ostring = () => stringType().optional();
4036
4036
  var onumber = () => numberType().optional();
4037
4037
  var oboolean = () => booleanType().optional();
4038
4038
  var coerce = {
4039
- string: (arg) => ZodString.create({ ...arg, coerce: true }),
4040
- number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
4041
- boolean: (arg) => ZodBoolean.create({
4039
+ string: ((arg) => ZodString.create({ ...arg, coerce: true })),
4040
+ number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
4041
+ boolean: ((arg) => ZodBoolean.create({
4042
4042
  ...arg,
4043
4043
  coerce: true
4044
- }),
4045
- bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
4046
- date: (arg) => ZodDate.create({ ...arg, coerce: true })
4044
+ })),
4045
+ bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
4046
+ date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
4047
4047
  };
4048
4048
  var NEVER = INVALID;
4049
4049
  var AuthController = class {
@@ -4067,25 +4067,29 @@ var AuthController = class {
4067
4067
  const credentials = Buffer.from(
4068
4068
  `${this.opts.clientId}:${this.opts.clientSecret}`
4069
4069
  ).toString("base64");
4070
+ const body = new URLSearchParams({
4071
+ grant_type: "client_credentials",
4072
+ scope: "payment-all"
4073
+ }).toString();
4070
4074
  const response = await this._client.post("/oauth2/token", {
4071
4075
  headers: {
4072
4076
  Authorization: `Basic ${credentials}`,
4073
- "Content-Type": "application/x-www-form-urlencoded"
4077
+ "Content-Type": "application/x-www-form-urlencoded",
4078
+ Accept: "application/json"
4074
4079
  },
4075
- body: new URLSearchParams({
4076
- grant_type: "client_credentials",
4077
- scope: "payment-all"
4078
- }).toString()
4080
+ body
4079
4081
  });
4080
- if (!response.ok || !response.value.access_token) {
4082
+ if (!response.ok || !response.value?.access_token) {
4081
4083
  throw new OperationFailedError("getAccessToken", "gopay", {
4082
- cause: new Error("Failed to obtain GoPay access token")
4084
+ cause: new Error(
4085
+ `Failed to obtain GoPay access token: ${JSON.stringify(response.value || response.error)}`
4086
+ )
4083
4087
  });
4084
4088
  }
4085
4089
  const expiryTime = Date.now() + (response.value.expires_in - 300) * 1e3;
4086
4090
  const accessToken = `${response.value.access_token}::paykit::${expiryTime}`;
4087
4091
  this._accessToken = accessToken;
4088
- return accessToken;
4092
+ return response.value.access_token;
4089
4093
  };
4090
4094
  getAuthHeaders = async () => {
4091
4095
  const token = await this.getAccessToken();
@@ -4096,10 +4100,15 @@ var AuthController = class {
4096
4100
  };
4097
4101
  };
4098
4102
  };
4103
+ var decodeHtmlEntities = (str) => {
4104
+ return str.replace(/"/g, '"').replace(/'/g, "'").replace(/"/g, '"').replace(/'/g, "'");
4105
+ };
4099
4106
  var paykitPayment$InboundSchema = (data) => {
4100
- const itemId = JSON.parse(
4101
- data.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4102
- ).itemId;
4107
+ const { item } = JSON.parse(
4108
+ decodeHtmlEntities(
4109
+ data.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4110
+ )
4111
+ );
4103
4112
  const metadata = omitInternalMetadata(
4104
4113
  data.additional_params?.reduce(
4105
4114
  (acc, param) => {
@@ -4109,28 +4118,66 @@ var paykitPayment$InboundSchema = (data) => {
4109
4118
  {}
4110
4119
  ) ?? {}
4111
4120
  );
4121
+ const statusMap = {
4122
+ CREATED: "pending",
4123
+ PAYMENT_METHOD_CHOSEN: "processing",
4124
+ PAID: "succeeded",
4125
+ AUTHORIZED: "requires_capture",
4126
+ CANCELED: "canceled",
4127
+ TIMEOUTED: "canceled",
4128
+ REFUNDED: "canceled",
4129
+ PARTIALLY_REFUNDED: "canceled"
4130
+ };
4131
+ const requiresAction = data.state === "CREATED" || data.state === "AUTHORIZED" ? true : false;
4112
4132
  return {
4113
4133
  id: data.id.toString(),
4114
4134
  amount: data.amount,
4115
4135
  currency: data.currency,
4116
- customer: data.payer ?? { email: data.payer?.email ?? "" },
4117
- status: data.state,
4118
- item_id: itemId,
4119
- metadata
4136
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4137
+ status: statusMap[data.state],
4138
+ item_id: item,
4139
+ metadata,
4140
+ requires_action: requiresAction,
4141
+ payment_url: data.gw_url ?? null
4142
+ };
4143
+ };
4144
+ var paykitCheckout$InboundSchema = (data) => {
4145
+ const { item, qty, type } = JSON.parse(
4146
+ decodeHtmlEntities(
4147
+ data.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4148
+ )
4149
+ );
4150
+ const metadata = omitInternalMetadata(
4151
+ data.additional_params?.reduce(
4152
+ (acc, param) => {
4153
+ acc[param.name] = String(param.value);
4154
+ return acc;
4155
+ },
4156
+ {}
4157
+ ) ?? {}
4158
+ );
4159
+ return {
4160
+ id: data.id.toString(),
4161
+ amount: data.amount,
4162
+ currency: data.currency,
4163
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4164
+ payment_url: data.gw_url ?? "",
4165
+ metadata,
4166
+ session_type: type,
4167
+ products: [{ id: item, quantity: parseInt(qty) }]
4120
4168
  };
4121
4169
  };
4122
4170
  var paykitInvoice$InboundSchema = (data, isSubscription) => {
4123
- const quantity = JSON.parse(
4124
- data.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4125
- ).qty;
4126
- const itemId = JSON.parse(
4127
- data.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4128
- ).itemId;
4171
+ const { item, qty } = JSON.parse(
4172
+ decodeHtmlEntities(
4173
+ data.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4174
+ )
4175
+ );
4129
4176
  const status = (() => {
4130
4177
  if (data.state === "PAID") return "paid";
4131
4178
  return "open";
4132
4179
  })();
4133
- const paidAt = isSubscription ? new Date(data.recurrence?.recurrence_date_from ?? "") : /* @__PURE__ */ new Date();
4180
+ const paidAt = isSubscription ? new Date(data.recurrence?.recurrence_date_to ?? "") : /* @__PURE__ */ new Date();
4134
4181
  const metadata = omitInternalMetadata(
4135
4182
  data.additional_params?.reduce(
4136
4183
  (acc, param) => {
@@ -4144,20 +4191,22 @@ var paykitInvoice$InboundSchema = (data, isSubscription) => {
4144
4191
  id: data.id.toString(),
4145
4192
  amount_paid: data.amount,
4146
4193
  currency: data.currency,
4147
- customer: data.payer ?? { email: data.payer?.email ?? "" },
4194
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4148
4195
  status,
4149
4196
  paid_at: paidAt.toISOString(),
4150
4197
  metadata: metadata ?? {},
4151
4198
  custom_fields: null,
4152
4199
  subscription_id: isSubscription ? data.id.toString() : null,
4153
4200
  billing_mode: isSubscription ? "recurring" : "one_time",
4154
- line_items: [{ id: itemId, quantity: parseInt(quantity) }]
4201
+ line_items: [{ id: item, quantity: parseInt(qty) }]
4155
4202
  };
4156
4203
  };
4157
4204
  var paykitSubscription$InboundSchema = (data) => {
4158
- const itemId = JSON.parse(
4159
- data.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4160
- ).itemId;
4205
+ const { item } = JSON.parse(
4206
+ decodeHtmlEntities(
4207
+ data.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4208
+ )
4209
+ );
4161
4210
  const billingIntervalMap = {
4162
4211
  DAY: "day",
4163
4212
  WEEK: "week",
@@ -4165,8 +4214,28 @@ var paykitSubscription$InboundSchema = (data) => {
4165
4214
  ON_DEMAND: "month"
4166
4215
  };
4167
4216
  const billingInterval = billingIntervalMap[data.recurrence?.recurrence_cycle ?? "ON_DEMAND"];
4168
- const currentPeriodStart = new Date(data.recurrence?.recurrence_date_from ?? "");
4217
+ const recurrencePeriod = data.recurrence?.recurrence_period ?? 1;
4218
+ const recurrenceCycle = data.recurrence?.recurrence_cycle;
4169
4219
  const currentPeriodEnd = new Date(data.recurrence?.recurrence_date_to ?? "");
4220
+ const currentPeriodStart = (() => {
4221
+ if (!currentPeriodEnd) return /* @__PURE__ */ new Date();
4222
+ const endDate = new Date(currentPeriodEnd);
4223
+ const startDate = new Date(endDate);
4224
+ switch (recurrenceCycle) {
4225
+ case "DAY":
4226
+ startDate.setDate(startDate.getDate() - recurrencePeriod);
4227
+ break;
4228
+ case "WEEK":
4229
+ startDate.setDate(startDate.getDate() - recurrencePeriod * 7);
4230
+ break;
4231
+ case "MONTH":
4232
+ startDate.setMonth(startDate.getMonth() - recurrencePeriod);
4233
+ break;
4234
+ default:
4235
+ startDate.setDate(startDate.getDate() - recurrencePeriod);
4236
+ }
4237
+ return startDate;
4238
+ })();
4170
4239
  const metadata = omitInternalMetadata(
4171
4240
  data.additional_params?.reduce(
4172
4241
  (acc, param) => {
@@ -4176,18 +4245,32 @@ var paykitSubscription$InboundSchema = (data) => {
4176
4245
  {}
4177
4246
  ) ?? {}
4178
4247
  );
4248
+ const requiresAction = data.state === "CREATED" ? true : false;
4249
+ const status = (() => {
4250
+ if (data.state === "CREATED") return "pending";
4251
+ if (data.state === "PAID") return "active";
4252
+ if (data.state === "CANCELED") return "canceled";
4253
+ if (data.state === "TIMEOUTED") return "canceled";
4254
+ if (data.state === "REFUNDED") return "canceled";
4255
+ if (data.state === "PARTIALLY_REFUNDED") return "canceled";
4256
+ if (data.state === "AUTHORIZED") return "active";
4257
+ if (data.state === "PAYMENT_METHOD_CHOSEN") return "active";
4258
+ return "pending";
4259
+ })();
4179
4260
  return {
4180
4261
  id: data.id.toString(),
4181
- status: "active",
4182
- customer: data.payer ?? { email: data.payer?.email ?? "" },
4183
- item_id: itemId,
4262
+ status,
4263
+ customer: data.payer?.contact?.email ? { email: data.payer.contact.email } : "",
4264
+ item_id: item,
4184
4265
  billing_interval: billingInterval,
4185
4266
  currency: data.currency,
4186
4267
  amount: data.amount,
4187
- metadata: metadata ?? {},
4268
+ metadata,
4188
4269
  custom_fields: null,
4189
4270
  current_period_start: currentPeriodStart,
4190
- current_period_end: currentPeriodEnd
4271
+ current_period_end: currentPeriodEnd,
4272
+ requires_action: requiresAction,
4273
+ payment_url: requiresAction ? data.gw_url ?? null : null
4191
4274
  };
4192
4275
  };
4193
4276
  var paykitRefund$InboundSchema = (data) => {
@@ -4217,7 +4300,7 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4217
4300
  super(gopayOptionsSchema, opts, providerName);
4218
4301
  this.opts = opts;
4219
4302
  const debug = opts.debug ?? true;
4220
- this.baseUrl = opts.isSandbox ? "https://gate.gopay.cz/api" : "https://gw.sandbox.gopay.com/api";
4303
+ this.baseUrl = opts.isSandbox ? "https://gw.sandbox.gopay.com/api" : "https://gate.gopay.cz/api";
4221
4304
  this._client = new HTTPClient({
4222
4305
  baseUrl: this.baseUrl,
4223
4306
  headers: {},
@@ -4245,7 +4328,7 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4245
4328
  );
4246
4329
  if (this.opts.debug) {
4247
4330
  console.info(
4248
- "Specify `lang` in the provider_metadata of createCheckout to set the language of the checkout, default is `EN`"
4331
+ "Specify `language` in the `provider_metadata` of createCheckout to set the language of the checkout, default is `EN`"
4249
4332
  );
4250
4333
  console.info("Creating checkout with metadata:", data.metadata);
4251
4334
  }
@@ -4274,31 +4357,42 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4274
4357
  type: "ITEM"
4275
4358
  }
4276
4359
  ],
4277
- lang: data.provider_metadata?.lang ? data.provider_metadata.lang : "EN",
4360
+ lang: data.provider_metadata?.language ? data.provider_metadata.language : "EN",
4278
4361
  callback: { return_url: data.success_url, notification_url: this.opts.webhookUrl },
4279
4362
  additional_params: Object.entries({
4280
4363
  ...data.metadata,
4281
4364
  [PAYKIT_METADATA_KEY]: JSON.stringify({
4282
- itemId: data.item_id,
4283
- qty: data.quantity
4365
+ item: data.item_id,
4366
+ qty: data.quantity,
4367
+ type: data.session_type
4284
4368
  })
4285
4369
  }).map(([name, value]) => ({
4286
4370
  name,
4287
4371
  value: String(value)
4288
4372
  }))
4289
4373
  };
4290
- const response = await this._client.post("/payments/payment", {
4291
- body: JSON.stringify(goPayRequest),
4292
- headers: await this.authController.getAuthHeaders()
4293
- });
4294
- console.dir({ response }, { depth: null });
4295
- return response.value;
4374
+ const response = await this._client.post(
4375
+ "/payments/payment",
4376
+ {
4377
+ body: JSON.stringify(goPayRequest),
4378
+ headers: await this.authController.getAuthHeaders()
4379
+ }
4380
+ );
4381
+ if (!response.ok) {
4382
+ throw new OperationFailedError("createCheckout", this.providerName, {
4383
+ cause: new Error("Failed to create checkout")
4384
+ });
4385
+ }
4386
+ return paykitCheckout$InboundSchema(response.value);
4296
4387
  };
4297
4388
  retrieveCheckout = async (id) => {
4298
4389
  const response = await this._client.get(
4299
4390
  `/payments/payment/${id}`,
4300
4391
  {
4301
- headers: await this.authController.getAuthHeaders()
4392
+ headers: {
4393
+ ...await this.authController.getAuthHeaders(),
4394
+ "Content-Type": "application/x-www-form-urlencoded"
4395
+ }
4302
4396
  }
4303
4397
  );
4304
4398
  if (!response.ok) {
@@ -4306,12 +4400,13 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4306
4400
  cause: new Error("Failed to retrieve checkout")
4307
4401
  });
4308
4402
  }
4309
- console.dir({ response }, { depth: null });
4310
- return response.value;
4403
+ return paykitCheckout$InboundSchema(response.value);
4311
4404
  };
4312
4405
  updateCheckout = async (id, params) => {
4313
4406
  if (this.opts.debug) {
4314
- console.info("Gopay doesn't support updating checkouts");
4407
+ console.info(
4408
+ "Gopay doesn't support updating checkouts, returning existing checkout"
4409
+ );
4315
4410
  }
4316
4411
  const existing = await this.retrieveCheckout(id);
4317
4412
  return existing;
@@ -4351,11 +4446,23 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4351
4446
  method: "createCheckout"
4352
4447
  });
4353
4448
  }
4354
- const { quantity, success_url } = validateRequiredKeys(
4355
- ["quantity", "success_url"],
4449
+ const { success_url } = validateRequiredKeys(
4450
+ ["success_url"],
4356
4451
  data.provider_metadata,
4357
4452
  "The following fields must be present in the provider_metadata of createCheckout: {keys}"
4358
4453
  );
4454
+ if (this.opts.debug) {
4455
+ if (data.billing_interval == "year") {
4456
+ console.info(
4457
+ "GoPay does not support yearly subscriptions, using monthly instead"
4458
+ );
4459
+ }
4460
+ if (!data.provider_metadata?.description) {
4461
+ console.info(
4462
+ `No description provided for the subscription \`provider_metadata.description\`, using default description \`Subscription by ${data.customer.email}\``
4463
+ );
4464
+ }
4465
+ }
4359
4466
  const intervalMap = {
4360
4467
  day: "DAY",
4361
4468
  week: "WEEK",
@@ -4385,54 +4492,66 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4385
4492
  amount: Number(data.amount),
4386
4493
  currency: data.currency ?? "CZK",
4387
4494
  order_number: crypto.randomBytes(8).toString("hex").slice(0, 15),
4388
- order_description: data.metadata?.description || "Subscription",
4389
- items: [
4390
- { name: data.item_id, amount: Number(data.amount), count: parseInt(quantity) }
4391
- ],
4495
+ order_description: data.provider_metadata?.description ? data.provider_metadata.description : "Subscription by " + data.customer.email,
4496
+ items: [{ name: data.item_id, amount: Number(data.amount), count: data.quantity }],
4392
4497
  recurrence: {
4393
4498
  recurrence_cycle: recurrenceCycle,
4394
- recurrence_period: parseInt(quantity),
4499
+ recurrence_period: data.quantity,
4395
4500
  recurrence_date_to: currentPeriodEnd
4396
4501
  },
4397
- callback: { return_url: success_url, notification_url: this.opts.webhookUrl }
4502
+ callback: { return_url: success_url, notification_url: this.opts.webhookUrl },
4503
+ additional_params: Object.entries({
4504
+ ...data.metadata,
4505
+ [PAYKIT_METADATA_KEY]: JSON.stringify({
4506
+ item: data.item_id,
4507
+ qty: data.quantity
4508
+ })
4509
+ }).map(([name, value]) => ({
4510
+ name,
4511
+ value: String(value)
4512
+ }))
4398
4513
  };
4399
- const response = await this._client.post("/payments/payment", {
4400
- body: JSON.stringify(goPaySubscriptionOptions),
4401
- headers: await this.authController.getAuthHeaders()
4402
- });
4514
+ const response = await this._client.post(
4515
+ "/payments/payment",
4516
+ {
4517
+ body: JSON.stringify(goPaySubscriptionOptions),
4518
+ headers: await this.authController.getAuthHeaders()
4519
+ }
4520
+ );
4403
4521
  if (!response.ok) {
4404
4522
  throw new OperationFailedError("createSubscription", this.providerName, {
4405
4523
  cause: new Error("Failed to create subscription")
4406
4524
  });
4407
4525
  }
4408
- console.dir({ response }, { depth: 100 });
4409
- return response.value;
4526
+ return paykitSubscription$InboundSchema(response.value);
4410
4527
  };
4411
4528
  updateSubscription = async (id, params) => {
4412
- console.info("Gopay doesn't support updating subscriptions");
4413
4529
  const subscription = await this.retrieveSubscription(id);
4414
4530
  if (!subscription) {
4415
- throw new OperationFailedError("updateSubscription", this.providerName, {
4416
- cause: new Error("Failed to retrieve subscription")
4531
+ throw new ProviderNotSupportedError("updateSubscription", this.providerName, {
4532
+ reason: "Gopay doesn't support updating subscriptions",
4533
+ alternative: "Use the payment API instead and update the subscription manually"
4417
4534
  });
4418
4535
  }
4419
4536
  return subscription;
4420
4537
  };
4421
4538
  cancelSubscription = async (id) => {
4422
- const response = await this._client.post(
4423
- `/payments/payment/${id}/void-recurrence`,
4424
- {
4425
- headers: await this.authController.getAuthHeaders()
4426
- }
4427
- );
4428
- console.dir({ response }, { depth: 100 });
4429
- const subscription = await this.retrieveSubscription(id);
4430
- if (!subscription) {
4539
+ const existingSubscription = await this.retrieveSubscription(id);
4540
+ if (!existingSubscription) {
4431
4541
  throw new OperationFailedError("cancelSubscription", this.providerName, {
4432
4542
  cause: new Error("Failed to retrieve subscription")
4433
4543
  });
4434
4544
  }
4435
- return { ...subscription, status: "canceled" };
4545
+ const response = await this._client.post(`/payments/payment/${id}/void-recurrence`, {
4546
+ headers: {
4547
+ ...await this.authController.getAuthHeaders(),
4548
+ "Content-Type": "application/x-www-form-urlencoded"
4549
+ }
4550
+ });
4551
+ return {
4552
+ ...existingSubscription,
4553
+ ...response.value?.result == "FINISHED" && { status: "canceled" }
4554
+ };
4436
4555
  };
4437
4556
  deleteSubscription = async (id) => {
4438
4557
  await this.cancelSubscription(id);
@@ -4450,14 +4569,13 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4450
4569
  cause: new Error("Failed to retrieve subscription")
4451
4570
  });
4452
4571
  }
4453
- console.dir({ response }, { depth: 100 });
4454
- return response.value;
4572
+ return paykitSubscription$InboundSchema(response.value);
4455
4573
  };
4456
4574
  createPayment = async (params) => {
4457
4575
  const { error, data } = createPaymentSchema.safeParse(params);
4458
4576
  if (error)
4459
4577
  throw ValidationError.fromZodError(error, this.providerName, "createPayment");
4460
- if (typeof data.customer == "string" || typeof data.customer === "object" && !data.customer.email) {
4578
+ if (typeof data.customer == "string" || typeof data.customer === "object" && !data.customer?.email) {
4461
4579
  throw new InvalidTypeError("customer", "object (customer) with email", "string", {
4462
4580
  provider: this.providerName,
4463
4581
  method: "createPayment"
@@ -4494,23 +4612,28 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4494
4612
  value: String(value)
4495
4613
  }))
4496
4614
  };
4497
- const response = await this._client.post("/payments/payment", {
4498
- body: JSON.stringify(goPayRequest),
4499
- headers: await this.authController.getAuthHeaders()
4500
- });
4615
+ const response = await this._client.post(
4616
+ "/payments/payment",
4617
+ {
4618
+ body: JSON.stringify(goPayRequest),
4619
+ headers: await this.authController.getAuthHeaders()
4620
+ }
4621
+ );
4501
4622
  if (!response.ok) {
4502
4623
  throw new OperationFailedError("createPayment", this.providerName, {
4503
4624
  cause: new Error("Failed to create payment")
4504
4625
  });
4505
4626
  }
4506
- console.dir({ response }, { depth: 100 });
4507
- return response.value;
4627
+ return paykitPayment$InboundSchema(response.value);
4508
4628
  };
4509
4629
  retrievePayment = async (id) => {
4510
4630
  const response = await this._client.get(
4511
4631
  `/payments/payment/${id}`,
4512
4632
  {
4513
- headers: await this.authController.getAuthHeaders()
4633
+ headers: {
4634
+ ...await this.authController.getAuthHeaders(),
4635
+ "Content-Type": "application/x-www-form-urlencoded"
4636
+ }
4514
4637
  }
4515
4638
  );
4516
4639
  if (!response.ok) {
@@ -4518,8 +4641,7 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4518
4641
  cause: new Error("Failed to retrieve payment")
4519
4642
  });
4520
4643
  }
4521
- console.dir({ response }, { depth: 100 });
4522
- return response.value;
4644
+ return paykitPayment$InboundSchema(response.value);
4523
4645
  };
4524
4646
  deletePayment = async (id) => {
4525
4647
  throw new ProviderNotSupportedError("deletePayment", this.providerName, {
@@ -4529,7 +4651,7 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4529
4651
  };
4530
4652
  capturePayment = async (id, params) => {
4531
4653
  const payment = await this._client.get(
4532
- `/payments/payment/${id}`,
4654
+ `/payments/payment/${id}/capture`,
4533
4655
  {
4534
4656
  headers: await this.authController.getAuthHeaders()
4535
4657
  }
@@ -4539,12 +4661,11 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4539
4661
  cause: new Error("Failed to retrieve payment")
4540
4662
  });
4541
4663
  }
4542
- const productId = JSON.parse(
4543
- payment.value.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4544
- ).itemId;
4545
- const quantity = JSON.parse(
4546
- payment.value.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4547
- ).qty;
4664
+ const { item, qty } = JSON.parse(
4665
+ decodeHtmlEntities(
4666
+ payment.value.additional_params?.find((param) => param.name === PAYKIT_METADATA_KEY)?.value ?? "{}"
4667
+ )
4668
+ );
4548
4669
  if (!payment) {
4549
4670
  throw new OperationFailedError("capturePayment", this.providerName, {
4550
4671
  cause: new Error("Payment not found after capture")
@@ -4552,12 +4673,15 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4552
4673
  }
4553
4674
  const captureBody = {
4554
4675
  amount: params.amount,
4555
- items: [{ name: productId, amount: params.amount, count: quantity }]
4676
+ items: [{ name: item, amount: params.amount, count: qty }]
4556
4677
  };
4557
- await this._client.post(`/payments/payment/${id}/capture`, {
4558
- body: JSON.stringify(captureBody),
4559
- headers: await this.authController.getAuthHeaders()
4560
- });
4678
+ await this._client.post(
4679
+ `/payments/payment/${id}/capture`,
4680
+ {
4681
+ body: JSON.stringify(captureBody),
4682
+ headers: await this.authController.getAuthHeaders()
4683
+ }
4684
+ );
4561
4685
  return paykitPayment$InboundSchema(payment.value);
4562
4686
  };
4563
4687
  cancelPayment = async (id) => {
@@ -4591,24 +4715,22 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4591
4715
  };
4592
4716
  async createRefund(params) {
4593
4717
  const { error, data } = createRefundSchema.safeParse(params);
4594
- if (error)
4718
+ if (error) {
4595
4719
  throw ValidationError.fromZodError(error, this.providerName, "createRefund");
4720
+ }
4596
4721
  const payment = await this.retrievePayment(data.payment_id);
4597
4722
  if (!payment) {
4598
4723
  throw new OperationFailedError("createRefund", this.providerName, {
4599
4724
  cause: new Error("Failed to retrieve payment")
4600
4725
  });
4601
4726
  }
4602
- const response = await this._client.post(
4603
- `/payments/payment/${data.payment_id}/refund`,
4604
- {
4605
- body: new URLSearchParams({ amount: String(data.amount) }).toString(),
4606
- headers: {
4607
- ...await this.authController.getAuthHeaders(),
4608
- "Content-Type": "application/x-www-form-urlencoded"
4609
- }
4727
+ const response = await this._client.post(`/payments/payment/${data.payment_id}/refund`, {
4728
+ body: new URLSearchParams({ amount: String(data.amount) }).toString(),
4729
+ headers: {
4730
+ ...await this.authController.getAuthHeaders(),
4731
+ "Content-Type": "application/x-www-form-urlencoded"
4610
4732
  }
4611
- );
4733
+ });
4612
4734
  if (!response.ok) {
4613
4735
  throw new OperationFailedError("createRefund", this.providerName, {
4614
4736
  cause: new Error("Failed to create refund")
@@ -4626,6 +4748,7 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4626
4748
  const { fullUrl } = payload;
4627
4749
  const paymentId = new URL(fullUrl).searchParams.get("id");
4628
4750
  const parentId = new URL(fullUrl).searchParams.get("parent_id");
4751
+ console.log({ paymentId, parentId });
4629
4752
  if (!paymentId) {
4630
4753
  throw new WebhookError("Payment ID is required", { provider: this.providerName });
4631
4754
  }
@@ -4634,9 +4757,13 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4634
4757
  }
4635
4758
  const [payment, error] = await tryCatchAsync(
4636
4759
  this._client.get(`/payments/payment/${paymentId}`, {
4637
- headers: await this.authController.getAuthHeaders()
4760
+ headers: {
4761
+ ...await this.authController.getAuthHeaders(),
4762
+ "Content-Type": "application/x-www-form-urlencoded"
4763
+ }
4638
4764
  })
4639
4765
  );
4766
+ console.log({ payment });
4640
4767
  if (error) {
4641
4768
  throw new WebhookError("Failed to retrieve payment", {
4642
4769
  provider: this.providerName
@@ -4713,7 +4840,9 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4713
4840
  canceled: (data) => {
4714
4841
  const payment2 = paykitPayment$InboundSchema(data);
4715
4842
  const isCancellingSubscription = parentId && data.recurrence?.recurrence_state == "STOPPED";
4716
- const subscription = paykitSubscription$InboundSchema(data);
4843
+ const subscription = paykitSubscription$InboundSchema(
4844
+ data
4845
+ );
4717
4846
  const subscriptionCanceledWebhookEvent = {
4718
4847
  type: "subscription.canceled",
4719
4848
  created: (/* @__PURE__ */ new Date()).getTime(),
@@ -4744,7 +4873,9 @@ var GoPayProvider = class extends AbstractPayKitProvider {
4744
4873
  succeeded: (data) => {
4745
4874
  const payment2 = paykitPayment$InboundSchema(data);
4746
4875
  const invoice = paykitInvoice$InboundSchema(data, !!parentId);
4747
- const subscription = paykitSubscription$InboundSchema(data);
4876
+ const subscription = paykitSubscription$InboundSchema(
4877
+ data
4878
+ );
4748
4879
  const subscriptionCreatedWebhookEvent = {
4749
4880
  type: "subscription.created",
4750
4881
  created: (/* @__PURE__ */ new Date()).getTime(),
@@ -4814,7 +4945,8 @@ var gopay = () => {
4814
4945
  clientSecret: envVars.GOPAY_CLIENT_SECRET,
4815
4946
  goId: envVars.GOPAY_GO_ID,
4816
4947
  isSandbox: envVars.GOPAY_SANDBOX === "true",
4817
- webhookUrl: envVars.GOPAY_WEBHOOK_URL
4948
+ webhookUrl: envVars.GOPAY_WEBHOOK_URL,
4949
+ debug: true
4818
4950
  });
4819
4951
  };
4820
4952