v1.3.27-e: Add workaround for credit-balance-summary

This commit is contained in:
Yudi Xiao 2025-10-14 18:52:56 +08:00
parent dc3f382cf6
commit b962eec96c
2 changed files with 31 additions and 3 deletions

View File

@ -1,7 +1,7 @@
{ {
"name": "@bowong/better-auth-stripe", "name": "@bowong/better-auth-stripe",
"author": "Bowong", "author": "Bowong",
"version": "1.3.27-d", "version": "1.3.27-e",
"main": "dist/index.cjs", "main": "dist/index.cjs",
"license": "MIT", "license": "MIT",
"keywords": [ "keywords": [

View File

@ -1408,6 +1408,7 @@ export const stripe = <O extends StripeOptions>(options: O) => {
{ {
method: "GET", method: "GET",
query: z.object({ query: z.object({
subscriptionId: z.string().meta({}),
filter: z.object({ filter: z.object({
type: z.enum(['credit_grant', 'applicability_scope']), type: z.enum(['credit_grant', 'applicability_scope']),
applicability_scope: z.object({ applicability_scope: z.object({
@ -1430,6 +1431,7 @@ export const stripe = <O extends StripeOptions>(options: O) => {
async (ctx) => { async (ctx) => {
const {user} = ctx.context.session; const {user} = ctx.context.session;
let customerId = user.stripeCustomerId; let customerId = user.stripeCustomerId;
let subscriptionId = ctx.query.subscriptionId;
const referenceId = ctx.body.referenceId || user.id; const referenceId = ctx.body.referenceId || user.id;
if (!customerId) { if (!customerId) {
@ -1459,14 +1461,40 @@ export const stripe = <O extends StripeOptions>(options: O) => {
} }
try { try {
const result = await client.billing.creditBalanceSummary.retrieve( // todo : stripe credit balance summary api not working yet, apply workaround
const creditBalance = await client.billing.creditBalanceSummary.retrieve(
{ {
...ctx.query, ...ctx.query,
customer: customerId customer: customerId
} }
); );
const upcomingInvoice = await client.invoices.createPreview({
subscription: subscriptionId
})
// const usageProductLineItem = upcomingInvoice.lines.data
// const usageProductLineItem = upcomingInvoice.lines.data.find(
// (line) =>
// line.pricing?.price_details?.product === price.data[0]?.product
// );
const subItemId = upcomingInvoice.lines.data[0]?.parent?.subscription_item_details?.subscription_item
return ctx.json(result); let perTokenPrice = 1
if (subItemId !== undefined) {
const subItem = await client.subscriptionItems.retrieve(subItemId)
perTokenPrice = subItem.price.unit_amount || 1
}
const usage = upcomingInvoice.subtotal
const currentCreditBalance = creditBalance.balances[0]?.available_balance.monetary?.value || 1000
const tokenBalance = currentCreditBalance / perTokenPrice
const remainingTokenBalance = tokenBalance - usage
return ctx.json({
tokenUsage: usage,
tokenBalance,
remainingTokenBalance,
currentCreditBalance
})
} catch (error: any) { } catch (error: any) {
ctx.context.logger.error( ctx.context.logger.error(
"Error submitting meter event", "Error submitting meter event",