PHP code example of ejosterberg / opensalestax

1. Go to this page and download the library: Download ejosterberg/opensalestax library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ejosterberg / opensalestax example snippets


$client = new OpenSalesTax\Client(baseUrl: 'http://your-engine:8080');

$result = $client->calculate(
    address: new Address(zip5: '55401'),
    lineItems: [new LineItem(amount: '100.00', category: 'general')],
);

echo $result->taxTotal;  // "8.025"

use OpenSalesTax\Client;
use OpenSalesTax\Address;
use OpenSalesTax\LineItem;

$client = new Client(baseUrl: 'http://localhost:8080');

$result = $client->calculate(
    address: new Address(zip5: '55401'),
    lineItems: [
        new LineItem(amount: '100.00', category: 'general'),
        new LineItem(amount: '50.00', category: 'clothing'),
    ],
);

echo $result->subtotal;  // "150.00"
echo $result->taxTotal;  // "8.025"

foreach ($result->lines as $line) {
    echo "{$line->category}: \${$line->tax}\n";
    if ($line->note !== null) {
        echo "  → {$line->note}\n";   // e.g. "Clothing is non-taxable in Minnesota..."
    }
}

$client = new Client(
    baseUrl: 'http://your-engine:8080',
    apiKey: 'optional-x-api-key',  // null if engine doesn't ealth();                          // HealthResponse{status, version, databaseConnected}
$client->states();                          // StatesResponse{states[StateInfo], total}
$client->rates(zip5: '55401');              // RatesResponse{input, jurisdictions[], combinedRatePct, disclaimer}
$client->calculate($address, $lineItems);   // CalculateResponse{subtotal, taxTotal, lines[], disclaimer}

foreach ($result->lines as $line) {
    foreach ($line->jurisdictions as $j) {
        echo "  {$j->type:9} {$j->name:50} {$j->ratePct}% \${$j->tax}\n";
        // state     Minnesota                                    6.875% $6.8750
        // county    Hennepin County                              0.15%  $0.1500
        // city      Minneapolis                                  0.5%   $0.5000
        // district  Hennepin County Transit Sales Tax            0.5%   $0.5000
    }
}

$cents = 9999;
$amount = number_format($cents / 100, 2, '.', '');  // "99.99"
new LineItem(amount: $amount, category: 'general');

try {
    $result = $client->calculate(...);
} catch (OpenSalesTaxApiException $e) {
    error_log("Engine returned {$e->statusCode}: {$e->rawBody}");
} catch (OpenSalesTaxNetworkException $e) {
    error_log("Cannot reach engine: " . $e->getMessage());
}