Graphql for unsubscribing newsletter.
In magento 2 we have graphql for only subscribing to a newsletter. We don’t have an unsubscribe newsletter or can say magento doesn’t provide graphql for unsubscribe newsletter.
Here we come with a solution to create a graphql for unsubscribing newsletter.
You need to create a schema.graphqls file at
app/code/Magesan/Extension/etc/schema.graphqls
The schema.graphqls file will contains :
type Mutation {
unsubscribeEmailToNewsletter(email: String! @doc(description: "The email address that will unsubscribe to the store's newsletter.")): SubscribeEmailToNewsletterOutput @doc(description:"Unsubscribe the specified email to the store's newsletter.") @resolver(class: "Magesan\\Extension\\Model\\Resolver\\UnsubscribeEmailToNewsletter")
}
You need to create a file at :
app/code/Magesan/Extension/Model/Resolver/UnsubscribeEmailToNewsletter.php
<?php
declare(strict_types=1);
namespace Magesan\Extension\Model\Resolver;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\EnumLookup;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Newsletter\Model\SubscriptionManagerInterface;
use Magento\Newsletter\Model\Subscriber;
use Psr\Log\LoggerInterface;
class UnsubscribeEmailToNewsletter implements ResolverInterface
{
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @var EnumLookup
*/
private $enumLookup;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var SubscriptionManagerInterface
*/
private $subscriptionManager;
/**
* @var Subscriber
*/
private $subscriber;
/**
* __construct
*
* @param CustomerRepositoryInterface $customerRepository
* @param EnumLookup $enumLookup
* @param LoggerInterface $logger
* @param SubscriptionManagerInterface $subscriptionManager
* @param Subscriber $subscriber
*/
public function __construct(
CustomerRepositoryInterface $customerRepository,
EnumLookup $enumLookup,
LoggerInterface $logger,
SubscriptionManagerInterface $subscriptionManager,
Subscriber $subscriber
) {
$this->customerRepository = $customerRepository;
$this->enumLookup = $enumLookup;
$this->logger = $logger;
$this->subscriptionManager = $subscriptionManager;
$this->subscriber = $subscriber;
}
/**
* @inheritDoc
*/
public function resolve(
Field $field,
$context,
ResolveInfo $info,
array $value = null,
array $args = null
) {
$email = trim($args['email']);
if (empty($email)) {
throw new GraphQlInputException(
__('You must specify an email address to unsubscribe to a newsletter.')
);
}
$currentUserId = (int)$context->getUserId();
$storeId = (int)$context->getExtensionAttributes()->getStore()->getId();
$websiteId = (int)$context->getExtensionAttributes()->getStore()->getWebsiteId();
try {
$confirmCode = $this->subscriber->loadBySubscriberEmail($email, $websiteId)->getSubscriberConfirmCode();
if ($confirmCode) {
$subscriber = $this->isCustomerSubscription($email, $currentUserId)
? $this->subscriptionManager->unsubscribeCustomer($currentUserId, $storeId)
: $this->subscriptionManager->unsubscribe($email, $storeId, $confirmCode);
$status = $this->enumLookup->getEnumValueFromField(
'SubscriptionStatusesEnum',
(string)$subscriber->getSubscriberStatus()
);
} else {
throw new GraphQlInputException(__('Cannot unsubscribe newsletter.'));
}
} catch (LocalizedException $e) {
$this->logger->error($e->getMessage());
throw new GraphQlInputException(__('Cannot unsubscribe newsletter.'));
}
return ['status' => $status];
}
/**
* Returns true if a provided email equals to a current customer one
*
* @param string $email
* @param int $currentUserId
* @return bool
* @throws LocalizedException
* @throws NoSuchEntityException
*/
private function isCustomerSubscription(string $email, int $currentUserId): bool
{
if ($currentUserId > 0) {
$customer = $this->customerRepository->getById($currentUserId);
if ($customer->getEmail() == $email) {
return true;
}
}
return false;
}
}
Then you can access it in graphql Playground.
mutation {
unsubscribeEmailToNewsletter(email: "test@gmail.com") {
status
}
}
It will give you the response
{
"data": {
"unsubscribeEmailToNewsletter": {
"status": "UNSUBSCRIBED"
}
}
}
Happy Codding…