@paykit-sdk/polar 1.1.92 → 1.1.96

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/README.md CHANGED
@@ -27,7 +27,10 @@ import { endpoints } from '@/lib/paykit';
27
27
  import { EndpointPath } from '@paykit-sdk/core';
28
28
  import { NextRequest, NextResponse } from 'next/server';
29
29
 
30
- export async function POST(request: NextRequest, { params }: { params: { endpoint: string[] } }) {
30
+ export async function POST(
31
+ request: NextRequest,
32
+ { params }: { params: { endpoint: string[] } },
33
+ ) {
31
34
  try {
32
35
  // Construct the endpoint path with full type safety
33
36
  const endpoint = ('/' + params.endpoint.join('/')) as EndpointPath;
@@ -102,42 +105,46 @@ const app = express();
102
105
 
103
106
  // IMPORTANT: Webhook route must come BEFORE express.json() middleware
104
107
  // This ensures we get the raw body for signature verification
105
- app.post('/api/webhooks/polar', express.raw({ type: 'application/json' }), async (req, res) => {
106
- try {
107
- const webhookSecret = process.env.POLAR_WEBHOOK_SECRET;
108
-
109
- if (!webhookSecret) {
110
- return res.status(500).json({ error: 'Webhook secret not configured' });
111
- }
112
-
113
- const webhook = paykit.webhooks
114
- .setup({ webhookSecret })
115
- .on('customer.created', async event => {
116
- console.log('Customer created:', event.data);
117
- })
118
- .on('subscription.created', async event => {
119
- console.log('Subscription created:', event.data);
120
- })
121
- .on('payment.created', async event => {
122
- console.log('Payment created:', event.data);
123
- })
124
- .on('refund.created', async event => {
125
- console.log('Refund created:', event.data);
108
+ app.post(
109
+ '/api/webhooks/polar',
110
+ express.raw({ type: 'application/json' }),
111
+ async (req, res) => {
112
+ try {
113
+ const webhookSecret = process.env.POLAR_WEBHOOK_SECRET;
114
+
115
+ if (!webhookSecret) {
116
+ return res.status(500).json({ error: 'Webhook secret not configured' });
117
+ }
118
+
119
+ const webhook = paykit.webhooks
120
+ .setup({ webhookSecret })
121
+ .on('customer.created', async event => {
122
+ console.log('Customer created:', event.data);
123
+ })
124
+ .on('subscription.created', async event => {
125
+ console.log('Subscription created:', event.data);
126
+ })
127
+ .on('payment.created', async event => {
128
+ console.log('Payment created:', event.data);
129
+ })
130
+ .on('refund.created', async event => {
131
+ console.log('Refund created:', event.data);
132
+ });
133
+
134
+ const body = req.body; // Raw buffer from express.raw()
135
+ const headers = req.headers;
136
+ await webhook.handle({ body, headers });
137
+
138
+ // Return immediately, processing happens in background
139
+ res.json({ success: true });
140
+ } catch (error) {
141
+ console.error('Webhook error:', error);
142
+ res.status(500).json({
143
+ message: error instanceof Error ? error.message : 'Webhook processing failed',
126
144
  });
127
-
128
- const body = req.body; // Raw buffer from express.raw()
129
- const headers = req.headers;
130
- await webhook.handle({ body, headers });
131
-
132
- // Return immediately, processing happens in background
133
- res.json({ success: true });
134
- } catch (error) {
135
- console.error('Webhook error:', error);
136
- res.status(500).json({
137
- message: error instanceof Error ? error.message : 'Webhook processing failed',
138
- });
139
- }
140
- });
145
+ }
146
+ },
147
+ );
141
148
 
142
149
  // Regular API routes use JSON middleware
143
150
  app.use(express.json());
@@ -192,4 +199,4 @@ POLAR_WEBHOOK_SECRET=polar_wh_...
192
199
 
193
200
  ## License
194
201
 
195
- GPL-3.0
202
+ ISC
package/dist/index.js CHANGED
@@ -4128,7 +4128,7 @@ var paykitPayment$InboundSchema = (checkout) => {
4128
4128
  customer: checkout.customerId ? checkout.customerId : { email: checkout.customerEmail ?? "" },
4129
4129
  status: statusMap[checkout.status],
4130
4130
  metadata: checkout.metadata ?? {},
4131
- product_id: checkout.products.length > 0 ? checkout.products[0].id : null
4131
+ item_id: checkout.products.length > 0 ? checkout.products[0].id : null
4132
4132
  };
4133
4133
  };
4134
4134
  var mapRefundReason = (debug, reason) => {
@@ -4140,7 +4140,9 @@ var mapRefundReason = (debug, reason) => {
4140
4140
  };
4141
4141
  const mapped = reasonMap[reason.toLowerCase()] ?? "other";
4142
4142
  if (debug && mapped === "other" && !reason.toLowerCase().includes("other")) {
4143
- console.warn(`[Polar Provider] Unmapped refund reason: "${reason}" -> defaulting to "other"`);
4143
+ console.warn(
4144
+ `[Polar Provider] Unmapped refund reason: "${reason}" -> defaulting to "other"`
4145
+ );
4144
4146
  }
4145
4147
  return mapped;
4146
4148
  };
@@ -4182,8 +4184,9 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4182
4184
  throw core.ValidationError.fromZodError(error, this.providerName, "createCheckout");
4183
4185
  }
4184
4186
  const { metadata, item_id, provider_metadata } = data;
4187
+ const checkoutMetadata = core.stringifyMetadataValues(metadata ?? {});
4185
4188
  const checkoutCreateOptions = {
4186
- metadata: Object.fromEntries(Object.entries(metadata ?? {}).map(([key, value]) => [key, JSON.stringify(value)])),
4189
+ metadata: checkoutMetadata,
4187
4190
  products: [item_id],
4188
4191
  ...provider_metadata
4189
4192
  };
@@ -4197,7 +4200,7 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4197
4200
  state: data.billing.address.state
4198
4201
  };
4199
4202
  checkoutCreateOptions.metadata = {
4200
- ...metadata,
4203
+ ...checkoutMetadata,
4201
4204
  _shipping_phone: data.billing.address.phone ?? "",
4202
4205
  _shipping_carrier: data.billing.carrier ?? ""
4203
4206
  };
@@ -4215,7 +4218,7 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4215
4218
  id,
4216
4219
  checkoutUpdate: {
4217
4220
  ...restData,
4218
- ...metadata && { metadata: Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, JSON.stringify(value)])) },
4221
+ ...metadata && { metadata: core.stringifyMetadataValues(metadata ?? {}) },
4219
4222
  ...item_id && { products: [item_id] },
