recently I would like to implement push message to all app user cilent. So I found a Google service gcm. Since there are so several ways to implement and usage of GCM. The actual implementation is:
Develop by:
HTTP mode / php + mysql
Usage:
send message (notification) to all app users
Here is the php code from online tutorial
<?php
define("GOOGLE_API_KEY", "AIzaSyCJiVkatisdQ44rEM353PFGbia29mBVscA");
define("GOOGLE_GCM_URL", "https://android.googleapis.com/gcm/send");
function send_gcm_notify($reg_id, $message) {
$fields = array(
'registration_ids' => array( $reg_id ),
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, GOOGLE_GCM_URL);
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($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Problem occurred: ' . curl_error($ch));
}
curl_close($ch);
echo $result;
}
$reg_id = "APA91bHuSGES.....nn5pWrrSz0dV63pg";
$msg = "Google Cloud Messaging working well";
send_gcm_notify($reg_id, $msg);
Are there any tutorial that suit my case and not deprecated? Thanks. I already got the API key and the google service account is ready.
Step 1: Create a php page where you can input the message that needs to be sent for all the users
message.php
html>
<head>
<link rel="stylesheet" type="text/css" href="design.css"/>
</head>
<body>
<div id="container">
<h6>GCM</h6>
<h3>MESSAGE</h3>
<form action="notification.php" method="post">
<textarea id="message" name="msg" rows="6" cols="41" autofocus="true"></textarea>
<br />
<br />
<input type="submit" class="btn_class" value="Send"/>
</form>
</div>
</body>
design.css
div#container{
position:absolute;
width:400px;
height:350px;
top:50%;
left:50%;
margin-top:-225px;
margin-left:-200px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.35);
}
#message{
margin-left:25px;
}
.btn_class{
color:blue;
margin-left:170px;
}
h6{
text-align:center;
font-family:sans-serif;
font-size:20px;
}
h3{
margin-left:30px;
font-family:sans-serif;
font-size:14px;
}
Step 2: create notification.php file that upon receiving the message will send it to all the users using your api key and reg ids
notification.php
<?php
$message=$_POST["msg"];
........
// construct sql query for database access
while($row=mysql_fetch_array($result)){
$registrationIDs[] = $row["gcm_regid"]; // store all reg ids from the column "gcm_regid" in the array
}
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ),
);
?>
The rest of the code is same as yours
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.