apiKey = config('services.mailerlite.api_key'); $this->groupId = config('services.mailerlite.group_id'); $this->baseUrl = config('services.mailerlite.base_url'); } /** * Subscribe a user to the newsletter * * @param string $email * @param string $name * @return bool */ public function subscribeToNewsletter($email, $name = null) { if (!$this->isConfigured()) { Log::error('MailerLite API key or Group ID not configured'); return false; } try { $data = [ 'email' => $email, 'groups' => [$this->groupId], 'status' => 'active', ]; if ($name) { $data['fields'] = [ 'name' => $name ]; } $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $this->baseUrl . 'subscribers', CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . $this->apiKey, 'Content-Type: application/json', 'Accept: application/json', ], CURLOPT_SSL_VERIFYPEER => true, CURLOPT_TIMEOUT => 30, ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $error = curl_error($ch); curl_close($ch); if ($error) { Log::error('MailerLite cURL Error: ' . $error); return false; } // Success codes: 200 (updated) or 201 (created) if ($httpCode === 200 || $httpCode === 201) { return true; } // If subscriber already exists (422), consider it a success if ($httpCode === 422) { return true; } Log::error('MailerLite API Error: HTTP ' . $httpCode . ' - ' . $response); return false; } catch (Exception $e) { Log::error('MailerLite Service Error: ' . $e->getMessage()); return false; } } /** * Check if the service is properly configured * * @return bool */ public function isConfigured() { return !empty($this->apiKey) && !empty($this->groupId); } }