Skip to content

⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.

add revenuecat webhook to backend

daniel31x132b638fb07eaa
diff --git a/apps/web/lib/api/controllers/users/postUser.ts b/apps/web/lib/api/controllers/users/postUser.ts
index e08396d3..53d69ae0 100644
--- a/apps/web/lib/api/controllers/users/postUser.ts
+++ b/apps/web/lib/api/controllers/users/postUser.ts
@@ -26,6 +26,17 @@ export default async function postUser(
return { response: "Registration is disabled.", status: 400 };
}
+ if (
+ !parentUser?.subscriptions?.stripeSubscriptionId ||
+ parentUser.subscriptions.revenueCatOriginalTransactionId
+ ) {
+ return {
+ response:
+ "Adding seats is only supported if you subscribed on web using Stripe.",
+ status: 400,
+ };
+ }
+
const dataValidation = PostUserSchema().safeParse(req.body);
if (!dataValidation.success) {
diff --git a/apps/web/lib/api/controllers/users/userId/deleteUserById.ts b/apps/web/lib/api/controllers/users/userId/deleteUserById.ts
index 5bf9d493..973b0558 100644
--- a/apps/web/lib/api/controllers/users/userId/deleteUserById.ts
+++ b/apps/web/lib/api/controllers/users/userId/deleteUserById.ts
@@ -90,7 +90,7 @@ export default async function deleteUserById(
},
});
- if (removeUser.emailVerified)
+ if (removeUser.emailVerified && user.subscriptions.stripeSubscriptionId)
await updateSeats(
user.subscriptions.stripeSubscriptionId,
user.subscriptions.quantity - 1
@@ -159,7 +159,7 @@ export default async function deleteUserById(
select: { stripeSubscriptionId: true },
});
- if (subscription) {
+ if (subscription?.stripeSubscriptionId) {
await stripe.subscriptions.cancel(
subscription.stripeSubscriptionId,
{
@@ -170,7 +170,11 @@ export default async function deleteUserById(
}
);
}
- } else if (user.subscriptions?.id && queryId === userId) {
+ } else if (
+ user.subscriptions?.id &&
+ user.subscriptions.stripeSubscriptionId &&
+ queryId === userId
+ ) {
await stripe.subscriptions.cancel(
user.subscriptions.stripeSubscriptionId,
{
@@ -182,6 +186,7 @@ export default async function deleteUserById(
);
} else if (
user.parentSubscription?.id &&
+ user.parentSubscription.stripeSubscriptionId &&
user &&
user.emailVerified
) {
diff --git a/apps/web/pages/api/v1/auth/[...nextauth].ts b/apps/web/pages/api/v1/auth/[...nextauth].ts
index 63e53c61..dc887f6a 100644
--- a/apps/web/pages/api/v1/auth/[...nextauth].ts
+++ b/apps/web/pages/api/v1/auth/[...nextauth].ts
@@ -1367,6 +1367,7 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {
if (
STRIPE_SECRET_KEY &&
parentSubscription?.quantity &&
+ parentSubscription.stripeSubscriptionId &&
verifiedChildUsersCount + 2 > // add current user and the admin
parentSubscription.quantity
) {
diff --git a/apps/web/pages/api/v1/webhooks/revenuecat.ts b/apps/web/pages/api/v1/webhooks/revenuecat.ts
new file mode 100644
index 00000000..427c8e7c
--- /dev/null
+++ b/apps/web/pages/api/v1/webhooks/revenuecat.ts
@@ -0,0 +1,159 @@
+import type { NextApiRequest, NextApiResponse } from "next";
+import { prisma } from "@linkwarden/prisma";
+
+type RevenueCatEvent = {
+ type?: string;
+ app_user_id?: string;
+ original_app_user_id?: string;
+ aliases?: string[];
+ environment?: "PRODUCTION" | "SANDBOX";
+ original_transaction_id?: string;
+ transaction_id?: string;
+ purchased_at_ms?: number;
+ expiration_at_ms?: number;
+};
+
+const subscriptionEvents = new Set([
+ "INITIAL_PURCHASE",
+ "RENEWAL",
+ "UNCANCELLATION",
+ "CANCELLATION",
+ "BILLING_ISSUE",
+ "EXPIRATION",
+ "SUBSCRIPTION_EXTENDED",
+ "TEMPORARY_ENTITLEMENT_GRANT",
+]);
+
+const isUuid = (value?: string) =>
+ Boolean(
+ value?.match(
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+ )
+ );
+
+export default async function revenueCatWebhook(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ if (req.method !== "POST") {
+ return res.status(405).json({ response: "Method not allowed." });
+ }
+
+ if (process.env.NEXT_PUBLIC_DEMO === "true")
+ return res.status(400).json({
+ response:
+ "This action is disabled because this is a read-only demo of Linkwarden.",
+ });
+
+ if (!process.env.REVENUECAT_WEBHOOK_AUTHORIZATION) {
+ return res.status(400).json({
+ response:
+ "This action is disabled because RevenueCat is not initialized.",
+ });
+ }
+
+ if (
+ req.headers.authorization !== process.env.REVENUECAT_WEBHOOK_AUTHORIZATION
+ ) {
+ return res.status(401).json({ response: "Invalid authorization header." });
+ }
+
+ const event = req.body?.event as RevenueCatEvent | undefined;
+
+ if (!event?.type || !subscriptionEvents.has(event.type)) {
+ return res.status(200).json({ response: "Event ignored." });
+ }
+
+ if (
+ event.environment === "SANDBOX" &&
+ process.env.REVENUECAT_ACCEPT_SANDBOX_WEBHOOKS !== "true" &&
+ process.env.NODE_ENV === "production"
+ ) {
+ return res.status(200).json({ response: "Sandbox event ignored." });
+ }
+
+ const appUserIds = [
+ event.app_user_id,
+ event.original_app_user_id,
+ ...(event.aliases ?? []),
+ ].filter(isUuid) as string[];
+
+ const originalTransactionId =
+ event.original_transaction_id ?? event.transaction_id;
+
+ if (
+ appUserIds.length === 0 ||
+ !originalTransactionId ||
+ !event.purchased_at_ms ||
+ !event.expiration_at_ms
+ ) {
+ return res.status(200).json({ response: "Event ignored." });
+ }
+
+ const currentPeriodStart = new Date(event.purchased_at_ms);
+ const currentPeriodEnd = new Date(event.expiration_at_ms);
+ const active = event.type !== "EXPIRATION" && currentPeriodEnd > new Date();
+
+ try {
+ const user = await prisma.user.findFirst({
+ where: {
+ uuid: {
+ in: appUserIds,
+ },
+ },
+ });
+
+ if (!user) {
+ return res.status(200).json({ response: "User not found." });
+ }
+
+ const subscription = await prisma.subscription.findUnique({
+ where: {
+ revenueCatOriginalTransactionId: originalTransactionId,
+ },
+ });
+
+ if (subscription) {
+ await prisma.subscription.update({
+ where: {
+ id: subscription.id,
+ },
+ data: {
+ active,
+ currentPeriodStart,
+ currentPeriodEnd,
+ quantity: 1,
+ userId: user.id,
+ },
+ });
+ } else {
+ await prisma.subscription.upsert({
+ where: {
+ userId: user.id,
+ },
+ create: {
+ active,
+ revenueCatOriginalTransactionId: originalTransactionId,
+ currentPeriodStart,
+ currentPeriodEnd,
+ quantity: 1,
+ userId: user.id,
+ },
+ update: {
+ active,
+ revenueCatOriginalTransactionId: originalTransactionId,
+ currentPeriodStart,
+ currentPeriodEnd,
+ quantity: 1,
+ },
+ });
+ }
+ } catch (error) {
+ console.error("Error handling RevenueCat webhook event:", error);
+ return res.status(500).send("Server Error");
+ }
+
+ return res.status(200).json({
+ response: "Done!",
+ });
+}
diff --git a/packages/prisma/migrations/20260602170000_add_revenuecat_subscription_id/migration.sql b/packages/prisma/migrations/20260602170000_add_revenuecat_subscription_id/migration.sql
new file mode 100644
index 00000000..07f3455e
--- /dev/null
+++ b/packages/prisma/migrations/20260602170000_add_revenuecat_subscription_id/migration.sql
@@ -0,0 +1,8 @@
+-- AlterTable
+ALTER TABLE "Subscription" ALTER COLUMN "stripeSubscriptionId" DROP NOT NULL;
+
+-- AlterTable
+ALTER TABLE "Subscription" ADD COLUMN "revenueCatOriginalTransactionId" TEXT;
+
+-- CreateIndex
+CREATE UNIQUE INDEX "Subscription_revenueCatOriginalTransactionId_key" ON "Subscription"("revenueCatOriginalTransactionId");
diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prisma
index 84b6b0e4..e659224e 100644
--- a/packages/prisma/schema.prisma
+++ b/packages/prisma/schema.prisma
@@ -219,17 +219,18 @@ model Tag {
}
model Subscription {
- id Int @id @default(autoincrement())
- active Boolean
- stripeSubscriptionId String @unique
- currentPeriodStart DateTime
- currentPeriodEnd DateTime
- quantity Int @default(1)
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
- userId Int @unique
- childUsers User[] @relation("ChildUsers")
- createdAt DateTime @default(now())
- updatedAt DateTime @default(now()) @updatedAt
+ id Int @id @default(autoincrement())
+ active Boolean
+ stripeSubscriptionId String? @unique
+ revenueCatOriginalTransactionId String? @unique
+ currentPeriodStart DateTime
+ currentPeriodEnd DateTime
+ quantity Int @default(1)
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ userId Int @unique
+ childUsers User[] @relation("ChildUsers")
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
}
model AccessToken {