Skip to content
Open
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
103 commits
Select commit Hold shift + click to select a range
728bcd0
refactor: create explicit type for processor IDs
Genyus Jul 26, 2025
61f5e73
refactor: move revenue calculation to processors
Genyus Jul 26, 2025
d3f3ed6
docs: improve comments
Genyus Jul 26, 2025
51d05ca
fix: update imports after previous refactoring
Genyus Jul 28, 2025
f07fa91
refactor: convert processor IDs to enum values
Genyus Jul 28, 2025
2b42cc6
feat: add validation of server env vars
Genyus Jul 28, 2025
a0276a3
feat: add initial Polar integration
Genyus Jul 28, 2025
0ebd0a3
feat: implement total revenue calculation
Genyus Jul 28, 2025
e84670d
feat: implement customer portal URL retrieval
Genyus Jul 28, 2025
54292a7
feat: implement checkout session creation
Genyus Jul 28, 2025
156823c
feat: implement webhook handling
Genyus Jul 28, 2025
2841121
feat: add dynamic payment processor selection
Genyus Jul 29, 2025
825eb66
fix: implement webhook handling
Genyus Jul 31, 2025
6ad783b
chore: rename file for consistency
Genyus Jul 31, 2025
a97b79f
Merge branch 'main' into polar
Genyus Jul 31, 2025
eb68932
fix: address typing errors
Genyus Aug 6, 2025
fca11f9
fix: resolve type assignment error
Genyus Aug 7, 2025
c71f29a
refactor: streamline payment processor integration
Genyus Aug 17, 2025
732b9ed
style: remove redundant JSDoc comments
Genyus Aug 17, 2025
2410e01
refactor: simplify error handling
Genyus Aug 21, 2025
f65cc67
refactor: fix customer portal implementation
Genyus Aug 21, 2025
df213c9
chore: update webhook response status codes
Genyus Aug 21, 2025
5f71cac
refactor: remove iteration for single customer lookup
Genyus Aug 21, 2025
882df67
refactor: simplify webhook error handling
Genyus Aug 21, 2025
7d0eb4e
refactor: rename polar client
Genyus Aug 21, 2025
3639c0d
refactor: refactor client configuration
Genyus Aug 21, 2025
2f5748c
refactor: remove standalone client config file
Genyus Aug 21, 2025
e5a63de
style: remove extraneous JSDoc comments
Genyus Aug 21, 2025
fda6a57
refactor: remove standalone type declarations file
Genyus Aug 21, 2025
add2038
docs: remove unnecessary README
Genyus Aug 21, 2025
254aae4
refactor: remodel webhook to align with current integrations
Genyus Aug 21, 2025
780d24c
fix: resolves issues found in testing
Genyus Aug 22, 2025
568c38b
chore: mention Polar as an available payment platform
Genyus Aug 22, 2025
721fd6f
chore: remove env validation
Genyus Aug 22, 2025
31ad46c
chore: remove redundant guard
Genyus Aug 22, 2025
f5892aa
chore: remove unsupported event type
Genyus Aug 22, 2025
32c8934
fix: update order completion handler
Genyus Aug 22, 2025
2b3195c
fix: throw error when credits can't be parsed from order
Genyus Aug 22, 2025
2a64914
revert: revert deletion of validation.ts
Genyus Aug 22, 2025
9658034
Merge pull request #1 from wasp-lang/main
Genyus Aug 22, 2025
9b3a26e
Merge pull request #2 from wasp-lang/main
Genyus Aug 22, 2025
033bdfe
chore: rename file for consistency
Genyus Aug 22, 2025
dbcfa08
style: reorder imports
Genyus Aug 22, 2025
e81b2db
fix: correct webhook event support
Genyus Aug 23, 2025
20e95f8
refactor: simplify webhook handlers
Genyus Aug 23, 2025
f31f176
style: restore missing line break
Genyus Aug 23, 2025
3003595
chore: add gitignore rules
Genyus Aug 26, 2025
6cce3fe
refactor: restore centralised payment stats
Genyus Aug 27, 2025
ce97f73
revert: restore original payment processor files
Genyus Aug 27, 2025
27b8ea7
revert: restore paymentProcessor comments
Genyus Aug 27, 2025
6471324
refactor: improve switch condition checking
Genyus Aug 27, 2025
1b72606
refactor: remove unused code
Genyus Aug 28, 2025
b0eaf88
refactor: rename function
Genyus Aug 28, 2025
3defeb9
refactor: simplify user updating
Genyus Aug 28, 2025
2741ea2
refactor: simplify webhook handling
Genyus Aug 28, 2025
543fa92
fix: remove default portal URL
Genyus Aug 28, 2025
ee65871
fix: improve type-safety
Genyus Aug 28, 2025
31a3b0b
fix: restore available processors
Genyus Aug 28, 2025
42cbf32
docs: remove JSDoc comment
Genyus Aug 28, 2025
adde113
refactor: remove redundant file
Genyus Aug 28, 2025
29ec825
refactor: streamline session management
Genyus Aug 29, 2025
ee820b3
refactor: rename method parameters
Genyus Sep 4, 2025
4b1ce80
refactor: refactor webhook handling
Genyus Sep 4, 2025
cbf0e62
refactor: refactor user update function
Genyus Sep 5, 2025
064abc1
refactor: refactor Polar client logic
Genyus Sep 5, 2025
5a46b2f
refactor: consolidate type declarations
Genyus Sep 5, 2025
ac66c28
Merge pull request #3 from wasp-lang/main
Genyus Sep 11, 2025
745516e
fix: update for Wasp 0.18.0
Genyus Sep 11, 2025
9a09fed
revert: undo client logic refactoring
Genyus Sep 13, 2025
33ab2a3
refactor: implement changes from review feedback
Genyus Sep 14, 2025
37ce885
refactor: relocate function
Genyus Sep 14, 2025
a9f51e3
refactor: remove redundant gate
Genyus Sep 14, 2025
17042bf
refactor: simplify webhook handling
Genyus Sep 14, 2025
9ce5cfc
refactor: further simplify webhook handling
Genyus Sep 15, 2025
8c9e8e5
refactor: implement additional webhook improvements
Genyus Sep 15, 2025
c110026
refactor: sort imports
Genyus Sep 15, 2025
4b343ff
refactor: refactor checkoutUtils.ts
Genyus Sep 15, 2025
d5d97af
docs: add Polar configuration to integration guide
Genyus Sep 15, 2025
99bda63
chore: remove superfluous .gitignore entries
Genyus Sep 15, 2025
22e1c6d
docs: add tip to Polar section
Genyus Sep 15, 2025
d8b9732
Merge pull request #4 from wasp-lang/main
Genyus Sep 15, 2025
a1671c8
Merge branch 'main' into polar
Genyus Sep 15, 2025
c2886ae
refactor: sort imports
Genyus Sep 16, 2025
9287ec3
docs: apply suggestions from code review
Genyus Sep 16, 2025
4c69038
docs: apply additional code review suggestions
Genyus Sep 16, 2025
11a7093
fix: prevent data integrity edge case
Genyus Sep 16, 2025
8c2254a
refactor: clean up webhook handling
Genyus Sep 16, 2025
456ef49
revert: revert .gitignore to original state
Genyus Sep 16, 2025
cae2372
docs: add illustrative images to integration guide
Genyus Sep 16, 2025
3593df3
docs: apply code review suggestions
Genyus Sep 17, 2025
18f3479
docs: remove redundant images
Genyus Sep 17, 2025
d2f2dd0
refactor: remove obsolete export
Genyus Sep 17, 2025
dbd67b3
style: apply Prettier formatting across template
Genyus Sep 17, 2025
6d85122
docs: add Polar references to guides
Genyus Sep 17, 2025
5384775
Merge pull request #5 from wasp-lang/main
Genyus Sep 23, 2025
f4b965c
Merge branch 'polar' of github.com:Genyus/open-saas into polar
Genyus Sep 25, 2025
45a9194
style: apply new Prettier formatting across template/src
Genyus Sep 25, 2025
fa246d4
Merge branch 'main' into polar
Genyus Sep 25, 2025
5527860
docs: fix typo
Genyus Sep 25, 2025
e6c11fe
fix: apply refinements
Genyus Oct 6, 2025
70d3220
refactor: rename and reorder arguments
Genyus Oct 9, 2025
893288d
fix: remove obsolete images
Genyus Oct 13, 2025
a4fff20
ci: update diffs
Genyus Oct 13, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions template/app/.env.server.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
# If you use `wasp start db` then you DO NOT need to add a DATABASE_URL env variable here.
# DATABASE_URL=

