Search by

ktulchu / yii2-webhook-inbox

Ktulchu

Transactional webhook inbox for Yii2 and MySQL

Package info

github.com/Ktulchu/yii2-webhook-inbox

pkg:composer/ktulchu/yii2-webhook-inbox

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.1.0 2026-12-04 08:50 UTC

This package is auto-updated.

Last update: 2026-12-04 10:59:26 UTC


README

Transactional webhook inbox for Yii2 and MySQL. It stores authenticated webhook deliveries, deduplicates them and runs application handlers in a database transaction.

Derived from php-webhook-inbox (MIT). The PostgreSQL package remains independent. This package contains no business or payment-provider logic.

Requirements

The Composer requirements are PHP ^8.2, ext-pdo, ext-pdo_mysql and Yii2 ^2.0.53. Use Oracle MySQL with InnoDB for the inbox and the tables modified by the handler. See Compatibility for the versions verified for this release. MySQL 5.6 and 5.7 are end-of-life. MariaDB is outside the compatibility matrix.

Use a Yii2 application with its asset repositories and Composer plugins configured, as in Yii2 Basic. Composer reads repository settings from the root application.

Installation

Run this from your Yii2 application:

composer require ktulchu/yii2-webhook-inbox:^0.1

Alternatively, install directly from the GitHub VCS repository:

composer config repositories.webhook-inbox vcs https://github.com/Ktulchu/yii2-webhook-inbox.git
composer require ktulchu/yii2-webhook-inbox:^0.1

Migrations

Add to the existing console application configuration (preserve other migration namespaces):

'aliases' => [
    '@Ktulchu/Yii2WebhookInbox' => '@vendor/ktulchu/yii2-webhook-inbox/src',
],
'controllerMap' => [
    'migrate' => [
        'class' => yii\console\controllers\MigrateController::class,
        'migrationNamespaces' => ['Ktulchu\Yii2WebhookInbox\migrations'],
    ],
],

Run php yii migrate/up. If the application configures read replicas, point the migrate controller's db setting at a master-only connection with the same tablePrefix (for example, 'db' => 'dbMigration', with dbMigration configured against the primary without replicas). Yii reads the migration history while applying DDL to the primary. The migration honors Yii's table prefix and creates one InnoDB table. Its down operation deletes inbox history. MySQL DDL is not transactional.

Receive

use Ktulchu\Yii2WebhookInbox\Inbox;

$inbox = new Inbox(Yii::$app->db);
// Verify provider-specific authentication first, using exact request bytes.
// Extract the provider's stable event ID; source is trusted server configuration.
$result = $inbox->receive($source, $eventId, $rawBody);

accepted = durably inserted; duplicate = same source, event ID and exact raw body hash; conflict = same ID but different bytes. Map these outcomes to the provider's required HTTP response. Database errors must not be acknowledged as success. Do not call inside a transaction. Autocommit is required. IDs are binary and limited to 64/200 bytes. Default payload limit 256 KiB; the raw body is retained as a BLOB, including non-JSON data. Do not delete inbox rows while their deduplication window is active.

Process

use Ktulchu\Yii2WebhookInbox\EventHandler;
use Ktulchu\Yii2WebhookInbox\Worker;
use yii\db\Connection;

$handler = new class implements EventHandler {
    public function handle(Connection $db, array $event): void
    {
        $data = json_decode($event['payload'], true, 512, JSON_THROW_ON_ERROR);
        // Validate business fields. Update your own InnoDB tables via $db.
        // Do not call a remote service, change connection or manage transactions.
    }
};
$worker = new Worker(Yii::$app->db, $handler, 5);
$worker->runOnce();

For dedicated worker connections, configure session isolation before starting any transaction, for example on each connection open using Yii's afterOpen event:

'on afterOpen' => static function ($event): void {
    $event->sender->createCommand('SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED')->execute();
},

Use a dedicated master-only worker connection; ensure the handler uses that same connection for all database effects. This setting does not change the global server isolation level.

Configure a Worker instance under the worker property of Ktulchu\Yii2WebhookInbox\console\WorkerController in the host console controllerMap (for example, as webhook-worker). Run php yii webhook-worker/run continuously or php yii webhook-worker/run 1 for one attempt. A supervisor should restart processes on infrastructure failures. For external side effects, use a transactional outbox with its own deduplication.

Quick start: payment webhook example

This end-to-end example uses Yii2 Basic with a primary-only MySQL connection, no table prefix, and a fictional payment provider. Its HMAC protocol is for local demonstration only; use your real provider's authentication, event identity, acknowledgement and replay rules in production. The application owns the invoice table and the handler.

1. Install and prepare the database

Run composer require ktulchu/yii2-webhook-inbox:^0.1, configure the migration alias and namespace as shown above, then run php yii migrate/up. In a disposable development database, create a sample invoice:

CREATE TABLE demo_invoice (
    id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
    amount_minor BIGINT UNSIGNED NOT NULL,
    currency CHAR(3) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
    status VARCHAR(16) NOT NULL,
    payment_id VARBINARY(200) NULL,
    UNIQUE KEY uq_demo_payment (payment_id)
) ENGINE=InnoDB;

