-
-
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
Draft
Genyus
wants to merge
60
commits into
wasp-lang:main
Choose a base branch
from
Genyus:polar
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Polar integration #461
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 61f5e73
refactor: move revenue calculation to processors
Genyus d3f3ed6
docs: improve comments
Genyus 51d05ca
fix: update imports after previous refactoring
Genyus f07fa91
refactor: convert processor IDs to enum values
Genyus 2b42cc6
feat: add validation of server env vars
Genyus a0276a3
feat: add initial Polar integration
Genyus 0ebd0a3
feat: implement total revenue calculation
Genyus e84670d
feat: implement customer portal URL retrieval
Genyus 54292a7
feat: implement checkout session creation
Genyus 156823c
feat: implement webhook handling
Genyus 2841121
feat: add dynamic payment processor selection
Genyus 825eb66
fix: implement webhook handling
Genyus 6ad783b
chore: rename file for consistency
Genyus a97b79f
Merge branch 'main' into polar
Genyus eb68932
fix: address typing errors
Genyus fca11f9
fix: resolve type assignment error
Genyus c71f29a
refactor: streamline payment processor integration
Genyus 732b9ed
style: remove redundant JSDoc comments
Genyus 2410e01
refactor: simplify error handling
Genyus f65cc67
refactor: fix customer portal implementation
Genyus df213c9
chore: update webhook response status codes
Genyus 5f71cac
refactor: remove iteration for single customer lookup
Genyus 882df67
refactor: simplify webhook error handling
Genyus 7d0eb4e
refactor: rename polar client
Genyus 3639c0d
refactor: refactor client configuration
Genyus 2f5748c
refactor: remove standalone client config file
Genyus e5a63de
style: remove extraneous JSDoc comments
Genyus fda6a57
refactor: remove standalone type declarations file
Genyus add2038
docs: remove unnecessary README
Genyus 254aae4
refactor: remodel webhook to align with current integrations
Genyus 780d24c
fix: resolves issues found in testing
Genyus 568c38b
chore: mention Polar as an available payment platform
Genyus 721fd6f
chore: remove env validation
Genyus 31ad46c
chore: remove redundant guard
Genyus f5892aa
chore: remove unsupported event type
Genyus 32c8934
fix: update order completion handler
Genyus 2b3195c
fix: throw error when credits can't be parsed from order
Genyus 2a64914
revert: revert deletion of validation.ts
Genyus 9658034
Merge pull request #1 from wasp-lang/main
Genyus 033bdfe
chore: rename file for consistency
Genyus dbcfa08
style: reorder imports
Genyus e81b2db
fix: correct webhook event support
Genyus 20e95f8
refactor: simplify webhook handlers
Genyus f31f176
style: restore missing line break
Genyus 3003595
chore: add gitignore rules
Genyus 6cce3fe
refactor: restore centralised payment stats
Genyus ce97f73
revert: restore original payment processor files
Genyus 27b8ea7
revert: restore paymentProcessor comments
Genyus 6471324
refactor: improve switch condition checking
Genyus 1b72606
refactor: remove unused code
Genyus b0eaf88
refactor: rename function
Genyus 3defeb9
refactor: simplify user updating
Genyus 2741ea2
refactor: simplify webhook handling
Genyus 543fa92
fix: remove default portal URL
Genyus ee65871
fix: improve type-safety
Genyus 31a3b0b
fix: restore available processors
Genyus 42cbf32
docs: remove JSDoc comment
Genyus adde113
refactor: remove redundant file
Genyus 29ec825
refactor: streamline session management
Genyus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
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; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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', | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ( | ||
Genyus marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
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, | ||
}, | ||
}); | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Ah now I see why
ensurePolarCustomer
was exported.Why do we
ensurePolarCustomer
here?ensurePolarCustomer
returnscustomer.id
which is also required inpolarPaymentProcessor.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
andexternalCustomerId
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 useexternalCustomerId
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?
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.
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.
polarPaymentProcessor.createCheckoutSession
accepts the Wasp user ID as a parameter, not the Polar customer ID, which is what this method returns.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.Uh oh!
There was an error while loading. Please reload this page.
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.
Inside of
polarPaymentProcessor.createCheckoutSession
we usecreatePolarCheckoutSession
which usesensurePolarCustomer
.That means on checkout we create a Polar customer.
We also connect it to our user via
prismaUserDelegate.update
where we update thepaymentProcessorUserId
.Checkout also doesn't mean the customer will make a purchase.
What I meant why not do:
This way we reduce the size input and output to
createPolarCheckoutSession
. Which did unnecessary work inside of it.That is how it should be.
One should use different database between sandbox and production.
This is okay.
We shouldn't handle that.
The different environment should be used with a different database.
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.
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.
Ok, understood