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);
Related
i want to use FCM in my android application , and i was wondering what is the best practice to store a static API such as Server Key API of FCM .
And after a lot o reading i found that even using ProGard doesn't save the API securely, so the conclusion is to never store keys in the app source code .
My solution is to save the key in a .php file like this, so that every time a device send a notification it sends data ( Notification title , message .. ) to my server that contain the server key and redirect the request to https://fcm.googleapis.com/fcm/send
My php file :
<?php
require_once __DIR__ . '/notification.php';
$notification = new Notification();
$title = "Notification Title";
$message = "Notification Message";
$notification->setTitle($title);
$notification->setMessage($message);
$firebase_api = "API_STATIC_SERVER_CODE_THAT_I_NEED_TO_HIDE";
$requestData = $notification->getNotificatin();
$fields = array(
'to' => '/topics/Test_Topic',
'data' => $requestData,
);
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . $firebase_api,
'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 temporarily
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 '<h2>Result</h2><hr/><h3>Request </h3><p><pre>';
echo json_encode($fields,JSON_PRETTY_PRINT);
echo '</pre></p><h3>Response </h3><p><pre>';
echo $result;
echo '</pre></p>';
?>
But, is that safe ? Could hackers some how download my php content ( without hacking my server ) , or the fact that i am using HTTPS connections keeps my data safe .
And what else can i do if it's not safe enough
Thank you
I'm trying to send push notifications to multiple device using Google Firebase and I always received the error : "InvalidRegistration".
This is the tokens that I sent in the "to"
:json_encode($tokensPerEvent):
["eV9g4oTwjZs:APA91bF3YLGtDkCDekvR6eahbVAn-jIY0sVGjxMWyBEyR-
3AB9q6RBhw4fyeqE4ZkZxQs0TsYhUee9Txy_exAGxtrBPV_-
sjKlWcV3z3nDYXOcVSVwlpPyGzUJKxGMU16drMR41bLI4t"]
and this is the response :
{
"multicast_id":***,
"success":0,
"failure":1,
"canonical_ids":0,
"results":[
{
"error":"InvalidRegistration"
}
]
}
another questions: if the one of the tokens not exist anymore, this is effect on all the other tokens , or just the only old one will effected ?
This is my code:
<?php
require_once '../CommonFunctions.php';
ignore_user_abort();
ob_start();
$url = 'https://fcm.googleapis.com/fcm/send';
//GET TOKENS FROM DB
$db = new Database();
$db->query("SELECT push_token FROM User");
$db1 = new Database();
$db1->query("SELECT phone FROM invite_list where event_id = 137");
$response = $db->resultset();
$response1 = $db1->resultset();
$arr2 = array_column($response1, 'phone');
$phones = join("','",$arr2);
$db2 = new Database();
$db2->query("SELECT push_token FROM User WHERE phone IN ('$phones')");
$tokensPerEvent = array();
$tokensrr = $db2->resultset();
$tokensPerEvent = array_column($tokensrr, 'push_token');
echo json_encode($tokensPerEvent);
$fields = array('to' => json_encode($tokensPerEvent),
'notification' => array('body' => 'HI', 'title' => ':)'));
define('GOOGLE_API_KEY', '***********');
$headers = array(
'Authorization:key='.GOOGLE_API_KEY,
'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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if($result === false)
die('Curl failed ' . curl_error());
curl_close($ch);
return $result;
?>
If you want to send push notification to many clients by theirs registration ids, you have to use registration_ids instead of to field. You can find this in docs (second parameter).
You are also encoding tokens two times:
$fields = array('to' => json_encode($tokensPerEvent), ...
and
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
Try by skipping encoding $tokensPerEvent in array:
$fields = array('to' => $tokensPerEvent, ...
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));
I've been dealing with this issue since 2 days. What I want to do is, I've to send multiple messages to registered GCM device. Till now I can send single message to device. Below is the code to send message.
send_message.php
<?php
if (isset($_REQUEST["regId"]) && isset($_REQUEST["message"])) {
$regId = $_REQUEST["regId"];
$message = $_REQUEST["message"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $registatoin_ids; echo $message;
echo $result;
}
GCM.php
<?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,
'message' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
//print_r($headers); exit();
// 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;
}
}
?>
Here message is being received on receiver side..
// code for this is in GCM.php
$fields = array(
'registration_ids' => $registatoin_ids,
'message' => $message,
);
But I want to send multiple messages in single notification. for that what I did...
send_message.php
<?php
if (isset($_REQUEST["regId"]) && isset($_REQUEST["message"]) && isset($_REQUEST["data"])) {
$regId = $_REQUEST["regId"];
$message = $_REQUEST["message"];
$data = $_REQUEST["data"]; //added third parameter
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$data = array("extra" => $data);
$result = $gcm->send_notification($registatoin_ids, $message, $data);
echo $registatoin_ids; echo $message; echo $data;
echo $result;
}
GCM.php
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message, $data) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'message' => $message,
'data' => $data,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
//print_r($headers); exit();
// 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;
}
}
?>
And in android I wrote the function to receive message like this...
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getStringExtra("price");
String newmessage = intent.getStringExtra("extra");
displayMessage(context, message + newmessage);
generateNotification(context, message + newmessage);
}
But I'm getting null result for "price" and getting result for "extra".
How can I receive multiple message string in single notification?
In send_message.php
Put both messages in the same object. I don't know why you call it price, but try like this:
$message = array('message' => $message,
'extra' => $data
);
In GCM.php
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
In your Android Service
protected void onMessage(Context context, Intent intent) {
//log the message in JSON format
Log.i(TAG, "Received message >> " + intent.getExtras().toString());
//Retrieve message and extra
String message = intent.getExtras().getString("message");
String newmessage = intent.getExtras().getString("extra");
//Now display the message
displayMessage(context, message + newmessage);
generateNotification(context, message + newmessage);
}
All the payload parameters you pass in your JSON should be within the data element.
Your JSON should look like this :
{
"registration_ids":["xxx", "yyy"],
"data": {
"price": "price value",
"extra": "extra value"
}
}
And not like this :
{
"registration_ids":["xxx", "yyy"],
"message": {
"price": "price value"
},
"data": {
"extra": "extra value"
}
}
you can write a JSON response that contain a multiple messages
and the you get the JSON in android , parse it and get your multiple Messages .
send_message.php
<?php
if (isset($_REQUEST["regId"]) && isset($_REQUEST["message"]) && isset($_REQUEST["extra"])) {
$regId = $_REQUEST["regId"];
$message = $_REQUEST["message"];
$extra= $_REQUEST["extra"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("message" => $message, "extra" => $extra);
$result = $gcm->send_notification($registatoin_ids, $message);
}
GCM.php
<?php
class GCM {
function __construct() {
}
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'
);
//print_r($headers); exit();
// 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';
echo json_encode($fields);
echo $result;
}
}
Android side
/**
* Method called on Receiving a new message
* */
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("extra");
String newmessage = intent.getExtras().getString("message");
displayMessage(context, message + newmessage);
generateNotification(context, message + newmessage);
}
I am trying to send a message from a server to client (android) using GCM and curl,
the code i used worked perfectly for localhost (emulator and device) , however it would not work for a regular server, attached is the code used and the error message,
are there any additional steps or changes i need to do to make the code work for online server. Any help is appreciated :)
<?php
function Reg($USER_REG_ID)
{
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$response = array();
$API_Key = 'AIzaSyCQgPGhpAzuWGuUd0DCI8pYaXXAItthEsg';
$url = 'https://android.googleapis.com/gcm/send';
$result = mysql_query("SELECT * FROM users where type = 'bus'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$Registration_ID = $row["user_RegID"];
array_push($response, $Registration_ID);
}
//THIS PART SENDS TEH REQUEST USING GCM
$fields = array(
'registration_ids' => $response,
'data' => array(
"message" => $USER_REG_ID
)
);
print_r ($fields);
$headers = array(
'Authorization: key=' . $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);
}
Reg(1)
?>
the fields array
Array ( [registration_ids] => Array ( [0] => APA91bFolV5ZK2diIbTyxwPLp6BqTMdhqaMDYgEsGOlznmxn4NRV6QQzPtfr58ORrpmxq0N_UMwz6s30gWgj--w5SqHxCEHh662PnvjDpGce_4EiHDe-muflVYMOsLlbVDRybvNDubX9aF_RE4VPJdArUsqQjcrQRg ) [data] => Array ( [message] => 1 ) )
The error message
Curl failed: Failed to connect to 2a00:1450:400c:c05::5f: Network is unreachable
This should do it:
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
If the above doesn't work, you can try to disable ipv6 system wide:
echo 1 > /proc/sys/net/ipv6/conf/all/disable_ipv6