Fullstack PHP & Laravel
Trang chủ / Module 9
⚡ Module 9 / 19 · 5 ngày 📅 Tuần 7 ●●●○ Khó

Realtime, file, thanh toán, notification & search trong Laravel

Những tính năng làm sản phẩm 'trông xịn': realtime với Laravel Reverb và broadcasting, lưu file trên S3 bằng presigned URL, thanh toán và subscription với Cashier/Stripe (và cổng nội địa), webhook an toàn, notification đa kênh, tìm kiếm với Scout + Meilisearch.

ReverbBroadcastingS3CashierWebhookScout
📌 Vì sao module này quan trọng

JD PHP lương cao (SaaS, e-commerce, fintech) gần như luôn có một trong các dòng "payment integration", "real-time", "search". Khó không nằm ở API của package, mà ở các vấn đề đi kèm: webhook đến hai lần hoặc sai thứ tự, file lớn làm treo PHP-FPM, sự kiện realtime trên nhiều server, đồng bộ dữ liệu tìm kiếm.

🎯 Mục tiêu học tập

  • Broadcast sự kiện realtime qua Reverb với private/presence channel có phân quyền
  • Upload và phục vụ file qua S3/R2 bằng presigned URL, xử lý ảnh bằng queue
  • Tích hợp subscription bằng Cashier (Stripe) và cổng thanh toán nội địa qua webhook
  • Xác minh chữ ký webhook, xử lý idempotent và bất đồng bộ
  • Tìm kiếm với Scout + Meilisearch/Typesense, notification đa kênh

Realtime với Reverb và broadcasting

final class TaskUpdated implements ShouldBroadcast
{
    public function __construct(public Task $task) {}

    public function broadcastOn(): array
    {
        return [new PrivateChannel("projects.{$this->task->project_id}")];
    }

    public function broadcastWith(): array            // chỉ gửi dữ liệu cần thiết
    {
        return TaskResource::make($this->task)->resolve();
    }
}

// routes/channels.php — phân quyền kênh
Broadcast::channel('projects.{project}', fn (User $user, Project $project) => $user->can('view', $project));

// Frontend (Laravel Echo)
Echo.private(`projects.${projectId}`).listen('TaskUpdated', (e) => queryClient.setQueryData(...));
  • Reverb: WebSocket server chính thức (giao thức Pusher), scale ngang nhiều node qua Redis. Thay thế: Pusher, Ably, Soketi.
  • Presence channel cho "ai đang xem board". Broadcast đi qua queue → cần worker chạy.
  • Database là nguồn sự thật; client reconnect thì tải lại dữ liệu, không trông chờ đủ mọi sự kiện.

File: S3, presigned URL, xử lý ảnh

// Upload trực tiếp từ trình duyệt lên S3 — PHP không phải giữ file lớn
['url' => $url, 'headers' => $headers] = Storage::disk('s3')->temporaryUploadUrl(
    "uploads/{$orgId}/" . Str::ulid() . '.jpg', now()->addMinutes(5)
);

// File riêng tư: link tải có hạn
$downloadUrl = Storage::disk('s3')->temporaryUrl($attachment->path, now()->addMinutes(10));

// Sau khi upload: job tạo thumbnail (Intervention Image / spatie/image), quét virus, ghi metadata
ProcessAttachment::dispatch($attachment->id);
  • Upload nhỏ qua form vẫn được, nhưng giới hạn upload_max_filesize, post_max_size, timeout — file lớn luôn dùng presigned/multipart.
  • spatie/laravel-medialibrary quản lý file gắn model, conversion, responsive image.
  • Phục vụ file công khai qua CDN; không bao giờ để file người dùng upload nằm trong thư mục PHP có thể thực thi.

Thanh toán: Cashier, webhook, cổng nội địa

// Subscription với Cashier (Stripe)
return $request->user()->currentOrganization
    ->newSubscription('default', 'price_pro_monthly')
    ->trialDays(14)
    ->checkout(['success_url' => route('billing.success'), 'cancel_url' => route('billing')]);

// Kiểm tra quyền theo gói
if (! $org->subscribed('default')) abort(402);

// Webhook tuỳ chỉnh: xác minh chữ ký trên raw body, ghi nhận idempotent, xử lý bằng queue
public function __invoke(Request $request)
{
    $payload = $request->getContent();
    $signature = hash_hmac('sha256', $payload, config('services.vnpay.secret'));
    abort_unless(hash_equals($signature, (string) $request->header('X-Signature')), 400);

    $event = json_decode($payload, true, flags: JSON_THROW_ON_ERROR);
    $inserted = WebhookEvent::insertOrIgnore(['id' => $event['id'], 'type' => $event['type'], 'payload' => $payload]);
    if ($inserted) ProcessPaymentWebhook::dispatch($event['id']);
    return response()->noContent();
}
  • Nguồn sự thật về thanh toán là webhook/IPN (hoặc gọi API kiểm tra trạng thái), không phải trang redirect "thành công" (người dùng có thể sửa URL).
  • Cổng nội địa (VNPay, MoMo, ZaloPay...) dùng chữ ký HMAC theo tài liệu từng bên — kiểm tra số tiền, mã đơn, trạng thái trong IPN khớp với đơn của bạn.
  • Webhook đến trùng/sai thứ tự → idempotent theo event id, quyết định theo trạng thái hiện tại; job đối soát hằng ngày.

Notification và tìm kiếm

// Notification đa kênh, chạy qua queue
final class TaskAssigned extends Notification implements ShouldQueue
{
    public function via(object $notifiable): array
    {
        return $notifiable->prefersEmail() ? ['database', 'broadcast', 'mail'] : ['database', 'broadcast'];
    }
    public function toMail(object $n): MailMessage { /* ... */ }
}

// Scout + Meilisearch
final class Task extends Model
{
    use Searchable;
    public function toSearchableArray(): array
    {
        return ['id' => $this->id, 'title' => $this->title, 'organization_id' => $this->organization_id];
    }
}
Task::search($q)->where('organization_id', $orgId)->paginate(20);   // LỌC TENANT trong truy vấn search
  • Scout đồng bộ index qua queue (SCOUT_QUEUE=true); có lệnh import lại toàn bộ khi cần.
  • Nhu cầu nhỏ: full-text index của MySQL/PostgreSQL có thể đủ trước khi thêm search engine.
  • Tiếng Việt: chuẩn hoá bỏ dấu để tìm "nguyen" ra "Nguyễn"; Meilisearch/Typesense xử lý tốt typo.

🏋️ Bài tập thực hành

Kanban realtime có gói trả phí

(1) Board Kanban cập nhật realtime qua Reverb (private channel có phân quyền), presence "ai đang xem". (2) Đính kèm file vào task bằng presigned upload lên MinIO/R2, job tạo thumbnail. (3) Gói Pro bằng Cashier Stripe (test mode), giới hạn tính năng theo gói; thêm một cổng thanh toán nội địa ở môi trường sandbox với IPN xác minh chữ ký. (4) Webhook idempotent, test bằng stripe trigger. (5) Notification khi được gán task (database + broadcast + mail). (6) Tìm kiếm task bằng Scout + Meilisearch có lọc tenant và test chứng minh không lộ dữ liệu tổ chức khác.

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Realtime có phân quyền kênh và chạy được nhiều node
  • File lớn đi thẳng lên object storage, file riêng tư dùng link có hạn
  • Trạng thái thanh toán chỉ cập nhật từ webhook đã xác minh, idempotent
  • Tìm kiếm luôn lọc theo tenant