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);
?>
Related
i received GCM registration token for my device but when i am sending message using REST api from PHP, it shows Success but not receving message on device. php code
<?php
$data = array( 'message' => 'Hello World! First Message from PHP' );
$ids = 'device registration token';
// Send a GCM push
sendGoogleCloudMessage( $data, $ids );
function sendGoogleCloudMessage( $data, $ids )
{
// Insert real GCM API key from Google APIs Console
// https://code.google.com/apis/console/
$apiKey = 'API Key'; //(server API Key)
// Define URL to GCM endpoint
$url = 'https://gcm-http.googleapis.com/gcm/send';
// Set GCM post variables (device IDs and push payload)
$post = array(
'to' => $ids,
'data' => $data,
);
// Set CURL request headers (authentication and type)
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Initialize curl handle
$ch = curl_init();
// Set URL to GCM endpoint
curl_setopt( $ch, CURLOPT_URL, $url );
// Set request method to POST
curl_setopt( $ch, CURLOPT_POST, true );
// Set our custom headers
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
// Get the response back as string instead of printing it
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// Set JSON post data
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $post ) );
// Actually send the push
$result = curl_exec( $ch );
// Error handling
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
// Close curl handle
curl_close( $ch );
// Debug GCM response
echo $result;
print_r($result);
}
?>
while submitting PHP file, it returns message as below, it seems message shows 'success' but no message received at device. can someone suggest if i need to take additional step or doing something wrong?
{"multicast_id":8550022549195779350,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1459795352923689%21f96bfff9fd7ecd"}]}
Be sure that your API key is correct, and that your server IP is listed as trusted by the certificate. Sometimes, WiFi connected devices become unresponsive to GCM after a while. Try to restart your device. It should start receiving all the messages you have sent.
Also, from this SO question, check if you mistakenly used android:permission="com.google.android.gcm.c2dm.permission.SEND" instead of android:permission="com.google.android.c2dm.permission.SEND".
Hope this helps!
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 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 developed a simple application in android just to send notifications from one user to other.as a quick overview of my app:
user register in the app using phone number.
in my database, a new record created contain the phone number and the GCM reg ID.
when the user try to send a notification to another user, the application will find the reg ID of the recipient in the DB and send a notification using a php code in my server.
My problem is most of times the notification didn't delivered to the recipient.
Java Code as I said, just search for the reg ID in the DB then submit it to the PHP server, and the PHP server when communicate with the GCM server.
PHP Code:
<?php
$con = mysqli_connect("localhost","username","my password","database name");
// Replace with real BROWSER API key from Google APIs
$apiKey = "my api key";
// Replace with real client registration IDs
$destinationcereg = mysqli_real_escape_string($con,$_REQUEST['destreg']);// this will provided by the app
$registrationIDs = array($destinationcereg);
// Message to be sent
$destinationcereg2 = &$destinationcereg;
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => 'You Recieved New Message'),
);
$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_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
echo ahmed;
?>
Also note that sometime the notification received after long time, most of times it's not received, and also sometimes it received immediately.
Can any one help me please ? Thanks in advance.