Add per-customer SMS and Bird credentials to Frontdesk Integrations.
Deploy Ladill Frontdesk / deploy (push) Successful in 45s
Deploy Ladill Frontdesk / deploy (push) Successful in 45s
NotificationDispatcher sends via customer relay and skips Frontdesk wallet debit when tenant keys are configured. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -5,6 +5,9 @@ namespace App\Http\Controllers\Frontdesk;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\Frontdesk\Concerns\ScopesToAccount;
|
||||
use App\Models\WebhookEndpoint;
|
||||
use App\Services\Messaging\CustomerSmsClient;
|
||||
use App\Services\Messaging\MessagingCredentialsService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
@@ -13,7 +16,7 @@ class IntegrationController extends Controller
|
||||
{
|
||||
use ScopesToAccount;
|
||||
|
||||
public function edit(Request $request): View
|
||||
public function edit(Request $request, MessagingCredentialsService $credentials): View
|
||||
{
|
||||
$this->authorizeAbility($request, 'settings.view');
|
||||
$organization = $this->organization($request);
|
||||
@@ -40,6 +43,7 @@ class IntegrationController extends Controller
|
||||
'webhookEvents' => config('frontdesk.webhook_events', []),
|
||||
'integrations' => config('frontdesk.integrations', []),
|
||||
'icalUrl' => $this->signedIcalUrl($organization->id, $this->ownerRef($request)),
|
||||
'credential' => $credentials->forOrganization($organization),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -84,6 +88,96 @@ class IntegrationController extends Controller
|
||||
return back()->with('success', 'Integration settings saved.');
|
||||
}
|
||||
|
||||
public function saveSms(Request $request, MessagingCredentialsService $credentials): RedirectResponse
|
||||
{
|
||||
$this->authorizeAbility($request, 'settings.manage');
|
||||
$organization = $this->organization($request);
|
||||
|
||||
if (! app(\App\Services\Frontdesk\PlanService::class)->hasFeature($organization, 'integrations')) {
|
||||
return back()->with('error', 'Messaging integrations require Frontdesk Pro.');
|
||||
}
|
||||
|
||||
$data = $request->validate([
|
||||
'sms_api_key' => ['required', 'string', 'max:200'],
|
||||
'sms_sender_id' => ['required', 'string', 'max:11'],
|
||||
]);
|
||||
|
||||
$result = $credentials->validateAndSaveSms(
|
||||
$organization,
|
||||
$data['sms_api_key'],
|
||||
$data['sms_sender_id'],
|
||||
);
|
||||
|
||||
if (! ($result['ok'] ?? false)) {
|
||||
return back()->withInput()->with('error', $result['error'] ?? 'Could not save SMS credentials.');
|
||||
}
|
||||
|
||||
return back()->with('success', 'Ladill SMS connected. Host alerts will use your key and sender ID.');
|
||||
}
|
||||
|
||||
public function disconnectSms(Request $request, MessagingCredentialsService $credentials): RedirectResponse
|
||||
{
|
||||
$this->authorizeAbility($request, 'settings.manage');
|
||||
$organization = $this->organization($request);
|
||||
$credentials->disconnectSms($organization);
|
||||
|
||||
return back()->with('success', 'Ladill SMS disconnected.');
|
||||
}
|
||||
|
||||
public function saveBird(Request $request, MessagingCredentialsService $credentials): RedirectResponse
|
||||
{
|
||||
$this->authorizeAbility($request, 'settings.manage');
|
||||
$organization = $this->organization($request);
|
||||
|
||||
if (! app(\App\Services\Frontdesk\PlanService::class)->hasFeature($organization, 'integrations')) {
|
||||
return back()->with('error', 'Messaging integrations require Frontdesk Pro.');
|
||||
}
|
||||
|
||||
$data = $request->validate([
|
||||
'bird_api_key' => ['required', 'string', 'max:200'],
|
||||
'bird_from_email' => ['required', 'email', 'max:255'],
|
||||
'bird_from_name' => ['nullable', 'string', 'max:100'],
|
||||
]);
|
||||
|
||||
$result = $credentials->validateAndSaveBird(
|
||||
$organization,
|
||||
$data['bird_api_key'],
|
||||
$data['bird_from_email'],
|
||||
$data['bird_from_name'] ?? null,
|
||||
);
|
||||
|
||||
if (! ($result['ok'] ?? false)) {
|
||||
return back()->withInput()->with('error', $result['error'] ?? 'Could not save Bird credentials.');
|
||||
}
|
||||
|
||||
return back()->with('success', 'Ladill Bird connected. Host email alerts will use your key and from address.');
|
||||
}
|
||||
|
||||
public function disconnectBird(Request $request, MessagingCredentialsService $credentials): RedirectResponse
|
||||
{
|
||||
$this->authorizeAbility($request, 'settings.manage');
|
||||
$organization = $this->organization($request);
|
||||
$credentials->disconnectBird($organization);
|
||||
|
||||
return back()->with('success', 'Ladill Bird disconnected.');
|
||||
}
|
||||
|
||||
public function previewSenders(Request $request, CustomerSmsClient $sms): JsonResponse
|
||||
{
|
||||
$this->authorizeAbility($request, 'settings.manage');
|
||||
|
||||
$data = $request->validate([
|
||||
'sms_api_key' => ['required', 'string', 'max:200'],
|
||||
]);
|
||||
|
||||
$result = $sms->senders(trim($data['sms_api_key']));
|
||||
if (! ($result['ok'] ?? false)) {
|
||||
return response()->json(['error' => $result['error'] ?? 'Could not load senders.'], 422);
|
||||
}
|
||||
|
||||
return response()->json($result['data'] ?? []);
|
||||
}
|
||||
|
||||
protected function signedIcalUrl(int $organizationId, string $ownerRef): string
|
||||
{
|
||||
$token = hash_hmac('sha256', "{$organizationId}:{$ownerRef}", (string) config('app.key'));
|
||||
|
||||
@@ -7,6 +7,9 @@ use App\Models\CampaignRecipient;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
|
||||
/**
|
||||
* Campaign batch dispatch — orphaned until Campaign model exists.
|
||||
*/
|
||||
class DispatchCampaignJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
@@ -15,6 +15,10 @@ use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Campaign delivery job — orphaned until Campaign / CampaignRecipient models exist.
|
||||
* Wire to CustomerSmsClient / CustomerEmailClient + MessagingCredentialsService when campaigns ship.
|
||||
*/
|
||||
class SendCampaignMessageJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToOwner;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
|
||||
class MessagingCredential extends Model
|
||||
{
|
||||
use BelongsToOwner;
|
||||
|
||||
public const STATUS_VALID = 'valid';
|
||||
|
||||
public const STATUS_INVALID = 'invalid';
|
||||
|
||||
protected $table = 'frontdesk_messaging_credentials';
|
||||
|
||||
protected $fillable = [
|
||||
'owner_ref',
|
||||
'organization_id',
|
||||
'sms_api_key_encrypted',
|
||||
'sms_api_key_prefix',
|
||||
'sms_sender_id',
|
||||
'sms_status',
|
||||
'sms_validated_at',
|
||||
'sms_last_error',
|
||||
'bird_api_key_encrypted',
|
||||
'bird_api_key_prefix',
|
||||
'bird_from_email',
|
||||
'bird_from_name',
|
||||
'bird_status',
|
||||
'bird_validated_at',
|
||||
'bird_last_error',
|
||||
];
|
||||
|
||||
protected $hidden = [
|
||||
'sms_api_key_encrypted',
|
||||
'bird_api_key_encrypted',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'sms_validated_at' => 'datetime',
|
||||
'bird_validated_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function organization(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Organization::class);
|
||||
}
|
||||
|
||||
public function hasValidSms(): bool
|
||||
{
|
||||
return $this->sms_status === self::STATUS_VALID
|
||||
&& filled($this->sms_api_key_encrypted)
|
||||
&& filled($this->sms_sender_id);
|
||||
}
|
||||
|
||||
public function hasValidBird(): bool
|
||||
{
|
||||
return $this->bird_status === self::STATUS_VALID
|
||||
&& filled($this->bird_api_key_encrypted)
|
||||
&& filled($this->bird_from_email);
|
||||
}
|
||||
|
||||
public function smsApiKey(): ?string
|
||||
{
|
||||
if (! filled($this->sms_api_key_encrypted)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return Crypt::decryptString($this->sms_api_key_encrypted);
|
||||
} catch (\Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public function birdApiKey(): ?string
|
||||
{
|
||||
if (! filled($this->bird_api_key_encrypted)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return Crypt::decryptString($this->bird_api_key_encrypted);
|
||||
} catch (\Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static function encryptKey(string $plain): string
|
||||
{
|
||||
return Crypt::encryptString($plain);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Services\Frontdesk;
|
||||
|
||||
use App\Models\Organization;
|
||||
use App\Services\Billing\BillingClient;
|
||||
use App\Services\Messaging\MessagingCredentialsService;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class NotificationBillingService
|
||||
@@ -13,10 +14,25 @@ class NotificationBillingService
|
||||
protected NotificationPricingService $pricing,
|
||||
protected NotificationUsageService $usage,
|
||||
protected PlanService $plans,
|
||||
protected MessagingCredentialsService $credentials,
|
||||
) {}
|
||||
|
||||
public function usesCustomerEmail(Organization $organization): bool
|
||||
{
|
||||
return $this->credentials->forOrganization($organization)->hasValidBird();
|
||||
}
|
||||
|
||||
public function usesCustomerSms(Organization $organization): bool
|
||||
{
|
||||
return $this->credentials->forOrganization($organization)->hasValidSms();
|
||||
}
|
||||
|
||||
public function emailCostMinor(Organization $organization): int
|
||||
{
|
||||
if ($this->usesCustomerEmail($organization)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$allowance = $this->plans->freeEmailsPerMonth($organization);
|
||||
if ($allowance === null || $this->usage->emailCountThisMonth($organization) < $allowance) {
|
||||
return 0;
|
||||
@@ -27,6 +43,10 @@ class NotificationBillingService
|
||||
|
||||
public function canAffordEmail(Organization $organization): bool
|
||||
{
|
||||
if ($this->usesCustomerEmail($organization)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$cost = $this->emailCostMinor($organization);
|
||||
if ($cost <= 0) {
|
||||
return true;
|
||||
@@ -37,6 +57,10 @@ class NotificationBillingService
|
||||
|
||||
public function canAffordSms(Organization $organization, string $message): bool
|
||||
{
|
||||
if ($this->usesCustomerSms($organization)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$cost = $this->pricing->smsCostMinor($message);
|
||||
if ($cost <= 0) {
|
||||
return true;
|
||||
@@ -47,9 +71,16 @@ class NotificationBillingService
|
||||
|
||||
/**
|
||||
* Debit after a successful send. Returns false if the wallet could not be charged.
|
||||
* Customer relay keys bill the Ladill SMS/Bird wallet directly — never double-debit Frontdesk.
|
||||
*/
|
||||
public function chargeEmail(Organization $organization, string $reference, string $description): bool
|
||||
{
|
||||
if ($this->usesCustomerEmail($organization)) {
|
||||
$this->usage->recordEmail($organization, 0);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$cost = $this->emailCostMinor($organization);
|
||||
if ($cost <= 0) {
|
||||
$this->usage->recordEmail($organization, 0);
|
||||
@@ -68,6 +99,12 @@ class NotificationBillingService
|
||||
|
||||
public function chargeSms(Organization $organization, string $message, string $reference, string $description): bool
|
||||
{
|
||||
if ($this->usesCustomerSms($organization)) {
|
||||
$this->usage->recordSms($organization, 0);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$cost = $this->pricing->smsCostMinor($message);
|
||||
if ($cost <= 0) {
|
||||
$this->usage->recordSms($organization, 0);
|
||||
|
||||
@@ -10,15 +10,17 @@ use App\Models\User;
|
||||
use App\Models\Visitor;
|
||||
use App\Models\Visit;
|
||||
use App\Notifications\FrontdeskAlertNotification;
|
||||
use App\Services\Comms\EmailService;
|
||||
use App\Services\Comms\SmsService;
|
||||
use App\Services\Messaging\CustomerEmailClient;
|
||||
use App\Services\Messaging\CustomerSmsClient;
|
||||
use App\Services\Messaging\MessagingCredentialsService;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class NotificationDispatcher
|
||||
{
|
||||
public function __construct(
|
||||
protected EmailService $email,
|
||||
protected SmsService $sms,
|
||||
protected MessagingCredentialsService $credentials,
|
||||
protected CustomerEmailClient $customerEmail,
|
||||
protected CustomerSmsClient $customerSms,
|
||||
protected NotificationPreferenceService $preferences,
|
||||
protected NotificationBillingService $billing,
|
||||
) {}
|
||||
@@ -194,40 +196,94 @@ class NotificationDispatcher
|
||||
): bool {
|
||||
$notified = false;
|
||||
$reference = $visit ? 'visit-'.$visit->id.'-'.($event ?? 'alert') : 'host-'.$host->id;
|
||||
$credential = $this->credentials->forOrganization($organization);
|
||||
|
||||
if (in_array('email', $channels, true) && $host->email) {
|
||||
if (! $this->billing->canAffordEmail($organization)) {
|
||||
Log::info('Frontdesk host email skipped — insufficient wallet balance', [
|
||||
if (! $credential->hasValidBird()) {
|
||||
Log::info('Frontdesk host email skipped — Ladill Bird not connected', [
|
||||
'host_id' => $host->id,
|
||||
'organization_id' => $organization->id,
|
||||
]);
|
||||
} else {
|
||||
try {
|
||||
$this->email->send($host->email, $title, $message);
|
||||
if ($this->billing->chargeEmail($organization, $reference, "Host alert: {$title}")) {
|
||||
$notified = true;
|
||||
$apiKey = $credential->birdApiKey();
|
||||
if (! $apiKey) {
|
||||
Log::info('Frontdesk host email skipped — Bird credentials could not be decrypted', [
|
||||
'host_id' => $host->id,
|
||||
'organization_id' => $organization->id,
|
||||
]);
|
||||
} elseif (! $this->billing->canAffordEmail($organization)) {
|
||||
Log::info('Frontdesk host email skipped — insufficient wallet balance', [
|
||||
'host_id' => $host->id,
|
||||
'organization_id' => $organization->id,
|
||||
]);
|
||||
} else {
|
||||
try {
|
||||
$html = nl2br(e($message));
|
||||
$sent = $this->customerEmail->send(
|
||||
$apiKey,
|
||||
(string) $credential->bird_from_email,
|
||||
$credential->bird_from_name,
|
||||
(string) $host->email,
|
||||
$title,
|
||||
$html,
|
||||
$message,
|
||||
);
|
||||
|
||||
if (! $sent) {
|
||||
Log::warning('Frontdesk host email failed', [
|
||||
'host_id' => $host->id,
|
||||
'error' => $this->customerEmail->lastError(),
|
||||
]);
|
||||
} elseif ($this->billing->chargeEmail($organization, $reference, "Host alert: {$title}")) {
|
||||
$notified = true;
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('Frontdesk host email failed', ['host_id' => $host->id, 'error' => $e->getMessage()]);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('Frontdesk host email failed', ['host_id' => $host->id, 'error' => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (in_array('sms', $channels, true) && $host->phone) {
|
||||
$smsBody = "{$title}: {$message}";
|
||||
if (! $this->billing->canAffordSms($organization, $smsBody)) {
|
||||
Log::info('Frontdesk host SMS skipped — insufficient wallet balance', [
|
||||
|
||||
if (! $credential->hasValidSms()) {
|
||||
Log::info('Frontdesk host SMS skipped — Ladill SMS not connected', [
|
||||
'host_id' => $host->id,
|
||||
'organization_id' => $organization->id,
|
||||
]);
|
||||
} else {
|
||||
try {
|
||||
$this->sms->send($host->phone, $smsBody);
|
||||
if ($this->billing->chargeSms($organization, $smsBody, $reference, "Host SMS: {$title}")) {
|
||||
$notified = true;
|
||||
$apiKey = $credential->smsApiKey();
|
||||
if (! $apiKey) {
|
||||
Log::info('Frontdesk host SMS skipped — SMS credentials could not be decrypted', [
|
||||
'host_id' => $host->id,
|
||||
'organization_id' => $organization->id,
|
||||
]);
|
||||
} elseif (! $this->billing->canAffordSms($organization, $smsBody)) {
|
||||
Log::info('Frontdesk host SMS skipped — insufficient wallet balance', [
|
||||
'host_id' => $host->id,
|
||||
'organization_id' => $organization->id,
|
||||
]);
|
||||
} else {
|
||||
try {
|
||||
$sent = $this->customerSms->send(
|
||||
$apiKey,
|
||||
(string) $host->phone,
|
||||
$smsBody,
|
||||
(string) $credential->sms_sender_id,
|
||||
);
|
||||
|
||||
if (! $sent) {
|
||||
Log::warning('Frontdesk host SMS failed', [
|
||||
'host_id' => $host->id,
|
||||
'error' => $this->customerSms->lastError(),
|
||||
]);
|
||||
} elseif ($this->billing->chargeSms($organization, $smsBody, $reference, "Host SMS: {$title}")) {
|
||||
$notified = true;
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('Frontdesk host SMS failed', ['host_id' => $host->id, 'error' => $e->getMessage()]);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('Frontdesk host SMS failed', ['host_id' => $host->id, 'error' => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,167 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Messaging;
|
||||
|
||||
use App\Models\MessagingCredential;
|
||||
use App\Models\Organization;
|
||||
|
||||
class MessagingCredentialsService
|
||||
{
|
||||
public function __construct(
|
||||
private CustomerSmsClient $sms,
|
||||
private CustomerEmailClient $email,
|
||||
) {}
|
||||
|
||||
public function forOrganization(Organization $organization): MessagingCredential
|
||||
{
|
||||
return MessagingCredential::query()->firstOrCreate(
|
||||
['organization_id' => $organization->id],
|
||||
['owner_ref' => $organization->owner_ref],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{ok: bool, error?: string, credential?: MessagingCredential, senders?: list<string>}
|
||||
*/
|
||||
public function validateAndSaveSms(Organization $organization, 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 1–11 characters.'];
|
||||
}
|
||||
|
||||
$me = $this->sms->me($apiKey);
|
||||
if (! ($me['ok'] ?? false)) {
|
||||
$credential = $this->forOrganization($organization);
|
||||
$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->forOrganization($organization);
|
||||
$credential->update([
|
||||
'sms_status' => MessagingCredential::STATUS_INVALID,
|
||||
'sms_last_error' => $error,
|
||||
]);
|
||||
|
||||
return ['ok' => false, 'error' => $error, 'credential' => $credential, 'senders' => $allowed];
|
||||
}
|
||||
|
||||
$credential = $this->forOrganization($organization);
|
||||
$credential->update([
|
||||
'owner_ref' => $organization->owner_ref,
|
||||
'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(Organization $organization, 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->forOrganization($organization);
|
||||
$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->forOrganization($organization);
|
||||
$credential->update([
|
||||
'bird_status' => MessagingCredential::STATUS_INVALID,
|
||||
'bird_last_error' => $error,
|
||||
]);
|
||||
|
||||
return ['ok' => false, 'error' => $error, 'credential' => $credential];
|
||||
}
|
||||
|
||||
$credential = $this->forOrganization($organization);
|
||||
$credential->update([
|
||||
'owner_ref' => $organization->owner_ref,
|
||||
'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(Organization $organization): MessagingCredential
|
||||
{
|
||||
$credential = $this->forOrganization($organization);
|
||||
$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(Organization $organization): MessagingCredential
|
||||
{
|
||||
$credential = $this->forOrganization($organization);
|
||||
$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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user