J'ai développé un site Web en utilisant php et mysql.Je veux envoyer une notification à un appareil Android pour chaque message posté sur mon site.
Est-il possible d'envoyer une notification via GCM Server? Si oui, comment puis-je envoyer une notification à tous les appareils sur lesquels l'application Android est installée?
J'ai décidé de poster une réponse à ma propre question
Maintenant, Google a introduit la FCM
<?php
define('API_ACCESS_KEY','Api key from Fcm add here');
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$token='235zgagasd634sdgds46436';
$notification = [
'title' =>'title',
'body' => 'body of message.',
'icon' =>'myIcon',
'sound' => 'mySound'
];
$extraNotificationData = ["message" => $notification,"moredata" =>'dd'];
$fcmNotification = [
//'registration_ids' => $tokenList, //multple token array
'to' => $token, //single token
'notification' => $notification,
'data' => $extraNotificationData
];
$headers = [
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$fcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
Il y a quelques changements dans le code en commentant define (ligne de clé api) cela fonctionne bien commenter ceci:
define('API_ACCESS_KEY','Api key from Fcm add here');
commentez ou remplacez cette ligne de code:
'Authorization: key=' . API_ACCESS_KEY
//define('API_ACCESS_KEY','Api key from Fcm add here');
$apiKey = 'Api key from Fcm add here';
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$token='235zgagasd634sdgds46436';
$notification = [
'title' =>'title',
'body' => 'body of message.',
'icon' =>'myIcon',
'sound' => 'mySound'
];
$extraNotificationData = ["message" => $notification,"moredata" =>'dd'];
$fcmNotification = [
//'registration_ids' => $tokenList, //multple token array
'to' => $token, //single token
'notification' => $notification,
'data' => $extraNotificationData
];
$headers = [
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$fcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
$result = curl_exec($ch);
curl_close($ch);
echo $result;