Documentation menu

Application services

Billing

Taphra\Billing creates customers and subscriptions, takes one-time charges and refunds, lists payment methods, opens hosted checkout and billing portal pages, and turns verified provider webhooks into billing.* events. Version 1 ships a Stripe provider, which calls the Stripe REST API over cURL (no Stripe SDK), and a null provider for development and tests.

Billing is part of taphra/taphra; nothing else to install. The same code runs without the framework: packages/billing/README.md covers that, the full result objects and how to add a provider.

Contents

#

Configuration

#

Providers are declared in app/Config/billing.yml, with the same environment sections as the other config files. This one uses Stripe everywhere and the null provider, under the name fake, in development:

app/Config/billing.yml
all:
  default_provider: stripe
  providers:
    stripe:
      secret_key: "${STRIPE_SECRET_KEY}"
      webhook_secret: "${STRIPE_WEBHOOK_SECRET}"
      # api_version: "2024-06-20"   # the Stripe API version sent with each call (this is the default)
      # timeout: 30                  # cURL timeout in seconds
      # webhook_tolerance: 300       # how old a webhook timestamp may be, in seconds
    fake:
      driver: "null"

dev:
  default_provider: fake
  • A value that is exactly ${NAME} is read from the environment variable NAME when the provider is built. Keep keys out of the file: set STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET in the server's environment, with sk_test_ keys outside production.
  • An environment section replaces whole top-level keys. The dev section above changes default_provider only, so both providers stay configured.
  • driver names the implementation and defaults to the provider's name. Quote "null": unquoted, YAML reads it as an empty value.
  • Only providers listed under providers can be used. Any other name, one taken from a webhook URL included, throws Taphra\Billing\BillingException with the code provider_not_configured.

The configuration is read on first use. To have the billing services in the container as well (Taphra\Billing\BillingManager and Taphra\Billing\BillingProviderInterface), list the package's provider:

YAML
# app/Config/app.yml
all:
  providers:
    - Taphra\Billing\BillingServiceProvider

With the provider listed, php taphra also has billing:migrate (creates the two billing tables on Billing::connection()), billing:sync and billing:webhooks.

Customers, subscriptions and charges

#

The Billing facade calls the default provider; Billing::provider('stripe') picks one by name. Every call returns a read-only result object (CustomerResult, SubscriptionResult, ChargeResult, PaymentMethodResult) with the provider's full response in raw. Amounts are integers in the smallest currency unit: cents for USD.

PHP
use Taphra\Billing\Billing;
use Taphra\Billing\BillingException;

echo Billing::defaultProvider(), "\n"; // fake (the dev section)

$customer = Billing::createCustomer(['email' => '[email protected]', 'name' => 'Ada']);

$sub = Billing::createSubscription($customer->id, 'price_monthly', ['trial_days' => 14]);
echo $sub->status, "\n";                   // trialing
var_dump($sub->isActive(), $sub->onTrial()); // true, true: active covers trialing

$sub = Billing::cancelSubscription($sub->id);                       // at the end of the period
$sub = Billing::cancelSubscription($sub->id, atPeriodEnd: false);   // now
var_dump($sub->isCanceled());              // true

$charge = Billing::charge($customer->id, 2999, 'usd', ['description' => 'Extra seats']);
echo $charge->status, ' ', $charge->amountFormatted(), "\n"; // succeeded 29.99

$refund = Billing::refund($charge->id, 1000);   // partial: 10.00; leave the amount out for a full refund
echo $refund->status, "\n";                     // refunded

foreach (Billing::listPaymentMethods($customer->id) as $method) {
    echo "{$method->brand} ending {$method->last4}\n";
}

try {
    Billing::provider('paddle');
} catch (BillingException $e) {
    echo $e->getProviderCode(), "\n";       // provider_not_configured
}

The provider object has the rest of the API: getCustomer(), updateCustomer(), deleteCustomer(), getSubscription(), updateSubscription(), resumeSubscription(), attachPaymentMethod(), detachPaymentMethod() and setDefaultPaymentMethod(). A failed Stripe call throws BillingException; getProviderCode() carries Stripe's error code.

