Add per-customer SMS and Bird Integrations for event messaging.
Deploy Ladill Events / deploy (push) Successful in 28s

Attendee and speaker comms use encrypted tenant relay credentials and skip platform-key fallback and Bird wallet double-debit.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
isaacclad
2026-07-12 17:05:54 +00:00
co-authored by Cursor
parent 13b2bd9702
commit 6e42cd1cb2
21 changed files with 1095 additions and 80 deletions
@@ -0,0 +1,92 @@
<?php
namespace App\Services\Messaging;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class CustomerEmailClient
{
private ?string $lastError = null;
public function lastError(): ?string
{
return $this->lastError;
}
private function base(): string
{
return rtrim((string) config('smtp.customer_relay_url', 'https://ladill.com/api/smtp'), '/');
}
/** @return array{ok: bool, data?: array<string, mixed>, error?: string, status?: int} */
public function me(string $apiKey): array
{
try {
$res = Http::withToken($apiKey)->acceptJson()->timeout(15)
->get($this->base().'/me');
if ($res->status() === 401) {
return ['ok' => false, 'error' => 'Invalid Bird API key.', 'status' => 401];
}
if ($res->failed()) {
return [
'ok' => false,
'error' => (string) ($res->json('error') ?: 'Could not validate Bird credentials.'),
'status' => $res->status(),
];
}
return ['ok' => true, 'data' => $res->json() ?? [], 'status' => $res->status()];
} catch (\Throwable $e) {
Log::warning('Customer Bird meta request failed', ['error' => $e->getMessage()]);
return ['ok' => false, 'error' => 'Could not reach Ladill Bird. Please try again.'];
}
}
public function send(
string $apiKey,
string $from,
?string $fromName,
string $to,
string $subject,
string $html,
?string $text = null,
): bool {
$this->lastError = null;
try {
$res = Http::withToken($apiKey)->acceptJson()->timeout(30)
->post($this->base().'/send', array_filter([
'from' => $from,
'from_name' => $fromName,
'to' => [$to],
'subject' => $subject,
'html' => $html,
'text' => $text,
], fn ($value) => $value !== null && $value !== ''));
if ($res->status() === 402) {
$this->lastError = (string) ($res->json('error') ?: 'Insufficient Bird email credits. Top up Bird and try again.');
return false;
}
if ($res->failed()) {
$this->lastError = (string) ($res->json('error') ?: $res->json('message') ?: 'The email could not be sent.');
Log::warning('Customer email send failed', ['status' => $res->status()]);
return false;
}
return (bool) ($res->json('success') ?? true);
} catch (\Throwable $e) {
$this->lastError = 'Could not reach the email service. Please try again.';
Log::warning('Customer email send error', ['error' => $e->getMessage()]);
return false;
}
}
}
@@ -0,0 +1,94 @@
<?php
namespace App\Services\Messaging;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class CustomerSmsClient
{
private ?string $lastError = null;
public function lastError(): ?string
{
return $this->lastError;
}
private function base(): string
{
return rtrim((string) config('sms.customer_relay_url', 'https://ladill.com/api/sms'), '/');
}
/** @return array{ok: bool, data?: array<string, mixed>, error?: string, status?: int} */
public function me(string $apiKey): array
{
return $this->get($apiKey, '/me');
}
/** @return array{ok: bool, data?: array<string, mixed>, error?: string, status?: int} */
public function senders(string $apiKey): array
{
return $this->get($apiKey, '/senders');
}
public function send(string $apiKey, string $to, string $text, string $senderId): bool
{
$this->lastError = null;
try {
$res = Http::withToken($apiKey)->acceptJson()->timeout(30)
->post($this->base().'/send', [
'to' => $to,
'text' => $text,
'sender_id' => $senderId,
]);
if ($res->status() === 402) {
$this->lastError = (string) ($res->json('error') ?: 'Insufficient SMS credit. Top up your Ladill SMS wallet and try again.');
return false;
}
if ($res->failed()) {
$this->lastError = (string) ($res->json('error') ?: $res->json('message') ?: 'The SMS could not be sent.');
Log::warning('Customer SMS send failed', ['status' => $res->status()]);
return false;
}
return (bool) ($res->json('success') ?? true);
} catch (\Throwable $e) {
$this->lastError = 'Could not reach the SMS service. Please try again.';
Log::warning('Customer SMS send error', ['error' => $e->getMessage()]);
return false;
}
}
/** @return array{ok: bool, data?: array<string, mixed>, error?: string, status?: int} */
private function get(string $apiKey, string $path): array
{
try {
$res = Http::withToken($apiKey)->acceptJson()->timeout(15)
->get($this->base().$path);
if ($res->status() === 401) {
return ['ok' => false, 'error' => 'Invalid SMS API key.', 'status' => 401];
}
if ($res->failed()) {
return [
'ok' => false,
'error' => (string) ($res->json('error') ?: 'Could not validate SMS credentials.'),
'status' => $res->status(),
];
}
return ['ok' => true, 'data' => $res->json() ?? [], 'status' => $res->status()];
} catch (\Throwable $e) {
Log::warning('Customer SMS meta request failed', ['path' => $path, 'error' => $e->getMessage()]);
return ['ok' => false, 'error' => 'Could not reach Ladill SMS. Please try again.'];
}
}
}
@@ -0,0 +1,163 @@
<?php
namespace App\Services\Messaging;
use App\Models\MessagingCredential;
class MessagingCredentialsService
{
public function __construct(
private CustomerSmsClient $sms,
private CustomerEmailClient $email,
) {}
public function forOwner(string $ownerRef): MessagingCredential
{
return MessagingCredential::query()->firstOrCreate(
['owner_ref' => $ownerRef],
);
}
/**
* @return array{ok: bool, error?: string, credential?: MessagingCredential, senders?: list<string>}
*/
public function validateAndSaveSms(string $ownerRef, string $apiKey, string $senderId): array
{
$apiKey = trim($apiKey);
$senderId = trim($senderId);
if (! str_starts_with($apiKey, 'lsk_sms_live_')) {
return ['ok' => false, 'error' => 'SMS API keys must start with lsk_sms_live_.'];
}
if ($senderId === '' || strlen($senderId) > 11) {
return ['ok' => false, 'error' => 'Sender ID must be 111 characters.'];
}
$me = $this->sms->me($apiKey);
if (! ($me['ok'] ?? false)) {
$credential = $this->forOwner($ownerRef);
$credential->update([
'sms_status' => MessagingCredential::STATUS_INVALID,
'sms_last_error' => $me['error'] ?? 'Invalid SMS API key.',
]);
return ['ok' => false, 'error' => $me['error'] ?? 'Invalid SMS API key.', 'credential' => $credential];
}
$senders = $this->sms->senders($apiKey);
$approved = collect($senders['data']['data'] ?? [])->pluck('sender_id')->map(fn ($id) => (string) $id)->all();
$defaultSender = (string) ($senders['data']['default_sender'] ?? '');
$allowed = array_values(array_unique(array_filter([...$approved, $defaultSender])));
if ($allowed !== [] && ! in_array($senderId, $allowed, true)) {
$error = 'Sender ID is not approved for this SMS key. Approved: '.implode(', ', $allowed);
$credential = $this->forOwner($ownerRef);
$credential->update([
'sms_status' => MessagingCredential::STATUS_INVALID,
'sms_last_error' => $error,
]);
return ['ok' => false, 'error' => $error, 'credential' => $credential, 'senders' => $allowed];
}
$credential = $this->forOwner($ownerRef);
$credential->update([
'sms_api_key_encrypted' => MessagingCredential::encryptKey($apiKey),
'sms_api_key_prefix' => substr($apiKey, 0, 16),
'sms_sender_id' => $senderId,
'sms_status' => MessagingCredential::STATUS_VALID,
'sms_validated_at' => now(),
'sms_last_error' => null,
]);
return ['ok' => true, 'credential' => $credential->fresh(), 'senders' => $allowed];
}
/**
* @return array{ok: bool, error?: string, credential?: MessagingCredential}
*/
public function validateAndSaveBird(string $ownerRef, string $apiKey, string $fromEmail, ?string $fromName): array
{
$apiKey = trim($apiKey);
$fromEmail = strtolower(trim($fromEmail));
$fromName = trim((string) $fromName);
if (! str_starts_with($apiKey, 'lsk_live_') && ! str_starts_with($apiKey, 'lsk_acct_')) {
return ['ok' => false, 'error' => 'Bird API keys must start with lsk_live_ or lsk_acct_.'];
}
if (! filter_var($fromEmail, FILTER_VALIDATE_EMAIL)) {
return ['ok' => false, 'error' => 'Enter a valid from email address.'];
}
$me = $this->email->me($apiKey);
if (! ($me['ok'] ?? false)) {
$credential = $this->forOwner($ownerRef);
$credential->update([
'bird_status' => MessagingCredential::STATUS_INVALID,
'bird_last_error' => $me['error'] ?? 'Invalid Bird API key.',
]);
return ['ok' => false, 'error' => $me['error'] ?? 'Invalid Bird API key.', 'credential' => $credential];
}
$domains = collect($me['data']['verified_domains'] ?? [])->map(fn ($d) => strtolower((string) $d))->all();
$fromDomain = strtolower((string) (explode('@', $fromEmail, 2)[1] ?? ''));
if ($domains !== [] && ! in_array($fromDomain, $domains, true)) {
$error = 'From email must use a verified Bird domain ('.implode(', ', $domains).').';
$credential = $this->forOwner($ownerRef);
$credential->update([
'bird_status' => MessagingCredential::STATUS_INVALID,
'bird_last_error' => $error,
]);
return ['ok' => false, 'error' => $error, 'credential' => $credential];
}
$credential = $this->forOwner($ownerRef);
$credential->update([
'bird_api_key_encrypted' => MessagingCredential::encryptKey($apiKey),
'bird_api_key_prefix' => substr($apiKey, 0, 16),
'bird_from_email' => $fromEmail,
'bird_from_name' => $fromName !== '' ? $fromName : null,
'bird_status' => MessagingCredential::STATUS_VALID,
'bird_validated_at' => now(),
'bird_last_error' => null,
]);
return ['ok' => true, 'credential' => $credential->fresh()];
}
public function disconnectSms(string $ownerRef): MessagingCredential
{
$credential = $this->forOwner($ownerRef);
$credential->update([
'sms_api_key_encrypted' => null,
'sms_api_key_prefix' => null,
'sms_sender_id' => null,
'sms_status' => null,
'sms_validated_at' => null,
'sms_last_error' => null,
]);
return $credential->fresh();
}
public function disconnectBird(string $ownerRef): MessagingCredential
{
$credential = $this->forOwner($ownerRef);
$credential->update([
'bird_api_key_encrypted' => null,
'bird_api_key_prefix' => null,
'bird_from_email' => null,
'bird_from_name' => null,
'bird_status' => null,
'bird_validated_at' => null,
'bird_last_error' => null,
]);
return $credential->fresh();
}
}