其实从 GCM 迁移到 FCM 并不难。来自this,据说你只需要更换:
gcm-http.googleapis.com/gcm/
到
fcm.googleapis.com/fcm/
这是从 mysql 数据库发送带有注册 ID 的 FCM 的示例:
首先创建一个函数来使用你的 serverKey 发送通知
function send_notification($tokens, $message){
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'data' => $message
);
$headers = array(
'Authorization:key =
AIzaYOUR_SERVER_KEY',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if($result === FALSE){
die('Curl failed : ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
使用上述功能需要查询registrationId的列表,例如:
$conn = mysqli_connect("localhost","dbuser","dbpass","dbname");
$sql = " Select Token From users";
$result = mysqli_query($conn,$sql);
$tokens = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$tokens[] = $row["Token"];
}
}
mysqli_close($conn);
$message = array("messageText" => " FCM PUSH NOTIFICATION TEST MESSAGE");
$message_status = send_notification($tokens,$message);
echo $message_status;