0
<?php

namespace Vendor\PushNotifications\Observer;

use \Magento\Framework\Event\ObserverInterface;
use \Magento\Framework\App\Config\ScopeConfigInterface;
use \Magento\Customer\Model\SessionFactory;
use \Magento\Customer\Model\CustomerFactory;
use \Magento\Framework\HTTP\ZendClient;
use \Magento\Framework\HTTP\Adapter\Curl;
use \Vendor\PushNotifications\Api\NotificationsRepositoryInterface;
use \Magento\Framework\App\Filesystem\DirectoryList;
use \Magento\Store\Model\StoreManagerInterface;

class SendPushNotifications implements ObserverInterface {

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;
    protected $customerSessionFactory;
    protected $_customerFactory;
    protected $_storeManager;
    protected $_httpAdapter;
    protected $_notificationsRepository;
    protected $_directoryList;
    protected $order;

    /**
     * Recipient email config path
     */
    const XML_PATH_IS_ENABLED_NOTIFICATION = 'customNotifications/general/enable';
    const XML_PATH_ANDROID_FIREBASE_SERVER_KEY = 'customNotifications/general/androidFirebaseServerKey';
    const DEVICE_TYPE = ['1' => 'ANDROID', '2' => 'IOS'];
    const FIREBASE_URL = "https://fcm.googleapis.com/fcm/send";

    public function __construct(
    DirectoryList $directoryList, NotificationsRepositoryInterface $notificationsRepository, Curl $httpAdapter, StoreManagerInterface $storeManager, CustomerFactory $customerFactory, SessionFactory $customerSessionFactory, ScopeConfigInterface $scopeConfig,\Magento\Sales\Model\Order $order
    ) {
        $this->_storeManager = $storeManager;
        $this->scopeConfig = $scopeConfig;
        $this->customerSessionFactory = $customerSessionFactory;
        $this->_customerFactory = $customerFactory;
        $this->_httpAdapter = $httpAdapter;
        $this->_notificationsRepository = $notificationsRepository;
        $this->_directoryList = $directoryList;
        $this->order = $order;
    }

    /**
     * customer register event handler
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer) {
        $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
        $notification = $observer->getData('notification');
        $currentsoreId = $notification['store_id'];
        $isEnable = $this->scopeConfig->getValue(self::XML_PATH_IS_ENABLED_NOTIFICATION, $storeScope,$currentsoreId);
        $currentsoreId->getWebsiteId();
        $customerSession = $this->customerSessionFactory->create();
        $customerFactory = $this->_customerFactory->create();

        if ($isEnable) {
            $notification = $observer->getData('notification');
            $customerId = ($customerSession->isLoggedIn()) ? $customerSession->getCustomerId() : $notification['customer_id'];
            $customerFactory->setWebsiteId('2');
            $customerData = $customerFactory->load($customerId);
            // Modified for common notification - By Deepak
            if ($customerData->getId()) {
                $deviceType = $customerData->getData('device_type');
                return $this->sendPushNotificationToDevice($deviceType, [$customerData->getData('device_token')], $notification);
            }
        }
    }
    // Modified for common notification - By Deepak
    private function sendPushNotificationToDevice($deviceType, $deviceToken, $notification) {
        $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
        $androidFirebaseServerKey = $this->scopeConfig->getValue(self::XML_PATH_ANDROID_FIREBASE_SERVER_KEY, $storeScope);

        $result = $this->_notificationsRepository->save($notification['customer_id'], $notification['message'], $notification['type'], $notification['targat_id'], $notification['status']);


        if ($result->getStatus()) {
            $notification['notification_id'] = $result->getNotificationId();
            $notification['body'] = $notification['message'];
            unset($notification['message']);
            $fields['registration_ids'] = $deviceToken;
            if ($deviceType) {
                if ($deviceType == 1) {
                    $fields['data'] = $notification;
                } elseif ($deviceType == 2) {
                    $notification['sound'] = 'Enabled';
                    $fields['notification'] = $notification;
                }
            }

            $headers = [
                'Authorization: key=' . $androidFirebaseServerKey,
                'Content-Type: application/json',
                'Content-Length: ' . strlen(json_encode($fields))
            ];

            $this->_httpAdapter->write(\Zend_Http_Client::POST, self::FIREBASE_URL, '1.1', $headers, json_encode($fields));
            $response = $this->_httpAdapter->read();
            $this->_httpAdapter->close();
        }
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.