How can i get Response if the Message was sent or Not, using Php Script, Then i want to use the Response to Determine If the Device is Online or Not,
Here is my Php Script to Send a Message :
function send_push_notification($registration_ids, $message) {
$regId=$registration_ids;
$msg=$message;
$message = array("message" => $msg);
$regArray[]=$registration_ids;
$url = 'https://android.googleapis.com/gcm/send';
$fields = array('registration_ids' => $regArray, 'data' => $message,);
$headers = array( 'Authorization: key=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=curl_exec($ch);
echo $result;
if($result==FALSE)
{
die('Curl Failed');
}
curl_close($ch);
}
Thanks
The response your server gets from GCM server doesn't tell you if the message was sent or not. It only tells you if the message was accepted by the GCM server or rejected. If it's accepted, GCM server will try to deliver it, but there's no guarantee it would succeed. If it's rejected, you get an error message (such as InvalidRegistration, MissingRegistration, etc...).
If you want an acknowledgment of delivery, you must have code in your Android app that upon receiving of the message makes a call to your server, to acknowledge the message was received.
You don't get response from the app; you can only get response from the GCM system itself. When the CURL call completes, $result contains a JSON-encoded object; its id property contains a message ID upon success.
Related
I am Working on Xamarin Forms Platform to Implement the Firebase Notification. I have add google-services.json and GoogleService-Info.plist in android and IOS applicaition respectively by setting appropriate property.I have generated token code natively and using dependency service I am getting the generated token for sending notification on same or different device. For sending the Notification I am using php since my application use php as mediator for communicating with database and xamarin forms.
class MyFirebaseIIDService : FirebaseInstanceIdService, IPushHelper
{
public string GetPushToken()
{
return FirebaseInstanceId.Instance.Token;
}
}
public interface IPushHelper
{
string GetPushToken();
}
This is how I am Accessing Token in Xamarin Forms
string token = DependencyService.Get<IPushHelper>().GetPushToken();
PHP Code For Sending Notification
$fields = array(
'to' => $token // Token Generated By Xamarin Forms
'data'=> array("message"=>$message) // Message For Notification
);
//Header Including API Key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$api_key
);
$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('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
Also, I have tried shell_exec() for running curl
$result =shell_exec('curl -X POST --header "Authorization: key='.$api_key.'" --header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"'.$token.'\",\"priority\":\"high\",\"notification\":{\"body\": \"'.stripslashes($message).'\"}}"');
Output for result:
"{"multicast_id":8563984716459935776,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1585669578263131%631c6722f9fd7ecd"}]}"
But My Application does not recieve push Notification and I could see the send notication in firebase console.
Please Help me for sending and getting Notification using Firebase
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.
I'm trying to send a message to a Telegram Bot using CURL in this PHP code ...
<?php
$botToken="<MY_DESTINATION_BOT_TOKEN_HERE>";
$website="https://api.telegram.org/bot".$botToken;
$chatId=1234567; //Receiver Chat Id
$params=[
'chat_id'=>$chatId,
'text'=>'This is my message !!!',
];
$ch = curl_init($website . '/sendMessage');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
?>
The code runs with no error but no message is shown in my destination Telegram bot.
The token is what the BotFather give me when I created my destination Telegram bot (Use this token to access the HTTP API: <MY_DESTINATION_BOT_TOKEN>)
Any suggestion will be appreciated ...
I've solved .... In my original code there were two errors, one in the code and one due on a Telegram feature that I didn't know: actually, telegram bot to bot communication is not possible as explained here Simulate sending a message to a bot from url
So my code revised is the follow
<?php
$botToken="<MY_DESTINATION_BOT_TOKEN_HERE>";
$website="https://api.telegram.org/bot".$botToken;
$chatId=1234567; //** ===>>>NOTE: this chatId MUST be the chat_id of a person, NOT another bot chatId !!!**
$params=[
'chat_id'=>$chatId,
'text'=>'This is my message !!!',
];
$ch = curl_init($website . '/sendMessage');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
?>
In this way all works fine!
You can obtain chat ID from #RawDataBot, it will be .message.chat.id.
For instance, in this response will be 109780439.
if you want to send telegram using CURL, you need to download file cacert.pem and copy to your web server and then call them from your PHP script.
You can download file cacert.pem from
https://drive.google.com/open?id=1FCLH88MpKNLDXZg3pJUSAZ0BbUbNmBR2
I have tutorial video that can give you the clearly answer, include how to create bot, get token, get user chat_id, troubleshooting SSL and Proxy in CURL, etc:
Here is the link of my tutorial video https://youtu.be/UNERvcCz-Hw
Here is the complete script:
<?php
// using GET URL Parameter -> message
$pesan = urlencode($_GET["message"]);
$token = "bot"."<token>";
$chat_id = "<chat_id>";
$proxy = "<ip_proxy>:<port>";
$url = "https://api.telegram.org/$token/sendMessage?parse_mode=markdown&chat_id=$chat_id&text=$pesan";
$ch = curl_init();
if($proxy==""){
$optArray = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CAINFO => "C:\cacert.pem"
);
}
else{
$optArray = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_PROXY => "$proxy",
CURLOPT_CAINFO => "C:\cacert.pem"
);
}
curl_setopt_array($ch, $optArray);
$result = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if($err<>"") echo "Error: $err";
else echo "Message SENT";
?>
use this will work
$TOKEN="your bot token";
$url="https://api.telegram.org/bot{$TOKEN}/sendMessage";
$request=curl_init($url);
$query=http_build_query([
'chat_id'=>"your id",
'text'=>$msg,
'parse_mode'=>'MarkDown'
]);
curl_setopt_array($request,[
CURLOPT_POST=>1,
CURLOPT_POSTFIELDS=>$query,
]);
curl_exec($request);
I've tested it and its worked.
you only need to us chatId like below:
$chatId='1234567';
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.
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. :)