首次打开我的应用程序时,我将用户的设备ID保存到数据库中的表中。当我使用下面的脚本从表格中选择发送推送通知时,
PHP脚本
$stmt = $conn->query("SELECT device_id from devices");
$gcmRegIds = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
array_push($gcmRegIds, $row['device_id']);
}
//echo json_encode($gcmRegIds);
$url = "https://fcm.googleapis.com/fcm/send";
$token =$gcmRegIds;
$serverKey = 'AIzxxyBbAxxxxxx-rJ0zoTExxx1Q';
$title = "New Alert from NCSC";
$body = 'test';
$notification = array('title' =>$title , 'message' => $body);
$data = array('timestamp'=>''.time(), 'id' => '90','display' => 'alert');
$arrayToSend = array('to' => $token, 'notification' => $notification, 'data' => $data);
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
我收到此错误,`“ to”字段必须是JSON字符串:
["fAx8pL2Ms9w:APA91bxxxxxnBidJg-kSxhA0DbfzmN9P6vrdxxxxxxxx-P"]
当我更改此行代码
$token = json_encode($gcmRegIds);
以json格式出现此错误
{
"multicast_id": 5909880630769187000,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"error": "InvalidRegistration"
}
]
}
这意味着我从数据库中选择的ID是从中获取的,但是当我在脚本中对设备ID进行硬编码时,它能够发送推送通知。