first commit
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace KupShop\MailerLiteBundle\Controller;
|
||||
|
||||
use KupShop\MailerLiteBundle\MailerLite;
|
||||
use KupShop\UserBundle\Util\UserConsent;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\Routing\Annotation\Route;
|
||||
|
||||
class MailerLiteController extends AbstractController
|
||||
{
|
||||
/**
|
||||
* @Route(path="/_mailerlite/webhook/")
|
||||
*/
|
||||
public function webhookAction(Request $request, MailerLite $mailerlite, UserConsent $userConsent)
|
||||
{
|
||||
$data = [];
|
||||
|
||||
if ($mailerlite->error) {
|
||||
$data['mailerlite_error'] = $mailerlite->error;
|
||||
$response = new JsonResponse($data, 500);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
$mailerlite_signature = $request->headers->get('X-MailerLite-Signature');
|
||||
if (!$mailerlite_signature) {
|
||||
$data['signature_error'] = "'X-MailerLite-Signature' was not sent";
|
||||
$response = new JsonResponse($data, 403);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
$events_json = $request->getContent();
|
||||
$signature = $this->generateSignature($events_json, $mailerlite->api_key);
|
||||
if ($signature != $mailerlite_signature) {
|
||||
$data['signature_error'] = 'Signature mismatch';
|
||||
$response = new JsonResponse($data, 403);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
$events = json_decode($events_json, true);
|
||||
if ($events) {
|
||||
$events = $events['events'];
|
||||
foreach ($events as $event) {
|
||||
$event_type = $event['type'];
|
||||
if ($event_type == 'subscriber.unsubscribe') {
|
||||
foreach ($event['data'] as $subscriber) {
|
||||
$user = \User::createFromLogin($subscriber['email']);
|
||||
if (!$user || ($user->get_news == 'N')) {
|
||||
$update_res = 'skipped';
|
||||
} else {
|
||||
$update_res = ($userConsent->updateNewsletter($user->id, 'N') ? 'unsubscribed' : 'error');
|
||||
}
|
||||
$data[$event_type][$subscriber['email']] = $update_res;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$response = new JsonResponse($data);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function generateSignature($jsonPayload, $apiKey)
|
||||
{
|
||||
return base64_encode(
|
||||
hash_hmac('sha256', $jsonPayload, $apiKey, true)
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user