FCMMessageing.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /* FCM - Messageing */
  3. $hostname = 'localhost';
  4. $username = 'narKampen';
  5. $pass = 'IfRLzj2HJBXA9eei';
  6. $database = 'narKampen';
  7. $conn = new mysqli($hostname, $username, $pass, $database);
  8. if (!$conn) {
  9. die("Connection Failed. ". mysqli_connect_error());
  10. }
  11. mysqli_set_charset($conn,'utf8');
  12. $messageType = $conn->real_escape_string(isset($_POST['type'])?$_POST['type']:"");
  13. $title = $conn->real_escape_string($_POST['title']);
  14. $messageToSend = $conn->real_escape_string($_POST['message']);
  15. $gameId = $conn->real_escape_string($_POST['gameId']);
  16. if ($messageType === "FCMNextPlayer") {
  17. $playerName = $conn->real_escape_string($_POST['playerName']);
  18. $token = getToken();
  19. if ($token != null && $token != "") {
  20. sendMessage($token);
  21. }
  22. } else if ($messageType === "InviteMessage") {
  23. $i = 0;
  24. while ($_POST['player' + $i] != null) {
  25. $token = getToken($gameId, $conn->real_escape_string($_POST['player' $i]));
  26. sendMessage($token);
  27. }
  28. }
  29. function getToken($gameId, $playerName) {
  30. $sql = "SELECT messageToken FROM `gamePlayers` INNER JOIN users ON users.id = playerId WHERE gameId = $gameId and users.username = '$playerName'";
  31. $result = $conn->query($sql);
  32. if ($result->num_rows == 1) {
  33. $returnArray = array();
  34. $data = $result->fetch_assoc();
  35. $token = $data['messageToken'];
  36. } else {
  37. echo "No games found for user";
  38. }
  39. return $token;
  40. }
  41. function sendMessage($token) {
  42. // Your Firebase project ID
  43. $project = "narkampen";
  44. // Creates a notification for subscribers to the debug topic
  45. $message = [
  46. "message" => [
  47. "token" => $token,
  48. "notification" => [
  49. "body" => $messageToSend,
  50. "title" => $title,
  51. ]
  52. ]
  53. ];
  54. // Send the Push Notification - use $response to inspect success or errors
  55. $response = $httpClient->post("https://fcm.googleapis.com/v1/projects/{$project}/messages:send", ['json' => $message]);
  56. }