how to implement push notification using GCM in android studio using php? - php

I am trying to get notification in my app using GCM. i am using android studio tool and i tried lots of tutorials. most of them where done using eclips tool.
finally, i tried this one,
http://rmarcejaeger.com/2015/09/18/tutorial-how-to-implement-push-notifications-using-google-cloud-messaging-for-android-part-1-client-app/#comment-576070,
https://github.com/googlesamples/google-services/tree/master/android/gcm
and i finish android client part using above tutorial. But the problem is, i need to setup app server in php which connect my application through GCM. i have no idea to make it possible. i tried the follwing link,
https://developers.google.com/cloud-messaging/server
but i couldn't get much more.So please anyone suggest me better solution.

you need to understand below steps
for more details Android Push Notifications using Google Cloud Messaging (GCM), PHP and MySQL

First you need to create browser key from Console.
This is the code you need to add for Sending notification GOOGLE_API_KEY is the key you created from Console.
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// 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));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
Now using this method of GCM class you can send notification to the device by calling its method.
pass reg.id that is token id you got from Android device and message you want to pass.
$gcm = new GCM();
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;

Related

cURL_init() stops the program from running

I have added the .php files on my server to send the notifications using FCM, but the code stops running when I create the actual message. I have a constructor for push and when I call it in sendSinglePush, it does not do anything.
The rest is working properly. I get the parameters ok, and the devicetoken. I just need to create that push and it should work. I've used the same sendSinglePush.php for testing on localhost, and it works. When I add it on server it just stops.
EDIT: As per #ADyson, who helped me understand abit about logging my errors, I started to log every variable from the start to the point where it crashes. The $push it's alright, the problem it's on Firebase.php:
<?php
class Firebase {
public function send($registration_ids, $message) {
$fields = array(
'registration_ids' => array($registration_ids),
'data' => $message,
);
//print_r($fields);
return $this->sendPushNotification($fields);
}
/*
* This function will make the actuall curl request to firebase server
* and then the message is sent
*/
private function sendPushNotification($fields) {
//importing the constant files
require_once 'Config.php';
//firebase server url to send the curl request
$url = 'https://fcm.googleapis.com/fcm/send';
//building headers for the request
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
//Initializing curl to open a connection
$ch = curl_init();
print_r(curl_error($ch));
//Setting the curl url
curl_setopt($ch, CURLOPT_URL, $url);
//setting the method as post
curl_setopt($ch, CURLOPT_POST, true);
//adding headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//disabling ssl support
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//adding the fields in json format
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//finally executing the curl request
$result = curl_exec($ch);
print_r($result);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
print_r(curl_error($ch));
}
//Now close the connection
curl_close($ch);
//and return the result
return $result;
}
}
And the methods are called from sendSinglePush.php, where all the variables are sent correctly:
$mPushNotification = $push->getPush();
//print_r($mPushNotification);
//getting the token from database object
$devicetoken = $db->getTokenByEmail($_POST['email']);
//print_r($devicetoken);
//creating firebase class object
$firebase = new Firebase();
//sending push notification and displaying result
$firebase->send($devicetoken, $mPushNotification);
I have added different print_r() to check the output using POSTMAN and, from that code, the $headers are fine, after the $ch = curl_init(); nothing else shows up. I tried to add print_r(curl_error($ch)); but it does not show enything. Also, I tried with print_r(1); under the $ch = curl_init();to see if the code keeps running, but on postman there was no answer, only a blank screen and 500 Internal Server Error.

How to set up the New Google Cloud Messaging API server implementation and Hosting using PHP?

I am using the new Google Cloud messaging functionality and it's developed successfully in client side and receiving push notification without any dropping. But I'm using an old Send function on the server. Now I want to implement new send function (XMPP) using PHP.
I have registered here also https://services.google.com/fb/forms/gcm/ and got the response mail and key from the google.
And from that I got that I have to implement the SmackCcsClient Java class and two libraries. But I have no idea how to host that file to my PHP server.
After some research I got the function for PHP and xmphp libraries for PHP
$conn = new XMPPHP_XMPP($host, $port, $user, $password, $resource,
$server, $printlog, $loglevel);
But can't get the success it's saying could not connect.
You can use this class:
class gcm {
public static function send_notification($deviceid, $message) {
// include config
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => (is_array($deviceid) ? $deviceid : array($deviceid)),
'data' => array("message" =>$message),
);
$headers = array(
'Authorization: key=YOUR-AUTH-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);
}
}

Android Push Notification unauthorized error 401

I have created an Android app with Googles' OAuth 2.0 (from developer console) and has an API key for Android application (it use Google Maps, which works by the way).
However, my problem is that I'm using Push Notifications and it works on the android application though (I get the registration ID), but on the server it doesn't work at all.
I'm using PHP and the problem seems to be the API key which is the same as the one I've for the Android application.
So what key am I supposed to use? And how do I retrieve it?
Code:
<?php
function send_push_notification($registatoin_ids, $message) {
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=An_Api_Key',
'Content-Type: application/json'
);
//print_r($headers);
// 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;
}?>
Please check allowed IP addresses in your Google API. You can restrict API access to certain IP addresses and by default one IP address is set when you create new API project.
Remove that IP address so that any IP address (Including your local machine's server) can connect and access the API.
I have implemented similar kind of code and got 401 error. Above fix worked for me. Hope that helps you as well.

GCM denying the access

I'm working on GCM to send messages to android devices. It worked perfectly with in localhost. But when I tried with the remote server, GCM not allowing the to access it. It shows as "Failed to connect to : Permission denied". I thought, it is the problem with using the same api key for both localhost and remote server. I also changed the api key. Can anyone explain me whats the problem with this. Thanks. The GCM code goes like this.
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// 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));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
Clear all the IP Address from Server Key Page of Google Console, maybe this will solve your problem. If not please contact in comments.

GCM messages not getting to API or sent, but success flag returned

I am trying to set up Google Cloud Messaging on Android with PHP (following this tutorial: http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/). My device registers successfully with GCM and then with the server (the regId is stored into the database).
When I try and send to the device nothing is received, although I get this response:
{"multicast_id":4701392840778619841,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1355907831651938%978fee92f9fd7ecd"}]}
Google API reports that no requests have been made.
This is my send_notification function in PHP:
public function send_notification($registration_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registration_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));
}
// Close connection
curl_close($ch);
echo $result;
}
From research, I have seen similar questions have been asked to this, however they vary slightly - for example, different programming languages and no solution that I have found has solved this problem.
Extra Info:
1. I have checked and cURL is enabled.
2. My onMessage method
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("price");
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
(price in the above just retrieves the message as its stored like this: $message = array("price" => $message); before being given as a parameter to the send_notification function on the server.
I have checked LogCat and 'Received message' does not appear.
Just solved this (although I don't know what was causing the original problem). I shut my device down and started it up again and it went mad receiving all the messages I had sent it over the last few days. Now it receives them as they are sent, so assuming everything else is correct, if anyone is having this problem, try restarting the device.
please generate and use server api key to view for live notification on device.
that is not mention in this post
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
I experienced a very similar (same?) problem. My issue was that I changed the String from "price" in the PHP code, but I hadn't done in the Android code. You need to do both. Maybe this will help someone. :)

Categories