Cart Total Reconciliation
Reconciles cart subtotal, discounts, tax, shipping, and grand total using integer cents.
Purpose
Reconciles cart subtotal, discounts, tax, shipping, and grand total using integer cents.
Snippet details
ContextEcommerceLevelAdvancedCopy-and-paste statusMarked safe after review.Categories
- Security
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Cart Total Reconciliation.
*
* Purpose:
* Reconciles cart subtotal, discounts, tax, shipping, and grand total using integer cents.
*
* @param array $cart_totals Cart totals in integer cents.
* @return array Reconciliation report.
*/
function ogSnippetCartTotalReconciliation(array $cart_totals): array {
$subtotal = 0;
if (isset($cart_totals['subtotal_cents'])) {
$subtotal = (int) $cart_totals['subtotal_cents'];
}
$discount = 0;
if (isset($cart_totals['discount_cents'])) {
$discount = (int) $cart_totals['discount_cents'];
}
$tax = 0;
if (isset($cart_totals['tax_cents'])) {
$tax = (int) $cart_totals['tax_cents'];
}
$shipping = 0;
if (isset($cart_totals['shipping_cents'])) {
$shipping = (int) $cart_totals['shipping_cents'];
}
$given = 0;
if (isset($cart_totals['grand_total_cents'])) {
$given = (int) $cart_totals['grand_total_cents'];
}
$calculated = $subtotal - $discount + $tax + $shipping;
return array('calculated_cents' => $calculated, 'given_cents' => $given, 'matches' => $calculated === $given, 'drift_cents' => $given - $calculated);
}
$cart_report = ogSnippetCartTotalReconciliation(array('subtotal_cents' => 12000, 'discount_cents' => 1500, 'tax_cents' => 660, 'shipping_cents' => 900, 'grand_total_cents' => 12060));
echo $cart_report['drift_cents'];