Magento – Magento2 Push notification for IOS and Android

apimagento2.2mobilenotificationrest api

I am creating a native app for my magento2 store, Want to create facility of Mobile notification for different module (default and custom), I have certificate for IOS that will be use regarding this.

How can I integrate this certificate and send push notification via rest api, And want the same for Android as well.

Best Answer

Below approach may help you:

Write the respective function in helper class.

    namespace PackageName\ModuleName\Helper;

    class Data extends \Magento\Framework\App\Helper\AbstractHelper
    {
        const API_ACCESS_KEY = "";//Api Access key for android.
        const PASSPHASE = ""; // passphase for IOS

        protected $dir;

        /**
         * @param \Magento\Framework\App\Helper\Context $context
         * @param \Magento\Framework\Filesystem\DirectoryList $dir
         */
        public function __construct(
          \Magento\Framework\App\Helper\Context $context,
          \Magento\Framework\Filesystem\DirectoryList $dir
        ) {
            $this->dir = $dir;
            parent::__construct($context);
        }

        /**
         * send push notification for ios
         */
        public function sendIosPushNotification($message,$devicetoken){
            $mediaPath = $this->dir->getPath('media').'/';
            $tCert = $mediaPath.'/iospemfile/pushcert.pem';// your certificates file location
            $ctx = stream_context_create();
            stream_context_set_option($ctx, 'ssl', 'local_cert', $tCert);
            stream_context_set_option($ctx, 'ssl', 'passphrase', self::PASSPHASE);
            $applegateway='ssl://gateway.sandbox.push.apple.com:2195';//for sanbox mode
            //$applegateway='ssl://gateway.push.apple.com:2195';//for production mode
            $fp = stream_socket_client($applegateway, $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
            if (!$fp)exit("Failed to connect: $err $errstr" . PHP_EOL);
              $body['aps'] = array(
              'alert' => $message,
              'sound' => 'default',
              'badge' => 1,
              );
            // Encode the payload as JSON
            $payload = json_encode($body);
            // Build the binary notification
            $msg = chr(0) . pack('n', 32) . pack('H*', $devicetoken) . pack('n', strlen($payload)) . $payload;
            // Send it to the server
            $result = fwrite($fp, $msg, strlen($msg));
            //set blocking
            stream_set_blocking($fp,0);
            //usleep(500000);
            //Check response
            $apple_error_response = fread($fp, 6);
            $error_response = unpack('Ccommand/Cstatus_code/Nidentifier', $apple_error_response); //unpack the error response (first byte 'command" should always be 8)
            // Close the connection to the server
            fclose($fp);
            if (!$result)
            return 'Message not delivered' . PHP_EOL;
            else
            return 'Message successfully delivered' . PHP_EOL;
        }

        /**
         * send push notification for android
         */
        public function sendAndroidPushNotification($message,$fcmtoken){
            $data = array('message' => $message,'title' => 'test title') ;
            $fields = array('data'  => $data ,'to' => $fcmtoken);

            $headers = array(
                                'Authorization: key=' . self::API_ACCESS_KEY,
                                'Content-Type: application/json'
                            );

            #Send Reponse To FireBase Server
            $ch = curl_init();
            curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
            curl_setopt( $ch,CURLOPT_POST, true );
            curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
            curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
            curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
            $result = curl_exec($ch );
            curl_close( $ch );
         }

    }

After that you can use those helper functions from anywhere by injecting the helper class in constructor of the where you want to use those functions:

If your helper class object is $this->notificationHelper then you can call the functions following way:

//for ios
 $msg = "test push for ios";
 $deviceToken = "iosdevicetoken";
 $this->notificationHelper->sendIosPushNotification($msg ,$deviceToken);

 //for android
 $msg = "test push for android";
 $fcmToken = "fcmToken ";
 $this->notificationHelper->sendAndroidPushNotification($msg ,$fcmToken );
Related Topic