feat: cli command to un-/register MailJet webhook url

This commit is contained in:
Björn Fromme
2026-04-29 10:36:04 +02:00
parent daf89f9189
commit a2bcedafc4
5 changed files with 349 additions and 1 deletions
+15
View File
@@ -1158,6 +1158,21 @@ Removes expired pending newsletter double opt-in requests.
- Scheduled cleanup removes all currently expired pending requests (`expires_at <= now`) as a safety net.
- Confirmed requests are converted into durable per-list newsletter consent records and then deleted.
#### app:mailjet:newsletter-webhook
```bash
php bin/console app:mailjet:newsletter-webhook register
php bin/console app:mailjet:newsletter-webhook remove 123
php bin/console app:mailjet:newsletter-webhook deactivate
```
Creates or deletes the Mailjet `unsub` callback for `POST /webhooks/mailjet/newsletter`.
- Uses `APP_BASE_URL` by default and appends the webhook path.
- Pass `--url` to target a different full webhook URL.
- `register` prints the API response payload so you can note the callback ID.
- `remove` and `deactivate` require the callback ID returned by Mailjet.
### 10.3 Setup Commands
#### app:crypto:generate-keys
@@ -0,0 +1,146 @@
<?php
declare(strict_types=1);
namespace App\Command;
use App\Exception\NewsletterProviderException;
use App\Service\MailjetApiClient;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
#[AsCommand(
name: 'app:mailjet:newsletter-webhook',
description: 'Creates or deletes the Mailjet newsletter webhook',
)]
final class MailjetNewsletterWebhookCommand extends Command
{
private const string ACTION_REGISTER = 'register';
private const string ACTION_REMOVE = 'remove';
private const string ACTION_DEACTIVATE = 'deactivate';
private const string EVENT_TYPE_UNSUBSCRIBE = 'unsub';
private const string WEBHOOK_PATH = '/webhooks/mailjet/newsletter';
private const int WEBHOOK_VERSION = 2;
public function __construct(
private readonly MailjetApiClient $mailjetApiClient,
#[Autowire('%env(APP_BASE_URL)%')]
private readonly string $defaultBaseUrl,
private readonly LoggerInterface $logger,
) {
parent::__construct();
}
protected function configure(): void
{
$this
->addArgument('action', InputArgument::REQUIRED, 'One of: register, remove, deactivate')
->addArgument('callback_id', InputArgument::OPTIONAL, 'Callback ID required for remove/deactivate')
->addOption('url', null, InputOption::VALUE_REQUIRED, 'Override the webhook URL to register');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$action = strtolower(trim((string) $input->getArgument('action')));
try {
return match ($action) {
self::ACTION_REGISTER => $this->register($io, $input->getOption('url')),
self::ACTION_REMOVE, self::ACTION_DEACTIVATE => $this->remove($io, $input->getArgument('callback_id')),
default => $this->invalidAction($io, $action),
};
} catch (NewsletterProviderException|\InvalidArgumentException $exception) {
$this->logger->error('Mailjet newsletter webhook command failed', [
'action' => $action,
'error' => $exception->getMessage(),
]);
$io->error($exception->getMessage());
return Command::FAILURE;
}
}
private function register(SymfonyStyle $io, mixed $overrideUrl): int
{
$webhookUrl = $this->resolveWebhookUrl($overrideUrl);
$payload = $this->mailjetApiClient->createEventCallbackUrl(self::EVENT_TYPE_UNSUBSCRIBE, $webhookUrl, self::WEBHOOK_VERSION);
$io->success(sprintf('Created Mailjet newsletter webhook at %s.', $webhookUrl));
$io->writeln($this->formatPayload($payload));
return Command::SUCCESS;
}
private function remove(SymfonyStyle $io, mixed $callbackId): int
{
$resolvedCallbackId = $this->resolveCallbackId($callbackId);
$this->mailjetApiClient->deleteEventCallbackUrl($resolvedCallbackId);
$io->success(sprintf('Deleted Mailjet newsletter webhook callback ID %d.', $resolvedCallbackId));
return Command::SUCCESS;
}
private function invalidAction(SymfonyStyle $io, string $action): int
{
$io->error(sprintf('Unknown action "%s". Use register, remove, or deactivate.', $action));
return Command::FAILURE;
}
private function resolveWebhookUrl(mixed $override): string
{
if (true === is_string($override) && '' !== trim($override)) {
$url = trim($override);
if (false === filter_var($url, FILTER_VALIDATE_URL)) {
throw new \InvalidArgumentException('The provided webhook URL is not valid.');
}
return rtrim($url, '/');
}
if ('' === trim($this->defaultBaseUrl)) {
throw new \InvalidArgumentException('APP_BASE_URL is not configured.');
}
return rtrim(trim($this->defaultBaseUrl), '/').self::WEBHOOK_PATH;
}
private function resolveCallbackId(mixed $callbackId): int
{
if (true === is_int($callbackId) && $callbackId > 0) {
return $callbackId;
}
if (true === is_string($callbackId) && true === ctype_digit(trim($callbackId))) {
$resolvedCallbackId = (int) trim($callbackId);
if ($resolvedCallbackId > 0) {
return $resolvedCallbackId;
}
}
throw new \InvalidArgumentException('A numeric callback ID is required for remove/deactivate.');
}
/**
* @param array<string, mixed> $payload
*/
private function formatPayload(array $payload): string
{
$encoded = json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if (false !== $encoded) {
return $encoded;
}
return var_export($payload, true);
}
}
+39 -1
View File
@@ -119,6 +119,28 @@ class MailjetApiClient
}
}
/**
* @return array<string, mixed>
*/
public function createEventCallbackUrl(string $eventType, string $url, int $version = 2, bool $isBackup = false): array
{
return $this->request('POST', 'eventcallbackurl', [
'json' => [
'EventType' => strtolower(trim($eventType)),
'Url' => $url,
'Version' => $version,
'isBackup' => $isBackup,
],
]);
}
public function deleteEventCallbackUrl(int $eventCallbackUrlId): void
{
$this->request('DELETE', sprintf('eventcallbackurl/%d', $eventCallbackUrlId), [
'allow_empty' => true,
]);
}
private function findOrCreateContactId(string $email): int
{
$contactId = $this->resolveContactId($email);
@@ -223,7 +245,9 @@ class MailjetApiClient
private function request(string $method, string $resource, array $options = []): array
{
$allow404 = true === ($options['allow_404'] ?? false);
$allowEmpty = true === ($options['allow_empty'] ?? false);
unset($options['allow_404']);
unset($options['allow_empty']);
$resourcePath = trim($resource, '/');
@@ -241,7 +265,21 @@ class MailjetApiClient
return [];
}
$payload = $response->toArray(false);
$content = $response->getContent(false);
if ('' === trim($content)) {
if (true === $allowEmpty && $statusCode < 400) {
return [];
}
throw new NewsletterProviderException(sprintf('Mailjet request returned an empty response for resource %s', $resource));
}
try {
$payload = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $exception) {
throw new NewsletterProviderException(sprintf('Mailjet request error for resource %s', $resource), previous: $exception);
}
if ($statusCode >= 400) {
$payloadSummary = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$payloadSummary = false === $payloadSummary ? null : $payloadSummary;
@@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace App\Tests\Command;
use App\Command\MailjetNewsletterWebhookCommand;
use App\Service\MailjetApiClient;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\CommandTester;
class MailjetNewsletterWebhookCommandTest extends TestCase
{
public function testRegisterCreatesWebhookAndPrintsPayload(): void
{
$mailjet = $this->createMock(MailjetApiClient::class);
$mailjet->expects(self::once())
->method('createEventCallbackUrl')
->with(
'unsub',
'https://my.ep-reisen.de/webhooks/mailjet/newsletter',
2,
false,
)
->willReturn([
'Data' => [
[
'ID' => 123,
],
],
]);
$mailjet->expects(self::never())->method('deleteEventCallbackUrl');
$tester = new CommandTester($this->createCommand($mailjet));
$tester->execute(['action' => 'register']);
self::assertSame(Command::SUCCESS, $tester->getStatusCode());
self::assertStringContainsString('Created Mailjet newsletter webhook', $tester->getDisplay());
self::assertStringContainsString('"ID": 123', $tester->getDisplay());
}
public function testRemoveDeletesWebhookById(): void
{
$mailjet = $this->createMock(MailjetApiClient::class);
$mailjet->expects(self::never())->method('createEventCallbackUrl');
$mailjet->expects(self::once())
->method('deleteEventCallbackUrl')
->with(321);
$tester = new CommandTester($this->createCommand($mailjet));
$tester->execute(['action' => 'remove', 'callback_id' => 321]);
self::assertSame(Command::SUCCESS, $tester->getStatusCode());
self::assertStringContainsString('Deleted Mailjet newsletter webhook callback ID 321', $tester->getDisplay());
}
public function testDeactivateUsesRemoveFlow(): void
{
$mailjet = $this->createMock(MailjetApiClient::class);
$mailjet->expects(self::never())->method('createEventCallbackUrl');
$mailjet->expects(self::once())
->method('deleteEventCallbackUrl')
->with(654);
$tester = new CommandTester($this->createCommand($mailjet));
$tester->execute(['action' => 'deactivate', 'callback_id' => '654']);
self::assertSame(Command::SUCCESS, $tester->getStatusCode());
self::assertStringContainsString('Deleted Mailjet newsletter webhook callback ID 654', $tester->getDisplay());
}
public function testRemoveFailsWithoutCallbackId(): void
{
$mailjet = $this->createMock(MailjetApiClient::class);
$mailjet->expects(self::never())->method('createEventCallbackUrl');
$mailjet->expects(self::never())->method('deleteEventCallbackUrl');
$tester = new CommandTester($this->createCommand($mailjet));
$tester->execute(['action' => 'remove']);
self::assertSame(Command::FAILURE, $tester->getStatusCode());
self::assertStringContainsString('A numeric callback ID is required', $tester->getDisplay());
}
private function createCommand(MailjetApiClient $mailjetApiClient): MailjetNewsletterWebhookCommand
{
return new MailjetNewsletterWebhookCommand(
$mailjetApiClient,
'https://my.ep-reisen.de',
$this->createMock(LoggerInterface::class),
);
}
}
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service;
use App\Service\MailjetApiClient;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
class MailjetNewsletterWebhookClientTest extends TestCase
{
public function testCreatesEventCallbackUrl(): void
{
$client = new MockHttpClient(static function (string $method, string $url, array $options): MockResponse {
self::assertSame('POST', $method);
self::assertSame('https://mailjet.test/eventcallbackurl', $url);
self::assertSame([
'EventType' => 'unsub',
'Url' => 'https://my.ep-reisen.de/webhooks/mailjet/newsletter',
'Version' => 2,
'isBackup' => false,
], json_decode((string) $options['body'], true, 512, JSON_THROW_ON_ERROR));
return new MockResponse(json_encode([
'Data' => [
[
'ID' => 456,
],
],
], JSON_THROW_ON_ERROR));
});
$mailjet = new MailjetApiClient($client, new NullLogger(), 'key', 'secret', 'https://mailjet.test', '111');
$response = $mailjet->createEventCallbackUrl('unsub', 'https://my.ep-reisen.de/webhooks/mailjet/newsletter');
self::assertSame(456, $response['Data'][0]['ID']);
}
public function testDeletesEventCallbackUrl(): void
{
$client = new MockHttpClient(static function (string $method, string $url, array $options): MockResponse {
self::assertSame('DELETE', $method);
self::assertSame('https://mailjet.test/eventcallbackurl/456', $url);
return new MockResponse('', ['http_code' => 204]);
});
$mailjet = new MailjetApiClient($client, new NullLogger(), 'key', 'secret', 'https://mailjet.test', '111');
$mailjet->deleteEventCallbackUrl(456);
}
}