INSERT INTO demo_invoice (id, amount_minor, currency, status)
VALUES (1, 1500, 'RUB', 'pending');

Amounts are integers in minor currency units, not floating-point numbers.

2. Receive the authenticated request

Create controllers/DemoWebhookController.php:

<?php
namespace app\controllers;

use Ktulchu\Yii2WebhookInbox\Inbox;
use Yii;
use yii\web\Controller;
use yii\web\Response;

final class DemoWebhookController extends Controller
{
    // This dedicated controller exposes only a signed machine-to-machine endpoint.
    public $enableCsrfValidation = false;

    public function actionReceive(): array
    {
        $request = Yii::$app->request;
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        if (!$request->isPost) {
            $response->statusCode = 405;
            $response->headers->set('Allow', 'POST');
            return ['error' => 'method_not_allowed'];
        }

        $rawBody = $request->getRawBody();
        if (strlen($rawBody) > 262144) {
            $response->statusCode = 413;
            return ['error' => 'payload_too_large'];
        }

        $secret = getenv('DEMO_WEBHOOK_SECRET');
        if ($secret === false || $secret === '') {
            throw new \RuntimeException('Webhook secret is not configured');
        }

        // Demonstration protocol only: HMAC-SHA256 of the exact request bytes.
        $signature = (string) $request->headers->get('X-Demo-Signature', '');
        if (!hash_equals(hash_hmac('sha256', $rawBody, $secret), $signature)) {
            $response->statusCode = 401;
            return ['error' => 'invalid_signature'];
        }

        try {
            $data = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
        } catch (\JsonException $e) {
            $response->statusCode = 400;
            return ['error' => 'invalid_json'];
        }

        $eventId = is_array($data) ? ($data['event_id'] ?? null) : null;
        if (!is_string($eventId) || $eventId === '' || strlen($eventId) > 200) {
            $response->statusCode = 400;
            return ['error' => 'invalid_event_id'];
        }

        // No surrounding transaction. Return success only after durable admission.
        $result = (new Inbox(Yii::$app->db))->receive('demo-payment', $eventId, $rawBody);
        $response->statusCode = $result === 'conflict' ? 409 : 200;
        return ['result' => $result];
    }
}

Do not expose a generic unsigned webhook endpoint. Configure request size limits and rate limits at the HTTP server as well. Database exceptions must remain non-success responses; never catch them and return HTTP 200.

3. Implement the business handler

Create services/PaymentEventHandler.php:

<?php
namespace app\services;

use Ktulchu\Yii2WebhookInbox\EventHandler;
use yii\db\Connection;

final class PaymentEventHandler implements EventHandler
{
    public function handle(Connection $db, array $event): void
    {
        $data = json_decode($event['payload'], true, 512, JSON_THROW_ON_ERROR);
        if (!is_array($data)
            || $event['source'] !== 'demo-payment'
            || ($data['event_id'] ?? null) !== $event['event_id']
            || ($data['type'] ?? null) !== 'invoice.paid'
            || !is_int($data['invoice_id'] ?? null) || $data['invoice_id'] < 1
            || !is_int($data['amount_minor'] ?? null) || $data['amount_minor'] < 1
            || !is_string($data['currency'] ?? null)
            || !is_string($data['payment_id'] ?? null)
            || $data['payment_id'] === '' || strlen($data['payment_id']) > 200
        ) {
            throw new \DomainException('Invalid payment event');
        }

        $invoice = $db->createCommand(
            'SELECT * FROM {{%demo_invoice}} WHERE id = :id FOR UPDATE',
            [':id' => $data['invoice_id']]
        )->noCache()->queryOne();

        if ($invoice === false
            || (string) $invoice['amount_minor'] !== (string) $data['amount_minor']
            || $invoice['currency'] !== $data['currency']
        ) {
            throw new \DomainException('Invoice or payment amount mismatch');
        }

        // Business idempotency: the same payment may arrive under different event IDs.
        if ($invoice['status'] === 'paid' && $invoice['payment_id'] === $data['payment_id']) {
            return;
        }

        if ($invoice['status'] !== 'pending' || $invoice['payment_id'] !== null) {
            throw new \DomainException('Unexpected invoice state or conflicting payment');
        }

        $db->createCommand()->update('{{%demo_invoice}}', [
            'status' => 'paid',
            'payment_id' => $data['payment_id'],
        ], ['id' => $data['invoice_id']])->execute();

        // Update other transactional business tables here using the same $db.
        // The worker acknowledges the inbox row and commits both changes together.
    }
}

The unique payment ID additionally prevents one payment from being applied to two invoices in this example. In a real system, namespace payment identities by provider and implement its business state transitions. The example deliberately rejects unsupported event types and conflicting payments; the worker retries handler exceptions according to its configured attempt limit.

4. Register the console worker

In config/console.php, before constructing the returned configuration array, create a dedicated connection using Yii2 Basic's primary-only config/db.php:

