# Recipe: custom domains in a Laravel app

Let the users of a Laravel app connect their own domain with Cnamio: a session route, the connect window in a Blade view, and a webhook route. There is no PHP SDK: this recipe calls the REST API with Laravel's HTTP client, exactly what the Node.js and Python SDKs do. The full guide is https://cnamio.com/agent-onboarding/SKILL.md; every route is in https://cnamio.com/openapi.json.

## 1. Configure

```bash
CNAMIO_APPLICATION_ID=app_…
CNAMIO_SECRET=cnm_sk_…        # server only, never committed
CNAMIO_OWNERSHIP_KEY=…        # any long random secret of yours
CNAMIO_WEBHOOK_SECRET=…
```

```php
// config/services.php
'cnamio' => [
    'application_id' => env('CNAMIO_APPLICATION_ID'),
    'secret' => env('CNAMIO_SECRET'),
    'ownership_key' => env('CNAMIO_OWNERSHIP_KEY'),
    'webhook_secret' => env('CNAMIO_WEBHOOK_SECRET'),
],
```

No account yet? A coding agent can call the MCP tool `start_signup` (or `POST https://api.cnamio.com/v1/agent/signup`) with your email, and work in the sandbox until you open the verification link.

## 2. A small client: `app/Services/Cnamio.php`

```php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class Cnamio
{
    /** A CNAME to your hosting plus a TXT only this user can satisfy (same values as recordsForUser in the SDKs). */
    public static function recordsFor(string|int $userId, string $target = 'customers.yourapp.com', string $prefix = 'cnamio-verify'): array
    {
        $value = substr(hash_hmac('sha256', (string) $userId, config('services.cnamio.ownership_key')), 0, 32);
        return [
            ['type' => 'CNAME', 'host' => '{SUBDOMAIN}', 'value' => $target, 'ttl' => 300],
            ['type' => 'TXT', 'host' => "_{$prefix}.{SUBDOMAIN}", 'value' => "{$prefix}={$value}", 'ttl' => 300],
        ];
    }

    /** POST /token: a 60-minute session bound to this user's records; returns what the connect window needs. */
    public static function createSession(string|int $userId, array $dnsRecords): array
    {
        $appId = config('services.cnamio.application_id');
        $token = Http::timeout(20)->post('https://api.cnamio.com/token', [
            'applicationId' => $appId, 'secret' => config('services.cnamio.secret'),
            'userId' => (string) $userId, 'dnsRecords' => $dnsRecords,
        ])->throw()->json('auth_token');
        return ['token' => $token, 'applicationId' => $appId, 'dnsRecords' => $dnsRecords];
    }

    /** Cnamio-Signature: sha256=<hex> of "{Cnamio-Timestamp}.{raw body}", timestamp within 5 minutes. */
    public static function verifyWebhook(string $rawBody, ?string $timestamp, ?string $signature): bool
    {
        $secret = config('services.cnamio.webhook_secret');
        if (!$secret || !preg_match('/^\d{1,12}$/', (string) $timestamp) || abs(time() - (int) $timestamp) > 300) {
            return false;
        }
        $expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
        return hash_equals($expected, (string) $signature);
    }
}
```

## 3. Routes

```php
// routes/web.php
use App\Services\Cnamio;
use Illuminate\Http\Request;

Route::post('/api/cnamio/session', function (Request $request) {
    $user = $request->user();
    try {
        return response()->json(Cnamio::createSession($user->id, Cnamio::recordsFor($user->id)));
    } catch (\Throwable $e) {
        return response()->json(['error' => 'cnamio_unavailable'], 502);
    }
})->middleware('auth');

// routes/api.php (no CSRF: Cnamio signs the request instead)
Route::post('/webhooks/cnamio', function (Request $request) {
    $raw = $request->getContent(); // the raw body: the signature is over these bytes
    if (!Cnamio::verifyWebhook($raw, $request->header('Cnamio-Timestamp'), $request->header('Cnamio-Signature'))) {
        return response('bad signature', 401);
    }
    $event = json_decode($raw, true);
    // Idempotent by $event['id']: the same event may arrive again.
    match ($event['type']) {
        'domain.added' => markDomainConnected($event['user_id'], $event['domain']),           // your code
        'domain.propagation.timeout' => markDomainFailed($event['user_id'], $event['domain']),
        default => null,
    };
    return response('ok');
});
```

Routes in `routes/api.php` are served under `/api`: register `https://yourapp.com/api/webhooks/cnamio` as the webhook URL.

## 4. Connect button: in a Blade view

```blade
<script src="https://connect.cnamio.com/sdk/v1.js"></script>
<button id="connect-domain">Connect your domain</button>
<script>
  document.getElementById('connect-domain').addEventListener('click', async () => {
    const r = await fetch('/api/cnamio/session', { method: 'POST', headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' } });
    if (!r.ok) return alert('Custom domains are unavailable right now.');
    window.cnamio.connectDomain({ ...(await r.json()), applicationName: 'Your App', locale: 'en' });
  });
</script>
```

## 5. Register the webhook and check it

```bash
curl -s -X PUT https://api.cnamio.com/v1/manage/webhook -u "$CNAMIO_APPLICATION_ID:$CNAMIO_SECRET" \
  -H 'Content-Type: application/json' -d '{"url":"https://yourapp.com/api/webhooks/cnamio"}'
curl -s -X POST https://api.cnamio.com/v1/manage/webhook-test -u "$CNAMIO_APPLICATION_ID:$CNAMIO_SECRET"   # → {"delivered":true}
```

With the test application's credentials every domain goes to the sandbox provider: `shop.example.com` connects at once, `conflict.example.com` shows a conflict, `pending.example.com` never propagates.
