Skip to content

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

revenuecat init

daniel31x138ca0e214d6ef
diff --git a/apps/mobile/.env.sample b/apps/mobile/.env.sample
index d8627759..1dedc38a 100644
--- a/apps/mobile/.env.sample
+++ b/apps/mobile/.env.sample
@@ -1,6 +1,8 @@
EXPO_PUBLIC_GOOGLE_WEB_CLIENT_ID=
EXPO_PUBLIC_GOOGLE_IOS_URL_SCHEME=
EXPO_PUBLIC_GOOGLE_IOS_CLIENT_ID=
+EXPO_PUBLIC_REVENUECAT_IOS_API_KEY=
+EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY=
SENTRY_AUTH_TOKEN=
EXPO_PUBLIC_SHOW_LOGS=
-# Expo: https://docs.expo.dev/more/expo-cli/#environment-variables
\ No newline at end of file
+# Expo: https://docs.expo.dev/more/expo-cli/#environment-variables
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index 005361ea..76b67ac7 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -12,7 +12,7 @@ import { SheetProvider } from "react-native-actions-sheet";
import "@/components/ActionSheets/Sheets";
import { useColorScheme } from "nativewind";
import { lightTheme, darkTheme } from "../lib/theme";
-import { View } from "react-native";
+import { Platform, View } from "react-native";
import { rawTheme, ThemeName } from "@/lib/colors";
import { useShareIntent } from "expo-share-intent";
import useDataStore from "@/store/data";
@@ -23,6 +23,7 @@ import { queryClient } from "@/lib/queryClient";
import { StatusBar } from "expo-status-bar";
import * as Sentry from "@sentry/react-native";
import OfflineSyncProvider from "@/components/OfflineSyncProvider";
+import Purchases, { LOG_LEVEL } from "react-native-purchases";
Sentry.init({
dsn: "https://00d7eed9e810cbbf91a7ed3547e37100@o4510998442475520.ingest.us.sentry.io/4511033679609856",
@@ -46,6 +47,26 @@ export default Sentry.wrap(function RootLayout() {
setAuth();
setData();
setReader();
+
+ Purchases.setLogLevel(
+ process.env.EXPO_PUBLIC_SHOW_LOGS === "true"
+ ? LOG_LEVEL.VERBOSE
+ : LOG_LEVEL.ERROR
+ );
+
+ // Platform-specific API keys
+ const iosApiKey =
+ process.env.EXPO_PUBLIC_REVENUECAT_IOS_API_KEY ??
+ "test_geEsJwIpuCVWRqsiEowgdyfOZAM";
+ const androidApiKey =
+ process.env.EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY ??
+ "test_geEsJwIpuCVWRqsiEowgdyfOZAM";
+
+ if (Platform.OS === "ios") {
+ Purchases.configure({ apiKey: iosApiKey });
+ } else if (Platform.OS === "android") {
+ Purchases.configure({ apiKey: androidApiKey });
+ }
}, []);
useEffect(() => {
diff --git a/apps/mobile/app/subscribe.tsx b/apps/mobile/app/subscribe.tsx
index 2c1e7acf..7048f4d2 100644
--- a/apps/mobile/app/subscribe.tsx
+++ b/apps/mobile/app/subscribe.tsx
@@ -1,8 +1,6 @@
import { Button } from "@/components/ui/Button";
import { rawTheme, ThemeName } from "@/lib/colors";
import {
- getSubscriptionDaysLeft,
- getTrialPeriodDays,
hasInactiveSubscription,
shouldRouteToSubscribe,
} from "@/lib/subscription";
@@ -13,9 +11,11 @@ import { Plan } from "@linkwarden/types/global";
import { router } from "expo-router";
import { useColorScheme } from "nativewind";
import FontAwesome5 from "@expo/vector-icons/FontAwesome5";
+import Purchases, { type PurchasesPackage } from "react-native-purchases";
import { useEffect, useMemo, useState } from "react";
import {
ActivityIndicator,
+ Alert,
Dimensions,
Image,
Platform,
@@ -33,12 +33,12 @@ const paymentButton = Platform.select({
ios: {
accessibilityLabel: "Subscribe with Apple Pay",
icon: "apple-pay",
- iconSize: 50,
+ iconSize: 40,
},
android: {
accessibilityLabel: "Subscribe with Google Pay",
icon: "google-pay",
- iconSize: 50,
+ iconSize: 40,
},
default: {
accessibilityLabel: "Complete Subscription",
@@ -47,15 +47,63 @@ const paymentButton = Platform.select({
},
});
+type RevenueCatPackages = {
+ monthly: PurchasesPackage | null;
+ yearly: PurchasesPackage | null;
+};
+
+const formatTrialPeriod = (
+ unit?: string,
+ units = 1,
+ cycles: number | null = 1
+) => {
+ const total = Math.max(1, units * (cycles || 1));
+ const normalizedUnit = (unit || "day").toLowerCase();
+ const label = total === 1 ? normalizedUnit : `${normalizedUnit}s`;
+
+ return `${total} ${label}`;
+};
+
+const getFreeTrialPeriod = (product?: PurchasesPackage["product"]) => {
+ const freePhase = product?.defaultOption?.freePhase;
+
+ if (freePhase) {
+ return formatTrialPeriod(
+ freePhase.billingPeriod.unit,
+ freePhase.billingPeriod.value,
+ freePhase.billingCycleCount
+ );
+ }
+
+ if (product?.introPrice?.price === 0) {
+ return formatTrialPeriod(
+ product.introPrice.periodUnit,
+ product.introPrice.periodNumberOfUnits,
+ product.introPrice.cycles
+ );
+ }
+
+ return null;
+};
+
export default function SubscribeScreen() {
const { auth, signOut } = useAuthStore();
const { colorScheme } = useColorScheme();
const [plan, setPlan] = useState<Plan>(Plan.yearly);
- const { data: user, isLoading: isUserLoading } = useUser(auth);
+ const {
+ data: user,
+ isLoading: isUserLoading,
+ refetch: refetchUser,
+ } = useUser(auth);
const config = useConfig(auth);
+ const [purchaseLoading, setPurchaseLoading] = useState(false);
+ const [restoreLoading, setRestoreLoading] = useState(false);
+ const [revenueCatPackages, setRevenueCatPackages] =
+ useState<RevenueCatPackages>({
+ monthly: null,
+ yearly: null,
+ });
- const trialPeriodDays = getTrialPeriodDays(config.data);
- const daysLeft = getSubscriptionDaysLeft(user?.createdAt, trialPeriodDays);
const isForcedSubscribe = shouldRouteToSubscribe(user, config.data);
const showSubscribe = hasInactiveSubscription(user, config.data);
const isChecking =
@@ -68,40 +116,126 @@ export default function SubscribeScreen() {
router.replace("/(tabs)/dashboard");
}, [auth.status, isChecking, showSubscribe]);
+ useEffect(() => {
+ let active = true;
+
+ const fetchOfferings = async () => {
+ try {
+ if (!active) return;
+
+ if (!(await Purchases.isConfigured())) {
+ setTimeout(fetchOfferings, 250);
+ return;
+ }
+
+ const offerings = await Purchases.getOfferings();
+ if (!active) return;
+
+ setRevenueCatPackages({
+ monthly: offerings.current?.monthly ?? null,
+ yearly: offerings.current?.annual ?? null,
+ });
+ } catch {}
+ };
+
+ fetchOfferings();
+
+ return () => {
+ active = false;
+ };
+ }, []);
+
const selectedPlan = useMemo(() => {
const isMonthly = plan === Plan.monthly;
- const deferredDays = config.data?.REQUIRE_CC ? trialPeriodDays : daysLeft;
+ const selectedPackage = isMonthly
+ ? revenueCatPackages.monthly
+ : revenueCatPackages.yearly;
+ const selectedProduct = selectedPackage?.product;
+ const totalPrice = selectedProduct?.priceString;
+ const monthlyPrice = isMonthly
+ ? totalPrice
+ : selectedProduct?.pricePerMonthString;
+ const freeTrialPeriod = getFreeTrialPeriod(selectedProduct);
return {
- price: isMonthly ? "4" : "3",
+ package: selectedPackage ?? null,
+ price: monthlyPrice ?? null,
billed: isMonthly ? "Billed monthly" : "Billed yearly",
- total:
- deferredDays > 0
- ? `After ${deferredDays} ${deferredDays === 1 ? "day" : "days"}: ${
- isMonthly ? "$4 per month" : "$36 per year"
- }, plus tax.`
- : `${isMonthly ? "$4 per month" : "$36 per year"}, plus tax.`,
+ total: totalPrice
+ ? freeTrialPeriod
+ ? `After ${freeTrialPeriod}: ${
+ isMonthly ? `${totalPrice} per month` : `${totalPrice} per year`
+ }.`
+ : `${
+ isMonthly ? `${totalPrice} per month` : `${totalPrice} per year`
+ }.`
+ : null,
+ trialText: selectedProduct
+ ? freeTrialPeriod
+ ? `Start with a ${freeTrialPeriod} free trial, cancel anytime.`
+ : "Subscribe to continue."
+ : null,
};
- }, [config.data?.REQUIRE_CC, daysLeft, plan, trialPeriodDays]);
+ }, [plan, revenueCatPackages.monthly, revenueCatPackages.yearly]);
if (isChecking || auth.status !== "authenticated" || !showSubscribe) {
return (
<View className="flex-1 items-center justify-center bg-base-100">
- <ActivityIndicator
- size="large"
- color={rawTheme[colorScheme as ThemeName]["base-content"]}
- />
+ <ActivityIndicator size="large" />
</View>
);
}
- const trialText = config.data?.REQUIRE_CC
- ? `Start with a ${trialPeriodDays}-day free trial, cancel anytime.`
- : daysLeft <= 0
- ? "Your free trial has ended. Subscribe to continue."
- : `You have ${daysLeft} ${
- daysLeft === 1 ? "day" : "days"
- } left in your free trial.`;
+ const activateSubscription = async (customerInfo: any) => {
+ if (Object.keys(customerInfo.entitlements.active).length === 0)
+ return false;
+
+ await refetchUser();
+ router.replace("/(tabs)/dashboard");
+ return true;
+ };
+
+ const restorePurchases = async () => {
+ if (restoreLoading) return;
+
+ setRestoreLoading(true);
+
+ try {
+ if (user?.uuid) await Purchases.logIn(user.uuid);
+
+ const customerInfo = await Purchases.restorePurchases();
+ const restored = await activateSubscription(customerInfo);
+
+ if (!restored) {
+ Alert.alert("No purchases found", "No active purchases were found.");
+ }
+ } catch {
+ Alert.alert("Restore failed", "Could not restore purchases.");
+ } finally {
+ setRestoreLoading(false);
+ }
+ };
+
+ const purchase = async () => {
+ if (!selectedPlan.package || purchaseLoading) return;
+
+ setPurchaseLoading(true);
+
+ try {
+ if (user?.uuid) await Purchases.logIn(user.uuid);
+
+ const { customerInfo } = await Purchases.purchasePackage(
+ selectedPlan.package
+ );
+ await activateSubscription(customerInfo);
+ } catch (error: any) {
+ if (!error?.userCancelled) {
+ Alert.alert("Purchase failed", "Could not complete purchase.");
+ }
+ } finally {
+ setPurchaseLoading(false);
+ }
+ };
return (
<ScrollView
@@ -118,7 +252,13 @@ export default function SubscribeScreen() {
<Text className="text-base-100 text-5xl font-bold mt-8">
Subscribe
</Text>
- <Text className="text-base-100 text-2xl mt-3">{trialText}</Text>
+ {selectedPlan.trialText ? (
+ <Text className="text-base-100 text-2xl mt-3">
+ {selectedPlan.trialText}
+ </Text>
+ ) : (
+ <View className="h-7 w-4/5 rounded-md bg-base-100/30 mt-3" />
+ )}
</SafeAreaView>
<Svg
@@ -141,6 +281,23 @@ export default function SubscribeScreen() {
Subscribe to start using Linkwarden. If you think this is a mistake,
</Text>
+ <TouchableOpacity
+ activeOpacity={0.8}
+ className="self-start"
+ disabled={restoreLoading}
+ onPress={restorePurchases}
+ >
+ {restoreLoading ? (
+ <ActivityIndicator
+ color={rawTheme[colorScheme as ThemeName].primary}
+ size="small"
+ />
+ ) : (
+ <Text className="text-primary font-semibold">
+ Restore Purchases
+ </Text>
+ )}
+ </TouchableOpacity>
<View className="bg-base-200 border border-neutral-content rounded-lg p-1 flex-row relative">
<TouchableOpacity
@@ -174,20 +331,17 @@ export default function SubscribeScreen() {
Yearly
</Text>
</TouchableOpacity>
-
- <View
- className="absolute -top-3 right-1 bg-red-600 px-2 py-0.5 rounded-md"
- style={{ transform: [{ rotate: "12deg" }] }}
- >
- <Text className="text-white text-xs font-semibold">25% off</Text>
- </View>
</View>
<View className="items-center gap-1">
- <Text className="text-base-content text-4xl font-semibold">
- ${selectedPlan.price}
- <Text className="text-neutral text-base font-normal">/mo</Text>
- </Text>
+ {selectedPlan.price ? (
+ <Text className="text-base-content text-4xl font-semibold">
+ {selectedPlan.price}
+ <Text className="text-neutral text-base font-normal">/mo</Text>
+ </Text>
+ ) : (
+ <View className="h-10 w-28 rounded-md bg-base-200" />
+ )}
<Text className="text-base-content text-base font-semibold">
{selectedPlan.billed}
</Text>
@@ -197,15 +351,23 @@ export default function SubscribeScreen() {
<Text className="text-base-content text-sm font-semibold mb-1">
Total
</Text>
- <Text className="text-neutral text-sm">{selectedPlan.total}</Text>
+ {selectedPlan.total ? (
+ <Text className="text-neutral text-sm">{selectedPlan.total}</Text>
+ ) : (
+ <View className="h-4 w-4/5 rounded bg-base-200" />
+ )}
</View>
- <TouchableOpacity
+ <Button
+ variant="ghost"
+ size="lg"
activeOpacity={0.85}
accessibilityRole="button"
accessibilityLabel={paymentButton.accessibilityLabel}
- className="w-full flex-row items-center justify-center rounded-lg bg-black px-4"
- onPress={() => undefined}
+ className="w-full flex-row bg-black px-4"
+ disabled={!selectedPlan.package || purchaseLoading}
+ onPress={purchase}
+ isLoading={purchaseLoading}
>
{paymentButton.icon ? (
<FontAwesome5
@@ -219,7 +381,7 @@ export default function SubscribeScreen() {
{paymentButton.label}
</Text>
)}
- </TouchableOpacity>
+ </Button>
{isForcedSubscribe ? (
<TouchableOpacity className="w-fit mx-auto" onPress={signOut}>
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index 2362d194..ce13262a 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -68,6 +68,7 @@
"react-native-mmkv": "4.1.2",
"react-native-nitro-modules": "0.34.1",
"react-native-pdf": "^7.0.3",
+ "react-native-purchases": "^10.2.0",
"react-native-reanimated": "4.1.1",
"react-native-safe-area-context": "^5.7.0",
"react-native-screens": "~4.23.0",
diff --git a/apps/web/pages/api/v1/webhook/index.ts b/apps/web/pages/api/v1/webhook/index.ts
index 3147c878..406bf737 100644
--- a/apps/web/pages/api/v1/webhook/index.ts
+++ b/apps/web/pages/api/v1/webhook/index.ts
@@ -1,3 +1,5 @@
+// Will be deprecated soon! Moved to /api/v1/webhooks/stripe
+
import type { NextApiRequest, NextApiResponse } from "next";
import handleSubscription from "@/lib/api/stripe/handleSubscription";
import stripeSDK from "@/lib/api/stripe/stripeSDK";
diff --git a/apps/web/pages/api/v1/webhooks/stripe.ts b/apps/web/pages/api/v1/webhooks/stripe.ts
new file mode 100644
index 00000000..37b62e53
--- /dev/null
+++ b/apps/web/pages/api/v1/webhooks/stripe.ts
@@ -0,0 +1,9 @@
+import webhook from "../webhook/index";
+
+export const config = {
+ api: {
+ bodyParser: false,
+ },
+};
+
+export default webhook;
diff --git a/packages/prisma/migrations/20260602155952_add_uuid_to_user_model/migration.sql b/packages/prisma/migrations/20260602155952_add_uuid_to_user_model/migration.sql
new file mode 100644
index 00000000..5e01b424
--- /dev/null
+++ b/packages/prisma/migrations/20260602155952_add_uuid_to_user_model/migration.sql
@@ -0,0 +1,22 @@
+/*
+ Warnings:
+
+ - A unique constraint covering the columns `[uuid]` on the table `User` will be added. If there are existing duplicate values, this will fail.
+ - The required column `uuid` was added to the `User` table with a prisma-level default value. This is not possible if the table is not empty. Please add this column as optional, then populate it before making it required.
+
+*/
+-- AlterTable
+
+ALTER TABLE "User" ADD COLUMN "uuid" UUID;
+
+-- Backfill existing users
+
+UPDATE "User" SET "uuid" = gen_random_uuid() WHERE "uuid" IS NULL;
+
+-- Make it required after backfill
+
+ALTER TABLE "User" ALTER COLUMN "uuid" SET NOT NULL;
+
+-- CreateIndex
+
+CREATE UNIQUE INDEX "User_uuid_key" ON "User"("uuid");
\ No newline at end of file
diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prisma
index e0a8aea8..84b6b0e4 100644
--- a/packages/prisma/schema.prisma
+++ b/packages/prisma/schema.prisma
@@ -27,6 +27,7 @@ model Account {
model User {
id Int @id @default(autoincrement())
+ uuid String @unique @default(uuid()) @db.Uuid
name String?
username String? @unique
email String? @unique
@@ -218,17 +219,17 @@ 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
+ 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 {
@@ -294,11 +295,11 @@ enum DashboardSectionType {
}
model AppMigration {
- id Int @id @default(autoincrement())
- name String @unique
+ id Int @id @default(autoincrement())
+ name String @unique
status AppMigrationStatus
finishedAt DateTime?
- createdAt DateTime @default(now())
+ createdAt DateTime @default(now())
}
enum AppMigrationStatus {
diff --git a/yarn.lock b/yarn.lock
index eae71484..3270398b 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5295,6 +5295,7 @@ __metadata:
react-native-mmkv: "npm:4.1.2"
react-native-nitro-modules: "npm:0.34.1"
react-native-pdf: "npm:^7.0.3"
+ react-native-purchases: "npm:^10.2.0"
react-native-reanimated: "npm:4.1.1"
react-native-safe-area-context: "npm:^5.7.0"
react-native-screens: "npm:~4.23.0"
@@ -7462,6 +7463,29 @@ __metadata:
languageName: node
linkType: hard
+"@revenuecat/purchases-js-hybrid-mappings@npm:18.8.0":
+ version: 18.8.0
+ resolution: "@revenuecat/purchases-js-hybrid-mappings@npm:18.8.0"
+ dependencies:
+ "@revenuecat/purchases-js": "npm:1.41.1"
+ checksum: 10c0/12915a0191efba55caa3da2298821b83af3c976df106e3388a169fbf0cd3b870baf5428567e7a4fe01f5f7849dd7c4b90f67926367c15d04b54caa3e6f5fa71a
+ languageName: node
+ linkType: hard
+
+"@revenuecat/purchases-js@npm:1.41.1":
+ version: 1.41.1
+ resolution: "@revenuecat/purchases-js@npm:1.41.1"
+ checksum: 10c0/ca3a412e597b08890e5f18a4c0063e6b39e5807e742bb9788970d08fae05d42d4f80e4f0722c27cbe1b22bf882b7f65fdc9871ea02416a24003b4c286b11b38d
+ languageName: node
+ linkType: hard
+
+"@revenuecat/purchases-typescript-internal@npm:18.8.0":
+ version: 18.8.0
+ resolution: "@revenuecat/purchases-typescript-internal@npm:18.8.0"
+ checksum: 10c0/7cf3aa9d356aa40e2cc33410fed8a71fe71b331f3fcc5ccd22d895206daff76e2ff0eca87f1c1a06e968d3c5c02cb9c78bd244996f1f64b0370424e4e60e826b
+ languageName: node
+ linkType: hard
+
"@rollup/rollup-android-arm-eabi@npm:4.55.1":
version: 4.55.1
resolution: "@rollup/rollup-android-arm-eabi@npm:4.55.1"
@@ -18913,6 +18937,23 @@ __metadata:
languageName: node
linkType: hard
+"react-native-purchases@npm:^10.2.0":
+ version: 10.2.0
+ resolution: "react-native-purchases@npm:10.2.0"
+ dependencies:
+ "@revenuecat/purchases-js-hybrid-mappings": "npm:18.8.0"
+ "@revenuecat/purchases-typescript-internal": "npm:18.8.0"
+ peerDependencies:
+ react: ">= 16.6.3"
+ react-native: ">= 0.73.0"
+ react-native-web: "*"
+ peerDependenciesMeta:
+ react-native-web:
+ optional: true
+ checksum: 10c0/1f1d68b1133ff7156d9e206831ff308ff04b7878a4fb621cdac489d78ba062d796a21d925bf6147cdd4222a4ba7fa2fccc1a52183dff0204a0c82dd8fc5d497e
+ languageName: node
+ linkType: hard
+
"react-native-reanimated@npm:4.1.1":
version: 4.1.1
resolution: "react-native-reanimated@npm:4.1.1"