FCMMessageing.php 2.2 KB

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