When my app opens for the first time, I save the user's device ID into a table in my database. When I select from the table with my below script to send push notifications,
PHP SCRIPT
$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);
I get this error `Field "to" must be a JSON string:
["fAx8pL2Ms9w:APA91bxxxxxnBidJg-kSxhA0DbfzmN9P6vrdxxxxxxxx-P"]
when I change this line of code
$token = json_encode($gcmRegIds);
to json format I get this error
{
"multicast_id": 5909880630769187000,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"error": "InvalidRegistration"
}
]
}
which means the ID which I'm picking from the db is from, but when I hard code the device ID in the script, it's able to send the push notification.