Skip to content
Draft
Show file tree
Hide file tree
Changes from 49 commits
Commits
Show all changes
64 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
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
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
27 changes: 27 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,30 @@

# Local Netlify folder
.netlify

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
dev-debug.log
# Dependency directories
node_modules/
# Environment variables
.env
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# OS specific

# Task files
# tasks.json
# tasks/
.taskmaster
template/e2e-tests
12 changes: 12 additions & 0 deletions template/app/.env.server.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# If you use `wasp start db` then you DO NOT need to add a DATABASE_URL env variable here.
# DATABASE_URL=


# 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 +18,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
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
31 changes: 29 additions & 2 deletions template/app/src/analytics/stats.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { listOrders } from '@lemonsqueezy/lemonsqueezy.js';
import Stripe from 'stripe';
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';
// @ts-ignore
import { OrderStatus } from '@polar-sh/sdk/models/components/orderstatus.js';
import { paymentProcessor } from '../payment/paymentProcessor';
import { SubscriptionStatus } from '../payment/plans';
import { polarClient } from '../payment/polar/polarClient';

export type DailyStatsProps = { dailyStats?: DailyStats; weeklyStats?: DailyStats[]; isLoading?: boolean };

Expand Down Expand Up @@ -50,6 +53,9 @@ export const calculateDailyStats: DailyStatsJob<never, void> = async (_args, con
case 'lemonsqueezy':
totalRevenue = await fetchTotalLemonSqueezyRevenue();
break;
case 'polar':
totalRevenue = await fetchTotalPolarRevenue();
break;
default:
throw new Error(`Unsupported payment processor: ${paymentProcessor.id}`);
}
Expand Down Expand Up @@ -198,3 +204,24 @@ async function fetchTotalLemonSqueezyRevenue() {
throw error;
}
}