Checkout and the billing portal

#

With Stripe, checkoutUrl() creates a hosted Checkout session for a subscription and billingPortalUrl() a customer portal session; both return the page to send the customer to. The null provider returns an empty string for both.

PHP
// app/Controllers/PlanController.php (excerpt)
public function subscribe(): void
{
    $customerId = $this->currentCustomerId(); // however your app stores it

    $url = Billing::provider()->checkoutUrl($customerId, 'price_monthly', [
        'success_url' => url('/billing/done'),
        'cancel_url'  => url('/plans'),
        'trial_days'  => 14,         // optional
        'quantity'    => 1,          // optional, default 1
        'metadata'    => ['plan' => 'pro'], // optional, stored on the subscription
    ]);

    $this->redirect($url);
}

url() builds absolute links from base_url in production (see Configuration). The subscription itself reaches your app through the billing.subscription.created webhook.

Keeping subscriptions in your database

#

The Taphra\Billing\Billable trait links an owner in your app (a user, a team) to its billing customer and keeps its subscriptions in two tables, billing_customers and billing_subscriptions.

The tables

#

Create them in a migration (php taphra make:migration create billing tables) that runs the package's own schema, then php taphra migrate:

app/Migrations/migration_20261130090000_CreateBillingTables.php
<?php
// app/Migrations/migration_20261130090000_CreateBillingTables.php

use Taphra\Billing\Migrations\CreateBillingTables;
use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;

class Migrate_migration_20261130090000_CreateBillingTables
{
    public $up = '';
    public $down = '';
    public $connection = '';

    public function up(array $args): void
    {
        (new CreateBillingTables())->up(new SchemaBuilder(DatabaseConnection::load('app_master')));
    }

    public function down(array $args): void
    {
        (new CreateBillingTables())->down(new SchemaBuilder(DatabaseConnection::load('app_master')));
    }
}

CreateBillingTables works on MySQL, PostgreSQL, SQLite and SQL Server, and skips a table that already exists.

The billable owner

#

The trait reads the owner's id, email and name from its row: on a DataStore, the record loaded with read($id); on any other class, a getRow() or toArray() method. Rows that finders such as findById() return are DataStoreRow objects, which carry no billing methods, so either use the trait on the DataStore and read() the owner, or put it on a small class around the row:

app/Billing/BillableUser.php
<?php
// app/Billing/BillableUser.php
namespace App\Billing;

use Taphra\Billing\Billable;
use Taphra\DataStoreRow;

final class BillableUser
{
    use Billable;

    public function __construct(private DataStoreRow $user) {}

    /** The id, email and name the trait sends to the provider. */
    protected function getRow(): array
    {
        return $this->user->toArray();
    }

    /** The billing tables live on the skeleton's connection. */
    protected function billingConnectionName(): string
    {
        return 'app_master';
    }
}

Two things to know. The billing tables use Billing::connection(): the connection key of billing.yml when set, else the connection of your AppDataStore (app_master in the skeleton), so the billingConnectionName() override above only matters for another connection. And the class name is stored with each customer row (billable_type), so keep it stable once customers exist. When your columns have other names, override billableId(), billableEmail() or billableName() as well.

app/DataStores/UserDataStore.php
<?php
// app/DataStores/UserDataStore.php
namespace App\DataStores;

class UserDataStore extends AppDataStore
{
    public $objectName = 'users';
}
PHP
use App\Billing\BillableUser;
use App\DataStores\UserDataStore;

$user = new BillableUser(UserDataStore::findById(1));

$sub = $user->subscribe('price_monthly', ['trial_days' => 7]); // creates the customer on first use
var_dump($user->subscribed(), $user->onTrial());               // true, true
echo $user->activeSubscription()['plan_id'], "\n";             // price_monthly
echo $user->billingProviderId() === $sub->customerId ? "linked\n" : "not linked\n";

$charge = $user->charge(500, 'usd', ['description' => 'Setup fee']);

$user->cancelSubscription(atPeriodEnd: false);  // ends it now
var_dump($user->subscribed());                  // false

