fluentcart-developer 2.3.0 → 2.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +59 -59
  2. package/dist/cards/fluentcart/tools.d.ts.map +1 -1
  3. package/dist/cards/fluentcart/tools.js +160 -12
  4. package/dist/cards/fluentcart/tools.js.map +1 -1
  5. package/dist/skills/fluentcart-developer/.claude-plugin/plugin.json +12 -12
  6. package/dist/skills/fluentcart-developer/.mcp.json +11 -11
  7. package/dist/skills/fluentcart-developer/examples/fluentcart-starter-child-theme/fluent-cart/checkout.php +32 -32
  8. package/dist/skills/fluentcart-developer/examples/fluentcart-starter-child-theme/functions.php +40 -40
  9. package/dist/skills/fluentcart-developer/examples/sample-fee-surcharge-plugin/fluentcart-fee-surcharge.php +38 -38
  10. package/dist/skills/fluentcart-developer/references/action-hooks-cart-checkout.md +1355 -1355
  11. package/dist/skills/fluentcart-developer/references/action-hooks-customers-users.md +266 -266
  12. package/dist/skills/fluentcart-developer/references/action-hooks-licenses.md +855 -855
  13. package/dist/skills/fluentcart-developer/references/action-hooks-orders.md +631 -631
  14. package/dist/skills/fluentcart-developer/references/action-hooks-payments-integrations.md +963 -963
  15. package/dist/skills/fluentcart-developer/references/action-hooks-products-coupons.md +585 -585
  16. package/dist/skills/fluentcart-developer/references/action-hooks-subscriptions.md +661 -661
  17. package/dist/skills/fluentcart-developer/references/database-models-query-builder.md +194 -194
  18. package/dist/skills/fluentcart-developer/references/database-models-reference.md +604 -604
  19. package/dist/skills/fluentcart-developer/references/engineering-notes.md +154 -154
  20. package/dist/skills/fluentcart-developer/references/fee-system-guide.md +449 -449
  21. package/dist/skills/fluentcart-developer/references/filter-hooks-cart-checkout.md +1202 -1202
  22. package/dist/skills/fluentcart-developer/references/filter-hooks-integrations-advanced.md +1598 -1598
  23. package/dist/skills/fluentcart-developer/references/filter-hooks-products-pricing.md +628 -628
  24. package/dist/skills/fluentcart-developer/references/filter-hooks-settings-configuration.md +1177 -1177
  25. package/dist/skills/fluentcart-developer/references/fluentcart-developer-guide.md +154 -154
  26. package/dist/skills/fluentcart-developer/references/ghost-product-selling.md +458 -458
  27. package/dist/skills/fluentcart-developer/references/modules-and-extensions-reference.md +224 -224
  28. package/dist/skills/fluentcart-developer/references/payment-gateway-integration.md +761 -761
  29. package/dist/skills/fluentcart-developer/references/rest-api-customer-profile.md +190 -190
  30. package/dist/skills/fluentcart-developer/references/rest-api-customers.md +1121 -1121
  31. package/dist/skills/fluentcart-developer/references/rest-api-dashboard-utilities.md +219 -219
  32. package/dist/skills/fluentcart-developer/references/rest-api-email-notifications.md +619 -619
  33. package/dist/skills/fluentcart-developer/references/rest-api-files.md +290 -290
  34. package/dist/skills/fluentcart-developer/references/rest-api-integrations.md +324 -324
  35. package/dist/skills/fluentcart-developer/references/rest-api-labels-attributes.md +321 -321
  36. package/dist/skills/fluentcart-developer/references/rest-api-order-bumps.md +200 -200
  37. package/dist/skills/fluentcart-developer/references/rest-api-overview.md +131 -131
  38. package/dist/skills/fluentcart-developer/references/rest-api-public-shop.md +172 -172
  39. package/dist/skills/fluentcart-developer/references/rest-api-reference.md +552 -552
  40. package/dist/skills/fluentcart-developer/references/rest-api-reports.md +377 -377
  41. package/dist/skills/fluentcart-developer/references/rest-api-roles-permissions.md +147 -147
  42. package/dist/skills/fluentcart-developer/references/rest-api-settings.md +528 -528
  43. package/dist/skills/fluentcart-developer/references/rest-api-shipping.md +799 -799
  44. package/dist/skills/fluentcart-developer/references/rest-api-tax.md +356 -356
  45. package/dist/skills/fluentcart-developer/references/subscription-customization.md +197 -197
  46. package/dist/skills/fluentcart-developer/scripts/cli.js +1 -1
  47. package/dist/version.d.ts +1 -1
  48. package/dist/version.js +1 -1
  49. package/package.json +65 -65
