File: /var/www/quadcode-site/app/Console/Commands/ActiveCampaignSender.php
<?php
namespace App\Console\Commands;
use App\Helpers\ActiveCampaignHelper;
use App\Models\AbstractQueue;
use App\Models\ActiveCampaignQueue;
use App\Repository\ActiveCampaignQueueRepository;
use Illuminate\Console\Command;
use Symfony\Component\Console\Command\Command as CommandAlias;
use Throwable;
class ActiveCampaignSender extends Command
{
protected $signature = 'active-campaign:send';
protected $description = 'Process ActiveCampaign queue';
private int $errorsCount = 0;
private function setError(AbstractQueue $queueItem, string $error): void
{
$this->warn($error);
$queueItem->error($error);
$this->errorsCount++;
}
public function handle(ActiveCampaignQueueRepository $activeCampaignQueueRepository, ActiveCampaignHelper $activeCampaignHelper): int
{
$listId = getenv('ACTIVE_CAMPAIGN_LIST_ID');
if (!$activeCampaignHelper->check() || empty($listId)) {
$this->error('Need to fill ACTIVE_CAMPAIGN_HOST, ACTIVE_CAMPAIGN_TOKEN or ACTIVE_CAMPAIGN_LIST in .env');
}
$this->info('Send leads to ActiveCampaign');
$queue = $activeCampaignQueueRepository->getNeedToSend();
$this->line('Found items: ' . $queue->count());
foreach ($queue as $queueItem) {
/** @var ActiveCampaignQueue $queueItem */
try {
$queueItem->inProgress();
$data = json_decode($queueItem->data, true);
$data['email'] = strtolower($data['email']);
$data['phone'] = empty($data['phone']) ? null : $data['phone'];
if (empty($data['landing_url'])) {
$url = explode('://', getenv('APP_URL'));
$landingUrl = $url[1] ?? $url[0] . $data['referrer'];
$data['landing_url'] = $landingUrl;
}
$response = $activeCampaignHelper->searchContact(['email' => $data['email']]);
if (!$response->successful()) {
$this->setError($queueItem, 'Response error: ' . $response->status());
continue;
}
$responseData = $response->json();
$contact = $responseData['contacts'][0] ?? null;
if (empty($contact)) {
$this->line('Create person ' . $data['email']);
$response = $activeCampaignHelper->createContact($data);
if (!$response->successful()) {
$this->setError($queueItem, 'Response error: ' . $response->status());
continue;
}
$responseData = $response->json();
$contact = $responseData['contact'] ?? null;
}
if (empty($contact)) {
$this->setError($queueItem, 'Contact not found or create');
continue;
}
$activeCampaignHelper->subscribeContact($contact['id'], $listId);
if (!$response->successful()) {
$this->setError($queueItem, 'Response error: ' . $response->status());
continue;
}
$queueItem->done();
} catch (Throwable $exception) {
$this->setError($queueItem, $exception->getMessage());
}
}
if (!empty($this->errorsCount)) {
$this->warn('Errors count: ' . $this->errorsCount);
}
$this->info(PHP_EOL . 'Done');
return CommandAlias::SUCCESS;
}
}