-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
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
26 changed files
with
1,910 additions
and
1,513 deletions.
There are no files selected for viewing
7 changes: 7 additions & 0 deletions
7
packages/backend/server/migrations/20241125035804_opt_user_invoices/migration.sql
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,7 @@ | ||
-- AlterTable | ||
ALTER TABLE "user_invoices" ALTER COLUMN "plan" DROP NOT NULL, | ||
ALTER COLUMN "recurring" DROP NOT NULL, | ||
ALTER COLUMN "reason" DROP NOT NULL; | ||
|
||
-- CreateIndex | ||
CREATE INDEX "user_invoices_user_id_idx" ON "user_invoices"("user_id"); |
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 |
---|---|---|
@@ -1,3 +1,3 @@ | ||
# Please do not edit this file manually | ||
# It should be added in your version-control system (i.e. Git) | ||
provider = "postgresql" | ||
provider = "postgresql" |
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,52 @@ | ||
import assert from 'node:assert'; | ||
|
||
import type { RawBodyRequest } from '@nestjs/common'; | ||
import { Controller, Logger, Post, Req } from '@nestjs/common'; | ||
import { EventEmitter2 } from '@nestjs/event-emitter'; | ||
import type { Request } from 'express'; | ||
import Stripe from 'stripe'; | ||
|
||
import { Public } from '../../core/auth'; | ||
import { Config, InternalServerError } from '../../fundamentals'; | ||
|
||
@Controller('/api/stripe') | ||
export class StripeWebhookController { | ||
private readonly webhookKey: string; | ||
private readonly logger = new Logger(StripeWebhookController.name); | ||
|
||
constructor( | ||
config: Config, | ||
private readonly stripe: Stripe, | ||
private readonly event: EventEmitter2 | ||
) { | ||
assert(config.plugins.payment.stripe); | ||
this.webhookKey = config.plugins.payment.stripe.keys.webhookKey; | ||
} | ||
|
||
@Public() | ||
@Post('/webhook') | ||
async handleWebhook(@Req() req: RawBodyRequest<Request>) { | ||
// Retrieve the event by verifying the signature using the raw body and secret. | ||
const signature = req.headers['stripe-signature']; | ||
try { | ||
const event = this.stripe.webhooks.constructEvent( | ||
req.rawBody ?? '', | ||
signature ?? '', | ||
this.webhookKey | ||
); | ||
|
||
this.logger.debug( | ||
`[${event.id}] Stripe Webhook {${event.type}} received.` | ||
); | ||
|
||
// Stripe requires responseing webhook immediately and handle event asynchronously. | ||
setImmediate(() => { | ||
this.event.emitAsync(`stripe:${event.type}`, event).catch(e => { | ||
this.logger.error('Failed to handle Stripe Webhook event.', e); | ||
}); | ||
}); | ||
} catch (err: any) { | ||
throw new InternalServerError(err.message); | ||
} | ||
} | ||
} |
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 { Injectable } from '@nestjs/common'; | ||
import { OnEvent } from '@nestjs/event-emitter'; | ||
import { Cron, CronExpression } from '@nestjs/schedule'; | ||
import { PrismaClient } from '@prisma/client'; | ||
|
||
import { EventEmitter, type EventPayload } from '../../fundamentals'; | ||
import { | ||
SubscriptionPlan, | ||
SubscriptionRecurring, | ||
SubscriptionVariant, | ||
} from './types'; | ||
|
||
@Injectable() | ||
export class SubscriptionCronJobs { | ||
constructor( | ||
private readonly db: PrismaClient, | ||
private readonly event: EventEmitter | ||
) {} | ||
|
||
@Cron(CronExpression.EVERY_HOUR) | ||
async cleanExpiredOnetimeSubscriptions() { | ||
const subscriptions = await this.db.userSubscription.findMany({ | ||
where: { | ||
variant: SubscriptionVariant.Onetime, | ||
end: { | ||
lte: new Date(), | ||
}, | ||
}, | ||
}); | ||
|
||
for (const subscription of subscriptions) { | ||
this.event.emit('user.subscription.canceled', { | ||
userId: subscription.userId, | ||
plan: subscription.plan as SubscriptionPlan, | ||
recurring: subscription.variant as SubscriptionRecurring, | ||
}); | ||
} | ||
} | ||
|
||
@OnEvent('user.subscription.canceled') | ||
async handleUserSubscriptionCanceled({ | ||
userId, | ||
plan, | ||
}: EventPayload<'user.subscription.canceled'>) { | ||
await this.db.userSubscription.delete({ | ||
where: { | ||
userId_plan: { | ||
userId, | ||
plan, | ||
}, | ||
}, | ||
}); | ||
} | ||
} |
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
56 changes: 56 additions & 0 deletions
56
packages/backend/server/src/plugins/payment/manager/common.ts
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,56 @@ | ||
import { UserStripeCustomer } from '@prisma/client'; | ||
|
||
import { | ||
KnownStripePrice, | ||
KnownStripeSubscription, | ||
SubscriptionPlan, | ||
SubscriptionRecurring, | ||
} from '../types'; | ||
|
||
export interface Subscription { | ||
status: string; | ||
plan: string; | ||
recurring: string; | ||
variant: string | null; | ||
start: Date; | ||
end: Date | null; | ||
trialStart: Date | null; | ||
trialEnd: Date | null; | ||
nextBillAt: Date | null; | ||
canceledAt: Date | null; | ||
} | ||
|
||
export interface Invoice { | ||
currency: string; | ||
amount: number; | ||
status: string; | ||
createdAt: Date; | ||
lastPaymentError: string | null; | ||
link: string | null; | ||
} | ||
|
||
export interface SubscriptionManager { | ||
filterPrices( | ||
prices: KnownStripePrice[], | ||
customer?: UserStripeCustomer | ||
): Promise<KnownStripePrice[]>; | ||
|
||
saveSubscription( | ||
subscription: KnownStripeSubscription | ||
): Promise<Subscription>; | ||
deleteSubscription(subscription: KnownStripeSubscription): Promise<void>; | ||
|
||
getSubscription( | ||
id: string, | ||
plan: SubscriptionPlan | ||
): Promise<Subscription | null>; | ||
|
||
cancelSubscription(subscription: Subscription): Promise<Subscription>; | ||
|
||
resumeSubscription(subscription: Subscription): Promise<Subscription>; | ||
|
||
updateSubscriptionRecurring( | ||
subscription: Subscription, | ||
recurring: SubscriptionRecurring | ||
): Promise<Subscription>; | ||
} |
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,2 @@ | ||
export * from './common'; | ||
export * from './user'; |
Oops, something went wrong.