百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
U

usage_credits

> 后端框架
开源

✨ 为您的 Rails 应用程序添加基于使用的信用额度

165 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

✨ 为您的 Rails 应用程序添加基于使用的信用额度

✨ usage_credits - Add usage-based credits to your Rails app

[!TIP] ** Ship your next Rails app 10x faster!** I've built RailsFast, a production-ready Rails boilerplate template that comes with everything you need to launch a software business in days, not weeks. Go check it out!

usage_credits allows your users to have in-app credits / tokens they can use to perform operations.

✨ Perfect for SaaS, AI apps, games, API products, and marketplace wallets that want to implement usage-based pricing or track money-like balances.

Not just for credits! While the gem is called "usage_credits", it's built on a production-grade double-entry ledger with row-level locking, FIFO allocation, and full audit trails. You can use it for marketplace seller balances, in-app wallets, reward points, or any system that needs to track money-like assets with proper accounting. See the "Beyond credits" section for examples.

[ Live interactive demo website ] [ Quick video overview ]

Refill user credits with Stripe subscriptions, allow your users to top up by purchasing booster credit packs at any time, rollover unused credits to the next billing period, expire credits, implement PAYG (pay-as-you-go) billing, award free credits as bonuses (for referrals, giving feedback, etc.), get a detailed history and audit trail of every transaction for billing / reporting, and more!

All with a simple DSL that reads just like English.

Requirements

  • An ActiveJob backend (Sidekiq, solid_queue, etc.) for subscription credit fulfillment
  • pay gem for Stripe/PayPal/Lemon Squeezy integration (sell credits, refill subscriptions)

‍ Example

usage_credits allows you to add credits to your Rails app in just one line of code. If you have a User model, just add has_credits to it and you're ready to go:

ruby
class User
  has_credits
end

With that, your users automatically get all credits functionality, and you can start performing operations:

ruby
@user.give_credits(100)

You can check any user's balance:

ruby
@user.credits
=> 100

And spend their credits securely:

ruby
@user.spend_credits_on(:send_email) do
  # Perform the actual operation here.
  # No credits will be spent if this block fails.
end

Defining credit-spending operations is as simple as:

ruby
operation :send_email do
  costs 1.credit
end

And defining credit-fulfilling subscriptions is really simple too:

ruby
subscription_plan :pro do
  gives 1_000.credits.every :month
  unused_credits :rollover # or :expire
end

This gem keeps track of every transaction and its cost + origin, so you can keep a clean audit trail for clear invoicing and reference / auditing purposes:

ruby
@user.credit_history.pluck(:category, :amount)
=> [["signup_bonus", 100], ["operation_charge", -1]]

Each transaction stores comprehensive metadata about the action that was performed:

ruby
@user.credit_history.last.metadata
=> {"operation"=>"send_email", "cost"=>1, "params"=>{}, "metadata"=>{}, "executed_at"=>"..."}

You can also expire credits, fulfill credits based on Stripe subscriptions, sell one-time booster credit packs, rollover/expire unused credits to the next fulfillment period, and more!

Sounds good? Let's get started!

Quick start

Add the gem to your Gemfile:

ruby
gem 'usage_credits'

Then run:

bash
bundle install
rails generate usage_credits:install
rails db:migrate

Add has_credits your user model (or any model that needs to have credits):

…

ruby operation :send_email do costs 1.credit end


