Go Back to Parent Doc

Developer Reference

Ollet is built so that developers can extend it without ever putting a balance at risk. This page covers the services you call to move money, the actions and filters, the REST API, WP-CLI, template overrides and the extension API that add-ons such as Ollet Pro use.

Ground rules

  • Move money only through LedgerService and HoldService. Never write to Ollet’s tables directly. The services lock the wallet, check the balance, write the entries and update the stored balance in one database transaction.
  • Use Money, never floats. Amounts are integers in the currency’s smallest unit (cents). Parse user input with Money::parse() and convert WooCommerce amounts with Money::from_wc_amount().
  • Give every posting an idempotency key when it comes from something that could run twice (a webhook, a cron job, a retried request). Posting the same key again returns the original result instead of moving money twice.
  • Wait for ollet_loaded. Ollet boots on plugins_loaded (priority 20), once WooCommerce is loaded. Its services are available from the ollet_loaded action onwards, and only when the requirements are met.

Getting the services

ollet() returns the plugin instance. Its get() method returns any service from the container:

use OlletWalletForWooCommerce\Accounts\AccountService;
use OlletWalletForWooCommerce\Ledger\LedgerService;
use OlletWalletForWooCommerce\Money\CurrencyRegistry;

add_action( 'ollet_loaded', function ( $plugin ) {
	$ledger     = $plugin->get( LedgerService::class );
	$accounts   = $plugin->get( AccountService::class );
	$currencies = $plugin->get( CurrencyRegistry::class );
} );

Outside the ollet_loaded callback, use ollet()->get( LedgerService::class ), and check ollet()->is_active() first: it’s false when a requirement (such as WooCommerce) is missing.

ServiceUse it to
Ledger\LedgerServicePost credits and debits (post()), reverse entries (reverse()).
Holds\HoldServiceReserve funds for an order (reserve()), capture (capture()) or release (release()) a reservation.
Accounts\AccountServiceRead a wallet (get(), get_or_create()), get balances (summary()), change status (set_status()).
Money\CurrencyRegistryGet the store currency (base()) or any currency (get( 'USD' )).
Ledger\ReconcilerRun the ledger check.

Posting money

Build a PostingRequest and pass it to LedgerService::post(). It returns a PostingResult, or a WP_Error when the posting is refused (for example ollet_insufficient_funds, ollet_account_locked or ollet_account_closed).

use OlletWalletForWooCommerce\Ledger\FundTypes;
use OlletWalletForWooCommerce\Ledger\LedgerService;
use OlletWalletForWooCommerce\Ledger\PostingRequest;
use OlletWalletForWooCommerce\Ledger\Reasons;
use OlletWalletForWooCommerce\Money\CurrencyRegistry;
use OlletWalletForWooCommerce\Money\Money;

$currency = ollet()->get( CurrencyRegistry::class )->base();
$amount   = Money::parse( '5.00', $currency );

$request = PostingRequest::credit( $user_id, $amount, FundTypes::STORE_CREDIT, Reasons::ADMIN_ADJUSTMENT )
	->idempotency_key( 'my-plugin:review-reward:' . $comment_id )
	->from_source( 'comment', $comment_id )
	->note( 'Thanks for your review!' )               // Shown to the customer.
	->internal_note( 'Review reward, my-plugin' );    // For your team only.

$result = ollet()->get( LedgerService::class )->post( $request );

if ( is_wp_error( $result ) ) {
	// Refused: nothing was written.
} elseif ( $result->is_duplicate() ) {
	// This key was already posted; $result holds the original entries.
} else {
	$balance_after = $result->balance_after_minor(); // Integer, in cents.
}

A debit is built with PostingRequest::debit( $user_id, $money, $reason ) and spends the fund types in the store’s spend order (filterable with ollet_spend_order). Other builder methods: fund_type(), allocation(), actor(), meta(), capturing_hold() and reversing().

To correct an entry, reverse it. Never post a manual opposite entry:

ollet()->get( LedgerService::class )->reverse( $entry_id, array( 'internal_note' => 'Duplicate reward' ) );

Fund types and reasons

Fund typeConstantMeaning
customer_fundsFundTypes::CUSTOMER_FUNDSMoney the customer paid you (top-ups).
store_creditFundTypes::STORE_CREDITValue the store granted.