# Supports Stripe, LemonSqueezy, Polar
PAYMENT_PROCESSOR_ID=Stripe

# For testing, go to https://dashboard.stripe.com/test/apikeys and get a test stripe key that starts with "sk_test_..."
STRIPE_API_KEY=sk_test_...
# After downloading starting the stripe cli (https://stripe.com/docs/stripe-cli) with `stripe listen --forward-to localhost:3001/payments-webhook` it will output your signing secret
Expand All @@ -17,6 +20,17 @@ LEMONSQUEEZY_STORE_ID=012345
# define your own webhook secret when creating a new webhook on https://app.lemonsqueezy.com/settings/webhooks
LEMONSQUEEZY_WEBHOOK_SECRET=my-webhook-secret

# After creating an organization, you can find your organization id in the organization settings https://sandbox.polar.sh/dashboard/[your org slug]/settings
POLAR_ORGANIZATION_ID=00000000-0000-0000-0000-000000000000
# Generate a token at https://sandbox.polar.sh/dashboard/[your org slug]/settings
POLAR_ACCESS_TOKEN=polar_oat_...
# Define your own webhook secret when creating a new webhook at https://sandbox.polar.sh/dashboard/[your org slug]/settings/webhooks
POLAR_WEBHOOK_SECRET=polar_whs_...
# The unauthenticated URL is at https://sandbox.polar.sh/[your org slug]/portal
POLAR_CUSTOMER_PORTAL_URL=https://sandbox.polar.sh/.../portal
# For production, set this to false, then generate a new organization and products from the live dashboard
POLAR_SANDBOX_MODE=true

