I'm trying to use php class to send data to app(phonegap) using GCM.
Here the data is stored to the database and it is send using the Php-GCM class.
The problem is that it is showing null values when sending for all columns.
<?php
class GCMPushMessage {
var $url = 'https://android.googleapis.com/gcm/send';
var $serverApiKey = "xxxxxxx";
var $devices = 0;
function setDevices($deviceIds)
{
if(is_array($deviceIds)){
$this->devices = $deviceIds;
} else {
$this->devices = array($deviceIds);
}
}
function send($message, $data = false)
{
if(!is_array($this->devices) || count($this->devices) == 0){
$this->error("No devices set");
}
if(strlen($this->serverApiKey) < 8){
$this->error("Server API Key not set");
}
$fields = array(
'registration_ids' => $this->devices,
'data' => array( "message" => $message ),
);
if(is_array($data)){
foreach ($data as $key => $value) {
$fields['data'][$key] = $value;
}
}
$headers = array(
'Authorization: key=' . $this->serverApiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $this->url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Avoids problem with https certificate
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
return $result;
}
}
$id=$_POST['id'];
$diagnosis=$_POST['diagnosis'];
$instructions=$_POST['instructions'];
$doc_name=$_POST['doc_name'];
$med_id=time().rand(11,99).time();
$str="insert into prescription values('$id','$diagnosis','$instructions','$doc_name','$med_id')";
$res=#mysql_query($str)or die(mysql_error());
$nf=$_POST['nf'];
$i=1;
while($i<=$nf)
{
$medicine=' ';
$tm1=$tm2=$tm3=0;
$medicine=$_POST['medicine_'.$i];
$tm='';
if(isset($_POST['tm_1_'.$i]))
{$tm1=1;}
if(isset($_POST['tm_2_'.$i]))
{$tm2=1;}
if(isset($_POST['tm_3_'.$i]))
{$tm3=1;}
$dosage=$_POST['dosage_'.$i];
$str="insert into medicine values('$med_id','$dosage','$medicine','$tm1','$tm2','$tm3')";
$res=#mysql_query($str)or die(mysql_error());
$i++;
}
$id = $_POST['id'];
$gcpm = new GCMPushMessage();
$sql=mysql_query("select token from device where id=".$id);
$rs=mysql_fetch_assoc($sql);
$gcpm->setDevices($rs['token']);
$query1=mysql_query("select * from medicine,prescription where med_id=mid and id=".$id);
while($rs1=mysql_fetch_assoc($query1))
{
$rows[]['medicine_name']=$rs['medicine_name'];
$rows[]['tm_1']=$rs['tm_1'];
$rows[]['tm_2']=$rs['tm_2'];
$rows[]['tm_3']=$rs['tm_3'];
$rows[]['dosage']=$rs['dosage'];
}
$rows[]['diagnosis']=$rs['diagnosis'];
$rows[]['instructions']=$rs['instructions'];
print_r($rows);
$response = $gcpm->send($message, $rows);
?>
When I try to display $rows,it is showing null value for all the items. But the data is getting inserted into the db. Sorry for posting the whole code. I'm a newbie. Please help.
It is difficult to figure out the root cause of the issue since you have not posted the log cat. The exact cause of the error may be a NULL value but at which line it is occuring would help more to diagnose the issue.
I would say you to have a look at this tutorial that deals with inserting and fetching up off multiple rows from two tables.
For GCM implementation please have a look at this tutorial. And make sure the structure is modular as described in the example.
Hope that Helps!!
Related
I am trying to get the message from server as a push notification in android. but I got null message from server when I change language to Thai but English working.
PHP File
class GCMPushMessage {
var $url = 'https://android.googleapis.com/gcm/send';
var $serverApiKey = "";
var $devices = array();
/*
Constructor
#param $apiKeyIn the server API key
*/
function GCMPushMessage($apiKeyIn){
$this->serverApiKey = $apiKeyIn;
}
/*
Set the devices to send to
#param $deviceIds array of device tokens to send to
*/
function setDevices($deviceIds){
if(is_array($deviceIds)){
$this->devices = $deviceIds;
} else {
$this->devices = array($deviceIds);
}
}
/*
Send the message to the device
#param $message The message to send
#param $data Array of data to accompany the message
*/
function send($message, $data = false){
if(!is_array($this->devices) || count($this->devices) == 0){
$this->error("No devices set");
}
if(strlen($this->serverApiKey) < 8){
$this->error("Server API Key not set");
}
$fields = array(
'registration_ids' => $this->devices,
'data' => array( "message" => $message ),
);
if(is_array($data)){
foreach ($data as $key => $value) {
$fields['data'][$key] = $value;
}
}
$headers = array(
'Authorization: key=' . $this->serverApiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $this->url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Avoids problem with https certificate
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
return $result;
}
function error($msg){
echo "Android send notification failed with error:";
echo "\t" . $msg;
exit(1);
}
onMessageReceived
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
String title = data.getString("title");
/*Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);*/
if (from.startsWith("/topics/")) {
// message received from some topic.
} else {
// normal downstream message.
}
help me please.
When I am using GCM for push notification , I got an error return as: field "data" must be a JSON array.
When user create the new post then notification will be send to all Registered devices. Any one have some idea of how to solve it? Thank you.
function Notification($post) {
global $wpdb;
$pub_post = get_post($post_ID);
$post_title=$pub_post->post_title;
$totalrecord = $this->get_allrecord();
$message = "Your New post, " .$post_title." has been published";
if (count($totalrecord) > 0) {
//$display_row = null;
foreach ($totalrecord as $row) {
$a = $row->token;
$this->sendPushNotification($a, $message);
}
}
}
function get_allrecord(){
global $wpdb;
$results =$wpdb->get_results('SELECT token FROM wp_push_tokens ', OBJECT);
return $results;
}
function sendPushNotification($registration_ids, $message) {
$apiKey = "xxxxxxxxxxxxxxxxxxxxxxx";
$headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
$fields = array(
'register' =>$registration_ids,
'data' =>$message );
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true );
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, wp_json_encode($fields));
// Execute post
$result = curl_exec($ch);
if($result === false)
die('Curl failed ' . curl_error());
// Close connection
curl_close($ch);
return $result;
}
Your content type is "application/json", which means the "data" field must be a JSON of the form :
"data": {
"message": "your message"
}
Note that the "message" key in this example is custom. You can use whatever keys you wish, and your app will have to search for those keys when it receives the message.
I don't know PHP, but something like this may work :
$fields = array(
'registration_ids' =>$registration_ids,
'data' => array('message' => $message));
Currently I have 2 android applications that share the same MySQL database. The first app will post data to the database. The second app will display the database data. How do I send a push notification to the second app AUTOMATICALLY and immediately after the first app post data to the database ?
Any idea how to solve this with GCM ?
after posting data to database , do the following code
$apiKey = "your api key";
$db_username = 'root';
$db_password = 'root';
$db_name = 'gcm001';
$db_host = 'localhost';
$mysqli = new mysqli($db_host, $db_username, $db_password,$db_name);
if($mysqli->connect_errno > 0){
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
//get registration id's from database, whom you want to send notification ... assuming you have stored registration ids of 2nd app in database
$query = "SELECT * FROM RegisteredDevices where userid = $userid";
$result = mysqli_query($mysqli, $query);
$i=0;
$data = array();
while($row = mysqli_fetch_assoc($result))
{
$data[$i] = $row['reg_id'];
$i++;
}
$registrationIDs = array_values($data);
//print_r($registrationIDs);
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => array_values( $registrationIDs ),
'data' => array( "message" => "Your notification message here" ),
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $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 ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
hope this helps....
I am trying to send data to device with GCM but getting curly braces in output(as below image). I'm new to php and I wonder how to fix this issue. Here is the part of PHP server code :
public function send_notification($registatoin_ids, $message, $title) {
// include config
include_once './config.php';
$url = 'https://android.googleapis.com/gcm/send';
$data = array("title" => $title, "message" => $message);
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $data
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
/////////
I changed the send_message.php like this and it fixed.
if (isset($_GET["regId"]) && isset($_GET["message"]) && isset($_GET["title"])) {
$regId = $_GET["regId"];
$messagem = $_GET["message"];
$titlem = $_GET["title"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("message" => $messagem);
$title = array($titlem);
$result = $gcm->send_notification($registatoin_ids, $messagem, $titlem);
echo $result;`
}
EDIT: sorry, with JSON GCM payload data should be an assoc array. Mixed up with an older flavor of the protocol. That said, what is your intent on the Android side like?
EDIT: dump the whole extra bundle.
Bundle b = intent.getExtras();
for(String k : b.keySet())
Log.d("tag", k + "=" + b.get(k).toString());
edited:
ok, I think your problem is you're posting the value {.....} with no key. it's like saying
http://..... com?{myjson:"stuff"}
I haven't reviewed the api, but it seems it should be something like post "data=".json_encode($fields);
I want to sent message from my server to phone, by PHP.
Here is my code:
$apiKey = "AIxxxxxxxxxxxxxxxxxxxx";
$registrationIDs = array( $c2dmId );
$url = "https://android.googleapis.com/gcm/send";
$headers = array(
'Authorization: key='.$apiKey,
'Content-Type: application/json'
);
$fields = array(
'collapse_key' => $collapseKey,
'data' => array(
"type" => $msgType,
"extra" => $msgExtra,
"uuid" => $uuid,
"user_id" => $userId),
'registration_ids' => $registrationIDs,
);
print (json_encode($fields));
echo "<br/>";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch);
$resultInfo = curl_getinfo($ch);
echo "resultinfo: $resultInfo <br>";
foreach ($resultInfo as $key => $value) {
echo "$key => $value <br>";
}
curl_close($ch);
die ("Result: $result");
Where $c2dmId is just registrationId which I send to server from phone. As a result I get (in $result variable):
<HTML>
<HEAD>
<TITLE>Not Found</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Not Found</H1>
<H2>Error 404</H2>
</BODY>
</HTML>
And I don't know why. Can anyone help? Documentation dosen't say anything about 404 code, so I really don't know what is going on.
Oh, I completely forgot about this question, sorry for that. I already find out what was the problem.
Earlier I used that code which I posted before to send messages via C2DM. I made only a few improvements to adjust it to GCM. And one of variables ($msgExtra) could equal null in some case. It was intended behaviour and with C2DM it worked just fine.
Unfortunately, when you try to pass null in JSON via GCM you get 404 error, although GCM documentation says nothing about that...
So code which I posted is good as far as you don't try to send null.
Solution of my problem is to replace null value with something like "".
And once again - sorry that I post it just now, I completely forgot about this question.
Generate a Browser API Key from the Google APIs Console, and use it instead of the server key in the "Authorization" header. Once you do that, this error will go away.
This is caused by a serious mistake in the GCM Documentation that states you should use a Server Key in the Authorization header (as written Over here).
may be its already resolved for you.But here is the working version of your code which i tested on device.
<?php
$apiKey = "AI.....";
$registrationIDs = array( "You registration key" );
$url = "https://android.googleapis.com/gcm/send";
$headers = array(
'Authorization: key='.$apiKey,
'Content-Type: application/json'
);
$msgType = "hello";
$msgExtra = "rock";
$uuid = '1234';
$userId = '5678';
/* data you need to define message you want to send in APP.For ex: here myssg in what i am fetching at client side, so in notification it will show hello. You can change accordingly. */
$fields = array(
'collapse_key' => $collapseKey,
'data' => array(
"mymsg" => $msgType,
"extra" => $msgExtra,
"uuid" => $uuid,
"user_id" => $userId),
'registration_ids' => $registrationIDs,
);
print (json_encode($fields));
echo "<br/>";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch);
$resultInfo = curl_getinfo($ch);
echo "resultinfo: $resultInfo <br>";
foreach ($resultInfo as $key => $value) {
echo "$key => $value <br>";
}
curl_close($ch);
die ("Result: $result");
?>
This will not give you 404 error.Hope this will help you or some looking for server side implementation in PHP .