You can get quite sophisticated in pricing, and define the cost of your operations based on parameters:
```ruby
operation :process_image do
  costs 10.credits + 1.credit_per(:mb)
end

[!NOTE] Credit costs must be whole numbers. Decimals are not allowed to avoid floating-point issues and ensure predictable billing.

ruby
1.credit              # ✅ Valid: whole number
10.credits            # ✅ Valid: whole number
1.credits_per(:mb)    # ✅ Valid: whole number rate

0.5.credits           # ❌ Invalid: decimal credits
1.5.credits_per(:mb)  # ❌ Invalid: decimal rate

For variable costs (like per MB), the final cost is rounded according to your configured rounding strategy (defaults to rounding up). For example, with 1.credits_per(:mb), using 2.3 MB will cost 3 credits by default, to avoid undercharging users.

Units and Rounding

For variable costs, you can specify units in different ways:

ruby
# Using megabytes
operation :process_image do
  costs 1.credits_per(:mb)  # or :megabytes, :megabyte
end

# Using units
operation :process_items do
  costs 1.credits_per(:units)  # or :unit
end

When using the operation, you can specify the size directly in the unit:

ruby
# Direct MB specification
@user.estimate_credits_to(:process_image, mb: 5)  # => 5 credits

# Or using byte size (automatically converted)
@user.estimate_credits_to(:process_image, size: 5.megabytes)  # => 5 credits

You can configure how fractional costs are rounded:

ruby
UsageCredits.configure do |config|
  # :ceil (default) - Always round up (2.1 => 3)
  # :floor - Always round down (2.9 => 2)
  # :round - Standard rounding (2.4 => 2, 2.6 => 3)
  config.rounding_strategy = :ceil
end

By default, we round up (:ceil) all credit costs to avoid undercharging. So if an operation costs 1 credit per megabyte, and the user submits a file that's 5.2 megabytes, we'll deduct 6 credits from the user's wallet.

It's also possible to add validations and metadata to your operations:

ruby
# With custom validation
operation :generate_ai_response do
  costs 5.credits
  validate ->(params) { params[:prompt].length  15 # (10 base + 5 MB * 1 credit/MB)

There's also a has_enough_credits_to? method to nicely check the user has enough credits before performing a certain operation:

ruby
if @user.has_enough_credits_to?(:process_image, size: 5.megabytes)
  # actually spend the credits
else
  redirect_to credits_path, alert: "Not enough credits!"
end

Finally, you can actually spend credits with spend_credits_on:

ruby
@user.spend_credits_on(:process_image, size: 5.megabytes)

To ensure credits are not subtracted from users during failed operations, you can pass a block to spend_credits_on. No credits are spent if the block doesn't succeed (it shouldn't raise any exceptions or throw any errors) This way, you ensure credits are only spent if the operation succeeds:

ruby
@user.spend_credits_on(:process_image, size: 5.megabytes) do
  process_image(params)  # If this raises an error, no credits are spent
end

If you want to spend the credits immediately, you can use the non-block form:

ruby
@user.spend_credits_on(:process_image, size: 5.megabytes)
process_image(params)  # If this fails, credits are already spent!

[!TIP] Always estimate and check credits before performing expensive operations. If validation fails (e.g., file too large), both methods will raise InvalidOperation. Perform your operation inside the spend_credits_on block OR make the credit spend conditional to the actual operation, so users are not charged if the operation fails.

Low balance alerts & other lifecycle callbacks

usage_credits makes it easy to add callbacks for important events.

You can hook into credit events, for example, to upsell credit packs to users when they reach a low balance:

ruby
config.on_low_balance_reached do |ctx|
  # Sell your users credits here
  # Example: LowCreditsMailer.buy_more(ctx.owner, remaining: ctx.new_balance).deliver_later
end

…

ruby
UsageCredits.configure do |config|
  # Prompt users to buy more credits when they run out
  config.on_balance_depleted do |ctx|
    # Send a mail here like "You've ran out of credits! Purchase more here!"
    OutOfCreditsMailer.buy_more(ctx.owner).deliver_later
  end

  # Log failed operations (useful for debugging)
  config.on_insufficient_credits do |ctx|
    Rails.logger.info "[Credits] User #{ctx.owner.id} needs #{ctx.amount}, has #{ctx.metadata[:available]}"
  end

  # Track purchases in your analytics (Mixpanel, Amplitude, Segment, etc.)
  config.on_credit_pack_purchased do |ctx|
    # Replace with your analytics service
    # Log something like: "User #{ctx.owner.id} purchased #{ctx.amount} credits"
  end
end

…

ruby
@user.give_credits(100, reason: "referral")

And the user will get the credits with the proper category in the transaction ledger (so bonus credits get differentiated from purchases / subscriptions for audit trail purposes)

Providing a reason for giving credits is entirely optional (it just helps you if you need to use or analyze the audit trail) – if you don't specify any reason, :manual_adjustment is the default reason.

You can also give credits with arbitrary expiration dates:

ruby
@user.give_credits(100, expires_at: 1.month.from_now)

So you can expire any batch of credits at any date in the future.

Sell credit packs

[!IMPORTANT] For all payment-related operations (sell credit packs, handle subscription-based fulfillment, etc.) this gem relies on the pay gem – make sure you have it installed and correctly configured with your payment processor (Stripe, Lemon Squeezy, PayPal, etc.) before continuing. Follow the pay README for more information and installation instructions.

In the config/initializers/usage_credits.rb file, define credit packs users can buy:

ruby
credit_pack :starter do
  gives 1000.credits
  costs 49.dollars
end

Then, you can prompt them to purchase it with our pay-based helpers:

ruby
# Create a Stripe Checkout session for purchase
credit_pack = UsageCredits.find_credit_pack(:starter)
session = credit_pack.create_checkout_session(current_user)
redirect_to session.url

The gem automatically handles:

  • Credit pack fulfillment after successful payment
  • Proportional credit removal on refunds (e.g., if 50% is refunded, 50% of credits are removed)
  • Prevention of double-processing of purchase
  • Support for multiple currencies (USD, EUR, etc.)
  • Detailed transaction tracking with metadata like:
    ruby
    {
      credit_pack: "starter",         # Credit pack identifier
      charge_id: "ch_xxx",            # Payment processor charge ID
      processor: "stripe",            # Payment processor used
      price_cents: 4900,              # Amount paid in cents
      currency: "usd",                # Currency used for payment
      credits: 1000,                  # Base credits given
      purchased_at: "2024-01-20"      # Purchase timestamp
    }

Subscription plans that grant credits

Users can subscribe to a plan (monthly, yearly, etc.) that gives them credits.

Defining a subscription plan is as simple as this:

ruby
subscription_plan :pro do
  stripe_price "price_XYZ"            # Link it to your Stripe price ID
  gives 10_000.credits.every(:month)  # Monthly credits
  signup_bonus 1_000.credits          # One-time bonus
  trial_includes 500.credits          # Trial period credits
  unused_credits :rollover            # Credits roll over to the next fulfillment period (:rollover or :expire)
  expire_after 30.days                # Optional: credits expire after cancellation
end

…

ruby
subscription_plan :pro do
  stripe_price "price_XYZ"
  # ...
end

For now, only Stripe subscriptions are supported (contribute to the codebase to help us add more payment processors!)

Subscriptions with a monthly + yearly price

For plans that offer multiple billing periods (e.g., monthly and yearly

Issues· 3 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubybillingbraintreebusinesscredit

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架