mpociot/vat-calculator
Composer 安装命令:
composer require mpociot/vat-calculator
包简介
EU VAT calculation, the way it should be.
README 文档
README
Handle all the hard stuff related to EU MOSS tax/vat regulations, the way it should be. Integrates with Laravel and Cashier — or in a standalone PHP application. Originally created by Marcel Pociot.
// Easy to use! VatCalculator::calculate(24.00, $countryCode = 'DE'); VatCalculator::calculate(24.00, $countryCode, $postalCode); VatCalculator::calculate(71.00, 'DE', '41352', $isCompany = true); VatCalculator::getTaxRateForLocation('NL'); // Check validity of a VAT number VatCalculator::isValidVATNumber('NL123456789B01');
Warning
This package does not provide any promises for correctly calculated taxes. You are still responsible to making sure that any calculated tax is correct for your use case. If you're uncertain if a certain tax is correct or not, it's best that you talk to an accountant.
Requirements
- PHP 7.3 or higher
- (optional) Laravel 6.0 or higher
Installation
Install the package with composer:
composer require mpociot/vat-calculator
Standalone
You can also use this package without Laravel. Simply create a new instance of the VatCalculator and use it. All documentation examples use the Laravel Facade code, so make sure not to call the methods as if they were static methods.
use Mpociot\VatCalculator\VatCalculator; $vatCalculator = new VatCalculator(); $vatCalculator->setBusinessCountryCode('DE'); $grossPrice = $vatCalculator->calculate(49.99, $countryCode = 'LU');
Upgrading
Please refer to the upgrade guide when upgrading the library.
Usage
Calculate the gross price
To calculate the gross price use the calculate method with a net price and a country code as parameters.
$grossPrice = VatCalculator::calculate(24.00, 'DE');
The third parameter is the postal code of the customer.
As a fourth parameter, you can pass in a boolean indicating whether the customer is a company or a private person. If the customer is a company, which you should check by validating the VAT number, the net price gets returned.
$grossPrice = VatCalculator::calculate(24.00, 'DE', '12345', $isCompany = true);
Receive more information
After calculating the gross price you can extract more information from the VatCalculator.
$grossPrice = VatCalculator::calculate(24.00, 'DE'); // 28.56 $taxRate = VatCalculator::getTaxRate(); // 0.19 $netPrice = VatCalculator::getNetPrice(); // 24.00 $taxValue = VatCalculator::getTaxValue(); // 4.56
Receive all tax rates for a given country
To receive an array with all available tax rates for a given country, use the getTaxRatesForCountry method.
VatCalculator::getTaxRatesForCountry('DE'); // ["high" => 0.19, "low" => 0.07]
Validate EU VAT numbers
Prior to validating your customers VAT numbers, you can use the shouldCollectVAT method to check if the country code requires you to collect VAT
in the first place.
if (VatCalculator::shouldCollectVAT('DE')) { // This country code requires VAT collection... }
To validate your customers VAT numbers, you can use the isValidVATNumber method. The VAT number should be in a format specified by the VIES. The given VAT numbers will be truncated and non relevant characters / whitespace will automatically be removed.
This service relies on a third party SOAP API provided by the EU. If, for whatever reason, this API is unavailable a VATCheckUnavailableException will be thrown.
try { $validVAT = VatCalculator::isValidVATNumber('NL 123456789 B01'); } catch (VATCheckUnavailableException $e) { // The VAT check API is unavailable... }
Alternatively, it is also possible to validate only the format of the VAT Number specified by VIES. This is useful, if you do not want to wait for a response from the SOAP API.
// This check will return false because no connection to VIES could be made... $validVAT = VatCalculator::isValidVATNumber('NL 123456789 B01'); // This check will return true because only the format is checked... $validVAT = VatCalculator::isValidVatNumberFormat('NL 123456789 B01');
Get EU VAT number details
To get the details of a VAT number, you can use the getVATDetails method. The VAT number should be in a format specified by the VIES. The given VAT numbers will be truncated and non relevant characters / whitespace will automatically be removed.
This service relies on a third party SOAP API provided by the EU. If, for whatever reason, this API is unavailable a VATCheckUnavailableException will be thrown.
try { $vat_details = VatCalculator::getVATDetails('NL 123456789 B01'); print_r($vat_details); /* Outputs stdClass Object ( [countryCode] => NL [vatNumber] => 123456789B01 [requestDate] => 2017-04-06+02:00 [valid] => false [name] => Name of the company [address] => Address of the company ) */ } catch (VATCheckUnavailableException $e) { // The VAT check API is unavailable... }
UK VAT Numbers
Note: Validating UK VAT numbers requires registering your application with the HMRC Developer Hub. Please follow the official HMRC API Documentation for details on authentication and setup.
UK VAT numbers are formatted a little differently:
try { $vat_details = VatCalculator::getVATDetails('GB 553557881'); print_r($vat_details); /* Outputs array(3) { ["name"]=> string(26) "Credite Sberger Donal Inc." ["vatNumber"]=> string(9) "553557881" ["address"]=> array(3) { ["line1"]=> string(18) "131B Barton Hamlet" ["postcode"]=> string(8) "SW97 5CK" ["countryCode"]=> string(2) "GB" } } */ } catch (VATCheckUnavailableException $e) { // The VAT check API is unavailable... }
🔐 Configuration
To use the UK VAT validation feature, you'll need to register your application with HMRC and set the following environment variables in your .env file:
HMRC_CLIENT_ID="your-client-id"
HMRC_CLIENT_SECRET="your-client-secret"
Laravel
Configuration
By default, the VatCalculator has all EU VAT rules predefined, so that it can easily be updated, if it changes for a specific country.
If you need to define other VAT rates, you can do so by publishing the configuration and add more rules.
Warning
Be sure to set your business country code in the configuration file, to get correct VAT calculation when selling to business customers in your own country.
To publish the configuration files, run the vendor:publish command
php artisan vendor:publish --provider="Mpociot\VatCalculator\VatCalculatorServiceProvider"
This will create a vat_calculator.php in your config directory.
Handling SOAP Faults
If for some reason, SOAP faults happen when the VIES API is faulty, these errors will be handled gracefully and false will be returned. However, if you explicitly want to be aware of any SOAP faults you may instruct VatCalculator to throw them as a VATCheckUnavailableException. The VATCheckUnavailableException will then contain the specific message of the SOAP fault.
Set the option to true in your config file:
<?php return [ 'forward_soap_faults' => true, ];
You can also set a timeout for the SOAP client. By default, SOAP aborts the request to VIES after 30 seconds. If you do not want to wait that long, you can reduce the timeout, for example to 10 seconds:
<?php return [ 'soap_timeout' => 10, ];
ValidVatNumber Validation Rule
VatCalculator also ships with a ValidVatNumber validation rule for VAT Numbers. You can use this when validation input from a form request or a standalone validator instance:
use Mpociot\VatCalculator\Rules\ValidVatNumber; $validator = Validator::make(Input::all(), [ 'first_name' => 'required', 'last_name' => 'required', 'company_vat' => ['required', new ValidVatNumber], ]); if ($validator->passes()) { // Input is correct... }
Warning
The validator extension returns false when the VAT ID Check SOAP API is unavailable.
Cashier Stripe Integration
Note
At the moment this package is not compatible with Cashier Stripe v13 or higher because it still relies on the old taxPercentage method which has been removed from Cashier v13. You can still use it on older Cashier Stripe versions in the meantime.
If you want to use this package in combination with Laravel Cashier Stripe you can let your billable model use the BillableWithinTheEU trait. Because this trait overrides the taxPercentage method of the Billable trait, we have to explicitly tell our model to do so.
use Laravel\Cashier\Billable; use Mpociot\VatCalculator\Traits\BillableWithinTheEU; use Laravel\Cashier\Contracts\Billable as BillableContract; class User extends Model implements BillableContract { use Billable, BillableWithinTheEU { BillableWithinTheEU::taxPercentage insteadof Billable; } protected $dates = ['trial_ends_at', 'subscription_ends_at']; }
By using the BillableWithinTheEU trait, your billable model has new methods to set the tax rate for the billable model.
Set everything in one command:
setTaxForCountry($countryCode, $company = false)
Or use the more readable, chainable approach:
useTaxFrom($countryCode)— Use the given countries tax rateasIndividual()— The billable model is not a company (default)asBusiness()— The billable model is a valid company
So in order to set the correct tax percentage prior to subscribing your customer, consider the following workflow:
$user = User::find(1); // For individuals use: $user->useTaxFrom('NL'); // For business customers with a valid VAT ID, use: $user->useTaxFrom('NL')->asBusiness(); $user->subscription('monthly')->create($creditCardToken);
Changelog
Check out the CHANGELOG in this repository for all the recent changes.
Maintainers
VatCalculator is maintained by Laravel. Originally created by Marcel Pociot.
License
VatCalculator is open-sourced software licensed under the MIT license.
mpociot/vat-calculator 适用场景与选型建议
mpociot/vat-calculator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4.19M 次下载、GitHub Stars 达 1.27k, 最近一次更新时间为 2015 年 08 月 31 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「vat」 「tax」 「cashier」 「EU Moss」 「tax calculation」 「vat calculation」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 mpociot/vat-calculator 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 mpociot/vat-calculator 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 mpociot/vat-calculator 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A VAT number check (Web Service) Plugin for CakePHP
API client for validating Tax Identification Number.
Validate the format of EU vat numbers.
Laravel Cashier provides an expressive, fluent interface to Braintree's subscription billing services.
Module allowing creation of tax rates and categories in the CMS via SiteConfig
PHP VAT checker based on the European Commission web service
统计信息
- 总下载量: 4.19M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1279
- 点击次数: 28
- 依赖项目数: 17
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2015-08-31