better-auth-paystack 3.4.0 → 3.4.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.
- package/README.md +8 -2
- package/dist/client.d.mts +9 -8
- package/dist/client.d.mts.map +1 -1
- package/dist/client.mjs +1 -1
- package/dist/client.mjs.map +1 -1
- package/dist/{index-ciWwfZ27.d.mts → index-C9c7-9sB.d.mts} +23 -38
- package/dist/index-C9c7-9sB.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +326 -258
- package/dist/index.mjs.map +1 -1
- package/dist/{version-DbATmzCS.mjs → version-BJvYyq-a.mjs} +2 -2
- package/dist/{version-DbATmzCS.mjs.map → version-BJvYyq-a.mjs.map} +1 -1
- package/package.json +20 -21
- package/skills/better-auth-paystack-setup/SKILL.md +4 -4
- package/skills/paystack-billing-flows/SKILL.md +2 -2
- package/skills/paystack-catalog-limits/SKILL.md +2 -2
- package/skills/paystack-client-api/SKILL.md +3 -3
- package/skills/paystack-local-subscriptions/SKILL.md +2 -2
- package/skills/paystack-organization-billing/SKILL.md +3 -3
- package/skills/paystack-schema-migrations/SKILL.md +2 -2
- package/skills/paystack-tanstack-start/SKILL.md +7 -5
- package/skills/paystack-testing-fixtures/SKILL.md +2 -2
- package/skills/paystack-webhooks-events/SKILL.md +2 -2
- package/dist/index-ciWwfZ27.d.mts.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { a as getMetadataBoolean, c as hasPaystackMetadata, i as createRenewalMetadata, l as parsePaystackMetadata, n as createCheckoutMetadata, o as getMetadataNumber, r as createProrationMetadata, s as getMetadataString, t as PACKAGE_VERSION, u as stringifyPaystackMetadata } from "./version-
|
|
1
|
+
import { a as getMetadataBoolean, c as hasPaystackMetadata, i as createRenewalMetadata, l as parsePaystackMetadata, n as createCheckoutMetadata, o as getMetadataNumber, r as createProrationMetadata, s as getMetadataString, t as PACKAGE_VERSION, u as stringifyPaystackMetadata } from "./version-BJvYyq-a.mjs";
|
|
2
2
|
import { HIDE_METADATA, defineErrorCodes } from "better-auth";
|
|
3
|
-
import { APIError, createAuthEndpoint, createAuthMiddleware, getSessionFromCtx,
|
|
3
|
+
import { APIError, createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, originCheckMiddleware, sessionMiddleware } from "better-auth/api";
|
|
4
4
|
import { defu } from "defu";
|
|
5
5
|
import { PaystackError, PaystackResponse } from "@alexasomba/paystack-node";
|
|
6
|
-
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
|
|
6
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
import { Buffer } from "node:buffer";
|
|
9
9
|
import { mergeSchema } from "better-auth/db";
|
|
@@ -79,7 +79,9 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
79
79
|
return sortSubscriptionsForCurrent(groupId === void 0 ? subscriptions : subscriptions.filter((subscription) => groupId === null ? subscription.groupId === void 0 || subscription.groupId === null || subscription.groupId === "" : subscription.groupId === groupId))[0] ?? null;
|
|
80
80
|
},
|
|
81
81
|
async retireCompetingSubscriptions(referenceId, groupId, exceptId) {
|
|
82
|
-
const
|
|
82
|
+
const subscriptions = await this.findSubscriptionsByReference(referenceId);
|
|
83
|
+
const selected = subscriptions.find((subscription) => subscription.id === exceptId);
|
|
84
|
+
const competitors = subscriptions.filter((subscription) => subscription.id !== exceptId && (selected === void 0 || new Date(subscription.createdAt).getTime() <= new Date(selected.createdAt).getTime()) && (subscription.status === "active" || subscription.status === "trialing") && (groupId === null ? subscription.groupId === void 0 || subscription.groupId === null || subscription.groupId === "" : subscription.groupId === groupId));
|
|
83
85
|
const now = /* @__PURE__ */ new Date();
|
|
84
86
|
for (const subscription of competitors) await this.updateSubscription(subscription.id, {
|
|
85
87
|
status: "canceled",
|
|
@@ -133,10 +135,13 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
133
135
|
model: PAYSTACK_MODELS.webhookEvent,
|
|
134
136
|
data
|
|
135
137
|
}),
|
|
136
|
-
findWebhookEvent: (eventId) => findOne(
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
138
|
+
findWebhookEvent: (eventId) => adapter.findOne({
|
|
139
|
+
model: PAYSTACK_MODELS.webhookEvent,
|
|
140
|
+
where: [{
|
|
141
|
+
field: "eventId",
|
|
142
|
+
value: eventId
|
|
143
|
+
}]
|
|
144
|
+
}),
|
|
140
145
|
updateWebhookEvent: (eventId, update) => adapter.update({
|
|
141
146
|
model: PAYSTACK_MODELS.webhookEvent,
|
|
142
147
|
update,
|
|
@@ -315,7 +320,7 @@ function unwrapSdkResult(result) {
|
|
|
315
320
|
if (IsPaystackResponse(result)) try {
|
|
316
321
|
return result.unwrap();
|
|
317
322
|
} catch (e) {
|
|
318
|
-
if (e instanceof PaystackError) throw new APIError("BAD_REQUEST", {
|
|
323
|
+
if (e instanceof PaystackError) throw new APIError(e.status === 404 ? "NOT_FOUND" : "BAD_REQUEST", {
|
|
319
324
|
message: e.message,
|
|
320
325
|
status: e.status
|
|
321
326
|
});
|
|
@@ -1046,6 +1051,15 @@ async function reconcilePaystackTransaction(ctx, options, input) {
|
|
|
1046
1051
|
const newPlan = getMetadataString(metadataObj, "newPlan");
|
|
1047
1052
|
const newSeatCount = getMetadataNumber(metadataObj, "newSeatCount");
|
|
1048
1053
|
if (subscriptionId !== void 0 && subscriptionId !== "" && newPlan !== void 0 && newPlan !== "") {
|
|
1054
|
+
const originalSubscription = await store.findSubscriptionById(subscriptionId);
|
|
1055
|
+
if (!originalSubscription || originalSubscription.status === "canceled" || originalSubscription.transactionReference === reference) return {
|
|
1056
|
+
ok: true,
|
|
1057
|
+
source,
|
|
1058
|
+
status,
|
|
1059
|
+
reference,
|
|
1060
|
+
data,
|
|
1061
|
+
...summary
|
|
1062
|
+
};
|
|
1049
1063
|
const updatedSubscription = await store.updateSubscription(subscriptionId, {
|
|
1050
1064
|
plan: newPlan,
|
|
1051
1065
|
...typeof newSeatCount === "number" ? { seats: newSeatCount } : {},
|
|
@@ -1073,6 +1087,14 @@ async function reconcilePaystackTransaction(ctx, options, input) {
|
|
|
1073
1087
|
summary.subscription.found = targetSub !== void 0;
|
|
1074
1088
|
summary.subscription.id = targetSub?.id;
|
|
1075
1089
|
summary.subscription.status = targetSub?.status;
|
|
1090
|
+
if (targetSub && targetSub.status !== "incomplete") return {
|
|
1091
|
+
ok: true,
|
|
1092
|
+
source,
|
|
1093
|
+
status,
|
|
1094
|
+
reference,
|
|
1095
|
+
data,
|
|
1096
|
+
...summary
|
|
1097
|
+
};
|
|
1076
1098
|
if (isTrial && targetPlan !== void 0 && trialEnd !== void 0) {
|
|
1077
1099
|
const email = data.customer?.email;
|
|
1078
1100
|
const planConfig = (await getPlans(options.subscription)).find((plan) => plan.name.toLowerCase() === targetPlan.toLowerCase());
|
|
@@ -1604,42 +1626,87 @@ const paystackWebhook = (options, path = "/webhook") => {
|
|
|
1604
1626
|
const reference = data?.reference;
|
|
1605
1627
|
const eventId = createHash("sha256").update(payload).digest("hex");
|
|
1606
1628
|
const store = createBillingStore(ctx);
|
|
1607
|
-
let
|
|
1608
|
-
let existingEvent = null;
|
|
1629
|
+
let claimStatus;
|
|
1609
1630
|
try {
|
|
1610
|
-
existingEvent = await store.findWebhookEvent(eventId);
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
updatedAt: /* @__PURE__ */ new Date()
|
|
1624
|
-
});
|
|
1625
|
-
} catch {
|
|
1626
|
-
try {
|
|
1631
|
+
let existingEvent = await store.findWebhookEvent(eventId);
|
|
1632
|
+
if (existingEvent?.status === "processed") return ctx.json({ received: true });
|
|
1633
|
+
if (existingEvent === null) try {
|
|
1634
|
+
existingEvent = await store.createWebhookEvent({
|
|
1635
|
+
eventId,
|
|
1636
|
+
eventType: eventName,
|
|
1637
|
+
reference: reference ?? null,
|
|
1638
|
+
payload,
|
|
1639
|
+
status: "pending",
|
|
1640
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
1641
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1642
|
+
});
|
|
1643
|
+
} catch (error) {
|
|
1627
1644
|
existingEvent = await store.findWebhookEvent(eventId);
|
|
1628
|
-
if (existingEvent
|
|
1629
|
-
}
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1645
|
+
if (!existingEvent) throw error;
|
|
1646
|
+
}
|
|
1647
|
+
if (existingEvent.status === "processed") return ctx.json({ received: true });
|
|
1648
|
+
if (existingEvent.status.startsWith("processing:") && new Date(existingEvent.updatedAt).getTime() > Date.now() - 3e5) throw new Error("Webhook is already processing; retry later.");
|
|
1649
|
+
claimStatus = `processing:${randomUUID()}`;
|
|
1650
|
+
if (await ctx.context.adapter.update({
|
|
1651
|
+
model: PAYSTACK_MODELS.webhookEvent,
|
|
1652
|
+
where: [{
|
|
1653
|
+
field: "eventId",
|
|
1654
|
+
value: eventId
|
|
1655
|
+
}, {
|
|
1656
|
+
field: "status",
|
|
1657
|
+
value: existingEvent.status
|
|
1658
|
+
}],
|
|
1659
|
+
update: {
|
|
1660
|
+
status: claimStatus,
|
|
1661
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1662
|
+
}
|
|
1663
|
+
}) === null) throw new Error("Webhook claim was lost; retry later.");
|
|
1664
|
+
if (eventName === "charge.success") {
|
|
1665
|
+
const reference = data?.reference;
|
|
1666
|
+
const paystackIdRaw = data?.id;
|
|
1667
|
+
const paystackId = paystackIdRaw !== void 0 && paystackIdRaw !== null ? String(paystackIdRaw) : void 0;
|
|
1668
|
+
if (reference !== void 0 && reference !== null && reference !== "") {
|
|
1669
|
+
try {
|
|
1670
|
+
await ctx.context.adapter.update({
|
|
1671
|
+
model: "paystackTransaction",
|
|
1672
|
+
update: {
|
|
1673
|
+
status: "success",
|
|
1674
|
+
paystackId,
|
|
1675
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1676
|
+
},
|
|
1677
|
+
where: [{
|
|
1678
|
+
field: "reference",
|
|
1679
|
+
value: reference
|
|
1680
|
+
}]
|
|
1681
|
+
});
|
|
1682
|
+
} catch (e) {
|
|
1683
|
+
ctx.context.logger.warn("Failed to update transaction status for charge.success", e);
|
|
1684
|
+
throw e;
|
|
1685
|
+
}
|
|
1686
|
+
try {
|
|
1687
|
+
const transaction = await ctx.context.adapter.findOne({
|
|
1688
|
+
model: "paystackTransaction",
|
|
1689
|
+
where: [{
|
|
1690
|
+
field: "reference",
|
|
1691
|
+
value: reference
|
|
1692
|
+
}]
|
|
1693
|
+
});
|
|
1694
|
+
if (transaction !== void 0 && transaction !== null && transaction.product !== void 0 && transaction.product !== null && transaction.product !== "") {
|
|
1695
|
+
if (options.paystackClient !== void 0 && options.paystackClient !== null) await syncProductQuantityFromPaystack(ctx, transaction.product, options.paystackClient);
|
|
1696
|
+
}
|
|
1697
|
+
} catch (e) {
|
|
1698
|
+
ctx.context.logger.warn("Failed to sync product quantity", e);
|
|
1699
|
+
throw e;
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
if (eventName === "charge.failure") {
|
|
1704
|
+
const reference = data?.reference;
|
|
1705
|
+
if (reference !== void 0 && reference !== null && reference !== "") try {
|
|
1638
1706
|
await ctx.context.adapter.update({
|
|
1639
1707
|
model: "paystackTransaction",
|
|
1640
1708
|
update: {
|
|
1641
|
-
status: "
|
|
1642
|
-
paystackId,
|
|
1709
|
+
status: "failed",
|
|
1643
1710
|
updatedAt: /* @__PURE__ */ new Date()
|
|
1644
1711
|
},
|
|
1645
1712
|
where: [{
|
|
@@ -1648,156 +1715,115 @@ const paystackWebhook = (options, path = "/webhook") => {
|
|
|
1648
1715
|
}]
|
|
1649
1716
|
});
|
|
1650
1717
|
} catch (e) {
|
|
1651
|
-
ctx.context.logger.warn("Failed to update transaction status for charge.
|
|
1718
|
+
ctx.context.logger.warn("Failed to update transaction status for charge.failure", e);
|
|
1719
|
+
throw e;
|
|
1652
1720
|
}
|
|
1653
|
-
try {
|
|
1654
|
-
const transaction = await ctx.context.adapter.findOne({
|
|
1655
|
-
model: "paystackTransaction",
|
|
1656
|
-
where: [{
|
|
1657
|
-
field: "reference",
|
|
1658
|
-
value: reference
|
|
1659
|
-
}]
|
|
1660
|
-
});
|
|
1661
|
-
if (transaction !== void 0 && transaction !== null && transaction.product !== void 0 && transaction.product !== null && transaction.product !== "") {
|
|
1662
|
-
if (options.paystackClient !== void 0 && options.paystackClient !== null) await syncProductQuantityFromPaystack(ctx, transaction.product, options.paystackClient);
|
|
1663
|
-
}
|
|
1664
|
-
} catch (e) {
|
|
1665
|
-
ctx.context.logger.warn("Failed to sync product quantity", e);
|
|
1666
|
-
}
|
|
1667
|
-
}
|
|
1668
|
-
}
|
|
1669
|
-
if (eventName === "charge.failure") {
|
|
1670
|
-
const reference = data?.reference;
|
|
1671
|
-
if (reference !== void 0 && reference !== null && reference !== "") try {
|
|
1672
|
-
await ctx.context.adapter.update({
|
|
1673
|
-
model: "paystackTransaction",
|
|
1674
|
-
update: {
|
|
1675
|
-
status: "failed",
|
|
1676
|
-
updatedAt: /* @__PURE__ */ new Date()
|
|
1677
|
-
},
|
|
1678
|
-
where: [{
|
|
1679
|
-
field: "reference",
|
|
1680
|
-
value: reference
|
|
1681
|
-
}]
|
|
1682
|
-
});
|
|
1683
|
-
} catch (e) {
|
|
1684
|
-
ctx.context.logger.warn("Failed to update transaction status for charge.failure", e);
|
|
1685
1721
|
}
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
const subscription = (await ctx.context.adapter.findMany({
|
|
1718
|
-
model: PAYSTACK_MODELS.subscription,
|
|
1719
|
-
where
|
|
1720
|
-
}))?.find((candidate) => groupIdFromMetadata === null ? candidate.groupId === void 0 || candidate.groupId === null || candidate.groupId === "" : candidate.groupId === groupIdFromMetadata);
|
|
1721
|
-
if (subscription !== void 0 && subscription !== null) {
|
|
1722
|
-
const plan = planFromCode ?? (planName !== void 0 && planName !== null && planName !== "" ? await getPlanByName(options, planName) : void 0);
|
|
1723
|
-
const now = /* @__PURE__ */ new Date();
|
|
1724
|
-
const persistedSubscription = {
|
|
1725
|
-
...subscription,
|
|
1726
|
-
subscriptionCode,
|
|
1727
|
-
status: "active",
|
|
1728
|
-
billingInterval: plan?.interval ?? subscription.billingInterval ?? null,
|
|
1729
|
-
periodEnd: subscriptionData.next_payment_date !== void 0 && subscriptionData.next_payment_date !== null ? new Date(subscriptionData.next_payment_date) : subscription.periodEnd,
|
|
1730
|
-
updatedAt: now
|
|
1731
|
-
};
|
|
1732
|
-
await ctx.context.adapter.update({
|
|
1722
|
+
if (options.subscription?.enabled === true) try {
|
|
1723
|
+
if (eventName === "subscription.create") {
|
|
1724
|
+
const subscriptionData = data;
|
|
1725
|
+
const subscriptionCode = subscriptionData.subscription_code ?? "";
|
|
1726
|
+
const customerCode = subscriptionData.customer?.customer_code;
|
|
1727
|
+
const planCode = subscriptionData.plan?.plan_code;
|
|
1728
|
+
const metadataObj = parsePaystackMetadata(subscriptionData.metadata);
|
|
1729
|
+
const referenceIdFromMetadata = typeof metadataObj.referenceId === "string" ? metadataObj.referenceId : void 0;
|
|
1730
|
+
let planNameFromMetadata = typeof metadataObj.plan === "string" ? metadataObj.plan : void 0;
|
|
1731
|
+
if (typeof planNameFromMetadata === "string") planNameFromMetadata = planNameFromMetadata.toLowerCase();
|
|
1732
|
+
const plans = await getPlans(options.subscription);
|
|
1733
|
+
const planFromCode = planCode !== void 0 && planCode !== null && planCode !== "" ? plans.find((p) => p.planCode === planCode) : void 0;
|
|
1734
|
+
const groupIdFromMetadata = typeof metadataObj.groupId === "string" ? normalizeSubscriptionGroup(metadataObj.groupId) : normalizeSubscriptionGroup(planFromCode?.group);
|
|
1735
|
+
const planPart = planFromCode?.name ?? planNameFromMetadata;
|
|
1736
|
+
const planName = planPart !== void 0 && planPart !== null && planPart !== "" ? planPart.toLowerCase() : void 0;
|
|
1737
|
+
if (subscriptionCode !== void 0 && subscriptionCode !== null && subscriptionCode !== "") {
|
|
1738
|
+
const where = [];
|
|
1739
|
+
if (referenceIdFromMetadata !== void 0 && referenceIdFromMetadata !== null && referenceIdFromMetadata !== "") where.push({
|
|
1740
|
+
field: "referenceId",
|
|
1741
|
+
value: referenceIdFromMetadata
|
|
1742
|
+
});
|
|
1743
|
+
else if (customerCode !== void 0 && customerCode !== null && customerCode !== "") where.push({
|
|
1744
|
+
field: "customerCode",
|
|
1745
|
+
value: customerCode
|
|
1746
|
+
});
|
|
1747
|
+
if (planName !== void 0 && planName !== null && planName !== "") where.push({
|
|
1748
|
+
field: "plan",
|
|
1749
|
+
value: planName
|
|
1750
|
+
});
|
|
1751
|
+
if (where.length > 0) {
|
|
1752
|
+
const subscription = (await ctx.context.adapter.findMany({
|
|
1733
1753
|
model: PAYSTACK_MODELS.subscription,
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
await createBillingStore(ctx).retireCompetingSubscriptions(subscription.referenceId, subscription.groupId ?? null, subscription.id);
|
|
1747
|
-
if (plan !== void 0 && plan !== null) {
|
|
1748
|
-
const callbackData = {
|
|
1749
|
-
event,
|
|
1750
|
-
subscription: persistedSubscription,
|
|
1751
|
-
plan
|
|
1754
|
+
where
|
|
1755
|
+
}))?.find((candidate) => candidate.status !== "canceled" && (candidate.subscriptionCode === subscriptionCode || candidate.status === "incomplete" || candidate.status === "trialing" && (candidate.subscriptionCode === void 0 || candidate.subscriptionCode === null || candidate.subscriptionCode === "")) && groupIdFromMetadata === null ? candidate.groupId === void 0 || candidate.groupId === null || candidate.groupId === "" : candidate.groupId === groupIdFromMetadata);
|
|
1756
|
+
if (subscription !== void 0 && subscription !== null) {
|
|
1757
|
+
const plan = planFromCode ?? (planName !== void 0 && planName !== null && planName !== "" ? await getPlanByName(options, planName) : void 0);
|
|
1758
|
+
const now = /* @__PURE__ */ new Date();
|
|
1759
|
+
const persistedSubscription = {
|
|
1760
|
+
...subscription,
|
|
1761
|
+
subscriptionCode,
|
|
1762
|
+
status: "active",
|
|
1763
|
+
billingInterval: plan?.interval ?? subscription.billingInterval ?? null,
|
|
1764
|
+
periodEnd: subscriptionData.next_payment_date !== void 0 && subscriptionData.next_payment_date !== null ? new Date(subscriptionData.next_payment_date) : subscription.periodEnd,
|
|
1765
|
+
updatedAt: now
|
|
1752
1766
|
};
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1767
|
+
await ctx.context.adapter.update({
|
|
1768
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1769
|
+
update: {
|
|
1770
|
+
subscriptionCode: persistedSubscription.subscriptionCode,
|
|
1771
|
+
status: persistedSubscription.status,
|
|
1772
|
+
billingInterval: persistedSubscription.billingInterval,
|
|
1773
|
+
periodEnd: persistedSubscription.periodEnd,
|
|
1774
|
+
updatedAt: persistedSubscription.updatedAt
|
|
1775
|
+
},
|
|
1776
|
+
where: [{
|
|
1777
|
+
field: "id",
|
|
1778
|
+
value: subscription.id
|
|
1779
|
+
}]
|
|
1780
|
+
});
|
|
1781
|
+
await createBillingStore(ctx).retireCompetingSubscriptions(subscription.referenceId, subscription.groupId ?? null, subscription.id);
|
|
1782
|
+
if (plan !== void 0 && plan !== null) {
|
|
1783
|
+
const callbackData = {
|
|
1784
|
+
event,
|
|
1785
|
+
subscription: persistedSubscription,
|
|
1786
|
+
plan
|
|
1787
|
+
};
|
|
1788
|
+
for (const callback of [
|
|
1789
|
+
options.subscription.onSubscriptionComplete,
|
|
1790
|
+
options.subscription.onSubscriptionCreated,
|
|
1791
|
+
options.subscription.onSubscriptionUpdate
|
|
1792
|
+
]) try {
|
|
1793
|
+
await callback?.(callbackData, ctx);
|
|
1794
|
+
} catch (error) {
|
|
1795
|
+
ctx.context.logger.error("Paystack subscription callback failed", error);
|
|
1796
|
+
throw error;
|
|
1797
|
+
}
|
|
1798
|
+
if (subscription.status === "trialing") try {
|
|
1799
|
+
await plan.freeTrial?.onTrialEnd?.(persistedSubscription);
|
|
1800
|
+
} catch (error) {
|
|
1801
|
+
ctx.context.logger.error("Paystack trial end callback failed", error);
|
|
1802
|
+
throw error;
|
|
1803
|
+
}
|
|
1766
1804
|
}
|
|
1767
1805
|
}
|
|
1768
1806
|
}
|
|
1769
1807
|
}
|
|
1770
1808
|
}
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
}
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
...existing,
|
|
1790
|
-
status: newStatus,
|
|
1791
|
-
cancelAtPeriodEnd: newStatus === "active",
|
|
1792
|
-
cancelAt: newStatus === "active" ? periodEnd ?? null : null,
|
|
1793
|
-
canceledAt: now,
|
|
1794
|
-
endedAt: newStatus === "canceled" ? now : null,
|
|
1795
|
-
...periodEnd ? { periodEnd } : {},
|
|
1796
|
-
updatedAt: now
|
|
1797
|
-
};
|
|
1798
|
-
await ctx.context.adapter.update({
|
|
1799
|
-
model: PAYSTACK_MODELS.subscription,
|
|
1800
|
-
update: {
|
|
1809
|
+
if (eventName === "subscription.disable" || eventName === "subscription.not_renew") {
|
|
1810
|
+
const subscriptionData = data;
|
|
1811
|
+
const subscriptionCode = subscriptionData.subscription_code ?? "";
|
|
1812
|
+
if (subscriptionCode !== "") {
|
|
1813
|
+
const existing = await ctx.context.adapter.findOne({
|
|
1814
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1815
|
+
where: [{
|
|
1816
|
+
field: "subscriptionCode",
|
|
1817
|
+
value: subscriptionCode
|
|
1818
|
+
}]
|
|
1819
|
+
});
|
|
1820
|
+
let newStatus = "canceled";
|
|
1821
|
+
const nextPaymentDate = subscriptionData.next_payment_date;
|
|
1822
|
+
const periodEnd = nextPaymentDate !== void 0 && nextPaymentDate !== null && nextPaymentDate !== "" ? new Date(nextPaymentDate) : existing?.periodEnd !== void 0 && existing.periodEnd !== null ? new Date(existing.periodEnd) : void 0;
|
|
1823
|
+
if (periodEnd !== void 0 && periodEnd.getTime() > Date.now()) newStatus = "active";
|
|
1824
|
+
const now = /* @__PURE__ */ new Date();
|
|
1825
|
+
const persistedSubscription = existing === null || existing === void 0 ? void 0 : {
|
|
1826
|
+
...existing,
|
|
1801
1827
|
status: newStatus,
|
|
1802
1828
|
cancelAtPeriodEnd: newStatus === "active",
|
|
1803
1829
|
cancelAt: newStatus === "active" ? periodEnd ?? null : null,
|
|
@@ -1805,85 +1831,125 @@ const paystackWebhook = (options, path = "/webhook") => {
|
|
|
1805
1831
|
endedAt: newStatus === "canceled" ? now : null,
|
|
1806
1832
|
...periodEnd ? { periodEnd } : {},
|
|
1807
1833
|
updatedAt: now
|
|
1808
|
-
}
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
},
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1834
|
+
};
|
|
1835
|
+
await ctx.context.adapter.update({
|
|
1836
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1837
|
+
update: {
|
|
1838
|
+
status: newStatus,
|
|
1839
|
+
cancelAtPeriodEnd: newStatus === "active",
|
|
1840
|
+
cancelAt: newStatus === "active" ? periodEnd ?? null : null,
|
|
1841
|
+
canceledAt: now,
|
|
1842
|
+
endedAt: newStatus === "canceled" ? now : null,
|
|
1843
|
+
...periodEnd ? { periodEnd } : {},
|
|
1844
|
+
updatedAt: now
|
|
1845
|
+
},
|
|
1846
|
+
where: [{
|
|
1847
|
+
field: "subscriptionCode",
|
|
1848
|
+
value: subscriptionCode
|
|
1849
|
+
}]
|
|
1850
|
+
});
|
|
1851
|
+
if (persistedSubscription !== void 0) {
|
|
1825
1852
|
try {
|
|
1826
|
-
await options.subscription.
|
|
1853
|
+
await options.subscription.onSubscriptionCancel?.({
|
|
1827
1854
|
event,
|
|
1828
|
-
subscription: persistedSubscription
|
|
1829
|
-
plan
|
|
1855
|
+
subscription: persistedSubscription
|
|
1830
1856
|
}, ctx);
|
|
1831
1857
|
} catch (error) {
|
|
1832
|
-
ctx.context.logger.error("Paystack subscription
|
|
1858
|
+
ctx.context.logger.error("Paystack subscription cancel callback failed", error);
|
|
1833
1859
|
}
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1860
|
+
const plan = await getPlanByName(options, persistedSubscription.plan);
|
|
1861
|
+
if (plan !== void 0 && plan !== null) {
|
|
1862
|
+
try {
|
|
1863
|
+
await options.subscription.onSubscriptionUpdate?.({
|
|
1864
|
+
event,
|
|
1865
|
+
subscription: persistedSubscription,
|
|
1866
|
+
plan
|
|
1867
|
+
}, ctx);
|
|
1868
|
+
} catch (error) {
|
|
1869
|
+
ctx.context.logger.error("Paystack subscription update callback failed", error);
|
|
1870
|
+
}
|
|
1871
|
+
if (existing?.status === "trialing" && newStatus === "canceled") try {
|
|
1872
|
+
await plan.freeTrial?.onTrialExpired?.(persistedSubscription);
|
|
1873
|
+
} catch (error) {
|
|
1874
|
+
ctx.context.logger.error("Paystack trial expiry callback failed", error);
|
|
1875
|
+
}
|
|
1838
1876
|
}
|
|
1839
1877
|
}
|
|
1840
1878
|
}
|
|
1841
1879
|
}
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
}
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
}
|
|
1865
|
-
}
|
|
1880
|
+
if (eventName === "charge.success" || eventName === "invoice.update") {
|
|
1881
|
+
const subscriptionCodeRaw = (data?.subscription)?.subscription_code ?? data?.subscription_code;
|
|
1882
|
+
const subscriptionCode = subscriptionCodeRaw !== void 0 && subscriptionCodeRaw !== null && subscriptionCodeRaw !== "" ? subscriptionCodeRaw : void 0;
|
|
1883
|
+
if (subscriptionCode !== void 0) {
|
|
1884
|
+
const existingSub = await ctx.context.adapter.findOne({
|
|
1885
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1886
|
+
where: [{
|
|
1887
|
+
field: "subscriptionCode",
|
|
1888
|
+
value: subscriptionCode
|
|
1889
|
+
}]
|
|
1890
|
+
});
|
|
1891
|
+
if (existingSub !== void 0 && existingSub !== null && existingSub.pendingPlan !== void 0 && existingSub.pendingPlan !== null && existingSub.pendingPlan !== "") await ctx.context.adapter.update({
|
|
1892
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1893
|
+
update: {
|
|
1894
|
+
plan: existingSub.pendingPlan,
|
|
1895
|
+
pendingPlan: null,
|
|
1896
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1897
|
+
},
|
|
1898
|
+
where: [{
|
|
1899
|
+
field: "id",
|
|
1900
|
+
value: existingSub.id
|
|
1901
|
+
}]
|
|
1902
|
+
});
|
|
1903
|
+
}
|
|
1866
1904
|
}
|
|
1905
|
+
} catch (_e) {
|
|
1906
|
+
ctx.context.logger.error("Failed to sync Paystack webhook event", _e);
|
|
1907
|
+
throw _e;
|
|
1867
1908
|
}
|
|
1868
|
-
|
|
1869
|
-
ctx.context.
|
|
1909
|
+
await options.onEvent?.(event);
|
|
1910
|
+
if (await ctx.context.adapter.update({
|
|
1911
|
+
model: PAYSTACK_MODELS.webhookEvent,
|
|
1912
|
+
where: [{
|
|
1913
|
+
field: "eventId",
|
|
1914
|
+
value: eventId
|
|
1915
|
+
}, {
|
|
1916
|
+
field: "status",
|
|
1917
|
+
value: claimStatus
|
|
1918
|
+
}],
|
|
1919
|
+
update: {
|
|
1920
|
+
status: "processed",
|
|
1921
|
+
processedAt: /* @__PURE__ */ new Date(),
|
|
1922
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1923
|
+
}
|
|
1924
|
+
}) === null) throw new Error("Webhook processing lease was lost.");
|
|
1925
|
+
return ctx.json({ received: true });
|
|
1926
|
+
} catch (error) {
|
|
1927
|
+
if (claimStatus !== void 0) await ctx.context.adapter.update({
|
|
1928
|
+
model: PAYSTACK_MODELS.webhookEvent,
|
|
1929
|
+
where: [{
|
|
1930
|
+
field: "eventId",
|
|
1931
|
+
value: eventId
|
|
1932
|
+
}, {
|
|
1933
|
+
field: "status",
|
|
1934
|
+
value: claimStatus
|
|
1935
|
+
}],
|
|
1936
|
+
update: {
|
|
1937
|
+
status: "pending",
|
|
1938
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1939
|
+
}
|
|
1940
|
+
});
|
|
1941
|
+
ctx.context.logger.error("Paystack webhook processing failed; delivery must be retried", error);
|
|
1942
|
+
throw new APIError("SERVICE_UNAVAILABLE", { message: "Webhook processing failed; retry delivery." });
|
|
1870
1943
|
}
|
|
1871
|
-
await options.onEvent?.(event);
|
|
1872
|
-
if (webhookEventsAvailable) await store.updateWebhookEvent(eventId, {
|
|
1873
|
-
status: "processed",
|
|
1874
|
-
processedAt: /* @__PURE__ */ new Date(),
|
|
1875
|
-
updatedAt: /* @__PURE__ */ new Date()
|
|
1876
|
-
});
|
|
1877
|
-
return ctx.json({ received: true });
|
|
1878
1944
|
});
|
|
1879
1945
|
};
|
|
1880
1946
|
const initializeTransaction = (options, path = "/initialize-transaction") => {
|
|
1881
1947
|
const subscriptionOptions = options.subscription;
|
|
1882
1948
|
const useMiddlewares = subscriptionOptions?.enabled === true ? [
|
|
1883
1949
|
sessionMiddleware,
|
|
1884
|
-
|
|
1950
|
+
originCheckMiddleware,
|
|
1885
1951
|
referenceMiddleware(options, "initialize-transaction")
|
|
1886
|
-
] : [sessionMiddleware,
|
|
1952
|
+
] : [sessionMiddleware, originCheckMiddleware];
|
|
1887
1953
|
return createAuthEndpoint(path, {
|
|
1888
1954
|
method: "POST",
|
|
1889
1955
|
body: initializeTransactionBodySchema,
|
|
@@ -1963,8 +2029,8 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
|
|
|
1963
2029
|
message: "Either 'plan', 'product', or 'amount' is required to initialize a transaction.",
|
|
1964
2030
|
status: 400
|
|
1965
2031
|
});
|
|
1966
|
-
let amount =
|
|
1967
|
-
const finalCurrency =
|
|
2032
|
+
let amount = plan !== void 0 ? plan.amount : product ? product.price ?? product.amount : bodyAmount;
|
|
2033
|
+
const finalCurrency = plan !== void 0 || product ? product?.currency ?? product?.currency ?? plan?.currency ?? "NGN" : currency ?? "NGN";
|
|
1968
2034
|
const referenceIdFromCtx = ctx.context.referenceId;
|
|
1969
2035
|
const referenceId = ctx.body.referenceId ?? referenceIdFromCtx ?? session.user.id;
|
|
1970
2036
|
const groupId = normalizeSubscriptionGroup(plan?.group);
|
|
@@ -1982,6 +2048,8 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
|
|
|
1982
2048
|
}, options);
|
|
1983
2049
|
if (scheduledChange !== null) return ctx.json(scheduledChange);
|
|
1984
2050
|
let validatedQuantity = quantity ?? 1;
|
|
2051
|
+
if (product && amount !== void 0) amount *= quantity ?? 1;
|
|
2052
|
+
if (amount !== void 0 && (!Number.isSafeInteger(amount) || amount <= 0)) throw new APIError("BAD_REQUEST", { message: "Catalog amount must be a positive safe integer." });
|
|
1985
2053
|
if (plan !== void 0) try {
|
|
1986
2054
|
if (getPlanSeatAmount(plan) !== void 0) {
|
|
1987
2055
|
const members = await ctx.context.adapter.findMany({
|
|
@@ -2129,7 +2197,7 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
|
|
|
2129
2197
|
referenceId,
|
|
2130
2198
|
userId: user.id,
|
|
2131
2199
|
amount: amount ?? 0,
|
|
2132
|
-
currency:
|
|
2200
|
+
currency: finalCurrency,
|
|
2133
2201
|
status: "pending",
|
|
2134
2202
|
plan: plan !== void 0 ? plan.name.toLowerCase() : void 0,
|
|
2135
2203
|
product: product !== void 0 ? product.name.toLowerCase() : void 0,
|
|
@@ -2196,9 +2264,9 @@ const verifyTransaction = (options, path = "/verify-transaction") => {
|
|
|
2196
2264
|
const verifyBodySchema = z.object({ reference: z.string() });
|
|
2197
2265
|
const useMiddlewares = options.subscription?.enabled === true ? [
|
|
2198
2266
|
sessionMiddleware,
|
|
2199
|
-
|
|
2267
|
+
originCheckMiddleware,
|
|
2200
2268
|
referenceMiddleware(options, "verify-transaction")
|
|
2201
|
-
] : [sessionMiddleware,
|
|
2269
|
+
] : [sessionMiddleware, originCheckMiddleware];
|
|
2202
2270
|
return createAuthEndpoint(path, {
|
|
2203
2271
|
method: "POST",
|
|
2204
2272
|
body: verifyBodySchema,
|
|
@@ -2231,9 +2299,9 @@ const listSubscriptions = (options, path = "/list-subscriptions") => {
|
|
|
2231
2299
|
const subscriptionOptions = options.subscription;
|
|
2232
2300
|
const useMiddlewares = subscriptionOptions?.enabled === true ? [
|
|
2233
2301
|
sessionMiddleware,
|
|
2234
|
-
|
|
2302
|
+
originCheckMiddleware,
|
|
2235
2303
|
referenceMiddleware(options, "list-subscriptions")
|
|
2236
|
-
] : [sessionMiddleware,
|
|
2304
|
+
] : [sessionMiddleware, originCheckMiddleware];
|
|
2237
2305
|
return createAuthEndpoint(path, {
|
|
2238
2306
|
method: "GET",
|
|
2239
2307
|
query: listQuerySchema,
|
|
@@ -2261,9 +2329,9 @@ const listTransactions = (options, path = "/list-transactions") => {
|
|
|
2261
2329
|
const listQuerySchema = z.object({ referenceId: z.string().optional() });
|
|
2262
2330
|
const useMiddlewares = options.subscription?.enabled === true ? [
|
|
2263
2331
|
sessionMiddleware,
|
|
2264
|
-
|
|
2332
|
+
originCheckMiddleware,
|
|
2265
2333
|
referenceMiddleware(options, "list-transactions")
|
|
2266
|
-
] : [sessionMiddleware,
|
|
2334
|
+
] : [sessionMiddleware, originCheckMiddleware];
|
|
2267
2335
|
return createAuthEndpoint(path, {
|
|
2268
2336
|
method: "GET",
|
|
2269
2337
|
query: listQuerySchema,
|
|
@@ -2289,9 +2357,9 @@ const listTransactions = (options, path = "/list-transactions") => {
|
|
|
2289
2357
|
const disablePaystackSubscription = (options, path = "/disable-subscription") => {
|
|
2290
2358
|
const useMiddlewares = options.subscription?.enabled === true ? [
|
|
2291
2359
|
sessionMiddleware,
|
|
2292
|
-
|
|
2360
|
+
originCheckMiddleware,
|
|
2293
2361
|
referenceMiddleware(options, "disable-subscription")
|
|
2294
|
-
] : [sessionMiddleware,
|
|
2362
|
+
] : [sessionMiddleware, originCheckMiddleware];
|
|
2295
2363
|
return createAuthEndpoint(path, {
|
|
2296
2364
|
method: "POST",
|
|
2297
2365
|
body: enableDisableBodySchema,
|
|
@@ -2393,9 +2461,9 @@ const disablePaystackSubscription = (options, path = "/disable-subscription") =>
|
|
|
2393
2461
|
const enablePaystackSubscription = (options, path = "/enable-subscription") => {
|
|
2394
2462
|
const useMiddlewares = options.subscription?.enabled === true ? [
|
|
2395
2463
|
sessionMiddleware,
|
|
2396
|
-
|
|
2464
|
+
originCheckMiddleware,
|
|
2397
2465
|
referenceMiddleware(options, "enable-subscription")
|
|
2398
|
-
] : [sessionMiddleware,
|
|
2466
|
+
] : [sessionMiddleware, originCheckMiddleware];
|
|
2399
2467
|
return createAuthEndpoint(path, {
|
|
2400
2468
|
method: "POST",
|
|
2401
2469
|
body: enableDisableBodySchema,
|
|
@@ -2451,9 +2519,9 @@ const getSubscriptionManageLink = (options, path = "/subscription-manage-link")
|
|
|
2451
2519
|
const manageLinkQuerySchema = z.object({ subscriptionCode: z.string() });
|
|
2452
2520
|
const useMiddlewares = options.subscription?.enabled === true ? [
|
|
2453
2521
|
sessionMiddleware,
|
|
2454
|
-
|
|
2522
|
+
originCheckMiddleware,
|
|
2455
2523
|
referenceMiddleware(options, "get-subscription-manage-link")
|
|
2456
|
-
] : [sessionMiddleware,
|
|
2524
|
+
] : [sessionMiddleware, originCheckMiddleware];
|
|
2457
2525
|
const handler = async (ctx) => {
|
|
2458
2526
|
const { subscriptionCode } = ctx.query;
|
|
2459
2527
|
if (isLocalSubscriptionCode(subscriptionCode)) return ctx.json({
|
|
@@ -2979,7 +3047,7 @@ async function syncPaystackPlans(ctx, options) {
|
|
|
2979
3047
|
}
|
|
2980
3048
|
}
|
|
2981
3049
|
async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
2982
|
-
const { subscriptionId
|
|
3050
|
+
const { subscriptionId } = input;
|
|
2983
3051
|
const store = createBillingStore(ctx);
|
|
2984
3052
|
const subscription = await store.findSubscriptionById(subscriptionId);
|
|
2985
3053
|
if (subscription === void 0 || subscription === null) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
|
|
@@ -2987,7 +3055,7 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
2987
3055
|
if (credentials?.authorizationCode === void 0 || credentials.authorizationCode === null || credentials.authorizationCode === "") throw new APIError("BAD_REQUEST", { message: "No authorization code found for this subscription" });
|
|
2988
3056
|
const plan = (await getPlans(options.subscription)).find((candidate) => candidate.name.toLowerCase() === subscription.plan.toLowerCase());
|
|
2989
3057
|
if (plan === void 0 || plan === null) throw new APIError("NOT_FOUND", { message: "Plan not found" });
|
|
2990
|
-
const amount =
|
|
3058
|
+
const amount = calculatePlanAmount(plan, subscription.seats ?? 1);
|
|
2991
3059
|
if (amount === void 0 || amount === null) throw new APIError("BAD_REQUEST", { message: "Plan amount is not defined" });
|
|
2992
3060
|
let email;
|
|
2993
3061
|
let billingUserId = subscription.userId;
|