Web Push Notification (Error 400)

0

I'm trying to implement push notification, but so far nothing works properly. I wonder if I'm doing something wrong.

When I send the message I get the 400 UnauthorizedRegistration error. I think the same should be in the request parameters or something like that.

This is my server-side code:

 // Lado do servidor
 include('config.php'); // Aqui tenho as chaves VAPIDs
 //Depois da subscrição recebo estes dados no servidor
 $json = file_get_contents('php://input');
 $obj  = json_decode($json, true);

 //Extraio os dados e formo a requisição de envio de messagem
 $url = $obj['endpoint'];

 $subscription = [
   'keys' => [
      'p256dh' => $obj['keys']['p256dh'],
      'auth' => $obj['keys']['auth']
   ]
 ];

 $options = [
   'publicKey'  => $keys['Public_key'],
   'privateKey'     => $keys['Private_key']
 ];

 $message = array( 
    'title'     => 'Test push',
    'body'      => 'Message test.',
    'vibrate'   => 1,
    'sound'     => 1,
    'tag'       => 'pushes'
 );

 $fields = array( 
    'subscription'     => $subscription,
    'data'             => $message,
    'applicationKeys'  => $options, 
 );

 $headers = array(  
   'Content-Type : application/json',
   'TTL : 15'
 );

 // Inicio o envio e efetuo o envio
 $curl = curl_init();

 curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => json_encode($fields),
    CURLOPT_HTTPHEADER => $headers,
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
   echo "cURL Error #:" . $err;
} else {
  echo $response;
}


// Lado cliente
// Service Worker

 self.addEventListener('push', function (event) {
     if (!(self.Notification && self.Notification.permission === 'granted')) 
     {
          return;
     }

     var sendNotification = function(message, tag) {
          self.refreshNotifications();

          var title = "New post",
          icon = 'http://localhost/push/img/icon.png';

          message = message || 'The new post was published';
          tag = tag || 'posts';

          return self.registration.showNotification(title, {
             body: message,
             icon: icon,
             tag: tag
          });
     };

    if (event.data) {
       var data = event.data.json();
         event.waitUntil(
             sendNotification(data.message, data.tag)
       );
   } else {
        event.waitUntil(

 self.registration.pushManager.getSubscription().then(function(subscription) 
 {
            if (!subscription) {
                return;
            }

            return fetch('api/notifications/last?endpoint=' + 
     encodeURIComponent(subscription.endpoint)).then(function (response) {
                if (response.status !== 200) {
                    throw new Error();
                }

                // Examine the text in the response
                return response.json().then(function (data) {
                    if (data.error || !data.notification) {
                        throw new Error();
                    }

                    return sendNotification(data.notification.message);
                });
            }).catch(function () {
                return sendNotification();
            });
        })
      );
     }
  });

I have another question: you need to register with firebase or not, because in the documentation I read including web-push libraries they did not mention the registry. But since I did not want to use any library I preferred to make requests via curl.

    
asked by anonymous 06.09.2018 / 13:19

0 answers