4220
4223
  ...provider_metadata
4221
4224
  }
@@ -4248,7 +4251,10 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4248
4251
  const response = await this.polar.customers.create({
4249
4252
  email,
4250
4253
  name,
4251
- metadata: { ...metadata, [core.PAYKIT_METADATA_KEY]: JSON.stringify({ phone: data?.phone ?? "" }) }
4254
+ metadata: {
4255
+ ...metadata,
4256
+ [core.PAYKIT_METADATA_KEY]: JSON.stringify({ phone: data?.phone ?? "" })
4257
+ }
4252
4258
  });
4253
4259
  return paykitCustomer$InboundSchema(response);
4254
4260
  };
@@ -4260,7 +4266,12 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4260
4266
  const { email, name, metadata, provider_metadata } = data;
4261
4267
  const response = await this.polar.customers.update({
4262
4268
  id,
4263
- customerUpdate: { ...email && { email }, ...name && { name }, ...metadata && { metadata }, ...provider_metadata }
4269
+ customerUpdate: {
4270
+ ...email && { email },
4271
+ ...name && { name },
4272
+ ...metadata && { metadata },
4273
+ ...provider_metadata
4274
+ }
4264
4275
  });
4265
4276
  return paykitCustomer$InboundSchema(response);
4266
4277
  };
