1 <?php 2 3 declare(strict_types=1); 4 5 namespace App\Webhooks; 6 7 use PDO; 8 9 final class WebhookSender 10 { 11 public function __construct(private readonly PDO $db) {} 12 13 public function send(int $endpointId, string $event, array $data): bool 14 { 15 $stmt = $this->db->prepare('SELECT url, secret FROM webhook_endpoints WHERE id = ? AND active = 1'); 16 $stmt->execute([$endpointId]); 17 $endpoint = $stmt->fetch(PDO::FETCH_ASSOC); 18 19 if ($endpoint === false) { 20 return false; 21 } 22 23 $body = json_encode(['event' => $event, 'data' => $data, 'sent_at' => time()], JSON_THROW_ON_ERROR); 24 $signature = hash_hmac('sha256', $body, $endpoint['secret']); 25 $headers = ['Content-Type: application/json', 'X-Signature: sha256='.$signature]; 26 27 $ch = curl_init($endpoint['url']); 28 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 29 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 30 curl_setopt_array($ch, [ 31 CURLOPT_POST => true, 32 CURLOPT_POSTFIELDS => $body, 33 CURLOPT_RETURNTRANSFER => true, 34 CURLOPT_HTTPHEADER => $headers, 35 ]); 36 37 $response = curl_exec($ch); 38 $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); 39 $saved = $response === false ? curl_error($ch) : mb_substr($response, 0, 4000); 40 41 $this->db 42 ->prepare('INSERT INTO webhook_deliveries (endpoint_id, event, status, response, created_at) VALUES (?, ?, ?, ?, NOW())') 43 ->execute([$endpointId, $event, $status, $saved]); 44 45 return $status >= 200 && $status < 300; 46 } 47 }