-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Polar integration #461
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Polar integration #461
Changes from all commits
728bcd0
61f5e73
d3f3ed6
51d05ca
f07fa91
2b42cc6
a0276a3
0ebd0a3
e84670d
54292a7
156823c
2841121
825eb66
6ad783b
a97b79f
eb68932
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -79,6 +79,10 @@ app OpenSaaS { | |
] | ||
}, | ||
|
||
server: { | ||
envValidationSchema: import { envValidationSchema } from "@src/server/validation", | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This change is something I think we will want to introduce to However, I would also ask you to remove it from the current PR. |
||
}, | ||
|
||
client: { | ||
rootComponent: import App from "@src/client/App", | ||
}, | ||
|
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'; | ||
|
@@ -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(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think we want this change. Additionally, this is also out of scope for this PR. |
||
const { totalViews, prevDayViewsChangePercent } = await getDailyPageViews(); | ||
|
||
let dailyStats = await context.entities.DailyStats.findUnique({ | ||
|
@@ -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; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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; | ||
|
@@ -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: 'customer@example.com', | ||
* paymentPlan: hobbyPlan, | ||
* prismaUserDelegate: context.entities.User | ||
* }); | ||
* // Redirect user to session.url for payment | ||
* ``` | ||
*/ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is too verbose. Jsdocs are useful when using the function is tricky and we want to show examples on how to use it properly. This is also again out of scope for this PR. |
||
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> = { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Related: Comment on We don't want to tie in the payment processors together. |
||
[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(); | ||
Genyus marked this conversation as resolved.
Show resolved
Hide resolved
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hey, it's great to see that you're trying to improve
open-saas
further above the Polar integration, but I wouldn't do this as part of this PR.Paddle integration PR had the same problem here:
https://github.com/wasp-lang/open-saas/pull/486/files#r2266908329
Doing in this PR will distract us from the main point (Polar), and will prolong the process to get the feature we want.
I've explained in the Paddle PR (linked above) why we don't believe this approach is right for us.
I would kindly ask you to remove non-Polar parts of the PR.
Thanks for the effort.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@FranjoMindek Thanks for the feedback. Happy to proceed, but one of the main reasons I adopted this approach was because I wanted to add e2e tests for Polar and the current architecture makes it impossible to run tests for more than one provider without modifying the source. Do you have any suggestions for how that limitation could be addressed?