# Blinkerbot booking connector (PHP)

Tek dosya, bağımlılıksız PHP paketi. Blinkerbot asistanının aldığı randevuları
**sizin rezervasyon sisteminizde gerçek kayıt** olarak oluşturur.
Single-file, dependency-free PHP package that lets the Blinkerbot assistant
create **real bookings in your own booking system**.

- PHP 7.4 – 8.3, PDO (MySQL/MariaDB InnoDB veya SQLite), Composer gerekmez.
- Dosya: [`blinkerbot-booking.php`](blinkerbot-booking.php) · Örnek ayar: [`example-config.php`](example-config.php)
- Tam örnek (SQLite): [`tests/demo-handlers.php`](tests/demo-handlers.php) + [`tests/demo-endpoint.php`](tests/demo-endpoint.php)
- Sözleşme: [`docs/developers/booking/openapi.yaml`](../../docs/developers/booking/openapi.yaml)

[Türkçe](#türkçe) · [English](#english)

---

## Türkçe

### Paket ne yapar, siz ne yaparsınız?

Paket şunları hazır getirir: imza doğrulama (Standard Webhooks), bağlantı kodu
kurulumu, `ping`, tekrar koruma tablosu (randevu kaydıyla **aynı veritabanı
işleminde**), hata kodları, `test: true` (işlem geri alınır) ve saat
değişikliği (`replaces_booking_id`).

Siz yalnız kendi tablolarınızı okuyan/yazan **4 küçük fonksiyonu** yazarsınız:

| Fonksiyon | Ne döner |
|---|---|
| `listServices(): array` | `[['id' => 'svc_1', 'name' => 'Saç kesimi', 'duration_minutes' => 30, 'price' => 500, 'staff' => [['id' => 'st_1', 'name' => 'Ayşe']]]]` (`price`, `staff` isteğe bağlı) |
| `findSlots(array $q): array` | `$q`: `service_id`, `staff_id?`, `from`, `to`, `timezone`, `limit` (1–500, en erken boş saatler; paket sıralar ve fazlasını keser) → `[['start' => '2026-11-20T14:00:00+03:00', 'end' => '…', 'staff_id' => 'st_1']]` |
| `createBooking(PDO $pdo, array $b): array` | `$b`: `service_id`, `staff_id?`, `start`, `end`, `timezone`, `customer` (`name`, `phone`, `email?`), `channel`, `note?` → `['booking_id' => '123', 'status' => 'confirmed']` |
| `cancelBooking(PDO $pdo, string $id): array` | `['booking_id' => '123', 'status' => 'cancelled']` — zaten iptalse yine başarı |
| `getBooking(string $id): ?array` (isteğe bağlı) | `['booking_id', 'status' => 'confirmed'\|'pending'\|'cancelled', 'start', 'end', 'staff_id?']` ya da `null` |

İş hatasında bir kod fırlatın: `throw new BlinkerbotBookingError('slot_unavailable');`

Kodlar: `slot_unavailable`, `invalid_service`, `invalid_staff`, `outside_hours`,
`invalid_customer`, `booking_not_found`, `cancellation_not_allowed`
(`idempotency_mismatch` ve `request_in_progress` paketin kendisi tarafından üretilir).

### Kurulum (yaklaşık 15 dakika + 4 fonksiyon)

1. `blinkerbot-booking.php` dosyasını sunucunuza koyun.
2. `example-config.php` dosyasını `blinkerbot-config.php` olarak kopyalayıp
   veritabanı bağlantınızı yazın. `secret_file` için **web kökünün dışında**
   bir yol seçin (ör. `public_html`'in bir üstü).
3. Uç dosyasını oluşturun, ör. `public_html/blinkerbot-endpoint.php`:

```php
<?php
declare(strict_types=1);

require __DIR__ . '/../blinkerbot-booking.php';
$config = require __DIR__ . '/../blinkerbot-config.php';

final class SalonBooking implements BlinkerbotBookingHandler
{
    private PDO $db;
    public function __construct(PDO $db) { $this->db = $db; }

    public function listServices(): array { /* SELECT ... FROM services */ }
    public function findSlots(array $q): array { /* boş saatleriniz */ }
    public function createBooking(PDO $pdo, array $b): array
    {
        // $pdo üzerinde yazın; işlemi paket açar ve kapatır (beginTransaction/commit ÇAĞIRMAYIN).
        // Saat doluysa: throw new BlinkerbotBookingError('slot_unavailable');
        $pdo->prepare('INSERT INTO appointments (...) VALUES (...)')->execute([...]);
        return ['booking_id' => (string) $pdo->lastInsertId(), 'status' => 'confirmed'];
    }
    public function cancelBooking(PDO $pdo, string $id): array { /* UPDATE ... SET status = 'cancelled' */ return []; }
    public function getBooking(string $id): ?array { /* isteğe bağlı */ return null; }
}

$pdo = ($config['pdo'])();
$config['pdo'] = $pdo;
BlinkerbotBooking::run($config, new SalonBooking($pdo));
```

Fonksiyonları dizi olarak da verebilirsiniz:
`BlinkerbotBooking::run($config, ['listServices' => fn() => [...], 'findSlots' => ..., 'createBooking' => ..., 'cancelBooking' => ...]);`

4. **Bağlantı kodunu girin.** Blinkerbot paneli > Ayarlar > Randevu > Kendi
   sistemim > "Bağlantı kodu oluştur". Kod 2 saat geçerlidir ve tek
   kullanımlıktır. İki yol var:
   - **Komut satırı (önerilen):**
     `php public_html/blinkerbot-endpoint.php pair blk_pair_XXXX --url https://www.siteniz.com/blinkerbot-endpoint.php`
     — komutu **web sunucusunun kullanıcısıyla** çalıştırın (ör.
     `sudo -u www-data php …`); sır dosyası `0600` olduğundan başka bir
     kullanıcının yazdığı dosyayı web sunucusu okuyamaz. Adres `https://`
     olmalı (`http://` yalnız testte, `allow_insecure_api_base => true` ile).
   - **Web ekranı:** yapılandırmada `setup_key` (16+ karakter) verin ve
     `https://www.siteniz.com/blinkerbot-endpoint.php?blinkerbot-setup`
     adresini açın. Kod, adres ve kurulum anahtarını girin. Eşleşmeden sonra
     ekran yeniden eşlemeyi reddeder (`allow_repair` açmadıkça). İşiniz
     bitince `setup_key`'i silin.

   Paket imza sırrını `secret_file`'a `0600` izniyle yazar ve hiçbir yerde
   göstermez. Elle kurulumda sırrı `signing_secret` ya da
   `BLINKERBOT_SIGNING_SECRET` ortam değişkeni ile verebilirsiniz.
5. Panelde otomatik test çalışır (9 adım). Yeşil olunca hizmetleri eşleyip
   bağlantıyı açarsınız.

### Bilmeniz gerekenler

- **Tek adres, POST.** Bütün işlemler aynı adrese gelir; işlem adı imzalı
  gövdededir. `.htaccess` kuralı gerekmez.
- **Aynı işlem.** Tekrar koruma satırı (`blinkerbot_idempotency`, ilk istekte
  otomatik oluşturulur) ile sizin randevu kaydınız aynı PDO işleminde yazılır.
  Tablolarınız MySQL'de **InnoDB** olmalı. `createBooking`/`cancelBooking`
  içinde `beginTransaction`/`commit` çağırmayın.
- **Tekrar koruması.** Aynı `idempotency_key` + aynı içerik → ilk cevap, yeni
  kayıt yok. Aynı anahtar + farklı içerik → `idempotency_mismatch`. Aynı
  anahtarla eşzamanlı istek kilidi 3 sn bekler, sonra `request_in_progress`
  döner (Blinkerbot sonra tekrar dener). İş hataları saklanmaz; aynı anahtarla
  tekrar deneme yeniden çalışır. Anahtarlar 30 gün tutulur.
- **`test: true`.** İşlem baştan sona çalışır, sonra geri alınır; randevu
  kalmaz. Aynı test anahtarının cevabı saklanır, böylece panel testi "aynı
  anahtar → aynı randevu numarası" adımını doğrulayabilir.
- **Saat değişikliği.** `replaces_booking_id` gelirse paket önce eski randevuyu
  `cancelBooking` ile iptal eder, sonra yenisini `createBooking` ile yazar
  (aynı işlemde) ve `replaced: true` döner. Yeni randevu oluşmazsa eskisi de
  değişmez. Kendiniz yönetmek isterseniz `auto_replace => false`.
  `auto_replace` açıkken `ping` cevabı `capabilities: ["replaces_booking_id"]`
  bildirir; Blinkerbot saat değişikliğini bu sayede tek istekte yapar.
- **Uygulanmayan işlem.** `getBooking` yoksa (ya da işlem bilinmiyorsa) cevap
  HTTP 200 `{"ok":false,"error":{"code":"not_implemented"}}` olur; Blinkerbot
  bunu "desteklenmiyor" sayar ve panel testi o adımı atlar. Hiçbir zaman 5xx
  dönülmez: Blinkerbot her 5xx'i (501 dahil) "ulaşılamadı" sayar.
- **Boş saat listesi.** `find_slots` cevabı başlangıca göre sıralanır ve en çok
  `limit` (yoksa 500) boş saat döner; cevap 64 KB sınırının altında kalacak
  şekilde kesilir. `findSlots` `$q['limit']` değerine bakarak gereksiz saat
  üretmeyebilir. Geçersiz `limit` (tam sayı değil ya da 1'den küçük) → HTTP 400.
- **Çıktı.** Fonksiyonlarınızın yazdırdığı HTML/uyarılar cevaba karışmaz
  (`ob_start`, `display_errors` kapalı, her zaman `application/json` ve
  `Cache-Control: no-store`). Beklenmeyen hata HTTP 500 olur; ayrıntı ve sır
  cevaba yazılmaz.
- **Saat.** Bütün saatler ISO 8601 + saat farkıyla (`2026-11-20T14:00:00+03:00`).
  `DateTimeInterface` dönerseniz paket biçimlendirir. Sunucu saatiniz doğru
  olmalı (imza 5 dakika tolerans kullanır; NTP açık olsun).

### Sorun giderme

| Belirti | Çözüm |
|---|---|
| Panel testi "imza" adımında kalıyor, her istek 403 | Cloudflare Bot Fight Mode / WAF ya da güvenlik eklentisi (Wordfence, ModSecurity) isteği engelliyor. Bu adres için kural ekleyin. |
| 401 dönüyor | Sır yanlış ya da eksik (`php blinkerbot-endpoint.php status`), sunucu saati kaymış, ya da gövde bir ara katman tarafından yeniden kodlanıyor. Ham gövdeyi değiştirmeyin. |
| Komut satırından eşledikten sonra her istek 401, ama `status` "paired: yes" diyor | Sır dosyası (`0600`) SSH kullanıcınıza ait; web sunucusu başka bir kullanıcıyla (www-data, nobody, apache) çalışıyor ve dosyayı okuyamıyor. Eşleme komutunu o kullanıcıyla çalıştırın (`sudo -u www-data php blinkerbot-endpoint.php pair …`) ya da web kurulum ekranını kullanın. `status` dosyanın sahibini ve iznini gösterir; PHP hata günlüğünde `secret_file exists but is not readable` satırı görünür. |
| Panel testinde `get_booking` ya da `cancel_booking` "ulaşılamadı" | Kendi kodunuz bu işlemler için 5xx dönüyor. Desteklemediğiniz işlem için HTTP 200 `not_implemented` dönün (paket bunu kendisi yapar). |
| Panel testinde "boş saat" adımı "cevap çok büyük" | Cevap 64 KB'ı aşıyor. Paket bunu keser; kendi ucunuzu yazdıysanız `limit` değerine uyun ve saatleri sıralayıp kesin. |
| "200 ile HTML" | Uç dosyası yerine bir sayfa (bakım, giriş, 404 şablonu) dönüyor. Adresi tarayıcıda açın: GET için `405` JSON görmelisiniz. |
| Cevap eski ya da herkese aynı | Önbellek eklentisi bu adresi önbelleğe alıyor; adresi önbellek dışına alın. |
| Saatler bir saat kayık | Saat dilimi: saatleri `+03:00` gibi farkla döndürün. |
| `request_in_progress` sık geliyor | `createBooking` yavaş ya da tablo kilitli; sorgularınızı ve indeksleri kontrol edin. |

**Yerel geliştirme:** Blinkerbot'un bilgisayarınıza ulaşması için bir tünel
kullanın: `cloudflared tunnel --url http://localhost:8080` ya da
`ngrok http 8080`; çıkan `https://…` adresini `--url` olarak verin.

### Testler

```bash
php tests/unit.php                                     # imza (Standard Webhooks test vektörü), tekrar koruması, test modu...
php -S 0.0.0.0:8080 tests/demo-endpoint.php            # örnek SQLite uç
node scripts/booking-connector/fake-blinkerbot.mjs test --url http://localhost:8080/ --secret whsec_… --full --strict
```

---

## English

### What the package does, what you do

The package brings: signature verification (Standard Webhooks), pairing code
setup, `ping`, the idempotency table (written in the **same database
transaction** as your booking), error codes, `test: true` (rolled back) and
time changes (`replaces_booking_id`).

You write **four small functions** that read and write your own tables:
`listServices()`, `findSlots(array $q)`, `createBooking(PDO $pdo, array $b)`,
`cancelBooking(PDO $pdo, string $id)` and optionally `getBooking(string $id)`.
Shapes are in the Turkish table above. For a business error throw
`new BlinkerbotBookingError('slot_unavailable')` (codes: `slot_unavailable`,
`invalid_service`, `invalid_staff`, `outside_hours`, `invalid_customer`,
`booking_not_found`, `cancellation_not_allowed`; the package itself produces
`idempotency_mismatch` and `request_in_progress`).

### Setup

1. Upload `blinkerbot-booking.php`.
2. Copy `example-config.php` to `blinkerbot-config.php`, set your PDO
   connection and a `secret_file` path **outside the web root**.
3. Create the endpoint file (see the example above) and call
   `BlinkerbotBooking::run($config, $handlers)`.
4. Pair: in the Blinkerbot panel create a pairing code (valid 2 hours, one
   use), then either run
   `php blinkerbot-endpoint.php pair blk_pair_XXXX --url https://www.example.com/blinkerbot-endpoint.php`
   or enable the web screen with a `setup_key` (16+ chars) and open
   `…/blinkerbot-endpoint.php?blinkerbot-setup`. The secret is written to
   `secret_file` with mode 0600 and never displayed. For manual setup use
   `signing_secret` or the `BLINKERBOT_SIGNING_SECRET` environment variable.
5. The panel runs the 9-step test; when it is green you map services and
   switch the connection on.

### Good to know

- One URL, POST only; the operation is inside the signed body.
- Do not call `beginTransaction`/`commit` in your functions: the package wraps
  the idempotency row and your booking in one transaction (use InnoDB).
- Same key + same content returns the first answer; other content returns
  `idempotency_mismatch`; a parallel request with the same key waits up to 3 s
  and then gets `request_in_progress`. Business errors are not stored.
- `test: true` runs everything and rolls back; only the answer for the test
  key is kept so "same key → same booking id" can be checked.
- `replaces_booking_id`: the old booking is cancelled and the new one created
  in the same transaction (`replaced: true`); `auto_replace => false` hands it
  to your `createBooking` instead. With `auto_replace` on, `ping` answers
  `capabilities: ["replaces_booking_id"]` so Blinkerbot moves a booking in one
  request.
- Missing `getBooking` (or an unknown operation) → HTTP 200
  `{"ok":false,"error":{"code":"not_implemented"}}`: Blinkerbot treats it as
  "not supported" and the panel test skips that step. Never a 5xx: Blinkerbot
  treats every 5xx (501 included) as "unreachable".
- `find_slots` answers are sorted by start and cut to `limit` (absent → 500,
  maximum 500) and below the 64 KB answer limit. Your `findSlots` receives
  `$q['limit']` so it can stop early. An invalid `limit` → HTTP 400.
- Run the CLI `pair` command **as the web server user** (e.g.
  `sudo -u www-data php blinkerbot-endpoint.php pair …`). The secret file is
  0600; if your SSH user writes it, a web server running as www-data/nobody
  cannot read it and every request gets 401 while `status` (run as you) still
  says `paired: yes`. `status` prints the file owner and mode, and the PHP
  error log shows `secret_file exists but is not readable`. The setup screen
  avoids this. The endpoint URL must be `https://` (`http://` only for tests
  with `allow_insecure_api_base => true`).
- Stray output never reaches the response; unexpected errors become HTTP 500
  without details. Keep the server clock in sync (5 minute tolerance).
- Troubleshooting and local tunnels: see the table above (Cloudflare/WAF 403,
  401 clock or body re-encoding, HTML with 200, caching plugins, time zones).

### Tests

`php tests/unit.php` (PHP 7.4 – 8.3) and the contract suite with
`scripts/booking-connector/fake-blinkerbot.mjs` (see above).

License: MIT.
