@visiblebase/plugin-balance
v0.1.3
Published
VisibleBase balance plugin for global user balance, ledger, and topup orders.
Maintainers
Readme
@visiblebase/plugin-balance
VisibleBase 官方全局余额插件。
这个插件只负责四件事:
- 用户全局余额
- 余额流水
- 充值单
- redeem_code
计费策略不写死在插件里。推荐在业务 hook 中直接调用插件的 read() / require() / sub() / add()。
如果你需要一次性礼品码充值,可以让 admin 创建 redeem_code,然后由用户直接兑换入账。
安装
pnpm add @visiblebase/plugin-balance使用
import { Base, AIService } from "@visiblebase/core";
import { balancePlugin } from "@visiblebase/plugin-balance";
const balance = balancePlugin({
init: 100,
unit: "credits",
});
base.use(balance);
const ai = new AIService();
ai.hook.before(async (ctx) => {
if (!ctx.user || ctx.action?.id !== "chat/completions") return;
await balance.require(ctx.user.user_id, 10);
ctx.locals.balance_amount = 10;
});
ai.hook.after(async (ctx) => {
if (!ctx.user || ctx.action?.id !== "chat/completions") return;
const amount = Number(ctx.locals.balance_amount ?? 0);
if (amount <= 0) return;
await balance.sub(ctx.user.user_id, amount, {
note: "agent chat",
meta: {
product_id: ctx.product?.product_id,
model_id: ctx.variant?.id,
},
});
});路由
GET /v1/balance/meGET /v1/balance/history/meGET /v1/balance/topups/mePOST /v1/balance/topups/createPOST /v1/balance/redeem-codes/redeemGET /v1/balance/usersGET /v1/balance/historyGET /v1/balance/topupsGET /v1/balance/redeem-codesPOST /v1/balance/addPOST /v1/balance/subPOST /v1/balance/topups/finishPOST /v1/balance/topups/cancelPOST /v1/balance/redeem-codes/createPOST /v1/balance/redeem-codes/disable