@@ -4287,7 +4298,11 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4287
4298
  this.cancelSubscription = async (id) => {
4288
4299
  const { error } = core.retrieveSubscriptionSchema.safeParse({ id });
4289
4300
  if (error) {
4290
- throw core.ValidationError.fromZodError(error, this.providerName, "retrieveSubscription");
4301
+ throw core.ValidationError.fromZodError(
4302
+ error,
4303
+ this.providerName,
4304
+ "retrieveSubscription"
4305
+ );
4291
4306
  }
4292
4307
  const subscription = await this.polar.subscriptions.revoke({ id });
4293
4308
  return paykitSubscription$InboundSchema(subscription);
@@ -4295,7 +4310,11 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4295
4310
  this.retrieveSubscription = async (id) => {
4296
4311
  const { error } = core.retrieveSubscriptionSchema.safeParse({ id });
4297
4312
  if (error) {
4298
- throw core.ValidationError.fromZodError(error, this.providerName, "retrieveSubscription");
4313
+ throw core.ValidationError.fromZodError(
4314
+ error,
4315
+ this.providerName,
4316
+ "retrieveSubscription"
4317
+ );
4299
4318
  }
4300
4319
  const response = await this.polar.subscriptions.get({ id });
4301
4320
  return paykitSubscription$InboundSchema(response);
@@ -4305,7 +4324,10 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4305
4324
  if (error) {
4306
4325
  throw core.ValidationError.fromZodError(error, this.providerName, "updateSubscription");
4307
4326
  }
4308
- const response = await this.polar.subscriptions.update({ id, subscriptionUpdate: { ...data.metadata ?? {} } });
4327
+ const response = await this.polar.subscriptions.update({
4328
+ id,
4329
+ subscriptionUpdate: { ...data.metadata ?? {} }
4330
+ });
4309
4331
  return paykitSubscription$InboundSchema(response);
4310
4332
  };
4311
4333
  this.deleteSubscription = async (id) => {
@@ -4318,17 +4340,20 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4318
4340
  this.createPayment = async (params) => {
4319
4341
  const { error, data } = core.createPaymentSchema.safeParse(params);
4320
4342
  if (error) {
4321
- throw core.ValidationError.fromZodError(error, "polar", "createPayment");
4343
+ throw core.ValidationError.fromZodError(error, this.providerName, "createPayment");
4322
4344
  }
4323
- const metadataCore = Object.fromEntries(Object.entries(data.metadata ?? {}).map(([key, value]) => [key, JSON.stringify(value)]));
4345
+ const paymentMetadata = core.stringifyMetadataValues(data.metadata ?? {});
4324
4346
  const checkoutCreateOptions = {
4347
+ ...data.provider_metadata && { ...data.provider_metadata },
4325
4348
  amount: data.amount,
4326
- ...typeof data.customer === "string" && { customerId: data.customer },
4327
- ...typeof data.customer === "object" && { customerEmail: data.customer.email },
4328
- metadata: metadataCore,
4329
- products: data.product_id ? [data.product_id] : [],
4330
- ...data.provider_metadata && { ...data.provider_metadata }
4349
+ metadata: paymentMetadata,
4350
+ products: data.item_id ? [data.item_id] : []
4331
4351
  };
4352
+ if (typeof data.customer === "string") {
4353
+ checkoutCreateOptions.customerId = data.customer;
4354
+ } else if (typeof data.customer === "object") {
4355
+ checkoutCreateOptions.customerEmail = data.customer.email;
4356
+ }
4332
4357
  if (data.billing) {
4333
4358
  checkoutCreateOptions.customerBillingAddress = {
4334
4359
  line1: data.billing.address.line1,
@@ -4339,9 +4364,11 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4339
4364
  state: data.billing.address.state
4340
4365
  };
4341
4366
  checkoutCreateOptions.metadata = {
4342
- ...metadataCore,
4343
- _shipping_phone: data.billing.address.phone ?? "",
4344
- _shipping_carrier: data.billing.carrier ?? ""
4367
+ ...paymentMetadata,
4368
+ [core.PAYKIT_METADATA_KEY]: JSON.stringify({
4369
+ _shipping_phone: data.billing.address.phone ?? "",
4370
+ _shipping_carrier: data.billing.carrier ?? ""
4371
+ })
4345
4372
  };
4346
4373
  }
4347
4374
  const checkoutResponse = await this.polar.checkouts.create(checkoutCreateOptions);
@@ -4350,16 +4377,16 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4350
4377
  this.updatePayment = async (id, params) => {
4351
4378
  const { error, data } = core.updatePaymentSchema.safeParse(params);
4352
4379
  if (error) {
4353
- throw core.ValidationError.fromZodError(error, "polar", "updatePayment");
4380
+ throw core.ValidationError.fromZodError(error, this.providerName, "updatePayment");
4354
4381
  }
4355
4382
  const { provider_metadata, ...rest } = data;
4356
- const metadata = Object.fromEntries(Object.entries(rest.metadata ?? {}).map(([key, value]) => [key, JSON.stringify(value)]));
4383
+ const paymentMetadata = core.stringifyMetadataValues(rest.metadata ?? {});
4357
4384
  const checkoutResponse = await this.polar.checkouts.update({
4358
4385
  id,
4359
4386
  checkoutUpdate: {
4360
4387
  ...rest,
4361
- ...rest.metadata && { metadata },
4362
- ...rest.product_id && { products: [rest.product_id] },
4388
+ ...rest.metadata && { metadata: paymentMetadata },
4389
+ ...rest.item_id && { products: [rest.item_id] },
4363
4390
  ...provider_metadata
4364
4391
  }
4365
4392
  });
@@ -4411,17 +4438,10 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4411
4438
  */
4412
4439
  this.handleWebhook = async (params) => {
4413
4440
  const { body, headers, webhookSecret } = params;
4414
- const requiredHeaders = ["webhook-id", "webhook-timestamp", "webhook-signature"];
4415
- const webhookHeaders = core.headersExtractor(headers, requiredHeaders).reduce(
4416
- (acc, kv) => {
4417
- acc[kv.key] = Array.isArray(kv.value) ? kv.value.join(",") : kv.value;
4418
- return acc;
4419
- },
4420
- {}
4421
- );
4422
- const { data, type } = webhooks.validateEvent(body, webhookHeaders, webhookSecret);
4423
- const id = webhookHeaders["webhook-id"];
4424
- const timestamp = webhookHeaders["webhook-timestamp"];
4441
+ const webhookId = headers.get("webhook-id");
4442
+ const webhookTimestamp = headers.get("webhook-timestamp");
4443
+ const plainHeaders = Object.fromEntries(headers.entries());
4444
+ const { data, type } = webhooks.validateEvent(body, plainHeaders, webhookSecret);
4425
4445
  const webhookHandlers = {
4426
4446
  /**
4427
4447
  * Invoice
@@ -4440,12 +4460,22 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4440
4460
  currency: data2.currency,
4441
4461
  customer: data2.customerId ? data2.customerId : { email: data2.customer.email ?? "" },
4442
4462
  status: data2.status === "paid" ? "succeeded" : "pending",
4443
- metadata: Object.fromEntries(Object.entries(metadata ?? {}).map(([key, value]) => [key, JSON.stringify(value)])),
4444
- product_id: data2.product.id
4463
+ metadata: core.stringifyMetadataValues(metadata ?? {}),
4464
+ item_id: data2.product.id
4445
4465
  };
4446
4466
  return [
4447
- core.paykitEvent$InboundSchema({ type: "payment.updated", created: parseInt(timestamp), id, data: payment }),
4448
- core.paykitEvent$InboundSchema({ type: "invoice.generated", created: parseInt(timestamp), id, data: invoice })
4467
+ core.paykitEvent$InboundSchema({
4468
+ type: "payment.updated",
4469
+ created: parseInt(webhookTimestamp),
4470
+ id: webhookId,
4471
+ data: payment
4472
+ }),
4473
+ core.paykitEvent$InboundSchema({
4474
+ type: "invoice.generated",
4475
+ created: parseInt(webhookTimestamp),
4476
+ id: webhookId,
4477
+ data: invoice
4478
+ })
4449
4479
  ];
4450
4480
  }
4451
4481
  return null;
@@ -4464,12 +4494,22 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4464
4494
  currency: data2.currency,
4465
4495
  customer: data2.customerId ? data2.customerId : { email: data2.customer.email ?? "" },
4466
4496
  status: data2.status === "paid" ? "succeeded" : "pending",
4467
- metadata: Object.fromEntries(Object.entries(metadata ?? {}).map(([key, value]) => [key, JSON.stringify(value)])),
4468
- product_id: data2.product.id
4497
+ metadata: core.stringifyMetadataValues(metadata ?? {}),
4498
+ item_id: data2.product.id
4469
4499
  };
4470
4500
  return [
4471
- core.paykitEvent$InboundSchema({ type: "payment.created", created: parseInt(timestamp), id, data: payment }),
4472
- core.paykitEvent$InboundSchema({ type: "invoice.generated", created: parseInt(timestamp), id, data: invoice })
4501
+ core.paykitEvent$InboundSchema({
4502
+ type: "payment.created",
4503
+ created: parseInt(webhookTimestamp),
4504
+ id: webhookId,
4505
+ data: payment
4506
+ }),
4507
+ core.paykitEvent$InboundSchema({
4508
+ type: "invoice.generated",
4509
+ created: parseInt(webhookTimestamp),
4510
+ id: webhookId,
4511
+ data: invoice
4512
+ })
4473
4513
  ];
4474
4514
  }
4475
4515
  return null;
@@ -4479,40 +4519,91 @@ var PolarProvider = class extends core.AbstractPayKitProvider {
4479
4519
  */
4480
4520
  "customer.created": (data2) => {
4481
4521
  const customer = paykitCustomer$InboundSchema(data2);
4482
- return [core.paykitEvent$InboundSchema({ type: "customer.created", created: parseInt(timestamp), id, data: customer })];
4522
+ return [
4523
+ core.paykitEvent$InboundSchema({
4524
+ type: "customer.created",
4525
+ created: parseInt(webhookTimestamp),
4526
+ id: webhookId,
4527
+ data: customer
4528
+ })
4529
+ ];
4483
4530
  },
4484
4531
  "customer.updated": (data2) => {
4485
4532
  const customer = paykitCustomer$InboundSchema(data2);
4486
- return [core.paykitEvent$InboundSchema({ type: "customer.updated", created: parseInt(timestamp), id, data: customer })];
4533
+ return [
4534
+ core.paykitEvent$InboundSchema({
4535
+ type: "customer.updated",
4536
+ created: parseInt(webhookTimestamp),
4537
+ id: webhookId,
4538
+ data: customer
4539
+ })
4540
+ ];
4487
4541
  },
4488
4542
  "customer.deleted": (data2) => {
4489
4543
  const customer = paykitCustomer$InboundSchema(data2);
4490
- return [core.paykitEvent$InboundSchema({ type: "customer.deleted", created: parseInt(timestamp), id, data: customer })];
4544
+ return [
4545
+ core.paykitEvent$InboundSchema({
4546
+ type: "customer.deleted",
4547
+ created: parseInt(webhookTimestamp),
4548
+ id: webhookId,
4549
+ data: customer
4550
+ })
4551
+ ];
4491
4552
  },
4492
4553
  /**
4493
4554
  * Subscription
4494
4555
  */
4495
4556
  "subscription.updated": (data2) => {
4496
4557
  const subscription = paykitSubscription$InboundSchema(data2);
4497
- return [core.paykitEvent$InboundSchema({ type: "subscription.updated", created: parseInt(timestamp), id, data: subscription })];
4558
+ return [
4559
+ core.paykitEvent$InboundSchema({
4560
+ type: "subscription.updated",
4561
+ created: parseInt(webhookTimestamp),
4562
+ id: webhookId,
4563
+ data: subscription
4564
+ })
4565
+ ];
4498
4566
  },
4499
4567
  "subscription.created": (data2) => {
4500
4568
  const subscription = paykitSubscription$InboundSchema(data2);
4501
- return [core.paykitEvent$InboundSchema({ type: "subscription.created", created: parseInt(timestamp), id, data: subscription })];
4569
+ return [
4570
+ core.paykitEvent$InboundSchema({
4571
+ type: "subscription.created",
4572
+ created: parseInt(webhookTimestamp),
4573
+ id: webhookId,
4574
+ data: subscription
4575
+ })
4576
+ ];
4502
4577
  },
4503
4578
  "subscription.revoked": (data2) => {
4504
4579
  const subscription = paykitSubscription$InboundSchema(data2);
4505
- return [core.paykitEvent$InboundSchema({ type: "subscription.canceled", created: parseInt(timestamp), id, data: subscription })];
4580
+ return [
4581
+ core.paykitEvent$InboundSchema({
4582
+ type: "subscription.canceled",
4583
+ created: parseInt(webhookTimestamp),
4584
+ id: webhookId,
4585
+ data: subscription
4586
+ })
4587
+ ];
4506
4588
  },
4507
4589
  "refund.created": (data2) => {
4508
4590
  const refund = paykitRefund$InboundSchema(data2);
4509
- return [core.paykitEvent$InboundSchema({ type: "refund.created", created: parseInt(timestamp), id, data: refund })];
4591
+ return [
4592
+ core.paykitEvent$InboundSchema({
4593
+ type: "refund.created",
4594
+ created: parseInt(webhookTimestamp),
4595
+ id: webhookId,
4596
+ data: refund
4597
+ })
4598
+ ];
4510
4599
  }
4511
4600
  };
4512
4601
  const handler = webhookHandlers[type];
4513
- if (!handler) throw new Error(`Unhandled event type: ${type} for provider: ${this.providerName}`);
4602
+ if (!handler)
4603
+ throw new Error(`Unhandled event type: ${type} for provider: ${this.providerName}`);
4514
4604
  const results = handler(data);
4515
- if (!results) throw new Error(`Unhandled event type: ${type} for provider: ${this.providerName}`);
4605
+ if (!results)
4606
+ throw new Error(`Unhandled event type: ${type} for provider: ${this.providerName}`);
4516
4607
  return results;
4517
4608
  };
4518
4609
  const { accessToken, isSandbox, debug = true, ...rest } = config;
@@ -4532,7 +4623,11 @@ var polar = () => {
4532
4623
  process.env,
4533
4624
  "Missing required environment variables: {keys}"
4534
4625
  );
4535
- return createPolar({ debug: true, accessToken: envVars.POLAR_ACCESS_TOKEN, isSandbox: envVars.POLAR_SANDBOX == "true" });
4626
+ return createPolar({
4627
+ debug: true,
4628
+ accessToken: envVars.POLAR_ACCESS_TOKEN,
4629
+ isSandbox: envVars.POLAR_SANDBOX == "true"
4630
+ });
4536
4631
  };
4537
4632
 
4538
4633
  exports.createPolar = createPolar;