useApplicationDefaultCredentials(); $client->addScope('https://www.googleapis.com/auth/firebase.messaging'); $httpClient = $client->authorize(); $hostname = 'localhost'; $username = 'narKampen'; $pass = 'IfRLzj2HJBXA9eei'; $database = 'narKampen'; $conn = new mysqli($hostname, $username, $pass, $database); if (!$conn) { die("Connection Failed. ". mysqli_connect_error()); } mysqli_set_charset($conn,'utf8'); $messageType = $conn->real_escape_string(isset($_POST['type'])?$_POST['type']:""); $title = $conn->real_escape_string($_POST['title']); $messageToSend = $conn->real_escape_string($_POST['message']); $gameId = $conn->real_escape_string($_POST['gameId']); file_put_contents("FCMMessageDebug.log", "Called $messageType at " . Date(), FILE_APPEND); if ($messageType === "FCMNextPlayer") { $playerName = $conn->real_escape_string($_POST['playerName']); $token = getToken($conn, $gameId, $playerName); if ($token != null && $token != "") { file_put_contents("FCMMessageNextPlayerDebug.log", "token: $token title: $title message: $messageToSend", FILE_APPEND); sendMessage($httpClient, $token, $title, $messageToSend, "NextPlayer"); } } else if ($messageType === "InviteMessage") { $i = 0; while ($_POST['player' . $i] != null) { $token = getToken($conn, $gameId, $conn->real_escape_string($_POST['player' . $i])); sendMessage($httpClient, $token, $title, $messageToSend, "GameInvite"); } } else if ($messageType === "gameFinishedMessage") { $i = 0; while ($_POST['player' . $i] != null) { $token = getToken($conn, $gameId, $conn->real_escape_string($_POST['player' . $i])); sendMessage($httpClient, $token, $title, $messageToSend, "GameFinished"); } } function getToken($conn, $gameId, $playerName) { $sql = "SELECT messageToken FROM `gamePlayers` INNER JOIN users ON users.id = playerId WHERE gameId = $gameId and users.username = '$playerName'"; $result = $conn->query($sql); if ($result->num_rows == 1) { $returnArray = array(); $data = $result->fetch_assoc(); $token = $data['messageToken']; } else { echo "No games found for user"; } return $token; } function sendMessage($httpClient, $token, $title, $messageToSend, $tag) { // Your Firebase project ID $project = "narkampen"; // Creates a notification for subscribers to the debug topic $message = [ "message" => [ "token" => $token, "notification" => [ "body" => $messageToSend, "title" => $title, "tag" => $tag, ] ] ]; // Send the Push Notification - use $response to inspect success or errors $response = $httpClient->post("https://fcm.googleapis.com/v1/projects/{$project}/messages:send", ['json' => $message]); file_put_contents("FCMMessageDebugResponse.log", print_r($response,true), FILE_APPEND); file_put_contents("FCMMessageDebugSendMessage.log", print_r($message,true), FILE_APPEND); }