Skip to content
Draft
Show file tree
Hide file tree
Changes from 59 commits
Commits
Show all changes
60 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
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
9 changes: 9 additions & 0 deletions template/app/.env.server.example
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,15 @@ 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_...
# 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
34 changes: 31 additions & 3 deletions template/app/src/analytics/stats.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
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';
import { assertUnreachable } from '../shared/utils';

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

Expand Down Expand Up @@ -50,8 +54,11 @@ 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}`);
assertUnreachable(paymentProcessor.id);
}

const { totalViews, prevDayViewsChangePercent } = await getDailyPageViews();
Expand Down Expand Up @@ -198,3 +205,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
4 changes: 3 additions & 1 deletion template/app/src/payment/paymentProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ 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';

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 ensurePolarCustomer(userId, userEmail);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah now I see why ensurePolarCustomer was exported.
Why do we ensurePolarCustomer here?
ensurePolarCustomer returns customer.id which is also required in polarPaymentProcessor.createCheckoutSession. We just used it here just to return it instead of using it before this function.

Hm, I see that we send both customerId and externalCustomerId customerEmail pair to Polar.
Is both of them required?

I would assume no.
I didn't check docs for this, but I would guess you use either customerId if you already created a customer (which we did) or you use externalCustomerId customerEmail pair if you want Polar to automatically handle customer creation for you instead.

Could you please check this?

If so we can simplify this a lot.
Is this possible?

export interface CreatePolarCheckoutSessionArgs {
  productId: string;
  customerId: string;
  mode: PolarMode;
}

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

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

  return {
    id: checkoutSession.id,
    url: checkoutSession.url,
  };
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we ensurePolarCustomer here?

For a first-time order, a customer record is created and linked to the Wasp user on the Polar side. The connection isn't saved on the Wasp side until the webhook event is handled.

ensurePolarCustomer returns customer.id which is also required in polarPaymentProcessor.createCheckoutSession. We just used it here just to return it instead of using it before this function.

polarPaymentProcessor.createCheckoutSession accepts the Wasp user ID as a parameter, not the Polar customer ID, which is what this method returns.

Hm, I see that we send both customerId and externalCustomerId customerEmail pair to Polar.
Is both of them required?

I ran into an issue when switching between sandbox and production environments because the Polar customer ID is different in each. The webhook handlers look up the user by their Wasp user ID, not their Polar customer ID, to ensure that the event is always associated with the correct user, even if the environment changes. The externalCustomerId value has to passed in to the checkout session in order to be retrieved in the webhook event and I included the email to make sure the Polar record is updated if the Wasp user ever changes their address.

Copy link
Contributor

@FranjoMindek FranjoMindek Aug 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For a first-time order, a customer record is created and linked to the Wasp user on the Polar side. The connection isn't saved on the Wasp side until the webhook event is handled.

Inside of polarPaymentProcessor.createCheckoutSession we use createPolarCheckoutSession which uses ensurePolarCustomer.
That means on checkout we create a Polar customer.
We also connect it to our user via prismaUserDelegate.update where we update the paymentProcessorUserId.

Checkout also doesn't mean the customer will make a purchase.

Why do we ensurePolarCustomer here?

For a first-time order, a customer record is created and linked to the Wasp user on the Polar side. The connection isn't saved on the Wasp side until the webhook event is handled.

What I meant why not do:

  const customer = await ensurePolarCustomer(userId, userEmail);
  const session = await createPolarCheckoutSession({
    productId: paymentPlan.getPaymentProcessorPlanId(),
    customerId: customer.id,
    mode: paymentPlanEffectToPolarMode(paymentPlan.effect),
  });

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

  return {
    session: {
      id: session.id,
      url: session.url,
    },
  };

This way we reduce the size input and output to createPolarCheckoutSession. Which did unnecessary work inside of it.

I ran into an issue when switching between sandbox and production environments because the Polar customer ID is different in each.

That is how it should be.
One should use different database between sandbox and production.
This is okay.

The webhook handlers look up the user by their Wasp user ID, not their Polar customer ID, to ensure that the event is always associated with the correct user, even if the environment changes.

We shouldn't handle that.
The different environment should be used with a different database.

The externalCustomerId value has to passed in to the checkout session in order to be retrieved in the webhook event and I included the email to make sure the Polar record is updated if the Wasp user ever changes their address.

This should be handled in the "change user email action".
When we update the user's email we should also update it on their payment processor.
Currently Wasp doesn't support email change so we shouldn't bother with this.
If somebody implements it it's their responsibility to handle that.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, understood

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,
};
}

async function ensurePolarCustomer(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;
}
}
79 changes: 79 additions & 0 deletions template/app/src/payment/polar/paymentProcessor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
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 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 null;
},
webhook: polarWebhook,
webhookMiddlewareConfigFn: polarMiddlewareConfigFn,
};

function paymentPlanEffectToPolarMode(planEffect: PaymentPlanEffect): PolarMode {
const effectToMode: Record<PaymentPlanEffect['kind'], PolarMode> = {
subscription: 'subscription',
credits: 'payment',
};

return effectToMode[planEffect.kind];
}
7 changes: 7 additions & 0 deletions template/app/src/payment/polar/polarClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Polar } from '@polar-sh/sdk';
import { requireNodeEnvVar } from '../../server/utils';

export const polarClient = new Polar({
accessToken: requireNodeEnvVar('POLAR_ACCESS_TOKEN'),
server: requireNodeEnvVar('POLAR_SANDBOX_MODE') === 'true' ? 'sandbox' : 'production',
});
34 changes: 34 additions & 0 deletions template/app/src/payment/polar/userPaymentDetails.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { PrismaClient } from '@prisma/client';
import type { PaymentPlanId, SubscriptionStatus } from '../plans';

export const updateUserPolarPaymentDetails = async (
{
userId,
polarCustomerId,
subscriptionPlan,
subscriptionStatus,
numOfCreditsPurchased,
datePaid,
}: {
userId: string;
polarCustomerId?: string;
subscriptionPlan?: PaymentPlanId;
subscriptionStatus?: SubscriptionStatus | string;
numOfCreditsPurchased?: number;
datePaid?: Date;
},
userDelegate: PrismaClient['user']
) => {
return await userDelegate.update({
where: {
id: userId,
},
data: {
...(polarCustomerId && { paymentProcessorUserId: polarCustomerId }),
subscriptionPlan,
subscriptionStatus,
datePaid,
credits: numOfCreditsPurchased !== undefined ? { increment: numOfCreditsPurchased } : undefined,
},
});
};
Loading