# If using Stripe, go to https://dashboard.stripe.com/test/products and click on + Add Product
# If using Lemon Squeezy, go to https://app.lemonsqueezy.com/products and create new products and variants
PAYMENTS_HOBBY_SUBSCRIPTION_PLAN_ID=012345
Expand Down
4 changes: 4 additions & 0 deletions template/app/main.wasp
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ app OpenSaaS {
]
},

server: {
envValidationSchema: import { envValidationSchema } from "@src/server/validation",
},

client: {
rootComponent: import App from "@src/client/App",
},
Expand Down
2 changes: 2 additions & 0 deletions template/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
"@headlessui/react": "1.7.13",
"@hookform/resolvers": "^5.1.1",
"@lemonsqueezy/lemonsqueezy.js": "^3.2.0",
"@polar-sh/express": "^0.3.2",
"@polar-sh/sdk": "^0.34.3",
"@radix-ui/react-accordion": "^1.2.11",
"@radix-ui/react-avatar": "^1.1.10",
"@radix-ui/react-checkbox": "^1.3.2",
Expand Down
84 changes: 1 addition & 83 deletions template/app/src/analytics/stats.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { type DailyStats } from 'wasp/entities';
import { type DailyStatsJob } from 'wasp/server/jobs';
import Stripe from 'stripe';
import { stripe } from '../payment/stripe/stripeClient';
import { listOrders } from '@lemonsqueezy/lemonsqueezy.js';
import { getDailyPageViews, getSources } from './providers/plausibleAnalyticsUtils';
// import { getDailyPageViews, getSources } from './providers/googleAnalyticsUtils';
import { paymentProcessor } from '../payment/paymentProcessor';
Expand Down Expand Up @@ -42,18 +39,7 @@ export const calculateDailyStats: DailyStatsJob<never, void> = async (_args, con
paidUserDelta -= yesterdaysStats.paidUserCount;
}

let totalRevenue;
switch (paymentProcessor.id) {
case 'stripe':
totalRevenue = await fetchTotalStripeRevenue();
break;
case 'lemonsqueezy':
totalRevenue = await fetchTotalLemonSqueezyRevenue();
break;
default:
throw new Error(`Unsupported payment processor: ${paymentProcessor.id}`);
}

const totalRevenue = await paymentProcessor.getTotalRevenue();
const { totalViews, prevDayViewsChangePercent } = await getDailyPageViews();

let dailyStats = await context.entities.DailyStats.findUnique({
Expand Down Expand Up @@ -130,71 +116,3 @@ export const calculateDailyStats: DailyStatsJob<never, void> = async (_args, con
});
}
};

