Send mail từ laravel sang ses có thông báo dữ liệu qua sns để biết tình trạng email có được mở không

Send mail từ laravel sang ses có thông báo dữ liệu qua sns để biết tình trạng email có được mở không

Việc gửi mail trong marketing là 1 trong các yếu tố quan trọng . Mình sẽ hướng dẫn kết nối laravel với ses và nhận các thông tin xem có mở hay chưa mở

Đầu tiên chúng ta cần biết luồng follow từ laravel ==> ses ==> sns ==> laravel hook 

Đầu tiên từ laravel : 

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Mail\Mailables\Headers;
use Illuminate\Queue\SerializesModels;

class TestEmail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     */

    public function __construct(protected $data)
    {
    }

    public function headers(): Headers
    {
        return new Headers(
            text: [
                'X-Email-Log-ID' => $this->data['id'],
            ]
        );
    }
    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: $this->data['subject'],
            // cực kì quan trọng nhé https://prnt.sc/UK192n65szSX
            using: [
                function ($message) {
                    $message->getHeaders()->addTextHeader(
                        'X-SES-CONFIGURATION-SET',
                        'tracking-mails'
                    );
                    $message->getHeaders()->addTextHeader(
                        'X-SES-MESSAGE-TAGS',
                        'email_id='.$this->data['id']
                    );
                },
            ],

        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'email.test',with:[
                'data' =>$this->data
        ] );
    }
    /**
     * Get the attachments for the message.
     *
     * @return array<int, Attachment>
     */
    public function attachments(): array
    {
        return [];
    }
}

Chúng ta cần để ý ở đây lưu ý đến   : X-SES-CONFIGURATION-SET là tên configuration sets trong ses 

2 Tiếp đến trong aws chúng ta cần config sns

Chúng ta cần đến https://ap-southeast-1.console.aws.amazon.com/sns/v3/home?region=ap-southeast-1#/topics để tạo topic như trong ảnh 

https://prnt.sc/E0PnmuXXZluW . Mình nên config Raw message delivery : Disabled với Endpoint : https://api.kiemtruyen.online/webhook/ses

3 : Connect giữa ses và sns

https://ap-southeast-1.console.aws.amazon.com/ses/home?region=ap-southeast-1#/configuration-sets 

bạn cần tạo configuration set với : Add event destination bạn chọn hết 

https://prnt.sc/HRW013GmDIn2

còn Amazon Simple Notification Service (SNS) topic chọn sns vừa tạo

4 : Webhook nhận tin 

<?php
namespace App\Http\Controllers\Webhook;
use App\Http\Controllers\Controller;
use App\Models\EmailLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class SesWebhookController extends Controller
{
    public function handle(Request $request)
    {
        $raw = $request->getContent();
        // Log::info('SNS Webhook Hit', [
        //     'raw' => $raw
        // ]);
        $payload = json_decode($raw, true);
        if (!$payload) {
            return response()->json([
                'error' => 'Invalid JSON'
            ], 400);
        }
        // SNS confirm subscription
        if (($payload['Type'] ?? '') === 'SubscriptionConfirmation') {
            $response = Http::get($payload['SubscribeURL']);
            Log::info('SNS Subscription Confirmed', [
                'status' => $response->status()
            ]);
            return response()->json([
                'message' => 'confirmed'
            ]);
        }
        // Notification
        if (($payload['Type'] ?? '') === 'Notification') {
            // SNS validation test
            if (($payload['Message'] ?? '') ===
                'Successfully validated SNS topic for Amazon SES event publishing.') {
                Log::info('SES SNS validation success');
                return response()->json([
                    'success' => true
                ]);
            }
            $message = json_decode($payload['Message'], true);
            if (!$message) {
                // Log::warning('SES Invalid Message JSON', [
                //     'message' => $payload['Message']
                // ]);
                return response()->json([
                    'error' => 'Invalid SES message'
                ], 400);
            }
            $eventType = $message['eventType'] ?? null;
            $mail = $message['mail'] ?? [];
            $messageId = $mail['messageId'] ?? null;
            // lấy custom header
            $headers = $mail['headers'] ?? [];
            $emailLogId = null;
            foreach ($headers as $header) {
                if (($header['name'] ?? '') === 'X-Email-Log-ID') {
                    $emailLogId = $header['value'] ?? null;
                    break;
                }
            }
            Log::info('SES Event Received', [
                'event' => $eventType,
                'message_id' => $messageId,
                'email_log_id' => $emailLogId,
            ]);

            $status = match ($eventType) {
                'Send' => 'sent',
                'Delivery' => 'delivered',
                'Open' => 'opened',
                'Click' => 'clicked',
                'Bounce' => 'bounce',
                'Complaint' => 'complaint',
                default => 'pending'
            };
            EmailLog::where('message_id', $messageId)
                ->orWhere('id', $emailLogId)
                ->update([
                    'status' => $status,
                    'meta' => $message
                ]);
        }
        return response()->json([
            'success' => true
        ]);
    }
}

Ở đây mình config router : 

Route::prefix('webhook')->group(function (){
    Route::post('/ses', [SesWebhookController::class, 'handle']);
});

Vậy là ta đã hoàn thành luồng follow gửi mail giữa laravel và ses