GCM Curl connection Error - php

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

Related

Can i store static API Key in php file safely

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

InvalidRegistration on sending push to muliple devices

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, ...

Getting curly braces in output - GCM send multiple data

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);

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.

MissingRegistraton error when trying to send data to GCM

I've searched a lot but couldn't find any solution for this question.
I'm using a PHP server and is trying to send PushNotifications to my Android app. But when I'm trying out my code in the browser I get this error: "Error=MissingRegistration".
Here is the code that I run:
registration_ids = array($regId);
$message = array(
'hangMessage' => $message,
'userId' => $user_id
);
$result = $gcm->send_notification($registration_ids, $message);
And this is the code that I call:
$url = "https://android.googleapis.com/gcm/send";
$fields = array(
'registration_ids' => $regisration_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_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 psot
$result = curl_exec($ch);
if($result == false){
die('Curl failed: ' . Curl_error($ch));
}
//Close connection
curl_close($ch);
echo $result;
The Request doesn't even come all the way to the server according to the Google APIs Console Report system.
Anyone have any idea what could be wrong?
Your request should look like this :
Content-Type:application/json
Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA
{
"registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."],
"data" : {
...
},
}
Therefore I believe the error might be in this line :
'Content-Type= application/json'
Try to change the = to :.
Since the content type header is invalid, the GCM server may assume a default value for the content type (which might be application/x-www-form-urlencoded;charset=UTF-8, in which case the Registration ID requires a different key, which would explain the MissingRegistration error).
BTW, the fact that you get a MissingRegistraton error means that the request does reach the GCM server. GCM requests are not logged in the Google APIs Console Report system.

Categories