Built-in reasons: topup, topup_reversal, order_payment, order_refund, admin_adjustment, cashback, cashback_reversal, signup_bonus, refund_credit (refund as store credit) and reversal. Register your own with the ollet_ledger_reasons filter, and your own fund types with ollet_fund_types.

Actions

ActionArgumentsFires
ollet_loadedPlugin $pluginWhen Ollet has booted and its services are available.
ollet_register_extensionsRegistry $registrySo add-ons can register themselves. See Extension API.
ollet_account_createdAccount $accountAfter a wallet was created.
ollet_account_status_changedAccount $account, string $previousAfter a wallet was locked, closed or reopened.
ollet_ledger_entry_postedEntry $entryAfter each ledger entry was committed.
ollet_ledger_transaction_postedPostingResult $result, PostingRequest $requestOnce per committed posting (which may write several entries).
ollet_ledger_entry_reversedEntry $reversal, Entry $originalAfter an entry was reversed.
ollet_hold_createdHold $holdAfter funds were reserved, or a reservation was resized or re-activated.
ollet_hold_capturedHold $hold, PostingResult $resultAfter a reservation was turned into a payment.
ollet_hold_releasedHold $holdAfter a reservation was released or expired.
ollet_topup_creditedEntry $entry, WC_Order $orderAfter a paid top-up was credited.
ollet_wallet_creditedstring $txn_idWhen a customer should be told money was added (triggers the email).
ollet_wallet_debitedstring $txn_idWhen a customer should be told money was removed (triggers the email).
ollet_wallet_low_balanceint $user_idWhen a customer’s available balance fell below the reminder amount (triggers the email). Since 1.2.0.
ollet_cashback_paidEntry $entry, WC_Order $orderAfter cashback was credited for a completed order. Since 1.2.0.
ollet_signup_bonus_paidEntry $entry, int $user_idAfter a sign-up bonus was credited. Since 1.2.0.
ollet_refunded_to_creditWC_Order_Refund $refund, PostingResult $result, WC_Order $orderAfter an order was refunded as store credit. Since 1.2.0.
ollet_reconciliation_checksReconciliationReport $report, int[]|null $account_idsDuring a ledger check, so integrations can add their own checks.
ollet_reconciliation_completedarray $reportAfter a ledger check finished.
ollet_rest_routesstring $namespaceAfter the core REST routes are registered.
ollet_admin_screen_{slug}—To render a tab added with ollet_admin_screens.

The ollet_ledger_* actions fire after the database transaction has committed, so it’s safe to send emails or call other systems from them.

Filters

FilterArgumentsUse it to
ollet_validate_postingtrue|WP_Error $result, PostingRequest $requestReject a posting with a WP_Error. Validation only: it can’t change the amount, and it runs before the wallet is locked.
ollet_spend_orderstring[] $fund_types, Account $accountChange which fund types a debit spends first.
ollet_fund_typesarray $types (slug => label)Register fund types. Slugs must match [a-z0-9_:]{1,32}; built-in types can’t be removed.
ollet_ledger_reasonsarray $reasons (slug => label)Register reasons. Slugs must match [a-z0-9_:]{1,40}.
ollet_gateway_is_availablebool $available, WC_Cart|null $cartHide or show the wallet at checkout. Returning true can’t make the wallet spend more than the balance: it’s checked again under a lock at payment.
ollet_topup_limitsarray{min:Money,max:Money} $limits, int $user_idSet per-customer top-up limits.
ollet_wallet_limitsarray{daily:?Money,max_balance:?Money} $limits, int $user_idSet the daily top-up limit and maximum balance per customer, for example per role. null means no limit. Since 1.2.0.
ollet_topup_limit_checktrue|WP_Error $result, Money $amount, int $user_idAdd your own top-up limits, such as a monthly limit. Return a WP_Error with a customer-ready message to refuse the top-up. Runs after the maximum balance and daily limit passed. Since 1.2.0.
ollet_spendable_minorint $available_minor, int $user_idLower how much of the available balance a customer can spend at checkout (full and split payments), for spend limits or a minimum balance. Never more than the available balance. Since 1.2.0.
ollet_cashback_amountint $amount, int $base_minor, array $contextChange the cashback in minor units, for example by product, category or role. $context has order, cart or product and user_id. The result is never more than $base_minor (the products total after discounts, without tax). Since 1.2.0.
ollet_cashback_eligiblebool $eligible, WC_Order $orderExclude an order from cashback. Guest orders, top-ups and orders in another currency are always excluded. Since 1.2.0.
ollet_signup_bonus_eligiblebool $eligible, int $user_idDecide who gets the sign-up bonus. Default: new users with the customer role who registered themselves. Since 1.2.0.
ollet_order_totals_rowsarray $rows, WC_Order $orderChange the wallet lines added to order emails, My Account and invoices. Since 1.2.0.
ollet_store_api_cart_dataarray $data, WC_Cart|null $cartAdd data to the ollet Store API cart extension used by the Cart & Checkout blocks. Since 1.2.0.
ollet_topup_excluded_gatewaysstring[] $gateway_idsExclude payment methods from top-ups. Default array( 'cod' ). Exclude every method that marks an order paid before the money arrives.
ollet_hold_should_expirebool $expire, Hold $holdKeep an overdue reservation, for example while an order still awaits payment.
ollet_my_account_endpointstring $slugChange the My Account endpoint (default wallet). Visit Settings → Permalinks after changing it.
ollet_template_pathstring $pathChange the theme folder for template overrides (default woocommerce/ollet/).
ollet_email_classesarray $emailsChange or replace the wallet email classes.
ollet_admin_screensarray $tabs (slug => [label, capability])Add tabs to WooCommerce → Wallets.
ollet_capability_rolesstring[] $rolesChoose the roles that get Ollet’s capabilities on install. Default administrator, shop_manager.

