Note, this question should be materially different from other questions with a similar name because of the fact that the API seems to have changed significantly over the past few years.
I am trying to send a push notification to an iOS device using GCM.
I have (I think) mostly set it up correctly. I have an API key from GCM, I've setup my SSL certificate on Apple Developer and I have my device correctly getting a registration id.
I've got a little test script written up to try to test it and I'm getting 401 unauthorized error in my result. Here's my code:
define('API_ACCESS_KEY', '<API KEY HERE>');
$fields = array(
'to' => '<REG_ID HERE>',
'registration_ids' => '<REG_ID HERE>',
'notification' => array('body' => 'test', 'title' => 'Test'),
$headers = array(
'Authorization: key=' . API_ACCESS_KEY,
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/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);
This key is unrestricted. To prevent unauthorized use and quota theft, restrict your key.
Key restriction lets you specify which web sites, IP addresses, or apps can use this key.
Update: There is now a visible note in the GCM docs saying:
Starting from Sept. 2016 new server key can only be created in the Firebase Console using the Cloud Messaging tab of the Settings panel. Existing projects that need to create a new server key can be imported in the Firebase console without affecting their existing configuration.
Update: It would also seem that Migrating from GCM to FCM fixes the issue for 401 Unauthorized Error.
If you are just starting to use GCM, instead of creating a project in the Google Developers Console, do it in the Firebase Console. After creating the project, simply use the auto-generated Server Key. Here are the steps where to find the Server Key:
For old GCM projects, you can simply Import the project to the Firebase Console:
I've been seeing a lot of this concern this past few days. It would seem that unrestricted keys return 401 errors and it may be because they are enforcing the security for all API keys (where you see the warning).
As such, what I commonly recommend
is to make use of the IP address restriction (seeing as this is for GCM, and it should be a Server Key) and add your server IP Address. See my answer here.