PHP code example of ejosterberg / opensalestax-stripe-php

1. Go to this page and download the library: Download ejosterberg/opensalestax-stripe-php 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-stripe-php example snippets


$breakdown = InvoiceCalculator::calculateForInvoice($invoice, $ostClient);
$taxRate   = \Stripe\TaxRate::create([...$breakdown->combinedRatePct... ]);
\Stripe\Invoice::update($invoice->id, ['default_tax_rates' => [$taxRate->id]]);

'billing_address_collection' => '

case 'invoice.created':
    self::applyOpenSalesTax($event->data->object);
    break;

use OpenSalesTax\Client as OpenSalesTaxClient;
use OpenSalesTax\Stripe\InvoiceCalculator;
use OpenSalesTax\Stripe\Exceptions\NonUSDException;
use OpenSalesTax\Stripe\Exceptions\MissingAddressException;

private static function applyOpenSalesTax(\Stripe\Invoice $invoice): void
{
    $client = new OpenSalesTaxClient(baseUrl: getenv('OPENSALESTAX_BASE_URL'));

    try {
        // Re-retrieve with expanded customer to ensure address is populated.
        $expanded = \Stripe\Invoice::retrieve([
            'id'     => $invoice->id,
            'expand' => ['customer'],
        ]);

        $breakdown = InvoiceCalculator::calculateForInvoice($expanded, $client);

        if ($breakdown->lines === [] || (float) $breakdown->taxTotal <= 0.0) {
            return;  // nothing to apply (zero-tax cart or all lines non-taxable)
        }

        $taxRate = \Stripe\TaxRate::create([
            'display_name' => 'Sales Tax',
            'percentage'   => (float) $breakdown->combinedRatePct,
            'inclusive'    => false,
            'jurisdiction' => 'US',
        ]);

        \Stripe\Invoice::update($invoice->id, [
            'default_tax_rates' => [$taxRate->id],
        ]);
    } catch (NonUSDException | MissingAddressException $e) {
        // Best-effort: log and let the invoice proceed without tax.
        // (Merchant handles compliance manually for these edge cases.)
        error_log('OST skip: ' . $e->getMessage());
    } catch (\Throwable $e) {
        error_log('OST error: ' . $e->getMessage());
    }
}

use OpenSalesTax\Client as OpenSalesTaxClient;
use OpenSalesTax\Stripe\InvoiceCalculator;

$ost = new OpenSalesTaxClient(baseUrl: 'http://localhost:8080');
$invoice = \Stripe\Invoice::retrieve($invoiceId);

$breakdown = InvoiceCalculator::calculateForInvoice($invoice, $ost);

echo $breakdown->subtotal;          // "100.00"
echo $breakdown->taxTotal;          // "8.025"
echo $breakdown->combinedRatePct;   // "8.025"

foreach ($breakdown->lines as $line) {
    echo "  {$line['stripe_line_id']} ({$line['category']}): \${$line['tax']}\n";
    if ($line['note'] !== null) {
        echo "    → {$line['note']}\n";
    }
}

foreach ($breakdown->jurisdictions as $j) {
    echo "  {$j['type']:9} {$j['name']:50} {$j['rate_pct']}% \${$j['tax']}\n";
}

use OpenSalesTax\Stripe\SessionCalculator;

$session = \Stripe\Checkout\Session::retrieve([
    'id'     => $sessionId,
    'expand' => ['line_items', 'line_items.data.price'],   // 

use OpenSalesTax\Stripe\TaxCodeMap;

$customMap = new TaxCodeMap([
    'txcd_30060006' => 'clothing',
    'txcd_40030003' => 'prepared_food',
]);

$breakdown = InvoiceCalculator::calculateForInvoice($invoice, $ost, $customMap);
bash
composer 

ejosterberg/opensalestax-stripe-php: ^0.1
opensalestax engine:                 v0.22+