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 .
Related
I am having trouble getting Google Cloud Messaging for Android working.
I have had it working before but it decides to stop working after the first couple of times.
In order to get it working again I have to delete my API key and recreate it.
I am using PHP with a SERVER API key with a IP whitelist of ::/0 (All IPv6 apparently)
Note: My android app requests a device message key each time the app is opened (Usually returns the same message key)
The Error I get is: Unauthorized Error 401
When I got to the following url to check my app message id i get 'invalid token'.
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=APA91bHuQEWGsvlRUhlSztNpqLVOZQGZPiGFHjQw2plcF-z8t29zvNNgNoDiRe-CbY9Fb-XcPQAFqJvy4HBfWTrTPPpzcY3pd5vX38WGalOsZ5iDiJeglpafLTC7eFkN4UA9JPKWZ4lqNiGLoH3w8W_GpFAFW5F-kLLzcbrPxwSFqyfUpmM8-14
The PHP code I am using is:
$data = array( 'message' => 'Hello World!222!' );
$ids = array('APA91bHuQEWGsvlRUhlSztNpqLVOZQGZPiGFHjQw2plcF-z8t29zvNNgNoDiRe-CbY9Fb-XcPQAFqJvy4HBfWTrTPPpzcY3pd5vX38WGalOsZ5iDiJeglpafLTC7eFkN4UA9JPKWZ4lqNiGLoH3w8W_GpFAFW5F-kLLzcbrPxwSFqyfUpmM8-14');
$apiKey = 'AIzaSyATkp_UTZh....'; //obviously the complete key is used...
$url = 'https://android.googleapis.com/gcm/send';
$post = array('registration_ids' => $ids, 'data' => $data);
$headers = array( 'Authorization: key=' . $apiKey, 'Content-Type: application/json');
$ch = curl_init();
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_POSTFIELDS, json_encode( $post ) );
$result = curl_exec( $ch );
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
echo $result;
Thanks for any help given.
EDIT: It seems to work since I unregistered my device and reregistered it with GCM. I am not sure if this is a permanent fix but it works for now.
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!!
I have to send Push Notifications with different messages for large number of devices(More than 10k devices per day).But sometimes its not receiving all of the devices.I set up a function pushNotificationToUsers($heading,$message,$registraionids) to send the push notification and I am not sure about my method is correct ,if i am wrong please correct me.
function pushNotificationToUsers($heading,$message,$registraionids){
//array of registration ids in $registraionids
$key="xxxxxxxxxxx";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' =>,$registraionids,
'data' => array( "message" => $message,"title"=>$heading,"soundname"=>"beep.wav" ),
);
$headers = array(
'Authorization: key=' . $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 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
}
I'm using php in my serverside
For Android,
The message size limit in GCM is 4 kbytes.
https://developer.android.com/google/gcm/server.html#params
The message size limit in C2DM is 1024 bytes. (DEPRECATED)
https://developers.google.com/android/c2dm/#limitations
For iOS,
in iOS the size limit is 256 bytes, but since the introduction of iOS 8 has changed to 2kb!
https://forums.aws.amazon.com/ann.jspa?annID=2626
Also, see below stuffs
After Google replaced C2DM with GCM, they took off all limits.
http://developer.android.com/google/gcm/c2dm.html#history
The only limits you run into the GCM documentation is this:
http://developer.android.com/google/gcm/adv.html#lifetime
I think this answer is enough clear for your question.
I tried this code.
function sendNotification( $apiKey, $registrationIdsArray, $messageData )
{
$headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
$data = array(
'data' => $messageData,
'registration_ids' => $registrationIdsArray
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
And to call this function:
$message = "the test message";
$tickerText = "ticker text message";
$contentTitle = "content title";
$contentText = "content body";
$registrationId = 'APA91bEgsAG3vmliDnJE7jfLAOGSUv3K9p41MkNranPFV4EY0svABRax8NY5oulOHv7s3v2Ks_bQutsLLw8j4mHOr5LkrRlFfXxfs3hxxwAlxIOG7cXCB4YPhlLCDspVtImyWBL_znGgkZzEWCncV3tidHMV'; (Id is wrong here for security reasons)
$apiKey = "AIzaSyD6kZoY3Qb_1ut57IEmwdRg0JuxC42W1"; (Key is wrong here for security reasons)
$response = sendNotification(
$apiKey,
array($registrationId),
array('message' => $message, 'tickerText' => $tickerText, 'contentTitle' => $contentTitle, "contentText" => $contentText) );
echo $response;
And now i am stuck. I just create a PHP page with my own registration id of device and google API key.
But it shows me error of:
Unauthorized
Error 401
When i run this URL http://vbought.com/sendnotification.php
i even added my server IP and domain name in the GCM reference
.vbought.com/
*.vbought.com
50.87.3.82
is there something i did wrong? Or i need to know? I am just trying to send one message to my only device.
Thank you! (in advance)
i found the answer. And the answer is i dont need to define anything in GCM. Like i defined my domain name and IP address. So i dont need to do anything. Just leave it blank and it will work like charm...
have a nice day :)
I have developed the android application in cordova 3.4 now I want to get the automatic notification to their mobile. For this I refer websites as below
http://devgirl.org/2013/07/17/tutorial-implement-push-notifications-in-your-phonegap-application/
http://devgirl.org/2012/10/25/tutorial-android-push-notifications-with-phonegap/
https://github.com/hollyschinsky/PushNotificationSample30/tree/master/platforms/android
I read all above links then did all stuff they told like create project on google cloud messaging , get the project id , create server key (In textbox I given my private server IP) then API Key, I also have registration id device and I wrote code in php for sending push notification to my device but it is giving me "unauthorised Error 404"
my code is as below
define( 'API_ACCESS_KEY', 'my api key' );
//$registrationIds = array( $_GET['id'] );
$registrationIds = array($id);
//var_dump($registrationIds);die;
//prep the bundle
$msg = array
(
'message' => 'New Jobs is updated',
'title' => 'get the job in cad',
'subtitle' => 'get the job in cad',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => 1,
'sound' => 1
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
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 );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
I just hit url and send the registration id of device to the my php page but this page give me the error unauthorised Error 401.
Que.1. Is this possible to send the push notification from php which is hosted on private server?
Que.2 Is device registration id compulsory for sending push notification to those user they installed the apps?
Please anybody help me how to solve this above error and if anybody have another solution then tell me. I tried from yesterday but not achieve my goal so please help me.
Here is the GCM code and its working properly with my device though its in CI framework but hope you can use it. It is compulsory to add device_id for the push and also the passphrase you'll get for the site. just try it.
function sendNotification($device_id,$message) {
/*echo $device_id;
echo "<br>";
echo $message;*/
// note: you have to specify API key in config before
$this->load->library('gcm');
// simple adding message. You can also add message in the data,
// but if you specified it with setMesage() already
// then setMessage's messages will have bigger priority
$msg = $this->gcm->setMessage($message);
//var_dump($message);
// add recepient or few
$this->gcm->addRecepient($device_id);
//var_dump($device_id);
// set additional data
//$this->gcm->setData($params);
// also you can add time to live
$this->gcm->setTtl(500);
// and unset in further
//$this->gcm->setTtl(false);
// set group for messages if needed
//$this->gcm->setGroup('Test');
// or set to default
//$this->gcm->setGroup(false);
// send
return $this->gcm->send();
}
Hope it'll solve your problem.
<?php
$register_keys = array("YOUR_REGISTRY_KEYS")
$google_api_key = "YOUR_API_KEY";
$registatoin_ids = $register_keys;
$message = array("price" => $message);
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$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));
}
//print_r($result);
// Close connection
curl_close($ch);
?>