Example: hide the wallet at checkout for a product category.

add_filter( 'ollet_gateway_is_available', function ( $available, $cart ) {
	if ( ! $available || ! $cart ) {
		return $available;
	}
	foreach ( $cart->get_cart() as $item ) {
		if ( has_term( 'gift-cards', 'product_cat', $item['product_id'] ) ) {
			return false;
		}
	}
	return $available;
}, 10, 2 );

Example: double the cashback when the order contains a product from a category (since 1.2.0). The same filter runs for the order, the cart and the product page, so handle all three to keep the “Earn X cashback” messages right. Amounts are integers in minor units.

add_filter( 'ollet_cashback_amount', function ( $amount, $base_minor, $context ) {
	$product_ids = array();
	if ( isset( $context['order'] ) ) {
		foreach ( $context['order']->get_items() as $item ) {
			$product_ids[] = $item->get_product_id();
		}
	} elseif ( isset( $context['cart'] ) ) {
		foreach ( $context['cart']->get_cart() as $item ) {
			$product_ids[] = $item['product_id'];
		}
	} elseif ( isset( $context['product'] ) ) {
		$product_ids[] = $context['product']->get_parent_id() ?: $context['product']->get_id();
	}
	foreach ( $product_ids as $product_id ) {
		if ( has_term( 'summer-sale', 'product_cat', $product_id ) ) {
			return $amount * 2;
		}
	}
	return $amount;
}, 10, 3 );

REST API

Namespace: ollet/v1. Authenticate as a WordPress user: cookie and nonce from JavaScript on your site, or Application Passwords from outside. Amounts are exchanged as decimal strings in the store currency (for example "12.50"), never as floats.

Method & routeWhoDescription
GET /me/walletLogged-in customerThe current user’s wallet: status, currency, balance, held (reserved), available and funds (balance per fund type).
GET /me/transactionsLogged-in customerThe current user’s ledger. per_page (1–100, default 20), before (entry ID, for paging), direction (credit or debit).
GET /me/holdsLogged-in customerThe current user’s active reservations.
GET /walletsollet_view_walletsAll wallets. page, per_page, search, status (active, locked, closed).
GET /wallets/{user_id}ollet_view_walletsOne customer’s wallet.
GET /wallets/{user_id}/transactionsollet_view_walletsOne customer’s ledger, with the same paging as /me/transactions.
POST /wallets/{user_id}/adjustmentsollet_manage_walletsAdd or remove money. Requires an Idempotency-Key header.
POST /entries/{id}/reversalollet_manage_walletsReverse an entry. Body: reason (5–500 characters).
GET /reconciliationollet_manage_walletsRun the ledger check and return the report.

Creating an adjustment

