-
-
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
64
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.
+687
−5
Draft
Polar integration #461
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 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 ee820b3
refactor: rename method parameters
Genyus 4b1ce80
refactor: refactor webhook handling
Genyus cbf0e62
refactor: refactor user update function
Genyus 064abc1
refactor: refactor Polar client logic
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 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> { | ||
Genyus marked this conversation as resolved.
Show resolved
Hide resolved
Genyus marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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,87 @@ | ||
// @ts-ignore | ||
import { OrderStatus } from '@polar-sh/sdk/models/components/orderstatus.js'; | ||
Genyus marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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'); | ||
Genyus marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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]; | ||
} |
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,17 @@ | ||
import { Polar } from '@polar-sh/sdk'; | ||
import { requireNodeEnvVar } from '../../server/utils'; | ||
|
||
function shouldUseSandboxMode(): boolean { | ||
const explicitSandboxMode = process.env.POLAR_SANDBOX_MODE; | ||
Genyus marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
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', | ||
}); |
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.
Uh oh!
There was an error while loading. Please reload this page.