v1.3.27-e: Add workaround for credit-balance-summary
This commit is contained in:
parent
dc3f382cf6
commit
b962eec96c
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "@bowong/better-auth-stripe",
|
||||
"author": "Bowong",
|
||||
"version": "1.3.27-d",
|
||||
"version": "1.3.27-e",
|
||||
"main": "dist/index.cjs",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
|
|
|
|||
32
src/index.ts
32
src/index.ts
|
|
@ -1408,6 +1408,7 @@ export const stripe = <O extends StripeOptions>(options: O) => {
|
|||
{
|
||||
method: "GET",
|
||||
query: z.object({
|
||||
subscriptionId: z.string().meta({}),
|
||||
filter: z.object({
|
||||
type: z.enum(['credit_grant', 'applicability_scope']),
|
||||
applicability_scope: z.object({
|
||||
|
|
@ -1430,6 +1431,7 @@ export const stripe = <O extends StripeOptions>(options: O) => {
|
|||
async (ctx) => {
|
||||
const {user} = ctx.context.session;
|
||||
let customerId = user.stripeCustomerId;
|
||||
let subscriptionId = ctx.query.subscriptionId;
|
||||
const referenceId = ctx.body.referenceId || user.id;
|
||||
|
||||
if (!customerId) {
|
||||
|
|
@ -1459,14 +1461,40 @@ export const stripe = <O extends StripeOptions>(options: O) => {
|
|||
}
|
||||
|
||||
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,
|
||||
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) {
|
||||
ctx.context.logger.error(
|
||||
"Error submitting meter event",
|
||||
|
|
|
|||
Loading…
Reference in New Issue