-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
19 changed files
with
500 additions
and
9 deletions.
There are no files selected for viewing
This file contains 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 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 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,21 @@ | ||
FROM node:alpine as builder | ||
WORKDIR /app | ||
COPY --chown=node:node package.json yarn.lock ./ | ||
RUN yarn install --frozen-lockfile | ||
COPY --chown=node:node . . | ||
RUN yarn build | ||
|
||
|
||
# Dev stage | ||
FROM builder as dev | ||
WORKDIR /app | ||
EXPOSE 3000 | ||
CMD ["yarn", "dev:billing"] | ||
|
||
|
||
# Prod stage | ||
FROM node:alpine as prod | ||
WORKDIR /app | ||
COPY --from=builder /app/node_modules ./dist/node_modules | ||
COPY --from=builder /app/dist/src ./dist/src | ||
CMD ["node", "dist/src/services/billing/server.js"] |
This file contains 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 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 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,14 @@ | ||
export const isProd = process.env.NODE_ENV === 'production' | ||
|
||
export const getConfig = () => { | ||
const commonConfig = { | ||
checkoutSuccessURL: process.env.CHECKOUT_SUCCESS_URL, | ||
checkoutCancelURL: process.env.CHECKOUT_CANCEL_URL | ||
} | ||
|
||
return isProd ? { | ||
...commonConfig | ||
} : { | ||
...commonConfig | ||
} | ||
} |
This file contains 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 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,3 @@ | ||
export type UserSettings = Partial<{ | ||
plan: string | ||
}> |
This file contains 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 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,54 @@ | ||
import Stripe from 'stripe' | ||
import { StripeProduct } from './stripeTypes' | ||
import { MissingData, StripePriceDoesNotExist, StripeProductDoesNotExist } from '../../../../exceptions/exceptions' | ||
import { getConfig } from '../../../../config' | ||
|
||
const stripeClient = new Stripe(process.env.STRIPE_SECRET_KEY, { | ||
apiVersion: '2022-11-15' | ||
}) | ||
|
||
export const createCheckoutSession = async (priceId: string, userId: string, userEmail: string, isUpdate = false) => { | ||
const price = await getPrice(priceId) | ||
if (!price) { | ||
throw new StripePriceDoesNotExist(priceId) | ||
} | ||
const product = await getProduct(price.product as string) | ||
if (!product) { | ||
throw new StripeProductDoesNotExist(price.product as string) | ||
} | ||
|
||
if (!product?.metadata?.plan) { | ||
throw new MissingData('plan', `Price ${priceId} metadata`) | ||
} | ||
const session = await stripeClient.checkout.sessions.create({ | ||
customer_email: userEmail, | ||
metadata: { | ||
userId, | ||
userEmail, | ||
plan: product.metadata?.plan | ||
}, | ||
mode: 'subscription', | ||
line_items: [ | ||
{ | ||
price: priceId, | ||
quantity: 1 | ||
} | ||
], | ||
success_url: `${getConfig().checkoutSuccessURL}${isUpdate ? '?fromSettings=true' : ''}`, | ||
cancel_url: `${getConfig().checkoutCancelURL}${isUpdate ? '?fromSettings=true' : ''}`, | ||
}) | ||
|
||
return session | ||
} | ||
|
||
export const constructEvent = (event, signature, secret) => { | ||
return stripeClient.webhooks.constructEvent(event, signature, secret) | ||
} | ||
|
||
export const getPrice = async (priceId: string): Promise<Stripe.Price> => { | ||
return await stripeClient.prices.retrieve(priceId) | ||
} | ||
|
||
export const getProduct = async (productId: string): Promise<StripeProduct> => { | ||
return await stripeClient.products.retrieve(productId) | ||
} |
This file contains 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,132 @@ | ||
import Stripe from "stripe"; | ||
|
||
export type StripeCheckoutSessionCompleted = { | ||
id: string; | ||
object: string; | ||
api_version: string; | ||
created: number; | ||
data: Data; | ||
livemode: boolean; | ||
pending_webhooks: number; | ||
request: Request; | ||
type: string; | ||
} | ||
|
||
type Request = { | ||
id?: any; | ||
idempotency_key?: any; | ||
} | ||
|
||
type Data = { | ||
object: Object; | ||
} | ||
|
||
type Object = { | ||
id: string; | ||
object: string; | ||
after_expiration?: any; | ||
allow_promotion_codes?: any; | ||
amount_subtotal: number; | ||
amount_total: number; | ||
automatic_tax: Automatictax; | ||
billing_address_collection?: any; | ||
cancel_url: string; | ||
client_reference_id?: any; | ||
consent?: any; | ||
consent_collection?: any; | ||
created: number; | ||
currency: string; | ||
currency_conversion?: any; | ||
custom_fields: any[]; | ||
custom_text: Customtext; | ||
customer?: any; | ||
customer_creation: string; | ||
customer_details: Customerdetails; | ||
customer_email?: any; | ||
expires_at: number; | ||
invoice?: any; | ||
invoice_creation: Invoicecreation; | ||
livemode: boolean; | ||
locale?: any; | ||
metadata: Metadata; | ||
mode: string; | ||
payment_intent: string; | ||
payment_link?: any; | ||
payment_method_collection: string; | ||
payment_method_options: Metadata; | ||
payment_method_types: string[]; | ||
payment_status: string; | ||
phone_number_collection: Phonenumbercollection; | ||
recovered_from?: any; | ||
setup_intent?: any; | ||
shipping_address_collection?: any; | ||
shipping_cost?: any; | ||
shipping_details?: any; | ||
shipping_options: any[]; | ||
status: string; | ||
submit_type?: any; | ||
subscription?: any; | ||
success_url: string; | ||
total_details: Totaldetails; | ||
url?: any; | ||
} | ||
|
||
type Totaldetails = { | ||
amount_discount: number; | ||
amount_shipping: number; | ||
amount_tax: number; | ||
} | ||
|
||
type Phonenumbercollection = { | ||
enabled: boolean; | ||
} | ||
|
||
type Invoicecreation = { | ||
enabled: boolean; | ||
invoice_data: Invoicedata; | ||
} | ||
|
||
type Invoicedata = { | ||
account_tax_ids?: any; | ||
custom_fields?: any; | ||
description?: any; | ||
footer?: any; | ||
metadata: Metadata; | ||
rendering_options?: any; | ||
} | ||
|
||
type Metadata = Record<string, any> | ||
|
||
type Customerdetails = { | ||
address: Address; | ||
email: string; | ||
name?: any; | ||
phone?: any; | ||
tax_exempt: string; | ||
tax_ids: any[]; | ||
} | ||
|
||
type Address = { | ||
city?: any; | ||
country?: any; | ||
line1?: any; | ||
line2?: any; | ||
postal_code?: any; | ||
state?: any; | ||
} | ||
|
||
type Customtext = { | ||
shipping_address?: any; | ||
submit?: any; | ||
} | ||
|
||
type Automatictax = { | ||
enabled: boolean; | ||
status?: any; | ||
} | ||
|
||
export type StripeProduct = Stripe.Product & { | ||
metadata: { | ||
plan?: string | ||
} | ||
} |
This file contains 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,52 @@ | ||
import { UserDoesNotExist } from '../../exceptions/exceptions' | ||
import { User } from '../../models/user' | ||
import { getUserById, getUserSettings, updateUserSettings } from '../../storage/user.storage' | ||
import * as billing from './DAL/stripe/stripe' | ||
import { StripeCheckoutSessionCompleted } from './DAL/stripe/stripeTypes' | ||
|
||
export const createCheckoutSession = async (priceId: string, user: User, isUpdate = false) => { | ||
const session = await billing.createCheckoutSession(priceId, user.id, user.email, isUpdate) | ||
return session | ||
} | ||
|
||
export const buildWebhookEvent = (event, signature, secret) => { | ||
return billing.constructEvent(event, signature, secret) | ||
} | ||
|
||
export const handleEvent = (eventType: string, data: any) => { | ||
const handlers = { | ||
'checkout.session.completed': handleCheckoutSession, | ||
} | ||
|
||
const handler = handlers[eventType] | ||
if (handler) { | ||
handler(data) | ||
} | ||
|
||
} | ||
|
||
const handleCheckoutSession = async (data: StripeCheckoutSessionCompleted['data']) => { | ||
const { userId, plan } = data.object.metadata | ||
if (!userId) { | ||
console.error('Missing userId in billing hook event') | ||
return | ||
} | ||
if (!plan) { | ||
console.error('Missing plan in billing hook event') | ||
return | ||
} | ||
|
||
const user = await getUserById(userId) | ||
if (!user) { | ||
throw new UserDoesNotExist() | ||
} | ||
console.log(`[BILLING][CHECKOUT][NEW SUB] User ${user.email} subscribed to plan ${plan}`) | ||
const userSettings = await getUserSettings(userId) || {} | ||
|
||
if (userSettings.plan !== plan) { | ||
// Only trigger an update if the plan has changed | ||
console.log(`[BILLING][CHECKOUT][NEW SUB] Updating settings of user ${user.email}...`) | ||
await updateUserSettings(userId, { ...userSettings, plan }) | ||
console.log(`[BILLING][CHECKOUT][NEW SUB] Updated settings of user ${user.email}`) | ||
} | ||
} |
Oops, something went wrong.