curl -X POST https://example.com/wp-json/ollet/v1/wallets/12/adjustments \
  -u "admin:xxxx xxxx xxxx xxxx xxxx xxxx" \
  -H "Idempotency-Key: crm-ticket-4821" \
  -H "Content-Type: application/json" \
  -d '{"direction":"credit","amount":"10.00","fund_type":"store_credit","reason":"Goodwill for late delivery","note":"Sorry for the wait!","notify":true}'
FieldRequiredDescription
directionYescredit or debit.
amountYesDecimal string, for example "10.00".
reasonYesInternal reason, 5–500 characters.
fund_typeNostore_credit (default) or customer_funds.
noteNoNote visible to the customer, up to 255 characters.
notifyNotrue to email the customer. Default false.

The Idempotency-Key header (up to 100 letters, digits, ., _, : or -) makes retries safe: sending the same key again returns the original adjustment instead of posting it twice. Sending the same key with different data returns an error.

Refusals return 409 Conflict when the wallet’s state prevents the change (ollet_insufficient_funds, ollet_account_locked, ollet_account_closed, ollet_already_reversed, ollet_idempotency_mismatch, ollet_cannot_reverse_reversal) and 400 for invalid input.

Add-ons can register routes in the same namespace on the ollet_rest_routes action.

WP-CLI

CommandDescription
wp ollet balance <user> [--format=<format>]Show a customer’s balances.
wp ollet ledger <user> [--limit=<number>] [--before=<entry-id>] [--format=<format>]List a customer’s ledger entries.
wp ollet adjust <user> <direction> <amount> --reason=<text> [--fund-type=<slug>] [--note=<text>] [--idempotency-key=<key>]Add (credit) or remove (debit) money.
wp ollet reconcile [--user=<user>] [--fix-cache] [--format=<format>]Run the ledger check. --fix-cache rebuilds stored balances from the ledger.

<user> accepts a user ID, login or email. Examples:

wp ollet balance 12
wp ollet ledger 12 --limit=50
wp ollet adjust 12 credit 10.00 --reason="Goodwill for late delivery"
wp ollet reconcile
wp ollet reconcile --user=12 --fix-cache

Template overrides

Copy a template from the plugin’s templates/ folder to your theme and edit the copy. The Wallet page goes in your-theme/woocommerce/ollet/; emails go where WooCommerce looks for all email templates, your-theme/woocommerce/. Keep the same sub-folders:

TemplateCopy toShows
myaccount/wallet.phpyour-theme/woocommerce/ollet/myaccount/wallet.phpThe Wallet page in My Account.
emails/customer-wallet-credited.phpyour-theme/woocommerce/emails/The wallet credited email (HTML).
emails/customer-wallet-debited.phpyour-theme/woocommerce/emails/The wallet debited email (HTML).
emails/customer-wallet-low-balance.phpyour-theme/woocommerce/emails/The low balance reminder (HTML, since 1.2.0).
emails/plain/…your-theme/woocommerce/emails/plain/The plain text versions of the three emails.

WooCommerce → Settings → Emails shows the exact path for each email, with a Copy file to theme button. Change the Wallet page folder with the ollet_template_path filter. Templates only display data: balances and history come from the services, so an override can never change an amount.

Public wallet API

Since 1.1.0 (OLLET_API_VERSION 1.1.0), plugins that only need to check a balance, take a payment or reserve funds can use these functions instead of the services. Amounts are Money objects or decimal strings in the store’s base currency (never floats). Functions that change money take a required idempotency key and return the result or a WP_Error.

FunctionWhat it does
ollet_get_balance( $user_id )Balance as a decimal string.
ollet_get_available_balance( $user_id )Balance minus reserved funds.
ollet_can_spend( $user_id, $amount )true, or WP_Error ollet_insufficient_funds with required, available, shortfall and topup_url in its data. Filter: ollet_can_spend.
ollet_credit( $user_id, $amount, $args )Adds money. Args: key, fund_type (default store_credit), reason, note, source_type, source_id.
ollet_debit( $user_id, $amount, $args )Takes money. Same args; reason defaults to order_payment.
ollet_hold( $user_id, $amount, $args )Reserves funds. Args: key, source (e.g. bid, [a-z0-9_]), source_id, ttl seconds or expires_at. Filter: ollet_hold_ttl.
ollet_capture_hold( $hold_id, $args )Takes reserved funds; pass order_id to link the payment to an order.
ollet_release_hold( $hold_id )Releases reserved funds.
ollet_get_topup_url( $amount, $return_url )Link to the top-up form with the amount prefilled; after paying, the thank-you page links back to $return_url (same site only).
// Before accepting a bid.
$check = ollet_can_spend( get_current_user_id(), '25.00' );
if ( is_wp_error( $check ) ) {
	wp_safe_redirect( $check->get_error_data()['topup_url'] );
	exit;
}
$hold = ollet_hold( get_current_user_id(), '25.00', array( 'key' => 'bid:' . $bid_id, 'source' => 'bid', 'source_id' => $bid_id, 'ttl' => DAY_IN_SECONDS ) );