@@ -1,449 +1,449 @@
1
- # Fee System (Surcharges & Additional Charges)
2
-
3
- FluentCart provides a built-in fee system that allows developers to attach additional charges to a cart during checkout. This is useful for processing fees, handling fees, small-order surcharges, payment gateway surcharges, environmental levies, and more.
4
-
5
- ---
6
-
7
- ## Overview
8
-
9
- Fees are stored as order items with `payment_type = 'fee'` and a cached `fee_total` column on the order for fast aggregation. The system provides two ways to register fees:
10
-
11
- - **Dynamic fees** via the `fluent_cart/cart/fees` filter — recalculated on every checkout update
12
- - **Persistent fees** via `$cart->addFee()` — stored directly on the cart and persisted to the database
13
-
14
- Fees automatically integrate with:
15
-
16
- - Checkout summary display
17
- - Order totals calculation
18
- - Email templates and PDF receipts
19
- - Admin order view and customer portal
20
- - Refund distribution (proportional)
21
- - REST API responses
22
-
23
- ---
24
-
25
- ## Fee Data Structure
26
-
27
- Every fee follows this structure:
28
-
29
- ```php
30
- [
31
- 'key' => 'processing_fee', // Unique slug (required)
32
- 'label' => 'Processing Fee', // Customer-facing name (required)
33
- 'amount' => 450, // Amount in cents, must be positive (required)
34
- 'taxable' => false, // Whether tax should be calculated (default: false)
35
- 'source' => 'my-addon', // Addon identifier (default: 'custom')
36
- 'meta' => ['rule_id' => 42], // Optional extra data stored in order item
37
- ]
38
- ```
39
-
40
- ### Rules:
41
-
42
- - `amount` must be a positive integer (in cents). Negative values are rejected.
43
- - `key` is sanitized with `sanitize_key()`. Combined with `source`, it forms a composite dedup key (`source:key`).
44
- - Duplicate `source:key` entries are deduplicated — the last one wins.
45
-
46
- ---
47
-
48
- ## Method 1: Dynamic Fees via Filter
49
-
50
- Use the `fluent_cart/cart/fees` filter to add fees that are recalculated on every checkout update (quantity change, coupon applied, payment method changed, etc.).
51
-
52
- ### Hook: `fluent_cart/cart/fees`
53
-
54
- **Parameters:**
55
-
56
- | Parameter | Type | Description |
57
- |-----------|------|-------------|
58
- | `$fees` | `array` | Current fees array (may contain fees from other addons or stored fees) |
59
- | `$context` | `array` | Cart context for condition evaluation |
60
-
61
- **Returns:** Modified fees array
62
-
63
- ### Context array contents:
64
-
65
- | Key | Type | Description |
66
- |-----|------|-------------|
67
- | `cart` | `Cart` | The Cart model instance |
68
- | `cart_items` | `array` | Current cart item data |
69
- | `cart_subtotal` | `int` | Cart subtotal in cents (before discounts) |
70
- | `shipping_total` | `int` | Shipping total in cents |
71
- | `customer_id` | `int` | Customer ID |
72
- | `payment_method` | `string` | Selected payment method key |
73
- | `checkout_data` | `array` | Full checkout data |
74
-
75
- ### Example: Small Order Surcharge
76
-
77
- Add a $5 fee when the cart subtotal is under $25:
78
-
79
- ```php
80
- add_filter('fluent_cart/cart/fees', function (array $fees, array $context) {
81
- // Get cart subtotal in cents
82
- $subtotal = $context['cart_subtotal'];
83
-
84
- // Apply $5 fee only when subtotal is between $0.01 and $24.99
85
- if ($subtotal > 0 && $subtotal < 2500) {
86
- $fees[] = [
87
- 'key' => 'small_order_fee',
88
- 'label' => __('Small Order Fee', 'my-addon'),
89
- 'amount' => 500,
90
- 'taxable' => false,
91
- 'source' => 'my-addon',
92
- 'meta' => ['reason' => 'subtotal_below_threshold'],
93
- ];
94
- }
95
-
96
- return $fees;
97
- }, 10, 2);
98
- ```
99
-
100
- ### Example: Payment Method Processing Fee
101
-
102
- Add a 2.9% processing fee for Stripe payments:
103
-
104
- ```php
105
- add_filter('fluent_cart/cart/fees', function (array $fees, array $context) {
106
- // Only apply fee for Stripe payment method
107
- if ($context['payment_method'] !== 'stripe') {
108
- return $fees;
109
- }
110
-
111
- $subtotal = $context['cart_subtotal'];
112
- if ($subtotal <= 0) {
113
- return $fees;
114
- }
115
-
116
- // Calculate 2.9% of subtotal, rounded to nearest cent
117
- $feeAmount = (int) round($subtotal * 0.029);
118
-
119
- $fees[] = [
120
- 'key' => 'stripe_processing',
121
- 'label' => __('Processing Fee (2.9%)', 'my-addon'),
122
- 'amount' => $feeAmount,
123
- 'taxable' => true,
124
- 'source' => 'my-addon',
125
- 'meta' => ['rate' => '2.9%'],
126
- ];
127
-
128
- return $fees;
129
- }, 10, 2);
130
- ```
131
-
132
- ### Example: Location-Based Fee
133
-
134
- Add a handling fee for orders shipping to remote areas:
135
-
136
- ```php
137
- add_filter('fluent_cart/cart/fees', function (array $fees, array $context) {
138
- // Extract shipping address from checkout data
139
- $checkoutData = $context['checkout_data'];
140
- $country = $checkoutData['form_data']['shipping_country'] ?? '';
141
- $state = $checkoutData['form_data']['shipping_state'] ?? '';
142
-
143
- // Define remote US territories
144
- $remoteAreas = ['AK', 'HI', 'PR']; // Alaska, Hawaii, Puerto Rico
145
-
146
- // Apply $15 handling fee for remote US areas
147
- if ($country === 'US' && in_array($state, $remoteAreas, true)) {
148
- $fees[] = [
149
- 'key' => 'remote_handling',
150
- 'label' => __('Remote Area Handling Fee', 'my-addon'),
151
- 'amount' => 1500,
152
- 'taxable' => false,
153
- 'source' => 'my-addon',
154
- ];
155
- }
156
-
157
- return $fees;
158
- }, 10, 2);
159
- ```
160
-
161
- ---
162
-
163
- ## Method 2: Persistent Fees via Cart Methods
164
-
165
- Use these methods to programmatically add or remove fees that are stored on the cart. Persistent fees survive page reloads and are included alongside dynamic fees.
166
-
167
- ### `$cart->addFee(array $fee): bool`
168
-
169
- Adds a fee to the cart and saves immediately. If a fee with the same `source:key` already exists, it will be updated.
170
-
171
- ```php
172
- // Find the cart by ID
173
- $cart = \FluentCart\App\Models\Cart::find($cartId);
174
-
175
- // Add a $2 handling fee to the cart
176
- $cart->addFee([
177
- 'key' => 'handling_fee',
178
- 'label' => 'Handling Fee',
179
- 'amount' => 200,
180
- 'source' => 'my-addon',
181
- 'taxable' => false,
182
- 'meta' => ['applied_by' => 'admin'],
183
- ]);
184
- ```
185
-
186
- ### `$cart->removeFee(string $key, ?string $source = null): bool`
187
-
188
- Removes a fee by key. Optionally filter by source to avoid removing another addon's fee with the same key.
189
-
190
- ```php
191
- // Remove a specific fee by key and source
192
- $cart->removeFee('handling_fee', 'my-addon');
193
-
194
- // Remove all fees with this key (regardless of source)
195
- $cart->removeFee('handling_fee');
196
- ```
197
-
198
- ### `$cart->removeFeesBySource(string $source): void`
199
-
200
- Removes all fees from a specific source. Useful for clearing all your addon's fees before recalculating.
201
-
202
- ```php
203
- // Clear all fees from your addon
204
- $cart->removeFeesBySource('my-addon');
205
- ```
206
-
207
- ### `$cart->getFees(): array`
208
-
209
- Returns all validated fees (stored + dynamic from filter).
210
-
211
- ### `$cart->getFeeTotal(): int`
212
-
213
- Returns the total of all fees in cents.
214
-
215
- ```php
216
- // Retrieve all fees and the total
217
- $fees = $cart->getFees();
218
- $total = $cart->getFeeTotal(); // e.g., 700 (= $7.00)
219
- ```
220
-
221
- ---
222
-
223
- ## How Fees Flow Through the System
224
-
225
- ```
226
- 1. REGISTRATION
227
- Addon registers fees via filter or $cart->addFee()
228
-
229
- 2. CHECKOUT SUMMARY
230
- WebCheckoutHandler recalculates on every cart change
231
- CartSummaryRender::renderFees() displays fee lines
232
- Fee total included in estimated total
233
-
234
- 3. ORDER CREATION
235
- CheckoutProcessor reads fees from cart
236
- Each fee becomes an OrderItem (payment_type = 'fee')
237
- fee_total cached on the Order record
238
- total_amount formula includes fee_total
239
-
240
- 4. POST-ORDER
241
- Admin view: fee rows in payment table
242
- Customer portal: fee rows in totals
243
- Emails: fee rows in items table
244
- PDF receipts: fee rows in summary
245
- Refunds: fees participate in proportional distribution
246
- ```
247
-
248
- ### Total Amount Formula
249
-
250
- ```
251
- total_amount = subtotal
252
- - coupon_discount_total
253
- - manual_discount_total
254
- + fee_total
255
- + shipping_total
256
- + tax_total (if exclusive)
257
- + shipping_tax (if exclusive)
258
- ```
259
-
260
- ---
261
-
262
- ## Fee Display Order
263
-
264
- Fees appear in the checkout summary and all post-order displays in this order:
265
-
266
- ```
267
- 1. Subtotal
268
- 2. Shipping
269
- 3. Fees ← your fees appear here
270
- 4. Coupons / Discounts
271
- 5. Tax
272
- 6. Total
273
- ```
274
-
275
- This ordering is intentional — fees are additions (like shipping), shown before subtractions (discounts).
276
-
277
- ---
278
-
279
- ## Reading Fees from Orders
280
-
281
- After an order is placed, fees are stored as order items. Use these methods to access them:
282
-
283
- ### `$order->feeItems()`
284
-
285
- Returns a `HasMany` relationship query for fee order items.
286
-
287
- ```php
288
- $order = \FluentCart\App\Models\Order::find($orderId);
289
-
290
- // Iterate over fee items attached to this order
291
- $feeItems = $order->feeItems()->get();
292
-
293
- foreach ($feeItems as $item) {
294
- echo $item->title; // "Processing Fee"
295
- echo $item->subtotal; // 450 (cents)
296
- echo $item->tax_amount; // 36 (cents, if taxable)
297
- }
298
- ```
299
-
300
- ### `$order->getAppliedFees()`
301
-
302
- Returns a simplified array of applied fees.
303
-
304
- ```php
305
- $fees = $order->getAppliedFees();
306
- // [
307
- // [
308
- // 'key' => 'processing_fee',
309
- // 'label' => 'Processing Fee',
310
- // 'amount' => 450,
311
- // 'source' => 'my-addon',
312
- // 'item_id' => 42,
313
- // ],
314
- // ]
315
- ```
316
-
317
- ### `$order->getProductItems()`
318
-
319
- Returns order items excluding fees and signup fees. Use this whenever displaying product line items to avoid showing fee rows in the product list.
320
-
321
- ```php
322
- // Correct: excludes fee and signup_fee items
323
- $products = $order->getProductItems();
324
-
325
- // Also available on the order: the cached total
326
- $feeTotal = $order->fee_total; // e.g., 650
327
- ```
328
-
329
- ---
330
-
331
- ## Fee Item Structure in Order Items
332
-
333
- When a fee becomes an order item, it has this structure in `fct_order_items`:
334
-
335
- | Column | Value | Notes |
336
- |--------|-------|-------|
337
- | `post_id` | `0` | No product |
338
- | `object_id` | `0` | No variation |
339
- | `title` | `"Processing Fee"` | The fee label |
340
- | `quantity` | `1` | Always 1 |
341
- | `unit_price` | `450` | Amount in cents |
342
- | `subtotal` | `450` | Same as unit_price |
343
- | `line_total` | `450` | Same as subtotal |
344
- | `payment_type` | `'fee'` | Identifies as a fee |
345
- | `other_info` | JSON | Contains `fee_key`, `source`, `taxable`, `meta` |
346
-
347
- ---
348
-
349
- ## Actions
350
-
351
- ### `fluent_cart/cart/fees_calculated`
352
-
353
- Fired after fees are collected and stored on the cart during checkout summary recalculation.
354
-
355
- ```php
356
- add_action('fluent_cart/cart/fees_calculated', function (array $fees, $cart) {
357
- // Log or track fee activity
358
- if (!empty($fees)) {
359
- error_log('Fees applied: ' . count($fees) . ' for cart #' . $cart->id);
360
- }
361
- }, 10, 2);
362
- ```
363
-
364
- ### `fluent_cart/order/fee_items_created`
365
-
366
- Fired after fee order items are created during order placement.
367
-
368
- ```php
369
- add_action('fluent_cart/order/fee_items_created', function (array $feeOrderItems, $order) {
370
- // Post-creation processing
371
- }, 10, 2);
372
- ```
373
-
374
- ---
375
-
376
- ## Important Behavior Notes
377
-
378
- - **Fees are recalculated on every checkout update.** Dynamic fees (via filter) run whenever the checkout summary refreshes — item changes, coupon application, payment method change, address change, etc.
379
-
380
- - **Fees are not applied to subscription renewals.** The filter is skipped when `checkout_data.renew_data.is_renewal` is `yes`.
381
-
382
- - **Fees are not applied to locked carts.** Custom/manual checkout carts that are locked return only stored fees without running the filter.
383
-
384
- - **Deduplication uses `source:key`.** Two addons can both register a fee with `key = 'processing_fee'` as long as they use different `source` values.
385
-
386
- - **Fees are read-only after order creation.** Once an order is placed, fee items cannot be edited from the admin panel.
387
-
388
- - **Fees participate in proportional refunds.** When an order is refunded, fee items are included in the proportional distribution automatically.
389
-
390
- - **Per-request caching.** `getFees()` caches results within a single request. Call `$cart->clearFeeCache()` if you modify fees and need to re-read within the same request.
391
-
392
- - **Recursion guard.** If your filter callback calls `$cart->getFees()`, it returns only stored fees (not the filter result) to prevent infinite loops.
393
-
394
- ---
395
-
396
- ## Complete Example: Tiered Handling Fee Addon
397
-
398
- A full working example that applies tiered handling fees based on cart subtotal:
399
-
400
- ```php
401
- <?php
402
- /**
403
- * Plugin Name: FluentCart Handling Fee
404
- * Description: Adds tiered handling fees based on cart subtotal.
405
- */
406
-
407
- add_filter('fluent_cart/cart/fees', function (array $fees, array $context) {
408
- $subtotal = $context['cart_subtotal'];
409
-
410
- // Skip if cart is empty
411
- if ($subtotal <= 0) {
412
- return $fees;
413
- }
414
-
415
- // Tiered handling fee based on cart subtotal
416
- $feeAmount = match (true) {
417
- $subtotal < 2000 => 500, // Under $20: $5.00 fee
418
- $subtotal < 5000 => 300, // $20-$49.99: $3.00 fee
419
- $subtotal < 10000 => 100, // $50-$99.99: $1.00 fee
420
- default => 0, // $100+: no fee
421
- };
422
-
423
- // Only add fee if amount is non-zero
424
- if ($feeAmount > 0) {
425
- $fees[] = [
426
- 'key' => 'handling_fee',
427
- 'label' => __('Handling Fee', 'my-handling-fee'),
428
- 'amount' => $feeAmount,
429
- 'taxable' => false,
430
- 'source' => 'handling-fee-addon',
431
- 'meta' => [
432
- 'tier' => $subtotal < 2000 ? 'small' : ($subtotal < 5000 ? 'medium' : 'large'),
433
- 'subtotal' => $subtotal,
434
- ],
435
- ];
436
- }
437
-
438
- return $fees;
439
- }, 10, 2);
440
- ```
441
-
442
- ---
443
-
444
- ## Related Documentation
445
-
446
- - [Developer Hooks](action-hooks-orders.md) - Complete hooks and filters reference
447
- - [Orders API](rest-api-reference.md) - Order management API
448
- - [Database Models](database-models-reference.md) - Data model documentation
449
- - [Ghost Product Selling](ghost-product-selling.md) - Custom product selling guide
1
+ # Fee System (Surcharges & Additional Charges)
2
+
3
+ FluentCart provides a built-in fee system that allows developers to attach additional charges to a cart during checkout. This is useful for processing fees, handling fees, small-order surcharges, payment gateway surcharges, environmental levies, and more.
4
+
5
+ ---
6
+
7
+ ## Overview
8
+
9
+ Fees are stored as order items with `payment_type = 'fee'` and a cached `fee_total` column on the order for fast aggregation. The system provides two ways to register fees:
10
+
11
+ - **Dynamic fees** via the `fluent_cart/cart/fees` filter — recalculated on every checkout update
12
+ - **Persistent fees** via `$cart->addFee()` — stored directly on the cart and persisted to the database
13
+
14
+ Fees automatically integrate with:
15
+
16
+ - Checkout summary display
17
+ - Order totals calculation
18
+ - Email templates and PDF receipts
19
+ - Admin order view and customer portal
20
+ - Refund distribution (proportional)
21
+ - REST API responses
22
+
23
+ ---
24
+
25
+ ## Fee Data Structure
26
+
27
+ Every fee follows this structure:
28
+
29
+ ```php
30
+ [
31
+ 'key' => 'processing_fee', // Unique slug (required)
32
+ 'label' => 'Processing Fee', // Customer-facing name (required)
33
+ 'amount' => 450, // Amount in cents, must be positive (required)
34
+ 'taxable' => false, // Whether tax should be calculated (default: false)
35
+ 'source' => 'my-addon', // Addon identifier (default: 'custom')
36
+ 'meta' => ['rule_id' => 42], // Optional extra data stored in order item
37
+ ]
38
+ ```
39
+
40
+ ### Rules:
41
+
42
+ - `amount` must be a positive integer (in cents). Negative values are rejected.
43
+ - `key` is sanitized with `sanitize_key()`. Combined with `source`, it forms a composite dedup key (`source:key`).
44
+ - Duplicate `source:key` entries are deduplicated — the last one wins.
45
+
46
+ ---
47
+
48
+ ## Method 1: Dynamic Fees via Filter
49
+
50
+ Use the `fluent_cart/cart/fees` filter to add fees that are recalculated on every checkout update (quantity change, coupon applied, payment method changed, etc.).
51
+
52
+ ### Hook: `fluent_cart/cart/fees`
53
+
54
+ **Parameters:**
55
+
56
+ | Parameter | Type | Description |
57
+ |-----------|------|-------------|
58
+ | `$fees` | `array` | Current fees array (may contain fees from other addons or stored fees) |
59
+ | `$context` | `array` | Cart context for condition evaluation |
60
+
61
+ **Returns:** Modified fees array
62
+
63
+ ### Context array contents:
64
+
65
+ | Key | Type | Description |
66
+ |-----|------|-------------|
67
+ | `cart` | `Cart` | The Cart model instance |
68
+ | `cart_items` | `array` | Current cart item data |
69
+ | `cart_subtotal` | `int` | Cart subtotal in cents (before discounts) |
70
+ | `shipping_total` | `int` | Shipping total in cents |
71
+ | `customer_id` | `int` | Customer ID |
72
+ | `payment_method` | `string` | Selected payment method key |
73
+ | `checkout_data` | `array` | Full checkout data |
74
+
75
+ ### Example: Small Order Surcharge
76
+
77
+ Add a $5 fee when the cart subtotal is under $25:
78
+
79
+ ```php
80
+ add_filter('fluent_cart/cart/fees', function (array $fees, array $context) {
81
+ // Get cart subtotal in cents
82
+ $subtotal = $context['cart_subtotal'];
83
+
84
+ // Apply $5 fee only when subtotal is between $0.01 and $24.99
85
+ if ($subtotal > 0 && $subtotal < 2500) {
86
+ $fees[] = [
87
+ 'key' => 'small_order_fee',
88
+ 'label' => __('Small Order Fee', 'my-addon'),
89
+ 'amount' => 500,
90
+ 'taxable' => false,
91
+ 'source' => 'my-addon',
92
+ 'meta' => ['reason' => 'subtotal_below_threshold'],
93
+ ];
94
+ }
95
+
96
+ return $fees;
97
+ }, 10, 2);
98
+ ```
99
+
100
+ ### Example: Payment Method Processing Fee
101
+
102
+ Add a 2.9% processing fee for Stripe payments:
103
+
104
+ ```php
105
+ add_filter('fluent_cart/cart/fees', function (array $fees, array $context) {
106
+ // Only apply fee for Stripe payment method
107
+ if ($context['payment_method'] !== 'stripe') {
108
+ return $fees;
109
+ }
110
+
111
+ $subtotal = $context['cart_subtotal'];
112
+ if ($subtotal <= 0) {
113
+ return $fees;
114
+ }
115
+
116
+ // Calculate 2.9% of subtotal, rounded to nearest cent
117
+ $feeAmount = (int) round($subtotal * 0.029);
118
+
119
+ $fees[] = [
120
+ 'key' => 'stripe_processing',
121
+ 'label' => __('Processing Fee (2.9%)', 'my-addon'),
122
+ 'amount' => $feeAmount,
123
+ 'taxable' => true,
124
+ 'source' => 'my-addon',
125
+ 'meta' => ['rate' => '2.9%'],
126
+ ];
127
+
128
+ return $fees;
129
+ }, 10, 2);
130
+ ```
131
+
132
+ ### Example: Location-Based Fee
133
+
134
+ Add a handling fee for orders shipping to remote areas:
135
+
136
+ ```php
137
+ add_filter('fluent_cart/cart/fees', function (array $fees, array $context) {
138
+ // Extract shipping address from checkout data
139
+ $checkoutData = $context['checkout_data'];
140
+ $country = $checkoutData['form_data']['shipping_country'] ?? '';
141
+ $state = $checkoutData['form_data']['shipping_state'] ?? '';
142
+
143
+ // Define remote US territories
144
+ $remoteAreas = ['AK', 'HI', 'PR']; // Alaska, Hawaii, Puerto Rico
145
+
146
+ // Apply $15 handling fee for remote US areas
147
+ if ($country === 'US' && in_array($state, $remoteAreas, true)) {
148
+ $fees[] = [
149
+ 'key' => 'remote_handling',
150
+ 'label' => __('Remote Area Handling Fee', 'my-addon'),
151
+ 'amount' => 1500,
152
+ 'taxable' => false,
153
+ 'source' => 'my-addon',
154
+ ];
155
+ }
156
+
157
+ return $fees;
158
+ }, 10, 2);
159
+ ```
160
+
161
+ ---
162
+
163
+ ## Method 2: Persistent Fees via Cart Methods
164
+
165
+ Use these methods to programmatically add or remove fees that are stored on the cart. Persistent fees survive page reloads and are included alongside dynamic fees.
166
+
167
+ ### `$cart->addFee(array $fee): bool`
168
+
169
+ Adds a fee to the cart and saves immediately. If a fee with the same `source:key` already exists, it will be updated.
170
+
171
+ ```php
172
+ // Find the cart by ID
173
+ $cart = \FluentCart\App\Models\Cart::find($cartId);
174
+
175
+ // Add a $2 handling fee to the cart
176
+ $cart->addFee([
177
+ 'key' => 'handling_fee',
178
+ 'label' => 'Handling Fee',
179
+ 'amount' => 200,
180
+ 'source' => 'my-addon',
181
+ 'taxable' => false,
182
+ 'meta' => ['applied_by' => 'admin'],
183
+ ]);
184
+ ```
185
+
186
+ ### `$cart->removeFee(string $key, ?string $source = null): bool`
187
+
188
+ Removes a fee by key. Optionally filter by source to avoid removing another addon's fee with the same key.
189
+
190
+ ```php
191
+ // Remove a specific fee by key and source
192
+ $cart->removeFee('handling_fee', 'my-addon');
193
+
194
+ // Remove all fees with this key (regardless of source)
195
+ $cart->removeFee('handling_fee');
196
+ ```
197
+
198
+ ### `$cart->removeFeesBySource(string $source): void`
199
+
200
+ Removes all fees from a specific source. Useful for clearing all your addon's fees before recalculating.
201
+
202
+ ```php
203
+ // Clear all fees from your addon
204
+ $cart->removeFeesBySource('my-addon');
205
+ ```
206
+
207
+ ### `$cart->getFees(): array`
208
+
209
+ Returns all validated fees (stored + dynamic from filter).
210
+
211
+ ### `$cart->getFeeTotal(): int`
212
+
213
+ Returns the total of all fees in cents.
214
+
215
+ ```php
216
+ // Retrieve all fees and the total
217
+ $fees = $cart->getFees();
218
+ $total = $cart->getFeeTotal(); // e.g., 700 (= $7.00)
219
+ ```
220
+
221
+ ---
222
+
223
+ ## How Fees Flow Through the System
224
+
225
+ ```
226
+ 1. REGISTRATION
227
+ Addon registers fees via filter or $cart->addFee()
228
+
229
+ 2. CHECKOUT SUMMARY
230
+ WebCheckoutHandler recalculates on every cart change
231
+ CartSummaryRender::renderFees() displays fee lines
232
+ Fee total included in estimated total
233
+
234
+ 3. ORDER CREATION
235
+ CheckoutProcessor reads fees from cart
236
+ Each fee becomes an OrderItem (payment_type = 'fee')
237
+ fee_total cached on the Order record
238
+ total_amount formula includes fee_total
239
+
240
+ 4. POST-ORDER
241
+ Admin view: fee rows in payment table
242
+ Customer portal: fee rows in totals
243
+ Emails: fee rows in items table
244
+ PDF receipts: fee rows in summary
245
+ Refunds: fees participate in proportional distribution
246
+ ```
247
+
248
+ ### Total Amount Formula
249
+
250
+ ```
251
+ total_amount = subtotal
252
+ - coupon_discount_total
253
+ - manual_discount_total
254
+ + fee_total
255
+ + shipping_total
256
+ + tax_total (if exclusive)
257
+ + shipping_tax (if exclusive)
258
+ ```
259
+
260
+ ---
261
+
262
+ ## Fee Display Order
263
+
264
+ Fees appear in the checkout summary and all post-order displays in this order:
265
+
266
+ ```
267
+ 1. Subtotal
268
+ 2. Shipping
269
+ 3. Fees ← your fees appear here
270
+ 4. Coupons / Discounts
271
+ 5. Tax
272
+ 6. Total
273
+ ```
274
+
275
+ This ordering is intentional — fees are additions (like shipping), shown before subtractions (discounts).
276
+
277
+ ---
278
+
279
+ ## Reading Fees from Orders
280
+
281
+ After an order is placed, fees are stored as order items. Use these methods to access them:
282
+
283
+ ### `$order->feeItems()`
284
+
285
+ Returns a `HasMany` relationship query for fee order items.
286
+
287
+ ```php
288
+ $order = \FluentCart\App\Models\Order::find($orderId);
289
+
290
+ // Iterate over fee items attached to this order
291
+ $feeItems = $order->feeItems()->get();
292
+
293
+ foreach ($feeItems as $item) {
294
+ echo $item->title; // "Processing Fee"
295
+ echo $item->subtotal; // 450 (cents)
296
+ echo $item->tax_amount; // 36 (cents, if taxable)
297
+ }
298
+ ```
299
+
300
+ ### `$order->getAppliedFees()`
301
+
302
+ Returns a simplified array of applied fees.
303
+
304
+ ```php
305
+ $fees = $order->getAppliedFees();
306
+ // [
307
+ // [
308
+ // 'key' => 'processing_fee',
309
+ // 'label' => 'Processing Fee',
310
+ // 'amount' => 450,
311
+ // 'source' => 'my-addon',
312
+ // 'item_id' => 42,
313
+ // ],
314
+ // ]
315
+ ```
316
+
317
+ ### `$order->getProductItems()`
318
+
319
+ Returns order items excluding fees and signup fees. Use this whenever displaying product line items to avoid showing fee rows in the product list.
320
+
321
+ ```php
322
+ // Correct: excludes fee and signup_fee items
323
+ $products = $order->getProductItems();
324
+
325
+ // Also available on the order: the cached total
326
+ $feeTotal = $order->fee_total; // e.g., 650
327
+ ```
328
+
329
+ ---
330
+
331
+ ## Fee Item Structure in Order Items
332
+
333
+ When a fee becomes an order item, it has this structure in `fct_order_items`:
334
+
335
+ | Column | Value | Notes |
336
+ |--------|-------|-------|
337
+ | `post_id` | `0` | No product |
338
+ | `object_id` | `0` | No variation |
339
+ | `title` | `"Processing Fee"` | The fee label |
340
+ | `quantity` | `1` | Always 1 |
341
+ | `unit_price` | `450` | Amount in cents |
342
+ | `subtotal` | `450` | Same as unit_price |
343
+ | `line_total` | `450` | Same as subtotal |
344
+ | `payment_type` | `'fee'` | Identifies as a fee |
345
+ | `other_info` | JSON | Contains `fee_key`, `source`, `taxable`, `meta` |
346
+
347
+ ---
348
+
349
+ ## Actions
350
+
351
+ ### `fluent_cart/cart/fees_calculated`
352
+
353
+ Fired after fees are collected and stored on the cart during checkout summary recalculation.
354
+
355
+ ```php
356
+ add_action('fluent_cart/cart/fees_calculated', function (array $fees, $cart) {
357
+ // Log or track fee activity
358
+ if (!empty($fees)) {
359
+ error_log('Fees applied: ' . count($fees) . ' for cart #' . $cart->id);
360
+ }
361
+ }, 10, 2);
362
+ ```
363
+
364
+ ### `fluent_cart/order/fee_items_created`
365
+
366
+ Fired after fee order items are created during order placement.
367
+
368
+ ```php
369
+ add_action('fluent_cart/order/fee_items_created', function (array $feeOrderItems, $order) {
370
+ // Post-creation processing
371
+ }, 10, 2);
372
+ ```
373
+
374
+ ---
375
+
376
+ ## Important Behavior Notes
377
+
378
+ - **Fees are recalculated on every checkout update.** Dynamic fees (via filter) run whenever the checkout summary refreshes — item changes, coupon application, payment method change, address change, etc.
379
+
380
+ - **Fees are not applied to subscription renewals.** The filter is skipped when `checkout_data.renew_data.is_renewal` is `yes`.
381
+
382
+ - **Fees are not applied to locked carts.** Custom/manual checkout carts that are locked return only stored fees without running the filter.
383
+
384
+ - **Deduplication uses `source:key`.** Two addons can both register a fee with `key = 'processing_fee'` as long as they use different `source` values.
385
+
386
+ - **Fees are read-only after order creation.** Once an order is placed, fee items cannot be edited from the admin panel.
387
+
388
+ - **Fees participate in proportional refunds.** When an order is refunded, fee items are included in the proportional distribution automatically.
389
+
390
+ - **Per-request caching.** `getFees()` caches results within a single request. Call `$cart->clearFeeCache()` if you modify fees and need to re-read within the same request.
391
+
392
+ - **Recursion guard.** If your filter callback calls `$cart->getFees()`, it returns only stored fees (not the filter result) to prevent infinite loops.
393
+
394
+ ---
395
+
396
+ ## Complete Example: Tiered Handling Fee Addon
397
+
398
+ A full working example that applies tiered handling fees based on cart subtotal:
399
+
400
+ ```php
401
+ <?php
402
+ /**
403
+ * Plugin Name: FluentCart Handling Fee
404
+ * Description: Adds tiered handling fees based on cart subtotal.
405
+ */
406
+
407
+ add_filter('fluent_cart/cart/fees', function (array $fees, array $context) {
408
+ $subtotal = $context['cart_subtotal'];
409
+
410
+ // Skip if cart is empty
411
+ if ($subtotal <= 0) {
412
+ return $fees;
413
+ }
414
+
415
+ // Tiered handling fee based on cart subtotal
416
+ $feeAmount = match (true) {
417
+ $subtotal < 2000 => 500, // Under $20: $5.00 fee
418
+ $subtotal < 5000 => 300, // $20-$49.99: $3.00 fee
419
+ $subtotal < 10000 => 100, // $50-$99.99: $1.00 fee
420
+ default => 0, // $100+: no fee
421
+ };
422
+
423
+ // Only add fee if amount is non-zero
424
+ if ($feeAmount > 0) {
425
+ $fees[] = [
426
+ 'key' => 'handling_fee',
427
+ 'label' => __('Handling Fee', 'my-handling-fee'),
428
+ 'amount' => $feeAmount,
429
+ 'taxable' => false,
430
+ 'source' => 'handling-fee-addon',
431
+ 'meta' => [
432
+ 'tier' => $subtotal < 2000 ? 'small' : ($subtotal < 5000 ? 'medium' : 'large'),
433
+ 'subtotal' => $subtotal,
434
+ ],
435
+ ];
436
+ }
437
+
438
+ return $fees;
439
+ }, 10, 2);
440
+ ```
441
+
442
+ ---
443
+
444
+ ## Related Documentation
445
+
446
+ - [Developer Hooks](action-hooks-orders.md) - Complete hooks and filters reference
447
+ - [Orders API](rest-api-reference.md) - Order management API
448
+ - [Database Models](database-models-reference.md) - Data model documentation
449
+ - [Ghost Product Selling](ghost-product-selling.md) - Custom product selling guide