| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <?php
- /* FCM - Messageing */
- require_once '../vendor/autoload.php';
- putenv('GOOGLE_APPLICATION_CREDENTIALS=/home/axel/configs/narkampen-firebase-adminsdk-k42j5-d3d0354e37.json');
- $client = new Google_Client();
- $client->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']);
-
- if ($messageType === "FCMNextPlayer") {
- $playerName = $conn->real_escape_string($_POST['playerName']);
- $token = getToken();
-
- if ($token != null && $token != "") {
- sendMessage($token);
- }
- } else if ($messageType === "InviteMessage") {
- $i = 0;
- while ($_POST['player' . $i] != null) {
- $token = getToken($gameId, $conn->real_escape_string($_POST['player' . $i]));
- sendMessage($token);
- }
- }
-
- function getToken($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($token) {
- // Your Firebase project ID
- $project = "narkampen";
- // Creates a notification for subscribers to the debug topic
- $message = [
- "message" => [
- "token" => $token,
- "notification" => [
- "body" => $messageToSend,
- "title" => $title,
- ]
- ]
- ];
- // 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]);
- }
|