You're getting 401 Unauthorized
because GCM is only accepting requests from HTTPS-based hosts, which your local console is not.
The easiest way to verify this (if you don't already have HTTPS-based website) is:
STAGE 1 - getting HTTPS-enabled website
- Create account on CloudFlare
- Change your domain's DNS to CloudFlare's
- Enter your server's IP in CloudFlare console
- Enable free HTTPS (and disable cache - it may be tricky sometimes)
Now traffic to your website will be redirected through CloudFlare.
Traffic from your clients to CloudFlare will be encrypted, and traffic from CloudFlare to your server won't.
While it's not 100% secure, it allows to secure most common vector of attack - malicious internet provider etc and it takes very little effort to get free service worker-ready website.
If you want your own cert, you can use Let's Encrypt
STAGE 2 - putting GCM sender on your HTTPS server
I have example code for you in PHP:
<?
function sendPushNotification($data, $ids)
{
echo("<br><br><b>Sending notifications...</b>");
// Insert real GCM API key from the Google APIs Console
$apiKey = 'AIza...';
// Set POST request body
$post = array(
'registration_ids' => $ids,
'data' => $data,
);
// Set CURL request headers
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Initialize curl handle
$ch = curl_init();
// Set URL to GCM push endpoint
curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send');
// Set request method to POST
curl_setopt($ch, CURLOPT_POST, true);
// Set custom request headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Get the response back as string instead of printing it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set JSON post data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
// Actually send the request
$result = curl_exec($ch);
// Handle errors
if (curl_errno($ch))
{
echo 'GCM error: ' . curl_error($ch);
}
// Close curl handle
curl_close($ch);
// Debug GCM response
echo $result;
}
$data = array('message' => 'JAAAREEEEK!');
// Please note that currently push payload is not supported. However if you're reading this answer from the future it might work
// The recipient registration tokens for this notification
// https://developer.android.com/google/gcm/
$ids = ['registrationid1','registrationid2']
// Send push notification via Google Cloud Messaging
sendPushNotification($data, $ids);
I had exactly the same problem and this solution solved it. If you'll have any further problems, please give me a shout.