cancelSubscription() without arguments cancels at the end of the paid period: Stripe keeps the subscription active until then, and so does the row.

subscribed() and onTrial() read billing_subscriptions, not the provider. subscribe() and cancelSubscription() update the table; changes that happen at the provider (a renewal, a failed payment, a cancellation from the Stripe dashboard) reach it only through a webhook listener, shown in Keeping the table in step.

Webhooks

#

The provider tells your app about renewals, failed payments and cancellations through webhooks. Taphra checks each one and fires it as an event.

The endpoint

#

Extend BillingController and declare webhook() in your class, since only methods your own controller declares are URL actions:

app/Controllers/BillingWebhookController.php
<?php
// 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: runs after the listeners, for every accepted event.
    }
}
app/Config/routes.yml
POST:
  /billing/webhook: BillingWebhook/webhook
  /billing/webhook/:provider: BillingWebhook/webhook

The second route takes the provider name from the URL, for apps with more than one. Point the provider's dashboard at https://your-app.example/billing/webhook.

webhook() reads the raw request body, verifies it, emits the event and answers with JSON:

Answer When
200 {"received":true} the event was verified and dispatched
200 {"received":true,"duplicate":true} the same event id was already accepted; it is not dispatched again
400 {"error":"..."} unknown provider, bad or missing signature, or a body that is not a valid event
405 any method other than POST
500 the event id could not be recorded (the cache failed); the provider retries the delivery later

A listener that throws makes the request fail and releases the event id, so the provider's retry is accepted. BillingController does not check CSRF tokens: webhooks are authenticated by their signature.

How webhooks are checked

#
  • Signature. The Stripe-Signature header must carry a timestamp within webhook_tolerance seconds (300 by default) of the server clock and a v1 HMAC-SHA256 signature made with your webhook_secret. During a secret rotation Stripe sends one signature per active secret, and any match is accepted. An empty webhook_secret refuses every webhook.
  • Replays. Each event id is accepted once within twice the tolerance plus a minute (11 minutes by default), which covers the time a captured request would still pass the timestamp check. The ids are kept in the framework cache, so use a cache shared by all your servers (see Cache). Keep listeners idempotent anyway: a provider may send an event again after that window.
  • The null provider cannot verify anything, so it accepts webhooks only while tests run (PHPUnit or Pest loaded, or APP_ENV set to test or testing) and answers 400 everywhere else. allow_unsigned_webhooks: true in its config accepts them anyway, for local experiments only.

Listening for events

#

The controller emits each event through Taphra\Event under a provider-neutral name, with a WebhookEvent as the payload. A service provider's boot() is a good place for the listeners (see Events):

PHP
use Taphra\Billing\Results\SubscriptionResult;
use Taphra\Billing\Results\WebhookEvent;
use Taphra\Event;

Event::on('billing.subscription.created', function (WebhookEvent $event) {
    /** @var SubscriptionResult $sub */
    $sub = $event->object;
    // turn on the plan's features for $sub->customerId
});

Event::on('billing.invoice.payment_failed', function (WebhookEvent $event) {
    $customerId = $event->raw['data']['object']['customer'] ?? null;
    // tell the customer to update their card
});
Event Stripe event $event->object
billing.subscription.created customer.subscription.created SubscriptionResult
billing.subscription.updated customer.subscription.updated SubscriptionResult
billing.subscription.canceled customer.subscription.deleted SubscriptionResult
billing.subscription.trial_ending customer.subscription.trial_will_end SubscriptionResult
billing.charge.succeeded payment_intent.succeeded ChargeResult
billing.charge.failed payment_intent.payment_failed ChargeResult
billing.charge.refunded charge.refunded ChargeResult
billing.payment_method.attached payment_method.attached PaymentMethodResult
billing.payment_method.detached payment_method.detached PaymentMethodResult
billing.invoice.payment_succeeded invoice.payment_succeeded null (read raw)
billing.invoice.payment_failed invoice.payment_failed null (read raw)
billing.unknown any other event null

$event->providerType keeps Stripe's own name, $event->id the event id, $event->provider the provider's name and $event->raw the whole payload.

