|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Http\Controllers; |
| 4 | + |
| 5 | +use App\Mail\WaitlistWelcome; |
| 6 | +use Illuminate\Http\RedirectResponse; |
| 7 | +use Illuminate\Http\Request; |
| 8 | +use Illuminate\Support\Facades\Log; |
| 9 | +use Illuminate\Support\Facades\Mail; |
| 10 | +use Resend; |
| 11 | + |
| 12 | +class NewsletterController extends Controller |
| 13 | +{ |
| 14 | + /** |
| 15 | + * Add an email to the waitlist (Resend contacts) and send a welcome email via Resend. |
| 16 | + */ |
| 17 | + public function store(Request $request): RedirectResponse |
| 18 | + { |
| 19 | + $validated = $request->validate([ |
| 20 | + 'email' => ['required', 'email'], |
| 21 | + ], [ |
| 22 | + 'email.required' => 'Please enter your email address.', |
| 23 | + 'email.email' => 'Please enter a valid email address.', |
| 24 | + ]); |
| 25 | + |
| 26 | + $key = config('services.resend.key'); |
| 27 | + if (! $key) { |
| 28 | + Log::warning('Newsletter signup attempted but RESEND_API_KEY is not set.'); |
| 29 | + |
| 30 | + return back()->with('newsletter_error', 'Signup is temporarily unavailable. Please try again later.'); |
| 31 | + } |
| 32 | + |
| 33 | + try { |
| 34 | + $resend = Resend::client($key); |
| 35 | + $resend->contacts->create([ |
| 36 | + 'email' => $validated['email'], |
| 37 | + 'unsubscribed' => false, |
| 38 | + ]); |
| 39 | + |
| 40 | + $segmentId = config('services.resend.segment_id'); |
| 41 | + if ($segmentId) { |
| 42 | + $resend->contacts->segments->add($validated['email'], $segmentId); |
| 43 | + } |
| 44 | + |
| 45 | + try { |
| 46 | + Mail::mailer('resend') |
| 47 | + ->to($validated['email']) |
| 48 | + ->send(new WaitlistWelcome); |
| 49 | + } catch (\Throwable $mailError) { |
| 50 | + Log::warning('Waitlist welcome email failed (contact was added): '.$mailError->getMessage(), [ |
| 51 | + 'email' => $validated['email'], |
| 52 | + ]); |
| 53 | + } |
| 54 | + } catch (\Throwable $e) { |
| 55 | + $message = $e->getMessage(); |
| 56 | + if (str_contains($message, 'already exists') || str_contains($message, 'already in')) { |
| 57 | + return back()->with('newsletter_success', true); |
| 58 | + } |
| 59 | + Log::error('Newsletter signup failed: '.$message, [ |
| 60 | + 'email' => $validated['email'], |
| 61 | + 'exception' => $e, |
| 62 | + ]); |
| 63 | + |
| 64 | + return back()->with('newsletter_error', 'Something went wrong. Please try again later.'); |
| 65 | + } |
| 66 | + |
| 67 | + return back()->with('newsletter_success', true); |
| 68 | + } |
| 69 | +} |
0 commit comments