Virtual Currencies
Read virtual-currency balances in your app and understand how granting and spending work server-side.
Virtual currencies let you define any number of named balances per subscriber — for example COINS, GEMS, or ENERGY — useful for AI generations, messages, or any metered feature. Balances are server-authoritative: the SDK caches the last-known values locally and syncs with the server automatically.
Granting virtual currency happens automatically when a user purchases a currency-pack product configured in the Rovenue dashboard, from your backend through POST /v1/virtual-currencies/:appUserId/:code/grants, or by hand from the dashboard. Spending (debiting) is a server-side operation — call POST /v1/virtual-currencies/:appUserId/:code/transactions from your backend using your secret API key — and a spend can be reversed when the work it paid for fails. There is no client-side spend method, and the secret key never ships in the app.
Types on this page
Virtual-currency balances are represented as a map of currency code to integer amount. The methods below are defined in the Methods reference.
| Method / Hook | Returns | Notes |
|---|---|---|
virtualCurrencies() | Record<string, number> | Cache read; returns {} if no balances are cached |
virtualCurrency(code) | number | Cache read; returns 0 if the code is absent |
refreshVirtualCurrencies() | void | Network call; updates the local cache |
useVirtualCurrencies() (RN) | Record<string, number> | Reactive hook; re-renders on VirtualCurrenciesChanged |
useVirtualCurrency(code) (RN) | number | Reactive hook; re-renders on VirtualCurrenciesChanged |
Swift uses virtualCurrencyBalances() -> [String: Int64] and virtualCurrency(_ code: String) -> Int64.
Kotlin uses virtualCurrencyBalances(): Map<String, Long> and virtualCurrency(code: String): Long.
Read balances
Use the reactive hooks in React Native components, or the imperative methods elsewhere.
import { Rovenue, useVirtualCurrencies, useVirtualCurrency } from '@rovenue/react-native-sdk';
// Reactive hook — re-renders automatically when any balance changes
function WalletSummary() {
const balances = useVirtualCurrencies(); // Record<string, number>
return (
<>
{Object.entries(balances).map(([code, amount]) => (
<Text key={code}>{code}: {amount}</Text>
))}
</>
);
}
// Single-currency reactive hook
function CoinsLabel() {
const coins = useVirtualCurrency('COINS'); // 0 if absent
return <Text>{coins} coins</Text>;
}
// Imperative cache reads (outside a component)
const all = Rovenue.virtualCurrencies(); // instant, no network
const coins = Rovenue.virtualCurrency('COINS'); // 0 if absent// Cache read — instant, no network
let balances = await Rovenue.shared.virtualCurrencyBalances() // [String: Int64]
let coins = await Rovenue.shared.virtualCurrency("COINS") // 0 if absent// Cache read — instant, no network
val balances = Rovenue.shared.virtualCurrencyBalances() // Map<String, Long>
val coins = Rovenue.shared.virtualCurrency("COINS") // 0 if absentvirtualCurrencies() and virtualCurrency(code) never hit the network. They are safe to call on the main thread and return instantly even in offline scenarios. Values reflect the last successful sync with the server.
Refresh from the server
Call refreshVirtualCurrencies() when you need a guaranteed-fresh set of balances — for example, after a server-side spend/grant that your app triggered.
import { Rovenue } from '@rovenue/react-native-sdk';
// Pull latest balances from server and update the local cache
await Rovenue.refreshVirtualCurrencies();
// Now virtualCurrencies() and useVirtualCurrencies() reflect the server values
const fresh = Rovenue.virtualCurrencies();// Pull latest balances from server and update the local cache
try await Rovenue.shared.refreshVirtualCurrencies()
// Now virtualCurrencyBalances() reflects the server values
let fresh = await Rovenue.shared.virtualCurrencyBalances()// Pull latest balances from server and update the local cache
Rovenue.shared.refreshVirtualCurrencies()
// Now virtualCurrencyBalances() reflects the server values
val fresh = Rovenue.shared.virtualCurrencyBalances()Balances also refresh automatically while the app is in the foreground. See App lifecycle for the polling behaviour. Manual refreshVirtualCurrencies() is only needed when you require immediate consistency after a server-side operation.
Grant virtual currency (server-side)
Virtual currency is granted when a user purchases a currency-pack product. Product-to-currency mapping is configured in the Rovenue dashboard — no client code is required.
After a successful purchase, PurchaseResult.virtualCurrencies already reflects the updated balances:
const result = await Rovenue.purchase(pkg);
console.log('COINS after purchase:', result.virtualCurrencies['COINS']);From your backend
Support tools, goodwill credits and other manual grants go through the secret-key grants endpoint:
POST /v1/virtual-currencies/:appUserId/:code/grants
Authorization: Bearer <rov_sk_live_…>
Content-Type: application/json
{
"amount": 50,
"referenceId": "support-ticket-4821",
"referenceType": "support",
"description": "Goodwill credits"
}amount is a positive integer. referenceId (required, ≤ 120 chars) is the idempotency key, matched across the user's merged accounts: retrying with the same referenceId, amount and referenceType grants once and returns the original grant. Reusing a referenceId with a different amount or referenceType returns 409 with error.code REFERENCE_CONFLICT. referenceType (≤ 60 chars) and description (≤ 200 chars) are optional. The grant is recorded as a BONUS transaction. An Idempotency-Key header is accepted too, but referenceId is the guarantee. A successful call returns:
{ "data": { "code": "COINS", "balance": 150, "transaction": { "id": "…", "code": "COINS", "type": "BONUS", "amount": 50, "balance": 150, "referenceType": "support", "referenceId": "support-ticket-4821", "description": "Goodwill credits", "rovenueId": "…", "createdAt": "2026-10-14T09:00:00.000Z" } } }balance is the wallet's live balance, also on a retry. Errors: 400 invalid body, 403 public key, 404 with error.code SUBSCRIBER_NOT_FOUND for an unknown user or NOT_FOUND for an unknown currency, 409 REFERENCE_CONFLICT, or 409 CONFLICT when the balance would exceed 2,147,483,647, 422 an Idempotency-Key reused for a different request.
Spend virtual currency (server-side only)
Spending a virtual currency is a server-side operation. From your backend, call the secret-key transactions endpoint:
POST /v1/virtual-currencies/:appUserId/:code/transactions
Authorization: Bearer <rov_sk_live_…>
Content-Type: application/json
{
"amount": 5,
"referenceId": "<unique-id-per-spend>",
"referenceType": "ai_generation",
"description": "AI image generation"
}amount is a positive integer: the number of units to debit. referenceId (required, ≤ 120 chars) is the idempotency key, matched across the user's merged accounts: retrying with the same referenceId, amount and referenceType debits once and returns the original spend. Reusing a referenceId with a different amount or referenceType returns 409 with error.code REFERENCE_CONFLICT. referenceType (≤ 60 chars) and description (≤ 200 chars) are optional.
A successful call returns { "data": { "code": "COINS", "balance": 95, "transaction": { … } } }. transaction is the SPEND row, in the shape described under Read the transaction history; its amount is negative. An unknown user returns 404 with error.code SUBSCRIBER_NOT_FOUND, an unknown currency code returns 404 with NOT_FOUND, and a balance smaller than amount returns 409 with error.code INSUFFICIENT_CREDITS (error.details carries balance and requested). Branch on error.code, not on the message.
Never put your secret API key (rov_sk_…) in the app binary. The transactions endpoint is server-to-server only. Expose a lightweight endpoint in your own backend that verifies the user session and calls Rovenue on their behalf. After the spend completes, call refreshVirtualCurrencies() on the client (or wait for the next foreground sync) to update the local cache.
Reverse a spend when the work fails
Debit before the work starts. If the work fails, give the debit back by its referenceId:
POST /v1/virtual-currencies/:appUserId/:code/transactions/:referenceId/reverse
Authorization: Bearer <rov_sk_live_…>There is no body. URL-encode referenceId (encodeURIComponent), since it may contain /, spaces or other reserved characters. The spend is reversed in full, as a REFUND transaction with referenceType spend_reversal and the spend's referenceId. The response has the same shape as a grant: { "data": { "code", "balance", "transaction" } }, with transaction the REFUND row.
- Reversing is idempotent: a second call returns the same reversal and credits nothing more.
404when no spend has thatreferenceIdin that currency. A grant'sreferenceIdnever matches, and neither does a spend in another currency.409witherror.codeREFERENCE_CONFLICTwhen two accounts that were later merged each spent the samereferenceId: Rovenue will not guess which one to reverse.- After a merge, the credits go back to the account the user has now (the surviving account), whether you call with the old or the new
appUserId.
const ref = `gen-${generationId}`;
await rovenue(`/v1/virtual-currencies/${encodeURIComponent(userId)}/COINS/transactions`, { amount: 5, referenceId: ref });
try {
await runGeneration();
} catch (err) {
await rovenue(`/v1/virtual-currencies/${encodeURIComponent(userId)}/COINS/transactions/${encodeURIComponent(ref)}/reverse`);
throw err;
}If the spend call itself timed out, you do not know whether it was recorded. Retry the spend with the same referenceId first (it is idempotent), then reverse. A reversal that arrives before an in-flight spend commits answers 404 and reverses nothing.
Read the transaction history
GET /v1/virtual-currencies/:appUserId/transactions?code=COINS&limit=50&cursor=…
Authorization: Bearer <rov_sk_live_…>Transactions come newest first. code keeps one currency. limit is 1–200 (default 50). Pass the previous page's nextCursor as cursor; it is null on the last page. A bad limit or cursor is 400, and an unknown code is 404. The read is consistent with your writes: a grant, spend or reversal shows up on the next call.
{ "data": { "transactions": [ { "id": "…", "code": "COINS", "type": "REFUND", "amount": 5, "balance": 100, "referenceType": "spend_reversal", "referenceId": "gen-42", "description": "Reversal of spend gen-42", "rovenueId": "…", "createdAt": "2026-10-14T09:00:01.000Z" } ], "nextCursor": null } }| Field | Type | Notes |
|---|---|---|
id | string | The ledger row's id |
code | string | Currency code (archived currencies included) |
type | string | PURCHASE, SPEND, REFUND, BONUS, EXPIRE, TRANSFER_IN, TRANSFER_OUT or CLAWBACK |
amount | integer | Signed: a credit is positive, a debit negative |
balance | integer | Running balance of the account this row belongs to, after the row |
referenceType | string | null | |
referenceId | string | null | |
description | string | null | |
rovenueId | string | The account the row was written on |
createdAt | string | ISO-8601 UTC |
- Rows of accounts merged into this user are included and carry their own
rovenueId, so you can tell inherited rows apart.balanceis per account, so it is not monotonic across accounts; a merge shows up as aTRANSFER_OUT/TRANSFER_INpair. - An erased user answers
404. - History reaches back as far as the project's data-retention window.
Never put personal data in referenceId, referenceType or description. They are kept with the ledger, which is retained after a user's erasure.
Grant rules for subscriptions
Each grant rule on a product says which currency it pays, how much, and when (Grant on in the product editor, grantOn on the wire). On a subscription product a rule can also pay on a schedule, pay a trial grant, and let its credits expire at the end of the period. None of this needs client code: the server applies the rule, and your app sees the result in its balances.
Every N days
A rule set to Every N days (grantOn: "PERIODIC", intervalDays 1–366) pays its amount once per period while the subscription is active, for example 200 credits every 7 days on a yearly plan. Periods count from the subscription's original purchase date.
- Only the current period is ever paid. If a period is missed (an outage, or the subscription was on hold), it is skipped, never paid later.
- No drips during a free trial or a grace period. When a trial converts or billing recovers, the current period is paid at once.
- A switch between plans of the same subscription (weekly to yearly, say) never pays one period twice.
- Each drip appears in the ledger as a
PURCHASErow withreferenceTypeperiodic_grant, and reaches webhooks withsource: "periodic". A refund claws periodic grants back like any other purchase grant. - A periodic rule is the only rule for its currency on that product. A product that also grants the same currency on purchase or renewal is refused with
400CURRENCY_GRANT_INVALIDanderror.details.reasonperiodic_exclusive. The first period already pays at purchase. - Like Renewal, it needs a subscription product.
Trial grants
Any rule on a subscription product can set a Trial grant (trialAmount; 0 means none). It is paid once, when the subscription starts a free trial, for each subscription and currency:
- It is a
BONUSrow withreferenceTypetrial_grantandreferenceId<store>:<originalTransactionId>. Webhooks carrysource: "store_purchase". - A replayed, restored or reinstalled trial start pays nothing more, and trial credits are never clawed back: there was no charge. At conversion the normal paid grant is added on top.
- When several rules for one currency set a trial grant (a Purchase rule and a Renewal rule, say), the largest is paid, once.
- A trial seen only through a store webhook is picked up by an hourly check, so its grant can land up to an hour after the trial starts. It is paid only while the trial is still running.
- A
trialAmounton a non-subscription product is refused with400CURRENCY_GRANT_INVALID, reasontrial_needs_subscription.
Expiring credits
A rule on a subscription product can set Unused credits expire at the end of each billing cycle (expiresAtPeriodEnd). Credits that rule grants and that are still unspent at the end of the period are removed.
- When: a purchase or renewal grant expires at the end of the billing period it was granted for. A periodic drip expires at the end of its own N-day period, and a trial grant at the end of the trial. During a grace period, credits still expire at the billing period end, not when grace ends.
- Renewals replace, they don't stack: when the next grant of the same subscription lands, the previous period's leftover expires first, in the same step. A renewal that arrives a few hours early never doubles the balance.
- Spend order: a spend takes the credits that expire soonest first, then the oldest, then credits that never expire.
- The write: expiry is checked every 5 minutes. Each expiry is an
EXPIRErow withreferenceTypecredit_expiration,referenceIdthe id of the grant row it came from, and a negativeamount. It reaches webhooks ascredit.ledger.appendedwithsource: "expiration". - Reversals: reversing a spend whose credits have since expired puts them back where they came from, and the next check expires them again. A reversal never turns expiring credits into permanent ones.
- What never expires: credits from one-time purchases (subscription products only; a rule with the flag on any other product type is refused with
400CURRENCY_GRANT_INVALID, reasonexpiry_needs_subscription), credits from rules without the flag, manual grants, and any balance the user held before expiring credits shipped. Turning the flag on or off affects only grants made after the change. - Analytics: expired credits leave the outstanding balance on the day they expire, and are not counted as burned (consumed) credits.
Your backend can see what is about to expire on the secret-key balance read:
GET /v1/virtual-currencies/:appUserId
Authorization: Bearer <rov_sec_…>{ "data": { "balances": { "GEMS": 140 }, "expiring": { "GEMS": [ { "amount": 100, "expiresAt": "2026-11-14T09:00:00.000Z" } ] } } }expiring lists, per currency code, the unspent units that have an expiry, soonest first, with units sharing one expiresAt summed. It is {} when nothing expires. The public-key GET /v1/virtual-currencies/me and the SDK return balances only.
Show what a package grants on your paywall
Every package carries virtualCurrencyGrants: the credits its product grants, read from the product's grant rule in the dashboard. The server grants by the same rule, so the number on your paywall can't drift from what a purchase pays. Each entry is { code, amount, grantOn, intervalDays, trialAmount, expiresAtPeriodEnd }. grantOn is "PURCHASE", "RENEWAL", "BOTH" or "PERIODIC" today, and any newer value passes through unchanged, so treat an unknown value as unknown, never as a purchase. trialAmount is the number paid once when a free trial starts (0 when the rule has no trial grant). expiresAtPeriodEnd is true when unspent credits from the rule expire at the end of the period, so you can say "unused credits expire". Use isPromoted for a "featured" badge, and metadata (set per package in the offering editor) for free-form labels such as bonusLabel.
const pkg = offerings.current?.packages.find((p) => p.identifier === "coins");
const gold = pkg?.virtualCurrencyGrants.find((g) => g.code === "GOLD" && g.grantOn !== "RENEWAL");
<Text>{gold ? `${gold.amount} GOLD` : null}{pkg?.metadata.bonusLabel ? ` · ${String(pkg.metadata.bonusLabel)}` : ""}</Text>
// A subscription package with a trial grant: "5 GOLD free during your trial"
const trial = offerings.current?.packages.find((p) => p.identifier === "pro")?.virtualCurrencyGrants.find((g) => g.code === "GOLD" && g.trialAmount > 0);
<Text>{trial ? `${trial.trialAmount} GOLD free during your trial${trial.expiresAtPeriodEnd ? " · unused credits expire" : ""}` : null}</Text>let pkg = offerings.current?.package(identifier: "coins")
let gold = pkg?.virtualCurrencyGrants.first { $0.code == "GOLD" && $0.grantOn != "RENEWAL" }
let label = pkg?.metadata["bonusLabel"] as? String
Text("\(gold.map { "\($0.amount) GOLD" } ?? "")\(label.map { " · \($0)" } ?? "")")
// A subscription package with a trial grant: "5 GOLD free during your trial"
let trial = offerings.current?.package(identifier: "pro")?.virtualCurrencyGrants.first { $0.code == "GOLD" && $0.trialAmount > 0 }
Text(trial.map { "\($0.trialAmount) GOLD free during your trial\($0.expiresAtPeriodEnd ? " · unused credits expire" : "")" } ?? "")val pkg = offerings.current?.packageBy("coins")
val gold = pkg?.virtualCurrencyGrants?.firstOrNull { it.code == "GOLD" && it.grantOn != "RENEWAL" }
val label = pkg?.metadata?.get("bonusLabel") as? String
text = listOfNotNull(gold?.let { "${it.amount} GOLD" }, label).joinToString(" · ")
// A subscription package with a trial grant: "5 GOLD free during your trial"
val trial = offerings.current?.packageBy("pro")?.virtualCurrencyGrants?.firstOrNull { it.code == "GOLD" && it.trialAmount > 0 }
val trialText = trial?.let { "${it.trialAmount} GOLD free during your trial" + if (it.expiresAtPeriodEnd) " · unused credits expire" else "" }final pkg = current?.packages.where((p) => p.identifier == 'coins').firstOrNull;
final gold = pkg?.virtualCurrencyGrants.where((g) => g.code == 'GOLD' && g.grantOn != 'RENEWAL').firstOrNull;
final label = pkg?.metadata['bonusLabel'] as String?;
Text([if (gold != null) '${gold.amount} GOLD', if (label != null) label].join(' · '));
// A subscription package with a trial grant: "5 GOLD free during your trial"
final trial = current?.packages.where((p) => p.identifier == 'pro').firstOrNull?.virtualCurrencyGrants.where((g) => g.code == 'GOLD' && g.trialAmount > 0).firstOrNull;
if (trial != null) Text('${trial.trialAmount} GOLD free during your trial${trial.expiresAtPeriodEnd ? ' · unused credits expire' : ''}');A periodic grant (grantOn: "PERIODIC") carries a non-null intervalDays, so the paywall can say "200 GOLD every 7 days". A package whose product grants nothing has virtualCurrencyGrants: [].