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.
Related
I am sending pushnotification to android devices from a php server,but some devices didn't get the pushnotification.
Here is the status from server
{"multicast_id":4893937277293136804,"success":4,"failure":10,"canonical_ids":0,"results":[{"error":"NotRegistered"},{"error":"NotRegistered"},{"error":"NotRegistered"},{"error":"NotRegistered"},{"message_id":"0:1452592669440333%c40440a4f9fd7ecd"},{"error":"NotRegistered"},{"error":"NotRegistered"},{"message_id":"0:1452592669442897%c40440a4f9fd7ecd"},{"error":"NotRegistered"},{"error":"NotRegistered"},{"message_id":"0:1452592669442899%c40440a4f9fd7ecd"},{"error":"NotRegistered"},{"error":"NotRegistered"},{"message_id":"0:1452592669442901%c40440a4f9fd7ecd"}]}
PHP
$key="XXXXXX";
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' =>$result,
'data' => array( "message" =>$msg,"title"=>$title,"soundname"=>"beep.wav" ),
);
$headers = array(
'Authorization: key=' . $key,
'Content-Type: application/json'
);
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
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 ) );
$res = curl_exec($ch);
print_r($res)
}
From the response only 4 devices successfully get the response,but 10 failures is occurred.
Whats is the problem?
One of these could be the problem why you are getting NotRegistered. See Downstream message error response codes.
Unregistered Device 200 + error:NotRegistered
An existing registration token may cease to be valid in a number of scenarios, including:
If the client app unregisters with GCM.
If the client app is automatically unregistered, which can happen if the user uninstalls the application. For example, on iOS, if the APNS Feedback Service reported the APNS token as invalid.
If the registration token expires (for example, Google might decide to refresh registration tokens, or the APNS token has expired for iOS devices).
If the client app is updated but the new version is not configured to receive messages.
For all these cases, remove this registration token from the app server and stop using it to send messages.
I have php script hosted in ftp server.
Its accessed from android app.
I did enabled Google Cloud Messaging in android and also php script.
So I want to send message every one hour.
So I need php schedule for trigger every one hour.
Message is constant.
My php code is:
<?php
define( "API_ACCESS_KEY", "***********************");
// Message to be sent
$message = "welcome to android app";
//RegistrationIds
$registrationid = "******************";
//call to gcm notification
send_push_notification($registrationid,$message);
//gcm push notification function
function send_push_notification($registrationids,$messages){
//GCM Implementation Code
// Set POST variables
$url = "https://android.googleapis.com/gcm/send";
$fields = array(
'registration_ids' => array($registrationids),
'data' => array( "message" => $messages ),
);
$headers = array(
'Authorization: key=' . API_ACCESS_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 );
cur_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;
}
?>
I want to call send push notification method every one hour.
You can use cron job for this. You dont have to add anything to the PHP script. Just running it every hour will solve the issue. Below is how you can add a cronjob. I believe you are on a Linux server.
0 * * * * /usr/bin/php /path/to/your/php/script.php
See this link to see how you can add/edit/delete cron tab - http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/
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);
?>
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 .