✨ 为您的 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
solid_queue, etc.) for subscription credit fulfillmentpay gem for Stripe/PayPal/Lemon Squeezy integration (sell credits, refill subscriptions)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:
class User
has_credits
endWith that, your users automatically get all credits functionality, and you can start performing operations:
@user.give_credits(100)You can check any user's balance:
@user.credits
=> 100And spend their credits securely:
@user.spend_credits_on(:send_email) do
# Perform the actual operation here.
# No credits will be spent if this block fails.
endDefining credit-spending operations is as simple as:
operation :send_email do
costs 1.credit
endAnd defining credit-fulfilling subscriptions is really simple too:
subscription_plan :pro do
gives 1_000.credits.every :month
unused_credits :rollover # or :expire
endThis 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:
@user.credit_history.pluck(:category, :amount)
=> [["signup_bonus", 100], ["operation_charge", -1]]Each transaction stores comprehensive metadata about the action that was performed:
@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!
Add the gem to your Gemfile:
gem 'usage_credits'Then run:
bundle install
rails generate usage_credits:install
rails db:migrateAdd 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.
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 rateFor 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.
For variable costs, you can specify units in different ways:
# 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
endWhen using the operation, you can specify the size directly in the unit:
# 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 creditsYou can configure how fractional costs are rounded:
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
endBy 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:
# 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:
if @user.has_enough_credits_to?(:process_image, size: 5.megabytes)
# actually spend the credits
else
redirect_to credits_path, alert: "Not enough credits!"
endFinally, you can actually spend credits with spend_credits_on:
@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:
@user.spend_credits_on(:process_image, size: 5.megabytes) do
process_image(params) # If this raises an error, no credits are spent
endIf you want to spend the credits immediately, you can use the non-block form:
@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 thespend_credits_onblock OR make the credit spend conditional to the actual operation, so users are not charged if the operation fails.
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:
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:
@user.give_credits(100, expires_at: 1.month.from_now)So you can expire any batch of credits at any date in the future.
[!IMPORTANT] For all payment-related operations (sell credit packs, handle subscription-based fulfillment, etc.) this gem relies on the
paygem – make sure you have it installed and correctly configured with your payment processor (Stripe, Lemon Squeezy, PayPal, etc.) before continuing. Follow thepayREADME for more information and installation instructions.
In the config/initializers/usage_credits.rb file, define credit packs users can buy:
credit_pack :starter do
gives 1000.credits
costs 49.dollars
endThen, you can prompt them to purchase it with our pay-based helpers:
# 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.urlThe gem automatically handles:
{
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
}Users can subscribe to a plan (monthly, yearly, etc.) that gives them credits.
Defining a subscription plan is as simple as this:
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"
# ...
endFor now, only Stripe subscriptions are supported (contribute to the codebase to help us add more payment processors!)
For plans that offer multiple billing periods (e.g., monthly and yearly
暂无开放 Issues,或尚未同步最近议题。