async function fetchTotalPolarRevenue(): Promise<number> {
let totalRevenue = 0;

const result = await polarClient.orders.list({
limit: 100,
});

for await (const page of result) {
const orders = page.result.items || [];

for (const order of orders) {
if (order.status === OrderStatus.Paid && order.totalAmount > 0) {
totalRevenue += order.totalAmount;
}
}
}

// Revenue is in cents so we convert to dollars
return totalRevenue / 100;
}
2 changes: 1 addition & 1 deletion template/app/src/payment/PricingPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ const PricingPage = () => {
</h2>
</div>
<p className='mx-auto mt-6 max-w-2xl text-center text-lg leading-8 text-muted-foreground'>
Choose between Stripe and LemonSqueezy as your payment provider. Just add your Product IDs! Try it
Choose between Stripe, LemonSqueezy or Polar as your payment provider. Just add your Product IDs! Try it
out below with test credit card number <br />
<span className='px-2 py-1 bg-muted rounded-md text-muted-foreground font-mono text-sm'>
4242 4242 4242 4242 4242
Expand Down
6 changes: 4 additions & 2 deletions template/app/src/payment/paymentProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import type { PaymentsWebhook } from 'wasp/server/api';
import type { MiddlewareConfigFn } from 'wasp/server';
import { PrismaClient } from '@prisma/client';
import { stripePaymentProcessor } from './stripe/paymentProcessor';
import { lemonSqueezyPaymentProcessor } from './lemonSqueezy/paymentProcessor';
// import { lemonSqueezyPaymentProcessor } from './lemonSqueezy/paymentProcessor';
// import { polarPaymentProcessor } from './polar/paymentProcessor';

export interface CreateCheckoutSessionArgs {
userId: string;
Expand All @@ -17,7 +18,7 @@ export interface FetchCustomerPortalUrlArgs {
};

export interface PaymentProcessor {
id: 'stripe' | 'lemonsqueezy';
id: 'stripe' | 'lemonsqueezy' | 'polar';
createCheckoutSession: (args: CreateCheckoutSessionArgs) => Promise<{ session: { id: string; url: string }; }>;
fetchCustomerPortalUrl: (args: FetchCustomerPortalUrlArgs) => Promise<string | null>;
webhook: PaymentsWebhook;
Expand All @@ -29,4 +30,5 @@ export interface PaymentProcessor {
* other payment processor code that you're not using from `/src/payment`
*/
// export const paymentProcessor: PaymentProcessor = lemonSqueezyPaymentProcessor;
// export const paymentProcessor: PaymentProcessor = polarPaymentProcessor;
export const paymentProcessor: PaymentProcessor = stripePaymentProcessor;
81 changes: 81 additions & 0 deletions template/app/src/payment/polar/checkoutUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// @ts-ignore
import { CheckoutCreate } from '@polar-sh/sdk/models/components/checkoutcreate.js';
// @ts-ignore
import { Customer } from '@polar-sh/sdk/models/components/customer.js';
import { env } from 'wasp/server';
import type { PolarMode } from './paymentProcessor';
import { polarClient } from './polarClient';

export interface CreatePolarCheckoutSessionArgs {
productId: string;
userEmail: string;
userId: string;
mode: PolarMode;
}

export interface PolarCheckoutSession {
id: string;
url: string;
customerId?: string;
}

export async function createPolarCheckoutSession({
productId,
userEmail,
userId,
mode,
}: CreatePolarCheckoutSessionArgs): Promise<PolarCheckoutSession> {
const baseUrl = env.WASP_WEB_CLIENT_URL.replace(/\/+$/, '');
const successUrl = `${baseUrl}/checkout?success=true`;
const existingCustomer = await fetchPolarCustomer(userId, userEmail);
const checkoutSessionArgs: CheckoutCreate = {
products: [productId],
externalCustomerId: userId,
customerEmail: userEmail,
successUrl: successUrl,
metadata: {
paymentMode: mode,
source: baseUrl,
},
...(existingCustomer && { customerId: existingCustomer.id }),
};
const checkoutSession = await polarClient.checkouts.create(checkoutSessionArgs);
const customerId = checkoutSession.customerId;

return {
id: checkoutSession.id,
url: checkoutSession.url,
customerId: customerId || undefined,
};
}

export async function fetchPolarCustomer(waspUserId: string, customerEmail: string): Promise<Customer> {
try {
const existingCustomer = await polarClient.customers.getExternal({
externalId: waspUserId,
});

if (existingCustomer) {
console.log('Using existing Polar customer');

return existingCustomer;
}
} catch (error) {
console.log('No existing Polar customer found by external ID, will create new one');
}

try {
console.log('Creating new Polar customer');

const newCustomer = await polarClient.customers.create({
externalId: waspUserId,
email: customerEmail,
});

return newCustomer;
} catch (error) {
console.error('Error creating Polar customer:', error);

throw error;
}
}
87 changes: 87 additions & 0 deletions template/app/src/payment/polar/paymentProcessor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// @ts-ignore
import { OrderStatus } from '@polar-sh/sdk/models/components/orderstatus.js';
import { requireNodeEnvVar } from '../../server/utils';
import {
type CreateCheckoutSessionArgs,
type FetchCustomerPortalUrlArgs,
type PaymentProcessor,
} from '../paymentProcessor';
import type { PaymentPlanEffect } from '../plans';
import { createPolarCheckoutSession } from './checkoutUtils';
import { polarClient } from './polarClient';
import { polarMiddlewareConfigFn, polarWebhook } from './webhook';

export type PolarMode = 'subscription' | 'payment';

export const polarPaymentProcessor: PaymentProcessor = {
id: 'polar',
createCheckoutSession: async ({
userId,
userEmail,
paymentPlan,
prismaUserDelegate,
}: CreateCheckoutSessionArgs) => {
const session = await createPolarCheckoutSession({
productId: paymentPlan.getPaymentProcessorPlanId(),
userEmail,
userId,
mode: paymentPlanEffectToPolarMode(paymentPlan.effect),
});

if (!session.customerId) {
throw new Error('Polar checkout session created without customer ID');
}

await prismaUserDelegate.update({
where: {
id: userId,
},
data: {
paymentProcessorUserId: session.customerId,
},
});

return {
session: {
id: session.id,
url: session.url,
},
};
},
fetchCustomerPortalUrl: async (args: FetchCustomerPortalUrlArgs) => {
const defaultPortalUrl = requireNodeEnvVar('POLAR_CUSTOMER_PORTAL_URL');
const user = await args.prismaUserDelegate.findUnique({
where: {
id: args.userId,
},
select: {
paymentProcessorUserId: true,
},
});

if (user?.paymentProcessorUserId) {
const customerSession = await polarClient.customerSessions.create({
customerId: user.paymentProcessorUserId,
});

return customerSession.customerPortalUrl;
}

return defaultPortalUrl;
},
webhook: polarWebhook,
webhookMiddlewareConfigFn: polarMiddlewareConfigFn,
};

/**
* Maps a payment plan effect to a Polar mode
* @param planEffect Payment plan effect
* @returns Polar mode
*/
function paymentPlanEffectToPolarMode(planEffect: PaymentPlanEffect): PolarMode {
const effectToMode: Record<PaymentPlanEffect['kind'], PolarMode> = {
subscription: 'subscription',
credits: 'payment',
};
return effectToMode[planEffect.kind];
}
17 changes: 17 additions & 0 deletions template/app/src/payment/polar/polarClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Polar } from '@polar-sh/sdk';
import { requireNodeEnvVar } from '../../server/utils';

function shouldUseSandboxMode(): boolean {
const explicitSandboxMode = process.env.POLAR_SANDBOX_MODE;

if (explicitSandboxMode !== undefined) {
return explicitSandboxMode === 'true';
}

return process.env.NODE_ENV !== 'production';
}

export const polarClient = new Polar({
accessToken: requireNodeEnvVar('POLAR_ACCESS_TOKEN'),
server: shouldUseSandboxMode() ? 'sandbox' : 'production',
});
Loading