Reserved funds with a source other than an order show in My Account as Reserved (filter ollet_hold_label to name them). Add your own panel to the Wallet page with the ollet_my_account_wallet_panels action.

Integrations

List your plugin on WooCommerce → Wallets → Integrations:

add_action( 'ollet_integrations', function () {
	ollet_register_integration( array(
		'id'           => 'my-auctions',
		'name'         => 'My Auctions',
		'description'  => 'Checks the wallet balance before a bid.',
		'version'      => MY_AUCTIONS_VERSION,
		'requires_api' => '1.1.0',
		'status'       => static function () { return my_auctions_wallet_enabled() ? 'active' : 'setup'; }, // active|setup|inactive
		'settings_url' => admin_url( 'admin.php?page=my-auctions' ),
		'docs_url'     => 'https://example.com/docs',
	) );
} );

An integration that needs a newer API is refused and administrators see a notice to update Ollet. Add settings to the Wallets Settings screen with ollet_settings_sections; values are saved and sanitised by type (checkbox, text, number, select) and read with ollet()->get( Settings::class )->get( 'my_key' ):

add_filter( 'ollet_settings_sections', function ( $sections ) {
	$sections['my_auctions'] = array(
		'title'  => 'My Auctions',
		'fields' => array(
			'my_auctions_bid_check' => array( 'type' => 'checkbox', 'label' => 'Check the balance before a bid', 'default' => 'yes' ),
		),
	);
	return $sections;
} );

Extension API

Add-ons plug into Ollet through a small, versioned contract. An extension implements OlletWalletForWooCommerce\Extension\ExtensionInterface and registers itself on ollet_register_extensions:

use OlletWalletForWooCommerce\Container;
use OlletWalletForWooCommerce\Extension\ExtensionInterface;

class My_Wallet_Extension implements ExtensionInterface {

	public function id(): string {
		return 'my-wallet-extension';
	}

	// Minimum Ollet extension API version (OLLET_API_VERSION) this extension needs.
	public function required_api_version(): string {
		return '1.0.0';
	}

	// Runs on plugins_loaded: register services. Don't translate strings here.
	public function register( Container $container ): void {
		$container->set( My_Service::class, static function ( Container $c ) {
			return new My_Service( $c->get( \OlletWalletForWooCommerce\Ledger\LedgerService::class ) );
		} );
	}

	// Runs on init: add hooks.
	public function boot(): void {
		add_action( 'ollet_topup_credited', array( $this, 'on_topup' ), 10, 2 );
	}
}

add_action( 'ollet_register_extensions', function ( $registry ) {
	$registry->add( new My_Wallet_Extension() );
} );

Ollet 1.2.0 provides API version 1.2.0, which adds the rewards and limits filters (ollet_cashback_amount, ollet_cashback_eligible, ollet_signup_bonus_eligible, ollet_wallet_limits, ollet_topup_limit_check, ollet_spendable_minor, ollet_order_totals_rows, ollet_store_api_cart_data). Ollet 1.1.0 provided 1.1.0. An extension is compatible when it needs the same major API version as Ollet provides and no newer minor version. An incompatible extension isn’t loaded: administrators see a notice asking them to update both plugins, and the site keeps working. Check whether an extension is active with ollet()->get( \OlletWalletForWooCommerce\Extension\Registry::class )->has( 'my-wallet-extension' ).

Constants

ConstantValue
OLLET_VERSIONPlugin version.
OLLET_API_VERSIONExtension API version.
OLLET_FILEPath to the main plugin file.
OLLET_PATHPlugin directory path, with trailing slash.
OLLET_URLPlugin directory URL, with trailing slash.
OLLET_BASENAMEPlugin basename (ollet-wallet-for-woocommerce/ollet-wallet-for-woocommerce.php).
Shopping Cart
  • Your cart is empty.