Skip to content
Open
Show file tree
Hide file tree
Changes from 99 commits
Commits
Show all changes
117 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
d183139
Merge remote-tracking branch 'origin/main' into polar
FranjoMindek Nov 7, 2025
bbbf9a2
start polishing
FranjoMindek Nov 7, 2025
9287cd9
Merge branch 'main' into polar
FranjoMindek Nov 13, 2025
671dcf0
improve polar, brush off some stuff to stripe
FranjoMindek Nov 13, 2025
8114346
changes to diffs
FranjoMindek Nov 13, 2025
9bd7278
remove polar filess + lemon deps
FranjoMindek Nov 13, 2025
2c0fbd0
Merge branch 'main' into polar
FranjoMindek Nov 14, 2025
cf10272
webhook changes
FranjoMindek Nov 14, 2025
b8ca44a
simplify + fix query
FranjoMindek Nov 14, 2025
9ea1170
test reset stipe stuff
FranjoMindek Nov 14, 2025
b1fcd54
Merge branch 'main' into polar
FranjoMindek Nov 14, 2025
80ffbe1
revert user
FranjoMindek Nov 14, 2025
a285d07
diff
FranjoMindek Nov 14, 2025
ce7c90a
abstract
FranjoMindek Nov 14, 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
Binary file added opensaas-sh/blog/src/assets/polar/user-table.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 14 additions & 0 deletions opensaas-sh/blog/src/content/docs/guides/deploying.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,20 @@ With the webhook url ready, go to your [Lemon Squeezy Webhooks Dashboard](https:
- subscription_cancelled
- click `save`

### Setting up your Production Polar Webhook

To set up your Polar webhook, you'll need the URL of your newly deployed server + `/payments-webhook`, e.g. `https://open-saas-wasp-sh-server.fly.dev/payments-webhook`.

With the webhook URL ready, go to `Settings` > `Webhooks` in your [Polar Dashboard](https://polar.sh/dashboard):
- click the `Add Endpoint` button.
Copy link
Member

Choose a reason for hiding this comment

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

It feels weird that every bullet ends with a period but start with a lowercase letter.

- paste the webhook forwarding URL in the `URL` field.
- set the `Format` to `"Raw"`
- select at least the following events to be sent:
- order.paid
- subscription.updated
Comment on lines +211 to +212
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
- order.paid
- subscription.updated
- `order.paid`
- `subscription.updated`

- click `Save`
- copy the generated webhook secret (a long, random string starting with `polar_whs_`).
- add this signing secret to your server's production environment variables under `POLAR_WEBHOOK_SECRET=`

## Deploying your Blog

Expand Down
162 changes: 154 additions & 8 deletions opensaas-sh/blog/src/content/docs/guides/payments-integration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -16,43 +16,67 @@ import variantId from '@assets/lemon-squeezy/variant-id.png';
import subscriptionVariantIds from '@assets/lemon-squeezy/subscription-variant-ids.png';
import ngrok from '@assets/lemon-squeezy/ngrok.png';
import storeId from '@assets/lemon-squeezy/store-id.png';
import addPolarProduct from '@assets/polar/add-product.png';
import addPolarToken from '@assets/polar/add-token.png';
import polarUserTable from '@assets/polar/user-table.png';
import polarWebhookLogs from '@assets/polar/webhook-log.png';

This guide will show you how to set up Payments for testing and local development with the following payment processors:
- Stripe
- Lemon Squeezy
- Polar

:::note[Which should I choose?]
Stripe is the industry standard, is more configurable, and has cheaper fees.
Lemon Squeezy acts a [Merchant of Record](https://www.lemonsqueezy.com/reporting/merchant-of-record). This means they take care of paying taxes in multiple countries for you, but charge higher fees per transaction.
Lemon Squeezy acts a [Merchant of Record](https://www.lemonsqueezy.com/reporting/merchant-of-record). This means they take care of paying taxes in multiple countries for you, but charge higher fees per transaction.
Polar is an open-source [Merchant of Record](https://docs.polar.sh/merchant-of-record/introduction#merchant-of-record) designed specifically for developers.
:::

## Important First Steps

First, go to `/src/payment/paymentProcessor.ts` and choose which payment processor you'd like to use, e.g. Stripe or Lemon Squeezy:
First, go to `/src/payment/paymentProcessor.ts` and choose which payment processor you'd like to use, e.g. Stripe, Lemon Squeezy, or Polar:

```ts title="src/payment/paymentProcessor.ts" ins={5, 7}
```ts title="src/payment/paymentProcessor.ts" ins={6, 8, 10}
import { stripePaymentProcessor } from './stripe/paymentProcessor';
import { lemonSqueezyPaymentProcessor } from './lemonSqueezy/paymentProcessor';
import { polarPaymentProcessor } from './polar/paymentProcessor';
//...

export const paymentProcessor: PaymentProcessor = stripePaymentProcessor;
// or...
export const paymentProcessor: PaymentProcessor = lemonSqueezyPaymentProcessor;
// or...
export const paymentProcessor: PaymentProcessor = polarPaymentProcessor;
```

At this point, you can delete:
- the unused payment processor code within the `/src/payment/<unused-provider>` directory,
- any unused environment variables from `.env.server` (they will be prefixed with the name of the provider your are not using):
- e.g. `STRIPE_API_KEY`, `STRIPE_CUSTOMER_PORTAL_URL`, `LEMONSQUEEZY_API_KEY`, `LEMONSQUEEZY_WEBHOOK_SECRET`
- e.g. `STRIPE_API_KEY`, `LEMONSQUEEZY_API_KEY`, `POLAR_ACCESS_TOKEN`
- Make sure to also uninstall the unused dependencies:
- `npm uninstall @lemonsqueezy/lemonsqueezy.js`
- or
- `npm uninstall stripe`
- If using Stripe
```sh
npm uninstall @lemonsqueezy/lemonsqueezy.js @polar-sh/sdk
```
- If using Lemon Squeezy
```sh
npm uninstall stripe @polar-sh/sdk
```
- If using Polar
```sh
npm uninstall @lemonsqueezy/lemonsqueezy.js stripe
```
- Remove any unused fields from the `User` model in the `schema.prisma` file if they exist:
- e.g. `lemonSqueezyCustomerPortalUrl`

Now your code is ready to go with your preferred payment processor and it's time to configure your payment processor's API keys, products, and other settings.

Follow the steps for your selected processor:

- [Stripe](#stripe)
- [Lemon Squeezy](#lemon-squeezy)
- [Polar](#polar)

## Stripe

First, you'll need to create a Stripe account. You can do that [here](https://dashboard.stripe.com/register).
Expand Down Expand Up @@ -306,6 +330,128 @@ Now go to your [Lemon Squeezy Webhooks Dashboard](https://app.lemonsqueezy.com/s

You're now ready to start consuming Lemon Squeezy webhook events in local development.

## Polar
Copy link
Member

Choose a reason for hiding this comment

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

Another idea to think about: splitting this page into 3 pages (one for each payment providers since it's getting long) - I don't feel too strongly about this - I'll let you decide if that makes sense right row or maybe with the next provider.


First, make sure you've defined your payment processor in `src/payment/paymentProcessor.ts`, as described in the [important first steps](#important-first-steps).

Next, you'll need to create a Polar account. You can do that [here](https://polar.sh).

:::tip[Star our Repo on GitHub! 🌟]
We've packed in a ton of features and love into this SaaS starter, and offer it all to you for free!

If you're finding this template and its guides useful, consider giving us [a star on GitHub](https://github.com/wasp-lang/wasp)
:::
Comment on lines +336 to +340
Copy link
Member

Choose a reason for hiding this comment

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

Out of scope for this PR - but this could be a separate component that we can reuse.


### Enable Sandbox Mode

For local development and testing, you'll want to use Polar's sandbox mode. The Polar sandbox is fully isolated, so there are separate URLs for the [sandbox dashboard](https://sandbox.polar.sh/dashboard) and [live dashboard](https://polar.sh/dashboard), each with independent products, sales, access tokens, etc.

Add the following to your `.env.server` file:

```ts title=".env.server"
POLAR_SANDBOX_MODE=true
```
Comment on lines +346 to +350
Copy link
Member

Choose a reason for hiding this comment

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

Nitpick: We have this in the example env server - do we use that context to say "Make sure that the POLAR_SANDBOX_MODE is set to true"


:::note[Going Live]
When you're ready to go live, change this to `false`.
:::

### Get your Polar API Access Token
Copy link
Member

Choose a reason for hiding this comment

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

We need to emphasize here a lot more that people need two accounts:

  1. Production at https://polar.sh
  2. Sandbox at https://sandbox.polar.sh

And then create the development token in Sandbox env.

I got confused by this, so I think our users will get confused as well.


Once you've created your account, you'll need to get your API access token. You can do that by navigating to the `Developers` section under your dashboard settings and creating a new personal access token.
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
Once you've created your account, you'll need to get your API access token. You can do that by navigating to the `Developers` section under your dashboard settings and creating a new personal access token.
Once you've created your account, you'll need to get your API access token. You can do that by navigating to the `Developers` section under your dashboard settings and creating a new personal access token:

Since there is a list after the sentence.

Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
Once you've created your account, you'll need to get your API access token. You can do that by navigating to the `Developers` section under your dashboard settings and creating a new personal access token.
Once you've created your account, you'll need to get your API access token. You can do that by navigating to the `Developers` section under dashboard `Settings > General` and creating a new organisation access token:

I wasn't looking for Settings because it wasn't highlighted like this.

Image


- Click on the `New Token` button to create a new token
- Give your token a name (e.g., "Open SaaS Development")
Copy link
Member

Choose a reason for hiding this comment

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

We are missing some steps, which scope to choose?

Image

Copy link
Member

Choose a reason for hiding this comment

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

Which expiration to choose?

SCR-20251118-kwsk

Copy link
Member

Choose a reason for hiding this comment

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

Also, I just realized I created the token in the production env and not sandbox! This means it wasn't really clear I need to go to https://sandbox.polar.sh create a new account and then create a token.

- Copy the generated token and paste it in your `.env.server` file, e.g. `POLAR_ACCESS_TOKEN=polar_oat_...`

### Create Test Products

To create test products in Polar, go to the `Products` section in your Polar dashboard.
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
To create test products in Polar, go to the `Products` section in your Polar dashboard.
To create test products in Polar, go to the `Products` section in your Polar dashboard:


- Click on the `New Product` button to create a new product
- Fill in the product details:
- **Name**: e.g., "Hobby Plan", "Pro Plan", or "10 Credits"
- **Description**: Brief description of what the product includes
- **Pricing**: Select "Monthly" or "Yearly" for recurring plans or "One-time purchase" for credits, then configure the desired pricing type
- Configure any remaining optional fields, e.g. **Media**, **Checkout Fields**, **Metadata**, etc
- Click `Create Product`

After creating each product, you'll need to copy the Product ID from the product page and add it to your `.env.server` file:

```ini title=".env.server"
PAYMENTS_HOBBY_SUBSCRIPTION_PLAN_ID=<your-hobby-product-id>
PAYMENTS_PRO_SUBSCRIPTION_PLAN_ID=<your-pro-product-id>
PAYMENTS_CREDITS_10_PLAN_ID=<your-credits-product-id>
```
Comment on lines +376 to +382
Copy link
Member

Choose a reason for hiding this comment

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

I feel like the previous section said "just create some products" and now we are specific three product we need to fill it. I'd maybe clarify it somewhere "this is what Open Saas comes with out of the box, you can of course change the plans like you want, make sure to modify the code ..."

If we are not doing it for other payment providers as well, I think we should, so it might be better handled with a separate issue.

If we are doing it for others, let's just do it here as well.


:::note[Product ID Location]
The Product ID can be acquired on the product page in your Polar dashboard. Tap the `⠇` icon in the top-right corner, then select `Copy Product ID`.
:::

### Create and Use the Polar Webhook in Local Development

Polar notifies your Wasp app through a webhook (for example, when a payment succeeds). During development, you need to expose your locally running Wasp server (started with `wasp start`) to the internet. Because the Wasp server runs on port 3001 by default, run `ngrok` on the same port. `ngrok` will generate a public URL that you can give to Polar.
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
Polar notifies your Wasp app through a webhook (for example, when a payment succeeds). During development, you need to expose your locally running Wasp server (started with `wasp start`) to the internet. Because the Wasp server runs on port 3001 by default, run `ngrok` on the same port. `ngrok` will generate a public URL that you can give to Polar.
Polar notifies your Wasp app through a webhook (for example, when a payment succeeds). During development, you need to expose your locally running Wasp server (started with `wasp start`) to the internet. Wasp server runs on port 3001 by default, so you can run for example, `ngrok` on the port 3001 to expose your server to the internet. `ngrok` will generate a public URL that you can give to Polar.

Felt weirdly formulated "Becuase Wasp runs on 3001, that's why you need ngrok" but we wanted to say something else "you can use ngrok to expose port 3001".


To do this, first make sure you have installed [`ngrok`](https://ngrok.com/docs/getting-started/).

Once `ngrok` is installed and your Wasp app is running, run:

```sh
ngrok http 3001
```
Comment on lines +394 to +398
Copy link
Member

Choose a reason for hiding this comment

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

I'm not sure if we have the same requirements for other providers? Do we need a "common" section with these kind of tips? If this is only for Polr, let's keep it like this.

Also, one completely free alternative to Ngrok is https://theboroer.github.io/localtunnel-www/

Copy link
Member

Choose a reason for hiding this comment

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

One extra tip for Ngrok, if users go to https://dashboard.ngrok.com/domains they can get their fixed domain which they can use like:

ngrok http 3001 --url <subdomain>.ngrok-free.app

And it will always be https://<subdomain>.ngrok-free.app


<Image src={ngrok} alt="ngrok" loading="lazy" />

`ngrok` will display a forwarding address. Copy this address and append `/payments-webhook` to it. This path is already configured in `main.wasp` under the `api paymentsWebhook` definition. It should look something like this:

```sh title="Callback URL"
https://89e5-2003-c7-153c-72a5-f837.ngrok-free.app/payments-webhook
```

Next, configure the webhook in your Polar dashboard:

- Go to `Webhooks` page under `Settings`
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
- Go to `Webhooks` page under `Settings`
- Go to `Settings > Webhooks` page.

Nitpick

- Click `Add Endpoint` to create a new endpoint
- In the URL field, paste your `ngrok` forwarding address with `/payments-webhook` appended (for example: `https://abc123.ngrok-free.app/payments-webhook`).
- Set the `Format` to `"Raw"`
- Select the following events to listen for:
- `order.paid`
- `subscription.updated`
- Click `Save`
- Copy the generated webhook secret and add it to your `.env.server` file:

```ini title=".env.server"
POLAR_WEBHOOK_SECRET=polar_whs_...
```

### Testing Payments via the Local Application
Copy link
Member

Choose a reason for hiding this comment

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

We are missing instructions for POLAR_ORGANIZATION_ID - we mention it in .env.server.example but I bet some people will miss it there.


Make sure that your **`ngrok` tunnel is running** and that the webhook is configured as described above.

You can then test the payment flow:

- Click a Buy button for any product on the homepage
- You should be redirected to Polar's checkout page
- Fill in the checkout form with [test payment information](https://docs.polar.sh/integrate/sandbox#testing-payments)
- Complete the payment
- You should be redirected back to your success page

Check the Polar dashboard for webhook event logs and verify the user's subscription status in your database:

<Image src={polarWebhookLogs} alt="How to check webhook logs in Polar dashboard" loading="lazy" />

```sh
wasp db studio
```
Comment on lines +440 to +442
Copy link
Member

Choose a reason for hiding this comment

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

This block just appears without any introduction e.g. check your DB by running...


Navigate to `localhost:5555` and check the `User` table to confirm the `subscriptionStatus` is `active` for the user who made the purchase.

<Image src={polarUserTable} alt="User table showing updated user" loading="lazy" />

:::note[Polar Test Cards]
Polar uses Stripe's test card numbers for development. Check their [testing documentation](https://docs.stripe.com/testing#cards) for further information.
:::

## Deploying

Once you deploy your app, you can follow the same steps, just make sure that you are no longer in test mode within the Stripe or Lemon Squeezy Dashboards. After you've repeated the steps in live mode, add the new API keys and price/variant IDs to your environment variables in your deployed environment.
Once you deploy your app, you can follow the same steps, just make sure that you are no longer in test/sandbox mode within the Stripe, Lemon Squeezy, or Polar dashboards. After you've repeated the steps in live mode, add the new API keys and price/variant IDs to your environment variables in your deployed environment.
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
Once you deploy your app, you can follow the same steps, just make sure that you are no longer in test/sandbox mode within the Stripe, Lemon Squeezy, or Polar dashboards. After you've repeated the steps in live mode, add the new API keys and price/variant IDs to your environment variables in your deployed environment.
Once you deploy your app, you can follow the same steps, just make sure that you are no longer in test/sandbox mode within the payment processor dashboard. After you've repeated the steps in live mode, add the new API keys and price/variant IDs to your environment variables in your deployed environment.

Makes it more maintainable for the future

12 changes: 6 additions & 6 deletions opensaas-sh/blog/src/content/docs/start/guided-tour.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,19 +186,19 @@ For development purposes, Wasp provides a `Dummy` email sender which Open SaaS c

We will explain more about these auth methods, and how to properly integrate them into your app, in the [Authentication Guide](/guides/authentication/).

### Subscription Payments with Stripe or Lemon Squeezy
### Subscription Payments with Stripe, Lemon Squeezy or Polar

No SaaS is complete without payments, specifically subscription payments. That's why this template comes with a fully functional Stripe or Lemon Squeezy integration.
No SaaS is complete without payments, specifically subscription payments. That's why this template comes with a fully functional Stripe, Lemon Squeezy or Polar integration.
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
No SaaS is complete without payments, specifically subscription payments. That's why this template comes with a fully functional Stripe, Lemon Squeezy or Polar integration.
No SaaS is complete without payments, specifically subscription payments. That's why this template comes with a fully functional Stripe, Lemon Squeezy and Polar integration.

They are all included by default.


Let's take a quick look at how payments are handled in this template.

1. a user clicks the `BUY` button and a **Checkout session** is created on the server
2. the user is redirected to the Checkout page where they enter their payment info
3. the user is redirected back to the app and the Checkout session is completed
4. Stripe / Lemon Squeezy sends a webhook event to the server with the payment info
4. Stripe / Lemon Squeezy / Polar sends a webhook event to the server with the payment info
5. The app server's **webhook handler** handles the event and updates the user's subscription status

The payment processor you choose (Stripe or Lemon Squeezy) and its related functions can be found at `src/payment/paymentProcessor.ts`. The `Payment Processor` object holds the logic for creating checkout sessions, webhooks, etc.
The payment processor you choose (Stripe, Lemon Squeezy or Polar) and its related functions can be found at `src/payment/paymentProcessor.ts`. The `Payment Processor` object holds the logic for creating checkout sessions, webhooks, etc.
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
The payment processor you choose (Stripe, Lemon Squeezy or Polar) and its related functions can be found at `src/payment/paymentProcessor.ts`. The `Payment Processor` object holds the logic for creating checkout sessions, webhooks, etc.
The payment processor you choose (Stripe, Lemon Squeezy or Polar) and its related functions can be found at `src/payment/paymentProcessor.ts`. The `PaymentProcessor` object holds the logic for creating checkout sessions, webhooks, etc.

Since PaymentProcessor is the actual type, it might be better to write it without space.


The logic for creating the Checkout session is defined in the `src/payment/operation.ts` file. [Actions](https://wasp.sh/docs/data-model/operations/actions) are a type of Wasp Operation, specifically your server-side functions that are used to **write** or **update** data to the database. Once they're defined in the `main.wasp` file, you can easily call them on the client-side:

Expand Down Expand Up @@ -226,7 +226,7 @@ const handleBuyClick = async (paymentPlanId) => {
};
```

The webhook handler is defined in the `src/payment/webhook.ts` file. Unlike Actions and Queries in Wasp which are only to be used internally, we define the webhook handler in the `main.wasp` file as an API endpoint in order to expose it externally to Stripe
The webhook handler is defined in the `src/payment/webhook.ts` file. Unlike Actions and Queries in Wasp which are only to be used internally, we define the webhook handler in the `main.wasp` file as an API endpoint in order to expose it externally to the payment processor.

```js title="main.wasp"
api paymentsWebhook {
Expand Down Expand Up @@ -277,7 +277,7 @@ For more info on integrating Plausible or Google Analytics, check out the [Analy
When you first start your Open SaaS app straight from the template, it will run, but many of the services won't work because they lack your own API keys. Here are list of services that need your API keys to work properly:

- Auth Methods (Google, GitHub)
- Stripe or Lemon Squeezy
- Stripe, Lemon Squeezy or Polar
- OpenAI (Chat GPT API)
- Email Sending (Sendgrid) -- you must set this up if you're using the `email` Auth method
- Analytics (Plausible or Google Analytics)
Expand Down
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
Copy link
Member

Choose a reason for hiding this comment

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

We are missing Polar instructions here.

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: 28 additions & 3 deletions template/app/src/analytics/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@ import {
getSources,
} from "./providers/plausibleAnalyticsUtils";
// import { getDailyPageViews, getSources } from './providers/googleAnalyticsUtils';
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;
Expand Down Expand Up @@ -60,10 +63,11 @@ export const calculateDailyStats: DailyStatsJob<never, void> = async (
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 @@ -211,3 +215,24 @@ async function fetchTotalLemonSqueezyRevenue() {
throw error;
}
}

async function fetchTotalPolarRevenue(): Promise<number> {
Copy link
Member

Choose a reason for hiding this comment

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

Can we create an issue to maybe move the stats bit next to each payment provider e.g.

  • src/payment/polar/stats.ts
  • src/payment/stripe/stats.ts
  • src/payment/lemonSqueezy/stats.ts

Copy link
Member

Choose a reason for hiding this comment

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

All the stats code being in the same file made it annoying to delete all the Stripe and LemonSqueezy stuff from this file

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) {
Copy link
Member

Choose a reason for hiding this comment

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

I'd maybe break this fn into two maybe, it feels very low level right now:

async function getAllPolarOrders(): Promise<Order[]> {
  const result = await polarClient.orders.list({
    limit: 100,
  });

  const pages = [];
  for await (const page of result) {
    pages.push(page);
  }

  return pages.flatMap(page => page.result.items || []);
}

function sumPaidOrderRevenue(orders: Order[]): number {
  const totalRevenue = orders
    .filter(order => order.status === OrderStatus.Paid && order.totalAmount > 0)
    .map(order => order.totalAmount)
    .reduce((sum, amount) => sum + amount, 0);

  return totalRevenue / 100;
}

async function fetchTotalPolarRevenue(): Promise<number> {
  const orders = await getAllPolarOrders();
  return sumPaidOrderRevenue(orders);
}

This all makes more sense if it lives in a separate file as I mentioned above, now it will overcrowd the file. I'm not sure if it makes sense to do it now. Your call.

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

// Revenue is in cents so we convert to dollars
return totalRevenue / 100;
}
6 changes: 3 additions & 3 deletions template/app/src/payment/PricingPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,9 @@ const PricingPage = () => {
</h2>
</div>
<p className="text-muted-foreground mx-auto mt-6 max-w-2xl text-center text-lg leading-8">
Choose between Stripe and LemonSqueezy as your payment provider. Just
add your Product IDs! Try it out below with test credit card number{" "}
<br />
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="bg-muted text-muted-foreground rounded-md px-2 py-1 font-mono text-sm">
4242 4242 4242 4242 4242
</span>
Expand Down
3 changes: 2 additions & 1 deletion template/app/src/payment/paymentProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export interface FetchCustomerPortalUrlArgs {
}

export interface PaymentProcessor {
id: "stripe" | "lemonsqueezy";
id: "stripe" | "lemonsqueezy" | "polar";
createCheckoutSession: (
args: CreateCheckoutSessionArgs,
) => Promise<{ session: { id: string; url: string } }>;
Expand All @@ -32,4 +32,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;
Loading