File: //var/www/quadcode/app/Jobs/SendGridAddContactTiListJob.php
<?php
namespace App\Jobs;
use App\Exceptions\SendGridJobException;
use App\Models\SendGridList;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use SendGrid;
class SendGridAddContactTiListJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
const LOG_CHANNEL = 'sendGrid';
private array $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function handle(): void
{
$apiKey = env('SENDGRID_API_KEY');
if (empty($apiKey)) {
$error = 'Need to fill SENDGRID_API_KEY in .env';
Log::channel(self::LOG_CHANNEL)->error($error);
throw new SendGridJobException($error);
}
$rules = [
'referrer' => ['required', 'string'],
'email' => ['required', 'string'],
'first_name' => ['string'],
'last_name' => ['string'],
'phone_number' => ['string'],
];
$validator = Validator::make($this->data, $rules);
if ($validator->fails()) {
$error = 'Validation failed';
Log::channel(self::LOG_CHANNEL)->error($error, ['data' => $this->data, 'errors' => $validator->errors()]);
throw new SendGridJobException($error);
}
$listName = $this->data['referrer'] ?? null;
/** @var SendGridList $sendGridList */
$sendGridList = SendGridList::query()->where('name', 'quadcode.com' . $listName)->first();
if (empty($sendGridList)) {
$error = 'SendGrid list not found';
Log::channel(self::LOG_CHANNEL)->error($error, $this->data);
throw new SendGridJobException($error);
}
$sendGrid = new SendGrid($apiKey);
$data = ['list_ids' => [$sendGridList->id]];
$contact = ['email' => $this->data['email']];
if (!empty($this->data['full_number'])) {
$contact['phone_number'] = str_replace('+', '', $this->data['full_number']);
} elseif (!empty($this->data['phone'])) {
$contact['phone_number'] = $this->data['phone'];
}
if (!empty($this->data['first_name'])) {
$contact['first_name'] = $this->data['first_name'];
}
if (!empty($this->data['last_name'])) {
$contact['last_name'] = $this->data['last_name'];
}
$data['contacts'][] = $contact;
Log::channel(self::LOG_CHANNEL)->info('Add or Update a Contact', $data);
try {
$response = $sendGrid->client->marketing()->contacts()->put($data);
$code = $response->statusCode();
$responseData = [
'code' => $code,
'headers' => $response->headers(),
'body' => json_decode($response->body(), true),
];
if (202 === $code) {
Log::channel(self::LOG_CHANNEL)->info('Add or Update a Contact', $responseData);
} else {
Log::channel(self::LOG_CHANNEL)->error('Add or Update a Contact', $responseData);
}
} catch (Exception $exception) {
Log::channel(self::LOG_CHANNEL)->error($exception->getMessage());
throw $exception;
}
}
}