taphra / billing
Billing layer for Taphra: provider abstraction, Stripe v1, subscriptions, webhooks.
Requires
- php: ^8.2
- ext-curl: *
- ext-json: *
- taphra/container: ^1.0
- taphra/db: ^1.0
Requires (Dev)
None
Suggests
- psr/simple-cache: Pass a PSR-16 cache to setWebhookCache() to reject replayed webhooks across requests (^3.0)
- symfony/console: Needed for the billing:migrate, billing:sync and billing:webhooks commands (^7.0)
- symfony/yaml: Reads app/Config/billing.yml when ext-yaml is not installed (^7.0)
Provides
None
Conflicts
None
Replaces
None
README
Documentation: https://taphra.dev/docs/packages/billing/. This package is a read-only copy of a folder in taphra/taphra; send issues and pull requests there.
Provider-agnostic billing layer for PHP, built for the Taphra framework and usable without it. Version 1 ships with a Stripe provider and a null provider for tests. Adding another provider (Paddle, Braintree, ...) takes one class and a config entry, with no changes to application code.
Requirements
- PHP 8.2+,
ext-curl,ext-json taphra/dbandtaphra/container(installed with the package)- Optional:
symfony/consolefor thebilling:*commands,symfony/yaml(orext-yaml) to readbilling.yml, and a PSR-16 cache (psr/simple-cache) for webhook replay protection across requests - Stripe: no SDK needed; the provider calls the Stripe REST API over cURL
The package works without the Taphra framework. The facade, the providers, the result objects, the DataStores and the webhook controller need only the packages above. Inside the framework, BillingController is a framework controller, events go to Taphra\Event, and the framework cache is used for webhook replay protection.
Installation
composer require taphra/billing
Add the service provider to app/Config/app.yml:
all: providers: - Taphra\Billing\BillingServiceProvider
Run the migration to create the billing tables:
php taphra billing:migrate
Standalone bootstrap
When using taphra/billing without the full Taphra framework, call Billing::configure() once before any billing operations:
use Taphra\Billing\Billing; Billing::configure([ 'default_provider' => 'stripe', 'providers' => [ 'stripe' => [ 'secret_key' => $_ENV['STRIPE_SECRET_KEY'], 'webhook_secret' => $_ENV['STRIPE_WEBHOOK_SECRET'], ], ], ]); $customer = Billing::createCustomer(['email' => 'alice@example.com']);
${ENV_VAR} placeholders in values are still resolved against getenv() / $_ENV. For more control, inject a pre-built manager directly:
Billing::setManager(new BillingManager($myConfig));
Configuration (framework mode)
Create app/Config/billing.yml and set your credentials through environment variables:
default_provider: stripe providers: stripe: driver: stripe secret_key: "${STRIPE_SECRET_KEY}" webhook_secret: "${STRIPE_WEBHOOK_SECRET}" # api_version: "2024-06-20" # optional: pin a Stripe API version # timeout: 30 # optional: cURL timeout in seconds # webhook_tolerance: 300 # optional: max age of a webhook timestamp in seconds
Only providers listed under providers can be used. Asking for any other name, for example one taken from a webhook URL, throws BillingException with the code provider_not_configured.
Set the environment variables in your server config, .env file, or shell:
STRIPE_SECRET_KEY=sk_live_... STRIPE_WEBHOOK_SECRET=whsec_...
Use sk_test_* keys in development and staging.
Basic usage
Static facade
use Taphra\Billing\Billing; // Customers $customer = Billing::createCustomer(['email' => 'alice@example.com', 'name' => 'Alice']); $customer = Billing::getCustomer('cus_xxx'); // Subscriptions $sub = Billing::createSubscription($customer->id, 'price_monthly'); $sub = Billing::createSubscription($customer->id, 'price_pro', ['trial_days' => 14]); $sub = Billing::cancelSubscription($sub->id); // cancels at period end $sub = Billing::cancelSubscription($sub->id, atPeriodEnd: false); // immediate // One-time charges (amount in the smallest currency unit, cents for USD) $charge = Billing::charge($customer->id, 2999, 'usd', ['description' => 'Add-on fee']); $refund = Billing::refund($charge->id); // full refund $refund = Billing::refund($charge->id, 1000); // partial refund ($10.00) // Payment methods $methods = Billing::listPaymentMethods($customer->id); Billing::attachPaymentMethod($customer->id, 'pm_xxx');
Provider-specific access
// Explicitly name the provider (useful when you have more than one configured) $customer = Billing::provider('stripe')->createCustomer(['email' => 'bob@example.com']); // Hosted billing portal (Stripe only in version 1) $url = Billing::provider()->billingPortalUrl($customer->id, 'https://yourapp.com/account'); // Hosted checkout $url = Billing::provider()->checkoutUrl($customer->id, 'price_monthly', [ 'success_url' => 'https://yourapp.com/billing/success', 'cancel_url' => 'https://yourapp.com/billing/cancel', 'trial_days' => 14, ]);
Billable trait
Apply the Billable trait to any DataStore-backed model to add billing capabilities directly on the model.
// app/DataStores/UserDataStore.php use Taphra\Billing\Billable; class UserDataStore extends DataStore { use Billable; public $connection = 'main'; public $objectName = 'users'; }
$user = new UserDataStore(); $user->read($id); // the trait works on the DataStore's loaded record // Create or retrieve the Stripe customer for this user $customer = $user->createOrGetBillingCustomer(); // Subscribe $sub = $user->subscribe('price_monthly'); $sub = $user->subscribe('price_pro', ['trial_days' => 14]); // Check status $user->subscribed(); // bool: active or trialing $user->onTrial(); // bool $sub = $user->activeSubscription(); // raw billing_subscriptions row or null // Cancel $user->cancelSubscription(); // at period end (default) $user->cancelSubscription(atPeriodEnd: false); // immediately // Charge $charge = $user->charge(999, 'usd', ['description' => 'Extra feature']); // Payment methods $methods = $user->paymentMethods(); // PaymentMethodResult[] // Get the provider-assigned customer ID $customerId = $user->billingProviderId(); // e.g. "cus_xxx"
Overriding column names
The trait reads id, email, and name by default. Override if your model uses different column names:
class UserDataStore extends DataStore { use Billable; protected function billableId(): int { return (int) $this->billableRow()['user_id']; } protected function billableEmail(): string { return (string) $this->billableRow()['contact_email']; } protected function billableName(): string { return (string) $this->billableRow()['full_name']; } }
The billing database connection
The billing tables use Billing::connection(): the connection key of billing.yml when set, else the connection of the app's AppDataStore (app_master in the skeleton), else main. billing:migrate uses the same default. To use another connection for one model, override billingConnectionName():
class UserDataStore extends DataStore { use Billable; protected function billingConnectionName(): string { return 'billing'; } }
Webhooks
1. Create the controller
// app/Controllers/BillingWebhookController.php namespace App\Controllers; use Taphra\Billing\BillingController; use Taphra\Billing\Results\WebhookEvent; class BillingWebhookController extends BillingController { public function webhook(?string $provider = null): string { return parent::webhook($provider); } protected function afterDispatch(WebhookEvent $event): void { // Optional: record the event, send an alert, ... } }
webhook() is the action the router calls: it reads the raw request body, verifies the signature, fires the normalised event, sets the HTTP status and Content-Type: application/json, and returns the JSON body. handle() does the same work and returns ['status' => int, 'body' => string] without sending anything, for when you call it from your own code.
2. Register the route
Add to app/Config/routes.yml:
POST: /billing/webhook: BillingWebhook/webhook /billing/webhook/:provider: BillingWebhook/webhook
With the second route the provider name comes from the URL; it must be one of the providers in your billing config, otherwise the request gets a 400.
3. Listen for events
The controller fires Event::emit('billing.subscription.created', $event) (or whichever normalised type matches) when the Taphra framework is installed. Register listeners anywhere; a ServiceProvider's boot() is the usual place:
use Taphra\Event; use Taphra\Billing\Results\WebhookEvent; use Taphra\Billing\Results\SubscriptionResult; Event::on('billing.subscription.created', function (WebhookEvent $event) { /** @var SubscriptionResult $sub */ $sub = $event->object; // activate features for $sub->customerId }); Event::on('billing.subscription.canceled', function (WebhookEvent $event) { // revoke access }); Event::on('billing.invoice.payment_failed', function (WebhookEvent $event) { // notify the user });
Without the framework, override afterDispatch() to act on each event.
How webhooks are checked
-
Signature. The
Stripe-Signatureheader must carry a timestamp withinwebhook_toleranceseconds (300 by default) of the server clock and av1signature made with yourwebhook_secret. While you roll a secret, Stripe sends onev1signature per active secret; the webhook is accepted when any of them matches. An emptywebhook_secretrefuses every webhook. -
Replays. Each event id is accepted once for twice the tolerance plus a minute (11 minutes by default), which covers the whole time a captured request would still pass the timestamp check. A second delivery of the same event in that time gets a 200 with
{"received": true, "duplicate": true}and is not dispatched again. If your listener throws, the event id is released so the provider's retry is accepted. Keep your listeners idempotent anyway: a provider can deliver an event again later than that. -
Where event ids are kept. In the PSR-16 cache you give the provider, otherwise in the framework cache when the framework is installed, otherwise in memory for the life of the PHP process (which does not cover separate PHP-FPM requests). Outside the framework, set a cache:
Billing::provider('stripe')->setWebhookCache($psr16Cache);
-
The null provider cannot verify signatures, so it accepts webhooks only while tests run (PHPUnit or Pest loaded, or
APP_ENVset totestortesting). Anywhere else it throws. Setallow_unsigned_webhooks: truein its config to accept unsigned webhooks, for local development only.
Normalised event types
Normalised (billing.*) |
Stripe event |
|---|---|
billing.subscription.created |
customer.subscription.created |
billing.subscription.updated |
customer.subscription.updated |
billing.subscription.canceled |
customer.subscription.deleted |
billing.subscription.trial_ending |
customer.subscription.trial_will_end |
billing.charge.succeeded |
payment_intent.succeeded |
billing.charge.failed |
payment_intent.payment_failed |
billing.charge.refunded |
charge.refunded |
billing.payment_method.attached |
payment_method.attached |
billing.payment_method.detached |
payment_method.detached |
billing.invoice.payment_succeeded |
invoice.payment_succeeded |
billing.invoice.payment_failed |
invoice.payment_failed |
billing.unknown |
(any unmapped Stripe event) |
Print the full map at any time:
php taphra billing:webhooks
Result objects
All provider methods return immutable readonly value objects. Use ->toArray() to serialize.
CustomerResult
$res->id // "cus_xxx"
$res->email
$res->name
$res->provider // "stripe"
$res->raw // full provider response array
SubscriptionResult
$res->id
$res->customerId
$res->planId
$res->status // active | trialing | past_due | canceled | incomplete | paused
$res->currentPeriodStart // Unix timestamp or null
$res->currentPeriodEnd // Unix timestamp or null
$res->trialEnd // Unix timestamp or null
$res->canceledAt // Unix timestamp or null
$res->isActive() // true when active or trialing
$res->onTrial() // true when trialing
$res->isCanceled()
ChargeResult
$res->id
$res->customerId
$res->amount // in smallest unit (e.g. cents)
$res->currency // "usd"
$res->status // succeeded | pending | failed | refunded
$res->description
$res->createdAt // Unix timestamp
$res->succeeded()
$res->amountFormatted() // "9.99"
PaymentMethodResult
$res->id
$res->customerId
$res->type // "card"
$res->last4
$res->brand // "visa", "mastercard", etc.
$res->expMonth
$res->expYear
$res->isDefault
$res->isExpired()
WebhookEvent
$event->id
$event->type // normalised "billing.*" name
$event->providerType // raw Stripe event name
$event->object // SubscriptionResult | ChargeResult | PaymentMethodResult | null
$event->raw // full provider payload
$event->provider // "stripe"
$event->createdAt // Unix timestamp
CLI commands
The commands need symfony/console. BillingServiceProvider::commands() returns them, and the Taphra console lists the commands of every booted provider, so they appear once the provider is in app.providers (or in app/Providers/).
# Create billing tables (run once after installation or after deploy to a new DB) php taphra billing:migrate php taphra billing:migrate --connection=billing # another connection from databases.yml # Re-sync subscription statuses from the provider (after webhook outage, initial import, etc.) php taphra billing:sync php taphra billing:sync --provider=stripe php taphra billing:sync --dry-run # preview without writing # Print the normalised event map with example listener code php taphra billing:webhooks
Testing
Use NullProvider in tests: no HTTP calls, no API keys, deterministic stubs. Its parseWebhook() accepts any payload while tests run and refuses it anywhere else (see "How webhooks are checked").
use Taphra\Billing\Billing; use Taphra\Billing\BillingManager; protected function setUp(): void { $manager = new BillingManager([ 'default_provider' => 'null', 'providers' => ['null' => ['driver' => 'null']], ]); Billing::setManager($manager); } protected function tearDown(): void { Billing::reset(); } public function testUserSubscribes(): void { $sub = Billing::createSubscription('cus_test', 'price_monthly'); $this->assertSame('active', $sub->status); }
Adding a new provider
To add Paddle, Braintree, or any other processor:
1. Implement the interface:
namespace App\Billing; use Taphra\Billing\AbstractBillingProvider; use Taphra\Billing\BillingProviderInterface; // ...implement all methods... class PaddleProvider extends AbstractBillingProvider { public function getName(): string { return 'paddle'; } // ... }
2. Register it (choose one approach):
// In a ServiceProvider boot(), explicit registration: Billing::extend('paddle', \App\Billing\PaddleProvider::class);
// Or place the class at Taphra\Billing\Providers\PaddleProvider to have it resolved by convention.
3. Add config (a provider that is not listed under providers cannot be used):
# app/Config/billing.yml default_provider: paddle providers: paddle: driver: paddle vendor_id: "${PADDLE_VENDOR_ID}" vendor_auth_code: "${PADDLE_AUTH_CODE}"
Application code using Billing::provider(), the Billable trait and Event::on('billing.*') listeners does not change. Your provider's parseWebhook() must verify the provider's signature; claimWebhookEvent() and releaseWebhookEvent() from AbstractBillingProvider give you the same replay protection as the Stripe provider.
Database tables
billing_customers
| Column | Type | Notes |
|---|---|---|
id |
INT PK | |
billable_type |
VARCHAR(150) | Owner class (e.g. App\DataStores\UserDataStore) |
billable_id |
INT | Owner primary key |
provider |
VARCHAR(50) | e.g. stripe |
provider_id |
VARCHAR(100) | e.g. cus_xxx |
email |
VARCHAR(255) | |
name |
VARCHAR(255) | nullable |
created_at |
DATETIME | |
updated_at |
DATETIME |
billing_subscriptions
| Column | Type | Notes |
|---|---|---|
id |
INT PK | |
billing_customer_id |
INT | FK → billing_customers.id |
provider |
VARCHAR(50) | e.g. stripe |
provider_id |
VARCHAR(100) | e.g. sub_xxx |
plan_id |
VARCHAR(100) | Price/plan ID at the provider |
status |
VARCHAR(30) | active · trialing · past_due · canceled · incomplete · paused |
trial_ends_at |
DATETIME | nullable |
current_period_start |
DATETIME | nullable |
current_period_end |
DATETIME | nullable |
canceled_at |
DATETIME | nullable |
created_at |
DATETIME | |
updated_at |
DATETIME |