Google Firebase notifications working on console b

2019-04-09 07:17发布

问题:

The notification work just fine when sent from the firebase console, but don't work when sent from the API. Even when the result displays a success: {"multicast_id":5946406103096345260,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1480093752122166%13791f60f9fd7ecd"}]}

Anyway heres the code:

<?php
// Payload data you want to send to Android device(s)
// (it will be accessible via intent extras)    
$data = array('title' => 'Notification Title' ,'message' => 'Hello World!');

// The recipient registration tokens for this notification  
$ids = array('TOKEN');

// Send push notification via Google Cloud Messaging
sendPushNotification($data, $ids);

function sendPushNotification($data, $ids)
{
    // Insert real GCM API key from the Google APIs Console        
    $apiKey = 'API_KEY';

    // 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://fcm.googleapis.com/fcm/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;
}

?> 

回答1:

FCM only sends push notifications when using the notification payload, e.g.:

{ 
  "to: "registration token",
  "priority": "high",
  "notification": {
    "title": "Title",
    "text": "Text"
  },
  ...
}

}

See also Firebase Docs



回答2:

For those unfamiliar with php (as me) @Simon Heinzle answer might be a bit cryptic. It just means that in the original code these changes should be made:

$data = array('title' => 'Notification Title' ,'text' => 'Hello World!');
...
$post = array(
              'registration_ids'  => $ids,
              'priority'  => 'high',
              'notification' => $data,
              );

Note that you could change registration_ids (which is an array of tokens) by to (a single token) if you just need to send the notification to a single device. More options for the notifications can be found in the FCM docs.