Skip to content
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

Usage billing support for overuse #278

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
"resend": "^3.2.0",
"robots-parser": "^3.0.1",
"scrapingbee": "^1.7.4",
"stripe": "^12.2.0",
"stripe": "^15.11.0",
"turndown": "^7.1.3",
"turndown-plugin-gfm": "^1.0.2",
"typesense": "^1.5.4",
Expand Down
8 changes: 4 additions & 4 deletions apps/api/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 33 additions & 0 deletions apps/api/src/services/billing/credit_billing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,26 @@ const FREE_CREDITS = 500;
export async function billTeam(team_id: string, credits: number) {
return withAuth(supaBillTeam)(team_id, credits);
}
// Initialize Stripe with your API key
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);


async function trackUsage(customer_id: string, quantity: number): Promise<void> {
try {
await stripe.billing.meterEvents.create({
event_name: 'credits',
payload: {
value: quantity.toString(),
stripe_customer_id: customer_id,
},
});
} catch (error) {
console.error('Error creating usage record:', error);
// throw new Error('Error creating usage record');
}
}


export async function supaBillTeam(team_id: string, credits: number) {
if (team_id === "preview") {
return { success: true, message: "Preview team, no credits used" };
Expand Down Expand Up @@ -153,6 +173,19 @@ export async function supaBillTeam(team_id: string, credits: number) {
return await createCreditUsage({ team_id, credits });
}

if(subscription.is_usage){
// console.log('subscription', subscription);
const { data: customer } = await supabase_service
.from("customers")
.select("*")
.eq("id", subscription.user_id)
.single();

if (customer) {
await trackUsage(customer.stripe_customer_id, credits);
}
}

return await createCreditUsage({
team_id,
subscription_id: subscription.id,
Expand Down
Loading