I'm developing an app and I'm on the final face where registered devices in the database are to receive push notifications at a time.
Currently, with the script I have, it can only send to one device. I have a table in my database called devices and the field that saves the device ID is called device_id. Please any help on how to send to multiple users?
<?php
$message = $_POST['title'];
$id = $_POST['id'];
// Replace with the real server API key from Google APIs
$apiKey = "AIzaSyDn9RPYmnlbs9*****WHKksz73klOqxM";
// Replace with the real client registration IDs
$registrationIDs = array("APA91bHhTiGeAKgphENoGH6********Blw9PspLCPAiprTSDN6mRuW3k253PZyppxgJaqPftTzYZOiWPt5C4XFVmkuqjbXp7MV3mAmpDAYM-11LdIdU0");
// Message to be sent
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message,"title" => "Today's Devotion","id" => $id),
);
$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));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_POST, true);
//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;
//print_r($result);
//var_dump($result);
?>
Fetch all the device ids from your database as below:
$registrationIDs = array();
$query = "select device_id from devices";
while($row = $db->database_fetch_assoc($query))
{
$registrationIDs[] = $row;
}
Now pass this array to the $field array.
create your query to get device ids in $registrationIDs and send all to server.
// Replace with the real client registration IDs
$registrationIDs = array("APA91bHhTiGeAKgphENoGH6********Blw9PspLCPAiprTSDN6mRuW3k253PZyppxgJaqPftTzYZOiWPt5C4XFVmkuqjbXp7MV3mAmpDAYM-11LdIdU0");
Related
The following code works for 2 or 3 users as long as I limit my query to 3 people. When I try it for 2000 people it no longer sends a notification. I also receive success:0 in response.
public function send_notification($registatoin_ids, $message) {
// Set POST variables
$googleapikey="AIzaSyCeFfqiRt3xFzZH2XDwICJDZkasF7uWBJI";
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . $googleapikey,
'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);
$result1=json_decode($result);
}
I'm also using the function above to call the function below to send my notifications. My problem is, It works when there are just 2 or 3 users, but when user's exceed 2000 it does not work as expected(sends notifications).
$qry = mysql_query("SELECT deviceToken FROM app_devices");
$devices = array();
while($row = mysql_fetch_assoc($qry))
{
$devices[] = $row['deviceToken'];
}
$gcm->send_notification($devices, $message);
To my knowledge we can at max send 1000 notifications from GCM at a time, so if u want to send more than that, divide the no of users into group of 1000 and send request in that manner.
For Eg:
If u want to send 2000 notifications then make 2 calls each having ids of 1000 users.
I advise you to use Firebase Cloud Messaging because it is the evolution of Google Cloud Messaging.
Try to use this:
$message = array ("message" => $bodyMail, "to" => $to, "From" => $from);
$id = array($to);
$message_status = sendPushNotification( $message, $id );
echo $message_status;
// Send push notification via Firebase Cloud Messaging
function sendPushNotification( $data, $ids )
{
// Insert real FCM API key from the Google APIs Console
$apiKey = "YourApiKey";
// Set POST request body
$fields = array(
'registration_ids' => $ids,
'data' => $data
);
// Set CURL request headers
$headers = array(
'Authorization: key =' . $apiKey,
'Content-Type: application/json'
);
// Initialize curl handle
$ch = curl_init();
// Set URL to GCM push endpoint
curl_setopt( $ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
// Set request method to POST
curl_setopt( $ch, CURLOPT_POST, true );
// Set custom request 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( $fields ) );
// Actually send the request
$result = curl_exec( $ch );
// Handle errors
if ( curl_errno( $ch ) )
{
echo 'FCM error: ' . curl_error( $ch );
}
// Close curl handle
curl_close( $ch );
// Debug GCM response
return $result;
}
I have a database with a column "regId" in a table users
What I want to do is select all rows but only that column (SELECT regId FROM users)
However, in PHP, I want this as
Array("the first row ID", "the second row ID", and so on)
I am building an app using the Google Cloud Messaging and the registration IDs are needed in an array like "Array("something", "something else")
Here's my code
<?php
session_start();
require_once("global.php");
$qry = "SELECT `regId` FROM `users` WHERE regId IS NOT NULL"; //Here's where the IDs are
$fetchQry = mysqli_query($connection, $qry);
// Replace with the real server API key from Google APIs
$apiKey = "/////";
// Replace with the real client registration IDs
$registrationIDs = array("","","",""); //heres how they need the IDs
// Message to be sent
$message = "somethinnnnnn";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $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));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_POST, true);
// 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;
//print_r($result);
//var_dump($result);
?>
And I have checked similar questions and they all use a while loop such as
$rows = [];
while($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
However, if I set the $registrationIDs variable equal to $rows or array($rows), it does not work! (even echoing them doesn't show the data)
I ended up sussing it out. Thanks to Create PHP array from MySQL column
Here's what I did:
$column = array();
while($row = mysqli_fetch_array($result)){
$column[] = $row['regId'];
//Edited - added semicolon at the End of line.1st and 4th(prev) line
}
I did earlier try this however it was originally mysql and not mysqli!!
I then also set my $registrationIDs variable equal to $column
try this one:
$rows = [];
while($row = mysqli_fetch_array($fetchQry)) {
$rows[] = $row;
}
see if it can work.
I have this script for sending a push notification on my android app :
<?php
// Replace with real BROWSER API key from Google APIs
$apiKey = "AIzaSyAATjQOVDdOUiHra0H-EfxpobQcqOsdwqa";
// Replace with real client registration IDs. Put the correct registration id you are getting from app. If you are using eclipse check your logcat you will get it there.
$registrationIDs = array("APA91bEmxWS9bsXLsixaYQ6zuByM0SzFWe5DEKVLO68923hW3Mo2qB6bIH2LarP5WgzKasMtFAdVyy8YQuwv0YbrRNwdGFORh1wQvQ9uKBkC3jH6uXBYAQOv5xfzrsjYjqcQK8syikrQ6dq6oRrp9XUnimdj_4oBbw" );
// Message to be sent
$message = "Push working!";
// Set POST variables.
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ) /*Make sure that message is the key you are using in GCMIntentService.java onMessage() -> extras.getString("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_SSL_VERIFYHOST, 0);
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
// Echo success or failure
echo $result;
?>
I never get any push notification on my phone. The thing is that actually i never get any output from the script like the echo $result; returns nothing.
Is this even possible?
Any ideas?
Solution
<?php
// Replace with real BROWSER API key from Google APIs
$apiKey = "AIzaSyAATjQOVDdOUiHra0H-EfxpobQcqOsdwqa";
// Replace with real client registration IDs. Put the correct registration id you are getting from app. If you are using eclipse check your logcat you will get it there.
$registrationIDs = array("APA91bEmxWS9bsXLsixaYQ6zuByM0SzFWe5DEKVLO68923hW3Mo2qB6bIH2LarP5WgzKasMtFAdVyy8YQuwv0YbrRNwdGFORh1wQvQ9uKBkC3jH6uXBYAQOv5xfzrsjYjqcQK8syikrQ6dq6oRrp9XUnimdj_4oBbw" );
// Message to be sent
$message = "Push working!";
// Set POST variables.
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ) /*Make sure that message is the key you are using in GCMIntentService.java onMessage() -> extras.getString("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_SSL_VERIFYPEER, 0);
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
// Echo success or failure
echo $result;
?>
Now it works perfectly.
Found the error.
Replace line curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
with line curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
I corrected the code on the question so now it works.
Who can tell me how can I get the "$registrationIDs = array( "reg id1","reg id2");", mentioned in the following code, which is posted here GCM with PHP (Google Cloud Messaging)
<?php
// Replace with real server API key from Google APIs
$apiKey = "your api key";
// Replace with real client registration IDs
$registrationIDs = array( "reg id1","reg id2");
// Message to be sent
$message = "hi Shailesh";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $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 ) );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_POST, true);
// 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;
//print_r($result);
//var_dump($result);
?>
You need to build a Web page that the app can use to communicate the RegID, once the app receives the RegID. You'll have to introduce some kind of server-side storage (a database, a file) that the RegID will be stored in.
Depending on your business, you might want to accept some additional parameters. POST form is a good place for those.
Then in the app, once you get the RegID, you perform a HTTP request, passing the RegID along. Word of caution: don't call HttpClient from the main thread. Use an AsyncTask, or spin a new Thread.
Searching for some info about how to send notifications using GCM but with PHP instead of servlets, i found this: GCM with PHP (Google Cloud Messaging)
I tested the working code of the responses of these questions, also i created a Key for browser apps (with referers), and i give permissions to this ip: .mywebsite.com/ (te php file is on this url: "http://www.mywebsite.com/~jma/cHtml5/cap/kk.php")
But i'm getting this response: Unauthorized Error 401
What i'm doing wrong?
this is the php file:
<?php
// Replace with real server API key from Google APIs
$apiKey = "fictional key";
// Replace with real client registration IDs
$registrationIDs = array( "APA91asdasdSDGGS232S13S4213abGqiNhCIXKjlxrkUYe_xTgTacNGB5n16b380XDd8i_9HpKGRHkvm8DDet4_WK3zumjDEKkTRWLgPS7kO-BrKzWz7eWFQaDD9PJ8zA6hlSqL9_zH21P8K22ktGKmo_VIF6YAdU9ejJovrKBTpgQktYkBZBf9Zw","APAasdasd32423dADFG91bHYYxYB7bFiX5ltbJt6A-4MBiNg7l4RS4Bqf3jIfYviaaUfZ810XJo2o66DY9-jdeJk_JR8FIZCyrmCv-eu_WLkGZ8KaoHgEDR_16H2QPm98uHpe1MjKVXbzYc4J89WMmcIrl5tHhWQnIQNzaI6Zp6yyFUNUQ");
// Message to be sent
$message = "Test Notificación PHP";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $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 ) );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_POST, true);
//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;
//print_r($result);
//var_dump($result);
?>
Solved!!!
you must use Key for server apps (with IP locking) instead of browser key
:)
You need to use the key for server apps in the field of API key in your server side coding.
While creating the server key don't enter anything inside IP address field.