i am trying to send the gcm message everything works fine the message is send from server and received in the phone , i am testing the code to send it to more than 1000 users so i am concatenating the count to each message however it just sends 1 as count and not actual count
how can i send the count in gcm messages
i am trying this for testing and i am totally new to php
<?php
require 'connect.php';
function sendPushNotification($registration_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
define('GOOGLE_API_KEY', 'gcmcode');
$headers = array(
'Authorization:key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
echo json_encode($fields);
$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;
}
$pushStatus = '';
if(!empty($_GET['push'])) {
$query = "SELECT gcm_regId FROM gcm_users";
if($query_run = mysql_query($query)) {
$gcmRegIds = array();
$i = 0;
while($query_row = mysql_fetch_assoc($query_run)) {
$i++;
$gcmRegIds[floor($i/1000)][] = $query_row['gcm_regId'];
echo $i . "</br>" ;
}
}
$pushMessage = $_POST['message'];
if(isset($gcmRegIds) && isset($pushMessage)) {
$pushStatus = array();
$j = 0;
foreach($gcmRegIds as $val)
{$j++;
$message = array('price' => $j . $pushMessage);
$pushStatus[] = sendPushNotification($val,$message);
}
}
}
?>
<html>
<head>
<title>Google Cloud Messaging (GCM) Server in PHP</title>
</head>
<body>
<h1>Google Cloud Messaging (GCM) Server in PHP</h1>
<form method = 'POST' action = 'send_all.php/?push=1'>
<div>
<textarea rows = 2 name = "message" cols = 23 placeholder = 'Messages to Transmit via GCM'></textarea>
</div>
<div>
<input type = 'submit' value = 'Send Push Notification via GCM'>
</div>
<p><h3><?php echo $pushStatus ?></h3></p>
</form>
</body>
</html>
You can call the count method of mysql which returns the total row count. I implemented a simple sample, do as you required.
$query = "SELECT count(gcm_regId) as total FROM gcm_users";
while($query_row = mysql_fetch_assoc($query_run)) {
$total = $query_row['total'] / 1000;
}
function getGCMCount(){
$total = "";
$query = "SELECT count(gcm_regId) as total FROM gcm_users";
while($query_row = mysql_fetch_assoc($query_run)) {
$total = $query_row['total'] / 1000;
}
return $total;
}
function sendPushNotification($registration_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message . " " . getGCMCount(),
);
define('GOOGLE_API_KEY', 'gcmcode');
$headers = array(
'Authorization:key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
echo json_encode($fields);
$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;
}
Related
I am developing a facebook chatbot. I am facing a issue which I cannot solve. I am developing this in laravel. Here I cannot get the postback payload. here is my code
public function index(Request $request) {
if ($request->hub_verify_token === $this->verifyToken) {
echo $request->hub_challenge;
exit;
}
$input = json_decode(file_get_contents("php://input"), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$pageId = $input['entry'][0]['id'];
$accessToken = "access_token_that_got_from_fb";
//set Message
if($messageText != "") {
$answer = "Howdy! User";
}
if($messageText == "hello") {
$answer = 'Testing hello from bot';
}
foreach ($input['entry'][0]['messaging'] as $message) {
// When bot receive message from user
if (!empty($message['postback'])) {
$answer = 'got it tada';
}
}
//send message to facebook bot
$response = [
'recipient' => [ 'id' => $senderId ],
'message' => [ 'text' => $answer ] //json_encode($request->getContent())
];
$ch = curl_init('https://graph.facebook.com/v2.11/me/messages?access_token='.$accessToken);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$result = curl_exec($ch);
curl_close($ch);
}
and my route is
Route::any('chatbot', 'ChatbotController#index');
here the message is working . but the postback payload request is not going to server. on the other hand using the same code in normal php file I am able to get postback paylod.
$hubVerifyToken = 'chatbot';
$accessToken = "access_token";
// check token at setup
if ($_REQUEST['hub_verify_token'] === $hubVerifyToken) {
echo $_REQUEST['hub_challenge'];
exit;
}
// handle bot's anwser
$input = json_decode(file_get_contents('php://input'), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$postback = isset($input['entry'][0]['messaging'][0]['postback']['payload']) ? $input['entry'][0]['messaging'][0]['postback']['payload'] : '' ;
//set Message
if($messageText == "hi") {
$answer = "Hello";
}
if($messageText == "hello") {
$answer = "Hello there, welcome to Chatleads";
}
if($postback) {
$answer = "postback TADA";
}
//send message to facebook bot
$response = [
'recipient' => [ 'id' => $senderId ],
'message' => [ 'text' => $answer ]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/v2.11/me/messages?access_token=$accessToken");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
How to solve this issue? can anyone show me a path?
Solved it by checking at laravel.log file.
$this->messageText = isset($this->input['entry'][0]['messaging'][0]['message']['text']) ? $this->input['entry'][0]['messaging'][0]['message']['text'] : '' ;
messageText should be like this. that's why its causing an error.
I have tried Firebase notification with Laravel to send notification to IOS and Android devices.
But IOS device not received the notifications but Android devices working good.
So what is the issue in my script?
I have tried following,
$firebase = new \Firebase();
$push = new \Push();
// optional payload
$payload = array();
$payload['team'] = 'India';
$payload['score'] = '5.6';
// notification title
$title = Input::get('title');
// notification message
$message = Input::get('message');
// push type - single user / topic
$push_type = Input::get('push_type');
// whether to include to image or not
$include_image = Input::get('include_image') ? TRUE : FALSE;
$include_image = TRUE;
$push->setTitle($title);
$push->setMessage($message);
if ($include_image) {
$push->setImage('http://api.androidhive.info/images/minion.jpg');
} else {
$push->setImage('');
}
$push->setIsBackground(FALSE);
$push->setPayload($payload);
$json = '';
$response = '';
if ($push_type == 'topic') {
$json = $push->getPush();
$response = $firebase->sendToTopic('global', $json);
} else if ($push_type == 'individual') {
$json = $push->getPush();
$regId = Input::get('regId');
$response = $firebase->send($regId, $json);
}
I have refer this question but there is no answer provided.
you need a 'notification' json block for iOS to respond
$url = "https://fcm.googleapis.com/fcm/send";
$token = "";
$serverKey = '';
$title = "Title";
$body = "Body of the message";
$notification = array('title' =>$title , 'text' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,
"POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
I am using PHP to send GCM notification to users. Based on their token saved in SQL on server. But I have a limit of 1000 notifications at once to send,
this is my working code , now i need to edit it to loop the process, and send 5000 notification in sections, 1000 than 1000 etc.
Here is my PHP code, and a simple HTML I didn't post here,
<?php
$mysqlHost = "";
$mysqlUser = "";
$mysqlPwd = ";
$mysqlDbname = "";
class GCM {
function __construct(){}
public function send_notification($registatoin_ids,$data) {
// GOOGLE API KEY
define("GOOGLE_API_KEY","************");
$url="https://android.googleapis.com/gcm/send";
$fields=array(
"registration_ids"=>$registatoin_ids,
"data"=>$data,
);
//var_dump($fields);
$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_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields));
$result_gcm=curl_exec($ch);
if($result_gcm===FALSE){
die("Curl failed: ".curl_error($ch));
}
curl_close($ch);
//echo $result_gcm;
}
}
// Create connection
$conn = mysqli_connect($mysqlHost, $mysqlUser, $mysqlPwd, $mysqlDbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$result = $conn->query("SELECT * FROM users WHERE users_android_token IS NOT NULL AND users_android_token <> ''");
$android_tokens = array();
$x=0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$android_tokens[] = $row["users_android_token"];
$x++;
}
} else {
echo "0 results";
}
$conn->close();
$title = $_POST['title'];
$msg = $_POST['message'];
$link = $_POST['link'];
if ($android_tokens != array()) {
$gcm=new GCM();
$data=array("title"=>$title,"description"=>$msg,"link"=>$link);
$result_android=$gcm->send_notification($android_tokens,$data);
}
?>
Rather than send notification by registrationId, why not using send notification by topic. You only need to make client subscribed to certain topic.
in GCM, you can send notification topic with this code :
function send_notification_topic($topicname, $message){
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'to' => '/topics/' . $topicname,
'data' => $message
);
$headers = array(
'Authorization: key=AIzablablablayourServerKey',
'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_SSL_VERIFYHOST, 0);
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($ch));
}
curl_close($ch);
return $result;
}
Use this code for divided your tokens .
if ($android_tokens != array()) {
$gcm = new GCM();
$data = array("title" => $title,"description" => $msg,"link" => $link);
//Divide array into 1000 tokens
$splitTokens = array_chunk($android_tokens, 1000);
//loop the array
//Obs: for looping notification may push slow
foreach($splitTokens as $tokens) {
$result_android = $gcm -> send_notification($tokens,$data);
}
}
For divide GCM may push the notification slow . it take up to 2 - 10 mins.
I have 100000 users, I am always sending information, in fact this information don't reach to all users and I don't know why.
I will attach the send php files, and please see if you can tell what is wrong with this and which logic I should use. Note if I change 1000 number to 3000 no user receive also I don't know why.
<?php include('session.php');?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<?php
header('Content-type: text/html; charset=utf-8');
//generic php function to send GCM push notification
function sendPushNotificationToGCM($registatoin_ids, $message) {
//Google cloud messaging GCM-API url
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
define("GOOGLE_API_KEY", "my_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_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
?>
<?php
header('Content-type: text/html; charset=utf-8');
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
if (isset($_GET['level']) &&isset($_GET['m1']) &&isset($_GET['m2']) &&isset($_GET['m3']) &&isset($_GET['m4']) &&isset($_GET['m5']) &&isset($_GET['m6']) &&isset($_GET['m7'])){
$level=$_GET['level'];
$m1=$_GET['m1'];
$m2=$_GET['m2'];
$m3=$_GET['m3'];
$m4=$_GET['m4'];
$m5=$_GET['m5'];
$m6=$_GET['m6'];
$m7=$_GET['m7'];
$m11=mysql_real_escape_string($_GET['m1']);
$m21=mysql_real_escape_string($_GET['m2']);
$m31=mysql_real_escape_string($_GET['m3']);
$m41=mysql_real_escape_string($_GET['m4']);
$m51=mysql_real_escape_string($_GET['m5']);
$m61=mysql_real_escape_string($_GET['m6']);
$m71=mysql_real_escape_string($_GET['m7']);
mysql_query("SET NAMES 'utf8'");
$resultaa = mysql_query("INSERT words (id, level, m1, m2, m3, m4, m5, m6, m7) VALUES (NULL,'$level','$m11','$m21','$m31','$m41','$m51','$m61','$m71')");
$id = mysql_insert_id();
if($level == 0){
$result = mysql_query("SELECT Rid FROM users ");
}else{
$result = mysql_query("SELECT Rid FROM users where level = '$level' OR level = '4'");
//$result = mysql_query("SELECT Rid FROM users where level = '$level'");
}
$message = array(
'word_id' => $id,
'm1' => $m1,
'm2' => $m2,
'm3' => $m3,
'm4' => $m4,
'm5' => $m5,
'm6' => $m6,
'm7' => $m7,
'level' => $level
);
if (mysql_num_rows($result) > 0) {
for($counter = 0; $counter<mysql_num_rows($result) ; $counter+=1000) {
$gcmRegIds=array();
for($counter2=$counter ; $counter2<$counter+1000;$counter2++){
if($counter2<mysql_num_rows($result)){
$row = mysql_fetch_array($result);
$gcmRegIds[]=$row["Rid"];
}
}
$pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
echo $pushStatus;
}
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
echo "Process Time: {$time}";
}else {
$response["success"] = 0;
$response["message"] = "No user found";
echo json_encode($response);
}
//echo $result;
}
else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
</body>
</html>
i am using following code to send gcm message using php and mysqldb i have successfully send the gcm message and received it on the device however the android guidelines state that gcm message should be send in batch of 1000 each http://developer.android.com/training/cloudsync/gcm.html#multicast
now my question is how can we send gcm messages in lots of 1000 to a database of say 10,000 registered users.
<?php
require 'connect.php';
function sendPushNotification($registration_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
define('GOOGLE_API_KEY', 'keys_value');
$headers = array(
'Authorization:key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
echo json_encode($fields);
$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;
}
$pushStatus = '';
if(!empty($_GET['push'])) {
$query = "SELECT gcm_regId FROM gcm_users";
if($query_run = mysql_query($query)) {
$gcmRegIds = array();
while($query_row = mysql_fetch_assoc($query_run)) {
array_push($gcmRegIds, $query_row['gcm_regId']);
}
}
$pushMessage = $_POST['message'];
if(isset($gcmRegIds) && isset($pushMessage)) {
$message = array('price' => $pushMessage);
$pushStatus = sendPushNotification($gcmRegIds, $message);
}
}
?>
<html>
<head>
<title>Google Cloud Messaging (GCM) Server in PHP</title>
</head>
<body>
<h1>Google Cloud Messaging (GCM) Server in PHP</h1>
<form method = 'POST' action = 'send_all.php/?push=1'>
<div>
<textarea rows = 2 name = "message" cols = 23 placeholder = 'Messages to Transmit via GCM'></textarea>
</div>
<div>
<input type = 'submit' value = 'Send Push Notification via GCM'>
</div>
<p><h3><?php echo $pushStatus ?></h3></p>
</form>
</body>
</html>
Make $gcmRegIds to be a 2D array and then foreach it to push msg:
if(!empty($_GET['push'])) {
$query = "SELECT gcm_regId FROM gcm_users";
if($query_run = mysql_query($query)) {
$gcmRegIds = array();
$i = 0;
while($query_row = mysql_fetch_assoc($query_run)) {
$i++;
$gcmRegIds[floor($i/1000)][] = $query_row['gcm_regId'];
}
}
$pushMessage = $_POST['message'];
if(isset($gcmRegIds) && isset($pushMessage)) {
$message = array('price' => $pushMessage);
$pushStatus = array();
foreach($gcmRegIds as $val) $pushStatus[] = sendPushNotification($val, $message);
}
}
Here is what i did for my scenario to resolve for FCM .You can also ignore some parts of the code
<?php
$saved_tokens=array(); // could be more than 1000 token the maximum size as per google FCM requirement
//$count=1;
$ID_SETS = array_chunk($saved_tokens, 1000); // make a group of 1000 items in each set
foreach ($ID_SETS as $value_ids) {
// echo "Chunk ".$count."<br>";
sendFCM_Notification("what_ever_parameter_data",$value_ids);
foreach ($value_ids as $value_i ) { // you can remove this part its not neccessary
//echo " ---- contents of Chunk ".$count ."with Value".$value_i."<br>";
}
// $count++;
}
function sendFCM_Notification($what_ever_parameter,$reg_ids_array){
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $reg_ids_array,
'data' => $what_ever_parameter
);
$headers = array(
'Authorization:key = YOUR_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_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
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($ch));
}
curl_close($ch);
return $result;
}
?>