async function fetchTotalStripeRevenue() {
let totalRevenue = 0;
let params: Stripe.BalanceTransactionListParams = {
limit: 100,
// created: {
// gte: startTimestamp,
// lt: endTimestamp
// },
type: 'charge',
};

let hasMore = true;
while (hasMore) {
const balanceTransactions = await stripe.balanceTransactions.list(params);

for (const transaction of balanceTransactions.data) {
if (transaction.type === 'charge') {
totalRevenue += transaction.amount;
}
}

if (balanceTransactions.has_more) {
// Set the starting point for the next iteration to the last object fetched
params.starting_after = balanceTransactions.data[balanceTransactions.data.length - 1].id;
} else {
hasMore = false;
}
}

// Revenue is in cents so we convert to dollars (or your main currency unit)
return totalRevenue / 100;
}

async function fetchTotalLemonSqueezyRevenue() {
try {
let totalRevenue = 0;
let hasNextPage = true;
let currentPage = 1;

while (hasNextPage) {
const { data: response } = await listOrders({
filter: {
storeId: process.env.LEMONSQUEEZY_STORE_ID,
},
page: {
number: currentPage,
size: 100,
},
});

if (response?.data) {
for (const order of response.data) {
totalRevenue += order.attributes.total;
}
}

hasNextPage = !response?.meta?.page.lastPage;
currentPage++;
}

// Revenue is in cents so we convert to dollars (or your main currency unit)
return totalRevenue / 100;
} catch (error) {
console.error('Error fetching Lemon Squeezy revenue:', error);
throw error;
}
}
45 changes: 43 additions & 2 deletions template/app/src/payment/lemonSqueezy/paymentProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,54 @@ import type { CreateCheckoutSessionArgs, FetchCustomerPortalUrlArgs, PaymentProc
import { requireNodeEnvVar } from '../../server/utils';
import { createLemonSqueezyCheckoutSession } from './checkoutUtils';
import { lemonSqueezyWebhook, lemonSqueezyMiddlewareConfigFn } from './webhook';
import { lemonSqueezySetup } from '@lemonsqueezy/lemonsqueezy.js';
import { lemonSqueezySetup, listOrders } from '@lemonsqueezy/lemonsqueezy.js';
import { PaymentProcessors } from '../types';

lemonSqueezySetup({
apiKey: requireNodeEnvVar('LEMONSQUEEZY_API_KEY'),
});

/**
* Calculates total revenue from LemonSqueezy orders
* @returns Promise resolving to total revenue in dollars
*/
async function fetchTotalLemonSqueezyRevenue(): Promise<number> {
try {
let totalRevenue = 0;
let hasNextPage = true;
let currentPage = 1;

while (hasNextPage) {
const { data: response } = await listOrders({
filter: {
storeId: process.env.LEMONSQUEEZY_STORE_ID,
},
page: {
number: currentPage,
size: 100,
},
});

if (response?.data) {
for (const order of response.data) {
totalRevenue += order.attributes.total;
}
}

hasNextPage = !response?.meta?.page.lastPage;
currentPage++;
}

// Revenue is in cents so we convert to dollars (or your main currency unit)
return totalRevenue / 100;
} catch (error) {
console.error('Error fetching Lemon Squeezy revenue:', error);
throw error;
}
}

export const lemonSqueezyPaymentProcessor: PaymentProcessor = {
id: 'lemonsqueezy',
id: PaymentProcessors.LemonSqueezy,
createCheckoutSession: async ({ userId, userEmail, paymentPlan }: CreateCheckoutSessionArgs) => {
if (!userId) throw new Error('User ID needed to create Lemon Squeezy Checkout Session');
const session = await createLemonSqueezyCheckoutSession({
Expand All @@ -33,6 +73,7 @@ export const lemonSqueezyPaymentProcessor: PaymentProcessor = {
// This is handled in the Lemon Squeezy webhook.
return user.lemonSqueezyCustomerPortalUrl;
},
getTotalRevenue: fetchTotalLemonSqueezyRevenue,
webhook: lemonSqueezyWebhook,
webhookMiddlewareConfigFn: lemonSqueezyMiddlewareConfigFn,
};
87 changes: 82 additions & 5 deletions template/app/src/payment/paymentProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import type { MiddlewareConfigFn } from 'wasp/server';
import { PrismaClient } from '@prisma/client';
import { stripePaymentProcessor } from './stripe/paymentProcessor';
import { lemonSqueezyPaymentProcessor } from './lemonSqueezy/paymentProcessor';
import { polarPaymentProcessor } from './polar/paymentProcessor';
import { PaymentProcessorId, PaymentProcessors } from './types';
import { getActivePaymentProcessor } from './validation';

export interface CreateCheckoutSessionArgs {
userId: string;
Expand All @@ -16,17 +19,91 @@ export interface FetchCustomerPortalUrlArgs {
prismaUserDelegate: PrismaClient['user'];
};

/**
* Standard interface for all payment processors
* Provides a consistent API for payment operations across different providers
*/
export interface PaymentProcessor {
id: 'stripe' | 'lemonsqueezy';
id: PaymentProcessorId;
/**
* Creates a checkout session for payment processing
* Handles both subscription and one-time payment flows based on the payment plan configuration
* @param args Checkout session creation arguments
* @param args.userId Internal user ID for tracking and database updates
* @param args.userEmail Customer email address for payment processor customer creation/lookup
* @param args.paymentPlan Payment plan configuration containing pricing and payment type information
* @param args.prismaUserDelegate Prisma user delegate for database operations
* @returns Promise resolving to checkout session with session ID and redirect URL
* @throws {Error} When payment processor API calls fail or required configuration is missing
* @example
* ```typescript
* const { session } = await paymentProcessor.createCheckoutSession({
* userId: 'user_123',
* userEmail: '[email protected]',
* paymentPlan: hobbyPlan,
* prismaUserDelegate: context.entities.User
* });
* // Redirect user to session.url for payment
* ```
*/
createCheckoutSession: (args: CreateCheckoutSessionArgs) => Promise<{ session: { id: string; url: string }; }>;
/**
* Retrieves the customer portal URL for subscription and billing management
* Allows customers to view billing history, update payment methods, and manage subscriptions
* @param args Customer portal URL retrieval arguments
* @param args.userId Internal user ID to lookup customer information
* @param args.prismaUserDelegate Prisma user delegate for database operations
* @returns Promise resolving to customer portal URL or null if not available
* @throws {Error} When user lookup fails or payment processor API calls fail
* @example
* ```typescript
* const portalUrl = await paymentProcessor.fetchCustomerPortalUrl({
* userId: 'user_123',
* prismaUserDelegate: context.entities.User
* });
* if (portalUrl) {
* // Redirect user to portal for billing management
* return { redirectUrl: portalUrl };
* }
* ```
*/
fetchCustomerPortalUrl: (args: FetchCustomerPortalUrlArgs) => Promise<string | null>;
/**
* Calculates the total revenue from this payment processor
* @returns Promise resolving to total revenue in dollars
*/
getTotalRevenue: () => Promise<number>;
webhook: PaymentsWebhook;
webhookMiddlewareConfigFn: MiddlewareConfigFn;
}

/**
* Choose which payment processor you'd like to use, then delete the
* other payment processor code that you're not using from `/src/payment`
* All available payment processors
*/
const paymentProcessorMap: Record<PaymentProcessors, PaymentProcessor> = {
[PaymentProcessors.Stripe]: stripePaymentProcessor,
[PaymentProcessors.LemonSqueezy]: lemonSqueezyPaymentProcessor,
[PaymentProcessors.Polar]: polarPaymentProcessor,
};

/**
* Get the payment processor instance based on environment configuration or override
* @param override Optional processor override for testing scenarios
* @returns The configured payment processor instance
* @throws {Error} When the specified processor is not found in the processor map
*/
export function getPaymentProcessor(override?: PaymentProcessorId): PaymentProcessor {
const processorId = getActivePaymentProcessor(override);
const processor = paymentProcessorMap[processorId];

if (!processor) {
throw new Error(`Payment processor '${processorId}' not found. Available processors: ${Object.keys(paymentProcessorMap).join(', ')}`);
}

return processor;
}

/**
* The currently configured payment processor.
*/
// export const paymentProcessor: PaymentProcessor = lemonSqueezyPaymentProcessor;
export const paymentProcessor: PaymentProcessor = stripePaymentProcessor;
export const paymentProcessor: PaymentProcessor = getPaymentProcessor();
Loading