Keeping the table in step

#

Webhooks only emit events; nothing writes to billing_subscriptions unless you do. This listener applies every subscription event to the row of a customer your app created:

PHP
use Taphra\Billing\DataStore\BillingCustomerDataStore;
use Taphra\Billing\DataStore\BillingSubscriptionDataStore;
use Taphra\Billing\Results\WebhookEvent;
use Taphra\Event;

$syncSubscription = function (WebhookEvent $event): void {
    $sub      = $event->object; // a SubscriptionResult
    $customer = (new BillingCustomerDataStore('app_master'))->findByProviderId($sub->customerId, $event->provider);
    if ($customer === null) {
        return; // not a customer this app created
    }
    (new BillingSubscriptionDataStore('app_master'))->syncFromProvider(
        billingCustomerId: (int) $customer['id'],
        provider:          $event->provider,
        providerId:        $sub->id,
        planId:            $sub->planId,
        status:            $sub->status,
        trialEnd:          $sub->trialEnd,
        periodStart:       $sub->currentPeriodStart,
        periodEnd:         $sub->currentPeriodEnd,
        canceledAt:        $sub->canceledAt,
    );
};

foreach (['created', 'updated', 'canceled'] as $change) {
    Event::on("billing.subscription.$change", $syncSubscription);
}

Testing

#

In unit tests, give the facade a manager that uses the null provider: no network, no keys, and null_-prefixed ids. Reset it afterwards so other tests read billing.yml again:

PHP
use Taphra\Billing\Billing;
use Taphra\Billing\BillingManager;

protected function setUp(): void
{
    Billing::setManager(new BillingManager([
        'default_provider' => 'null',
        'providers'        => ['null' => ['driver' => 'null']],
    ]));
}

protected function tearDown(): void
{
    Billing::reset();
}

To test your webhook handling end to end, sign a payload with a test secret the way Stripe does and pass it to handle(), which runs the same checks as webhook() and returns the answer instead of sending it. rawBody() is the hook for supplying the body. This test runs the listener above against a customer row it creates first:

PHP
use App\Controllers\BillingWebhookController;
use Taphra\Billing\Billing;
use Taphra\Billing\DataStore\BillingCustomerDataStore;
use Taphra\Billing\DataStore\BillingSubscriptionDataStore;

Billing::configure([
    'default_provider' => 'stripe',
    'providers'        => ['stripe' => ['secret_key' => 'sk_test_unused', 'webhook_secret' => 'whsec_test']],
]);
(new BillingCustomerDataStore('app_master'))
    ->upsertForBillable(\App\Billing\BillableUser::class, 2, 'stripe', 'cus_1', '[email protected]', 'Grace');

$payload = json_encode([
    'id'   => 'evt_test_1',
    'type' => 'customer.subscription.created',
    'data' => ['object' => [
        'id' => 'sub_1', 'customer' => 'cus_1', 'status' => 'active',
        'items' => ['data' => [['price' => ['id' => 'price_monthly']]]],
    ]],
]);
$time = time();
$_SERVER['HTTP_STRIPE_SIGNATURE'] = "t=$time,v1=" . hash_hmac('sha256', "$time.$payload", 'whsec_test');

$controller = new class extends BillingWebhookController {
    public string $body = '';
    protected function rawBody(): string { return $this->body; }
};
$controller->body = $payload;

print_r($controller->handle());   // status 200, {"received":true}
print_r($controller->handle());   // status 200, {"received":true,"duplicate":true}
echo (new BillingSubscriptionDataStore('app_master'))->findByProviderId('sub_1')['status'], "\n"; // active

$_SERVER['HTTP_STRIPE_SIGNATURE'] = "t=$time,v1=" . str_repeat('0', 64);
$controller->body = str_replace('evt_test_1', 'evt_test_2', $payload);
print_r($controller->handle());   // status 400: the signature does not match

Limitations in 1.0

#
  • Version 1 has one payment provider, Stripe. The package README shows how to add another.
  • Each Stripe call is also written to app/tmp/Log/billing.log (see Logging).