$workerConfig = require __DIR__ . '/db.php';
$workerConfig['enableSlaves'] = false;
$workerConfig['slaves'] = [];
$workerConfig['on afterOpen'] = static function ($event): void {
    $event->sender->createCommand(
        'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED'
    )->execute();
};
$workerDb = \Yii::createObject($workerConfig);

Add this entry to the existing controllerMap (keep the migration configuration):

'webhook-worker' => [
    'class' => \Ktulchu\Yii2WebhookInbox\console\WorkerController::class,
    'worker' => new \Ktulchu\Yii2WebhookInbox\Worker(
        $workerDb,
        new \app\services\PaymentEventHandler(),
        5
    ),
],

The worker connection must point to the same primary database and table prefix as the receiver and invoice table. Do not start a transaction in the handler or open another connection.

5. Try it locally

In a development shell, generate a temporary secret and run the Yii2 Basic development server:

export DEMO_WEBHOOK_SECRET="$(php -r 'echo bin2hex(random_bytes(32));')"
php yii serve --port=8080 &
body='{"event_id":"evt-1","type":"invoice.paid","invoice_id":1,"amount_minor":1500,"currency":"RUB","payment_id":"pay-1"}'
signature=$(printf '%s' "$body" | php -r 'echo hash_hmac("sha256", stream_get_contents(STDIN), getenv("DEMO_WEBHOOK_SECRET"));')
curl -i -H "X-Demo-Signature: $signature" -H 'Content-Type: application/json' \
  --data-binary "$body" 'http://127.0.0.1:8080/index.php?r=demo-webhook/receive'
php yii webhook-worker/run 1
curl -i -H "X-Demo-Signature: $signature" -H 'Content-Type: application/json' \
  --data-binary "$body" 'http://127.0.0.1:8080/index.php?r=demo-webhook/receive'
php yii webhook-worker/run 1

Expected: the first HTTP response contains accepted, the second contains duplicate, and the second worker invocation finds no new eligible event. Inspect the database:

SELECT id, status, payment_id FROM demo_invoice WHERE id = 1;
SELECT event_id, status, attempts FROM webhook_inbox WHERE source = 'demo-payment';

Expected invoice: 1, paid, pay-1. Expected inbox: one row, evt-1, done, 1. For production, run php yii webhook-worker/run under a process supervisor and keep the provider-specific security and operational requirements below in mind.

Guarantees and limits

  • Unique binary (source, event_id); only MySQL duplicate-key error 1062 is translated into a duplicate/conflict, after reading the master. No INSERT IGNORE.
  • MySQL 8 uses SKIP LOCKED. MySQL 5.6/5.7 uses a single ordered blocking FOR UPDATE current read and can wait behind a worker holding the first eligible row. With REPEATABLE READ, either strategy can encounter deadlocks on the inbox readiness index during concurrent processing. Configure READ COMMITTED on dedicated worker connections and supervise worker restarts after deadlocks. The package uses the application's connection isolation setting.
  • Claim, handler effects and acknowledgement share one transaction and physical master connection. The host must use transactional InnoDB tables. A crash before commit releases locks and rolls back effects; no durable processing lease is needed.
  • Handler exceptions roll back to a savepoint and record a bounded retry (2^attempt seconds capped at one hour); after maxAttempts the row is failed. Only the exception class is retained, not potentially sensitive exception messages.
  • Deadlocks and loss of the transaction are infrastructure failures; propagate them rather than writing a retry without the lock. A supervisor must retry. A lock timeout or transaction failure can prevent a retry counter update. There is no exactly-once promise for external effects, arbitrary handler code or an event admitted under different IDs.
  • The worker owns its transaction, rejects nested/native transactions and routes queries to master without query cache. Do not invoke a handler that commits, uses DDL/nontransactional tables, or bypasses the connection contract.
  • Authentication, provider-specific deduplication semantics, rate limiting, retention, dead-letter redrive and monitoring belong to the application. No HTTP controller with a generic signature protocol is exposed.

Compatibility

Verification Environment
GitHub Actions CI PHP 8.2 and 8.4 across the MySQL 5.6, 5.7, 8.0 and 8.4 matrix
Independent integration and concurrency acceptance Yii2 Basic 2.0.55 and PHP 8.2.36 on MySQL 5.6.51, 5.7.44, 8.0.46 and 8.4.13
Targeted installation and replication recheck All four exact MySQL versions with real asynchronous replication, migration rollback and reapplication, and session isolation across worker reconnects

The independent concurrency run submitted 100 identical requests and processed 1,000 unique events with three workers at both isolation levels on each MySQL version. It found no lost events or repeated business operations. REPEATABLE READ required retries after deadlocks. Results describe that test environment and workload.

Development

Run composer install, composer lint and composer test. Integration tests require a dedicated disposable MySQL database because the suite drops its own tables. Set INBOX_DSN, INBOX_USER and INBOX_PASSWORD. The built-in concurrent tests use READ COMMITTED. The built-in deadlock test injects a driver exception. The independent acceptance exercised actual server deadlocks and lock wait timeouts.

License

MIT, with attribution to the original php-webhook-inbox project. See third-party licenses for the audited Yii2 Basic dependency set. Composer resolves dependencies separately for each application.