Google Firebase 通知适用于控制台,但不适用于 API

2024-01-01

从 firebase 控制台发送时通知工作正常,但从 API 发送时则不起作用。即使结果显示成功: {"multicast_id":5946406103096345260,"成功":1,"失败":0,"canonical_ids":0,"结果":[{"message_id":"0:1480093752122166%13791f60f9fd7ecd"}]}

不管怎样,代码如下:

<?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;
}

?> 

FCM 仅在使用时发送推送通知notification有效负载,例如:

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

}

也可以看看Firebase 文档 https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Google Firebase 通知适用于控制台,但不适用于 API 的相关文章

随机推荐