67 lines
1.8 KiB
PHP
67 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use RuntimeException;
|
|
|
|
class ResendEmailService
|
|
{
|
|
private string $endpoint = 'https://api.resend.com/emails';
|
|
|
|
public function send(array $payload): array
|
|
{
|
|
$apiKey = config('services.resend.key');
|
|
|
|
if (! $apiKey) {
|
|
throw new RuntimeException('RESEND_API_KEY belum diatur.');
|
|
}
|
|
|
|
$body = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
|
|
|
if ($body === false) {
|
|
throw new RuntimeException('Gagal menyiapkan payload email untuk Resend.');
|
|
}
|
|
|
|
$ch = curl_init($this->endpoint);
|
|
|
|
if ($ch === false) {
|
|
throw new RuntimeException('Gagal inisialisasi cURL.');
|
|
}
|
|
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_POST => true,
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_HTTPHEADER => [
|
|
'Authorization: Bearer '.$apiKey,
|
|
'Content-Type: application/json',
|
|
],
|
|
CURLOPT_POSTFIELDS => $body,
|
|
CURLOPT_CONNECTTIMEOUT => 10,
|
|
CURLOPT_TIMEOUT => 30,
|
|
]);
|
|
|
|
$response = curl_exec($ch);
|
|
$statusCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
|
|
if ($response === false) {
|
|
$error = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
throw new RuntimeException('Resend request gagal: '.$error);
|
|
}
|
|
|
|
curl_close($ch);
|
|
|
|
$decoded = json_decode($response, true);
|
|
|
|
if ($statusCode < 200 || $statusCode >= 300) {
|
|
$message = is_array($decoded) && isset($decoded['message'])
|
|
? $decoded['message']
|
|
: $response;
|
|
|
|
throw new RuntimeException('Resend API error: '.$message);
|
|
}
|
|
|
|
return is_array($decoded) ? $decoded : ['raw' => $response];
|
|
}
|
|
} |