I have device token "apid" from android phone. I get the valid response that notification is send. but i dont receive the notification. can some one please guide me i am using the following code. i am using php for sending notification
$contents = array();
$contents['alert'] = 'test notification for android';
$notification = array();
$notification['android'] = $contents;
$platform = array();
array_push($platform, "android");
$dev['apid'] = 'valid_device_token_from_android' ;
$push = array("audience"=> $dev, "notification"=>$notification, "device_types"=>$platform);
$json = json_encode($push);
echo "Payload: " . $json . "\n"; //show the payload
$session = curl_init(PUSHURL);
curl_setopt($session, CURLOPT_USERPWD, APPKEY . ':' . PUSHSECRET);
curl_setopt($session, CURLOPT_POST, True);
curl_setopt($session, CURLOPT_POSTFIELDS, $json);
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_RETURNTRANSFER, True);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept: application/vnd.urbanairship+json; version=3;'));
$content = curl_exec($session);
echo "Response: " . $content . "\n";
Thanks
Related
I am trying to use cordova fcm plugin on Android to implement the data sent by Firebase Cloud Messaging. I successfully received the notifications, but when I tap them they are not giving the alert I want.
Here is the code used in index.js:
onDeviceReady: function() {
app.receivedEvent('deviceready');
FCMPlugin.onNotification(
function(data){
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
alert( JSON.stringify(data) );
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
alert( JSON.stringify(data) );
}
},
function(msg){
alert('onNotification callback successfully registered: ' + msg);
},
function(err){
alert('Error registering onNotification callback: ' + err);
}
);
},
And here is the php code I used to send the notification:
function pushAndroidNotification ($productUrl, $message, $deviceToken) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => array($deviceToken),
'notification' => array(
"title" => "rBUX",
"body" => $message,
"icon" => "name_of_icon" ),
'data' => array("url" => $productUrl)
);
$jfields = json_encode($fields);
echo "\r\n<br>Post json:".$jfields;
$headers = array(
'Authorization: key = AIzaSyBPRoJ7zgmevPYIzoDweVgNTbmsPBW5ofo',
'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, $jfields);
$result = curl_exec($ch);
if ($result === FALSE) {
echo "\r\n<br>Notify Failed:".curl_error($ch);
die('Curl failed: '.curl_error($ch));
}else{
echo "\r\n<br>Notify passed:".$result;
}
$jresponse = json_decode($result, true);
curl_close($ch);
return $jresponse;
}
But every time I launch the app, I can see the alert "onNotification callback successfully registered: OK", so the FCM plugin is not completely disabled.
I would like to launch the url when I tap on the notification, but for now it appears that I can't even use the data. If anyone knows how to solve this please tell me, and please let me know how to use stringified data to launch the url in cordova inAppBrowser, thank you.
For "cordova-plugin-fcm" plugin, You need to set click_action to FCM_PLUGIN_ACTIVITY in the notification payload part.
I got the following from their website:
{
"notification":{
"title":"Notification title", //Any value
"body":"Notification body", //Any value
"sound":"default", //If you want notification sound
"click_action":"FCM_PLUGIN_ACTIVITY", //Must be present for Android
"icon":"fcm_push_icon" //White icon Android resource
},
"data":{
"param1":"value1", //Any data to be retrieved in the notification callback
"param2":"value2"
},
"to":"/topics/topicExample", //Topic or single device
"priority":"high", //If not set, notification won't be delivered on completely closed iOS app
"restricted_package_name":"" //Optional. Set for application filtering
}
I am developing Firebase push notification using Server API call in Android application.it works perfectly when application is in foreground but when application is not in foreground i am not able to get the push notification.
I am sending JSON data in which header contains Server API key and content type and the value contains data which have body as array. Appreciate any help.
PHP code:
$url = 'https://fcm.googleapis.com/fcm/send';
$fields =array('registration_ids' => $tokens,'data' => $message);
$headers = array('Authorization:key = value','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);?>
Look at my code. Maybe it will help you:
$token = getTokenDevice($dn);
$path_to_firebase_cm = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'to' => $token,
'priority' => 'normal',
'content_available' => true,
'data' => array('type' => $type, 'title' => $title, 'body' => $message)
);
$headers = array(
'Authorization:key='.$server_key,
'Content-Type:application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $path_to_firebase_cm);
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_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
I use content_available for iOS devices. That code works for me in Android and iOS when apps are in background.
So you should check your FirebaseMessaging service. Mine looks like this:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Auth auth = new Auth(getApplicationContext());
Map<String, String> data = remoteMessage.getData();
if (auth.isNotificationEnabled(data.get("type"))) {
Log.e(TAG, "data: " + remoteMessage.getData());
sendNotification(data.get("title"), data.get("body"));
}
}
I too felt this was happening in the beginning but then discovered that my Android App was indeed waking up. Unfortunately it was not waking up enough to do what I wanted (send a heartbeat REST message to my Server). So I will answer your question with a question - why did you decide you did not get a push notification ? For me, when I logged messages from within the onMessageReceived ....
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getData());
}
It proved the App got woken up each time the Fire Cloud Messaging service sent a message, regardless if the App was in foreground or background.
Other mistakes, I made initially I shall share with you:
I had to make some changes to my Server side to ensure that the Android App onMessageReceived() method was always called even in background mode. My messages were JSON and HTTP and Upstream. My server is written in C#.
In Firebase there are 2 types of payload downstream messaging. (a) Notification and (b) Data. The type depicts how the App behave when receiving messages depend on whether the app is in background or the foreground. Hence I needed (b) Data type payload to meet my requirement. Just add the “data”
I then had to make my messages High Priority rather than normal. I did a load of tests with both normal and high. Normal did not work once the Android App went into Doze mode. I found this reference useful. https://developer.android.com/training/monitoring-device-state/doze-standby.html#support_for_other_use_cases
I have implemented the rest api of payment with paypal in android application using this code
:
if (isset($_POST['paypal_response']) ) {
$json = json_decode( $_POST['paypal_response'], true );
if (isset($json['proof_of_payment']['rest_api']) ) {
echo 'rest api et voila le payment_id : '.$json['proof_of_payment']['rest_api']['payment_id'].'\n';
$http_header_card = array(
'Content-Type:application/json',
'Authorization:Bearer ENxom5Fof1KqAffEsXtxwEDa6E1HTEK__KVdIsaCYF8C'
);
$ch = curl_init();
$get_request = "https://api.sandbox.paypal.com/v1/payments/payment/{".$json['proof_of_payment']['rest_api']['payment_id']."}";
curl_setopt($ch, CURLOPT_URL, $get_request);
curl_setopt($ch, CURLOPT_HTTPHEADER, $http_header_card );
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$html = curl_exec ($ch);
echo $html;
I have also implemeted the verification of proof for adaptive payment (with paypal account)
but this one above, always send me this response :
{"name":"INTERNAL_SERVICE_ERROR","message":"An internal service error has occurred","information_link":"https://api.sandbox.paypal.com/docs/api/#INTERNAL_SERVICE_ERROR"}1
I don't know the reason knowing that I have followed the official documentation here
here is the code of the doc which I have converted to php :
curl https://api.sandbox.paypal.com/v1/payments/payment/PAY-5YK922393D847794YKER7MUI \
-H "Content-Type:application/json" \
-H "Authorization:Bearer ENxom5Fof1KqAffEsXtxwEDa6E1HTEK__KVdIsaCYF8C"
how can I fix this issue
thanks
I am running the Google GCM test code from here and it runs on both emulator and phone, however when I do a send message the notification only works on the emulator and not the phone.
GCMIntentService Notifcation
import android.support.v4.app.NotificationCompat;
...
// issues a notification to inform the user that server has sent a message
private void generateNotification(Context context, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher)
.setTicker(context.getString(R.string.app_name)).setContentText(message);
Intent notificationIntent = new Intent(context, Main.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// add notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(FM_NOTIFICATION_ID, builder.build());
}
PHP Send message and send function
require_once 'push_db_functions.php';
$dbf = new push_db_functions();
$id = '40';
$message = "Test Message";
$response = $dbf->sendMessage($id, $message);
$response = json_decode($response);
print_r($response);
public function sendMessage($id, $message) {
$results = mysql_query("SELECT regid FROM test WHERE id = '$id'");
$processed = mysql_fetch_row($results);
$url = 'https://android.googleapis.com/gcm/send';
$apiKey = "AIzaSyD-xxx";
$fields = array('registration_ids' => $processed, '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));
// execute post
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Send message response
stdClass Object ( [multicast_id] => 5036849453049739126 [success] => 1 [failure] => 0 [canonical_ids] => 0 [results] => Array ( [0] => stdClass Object ( [message_id] => 0:1353799902066759%04108f12f9fd7ecd ) ) ) success
I have 2 regId records in my database, one for the emulator and one for the phone $id 39 and 40 and change them accordingly to send messages to either device.
Database records
id | regid
39 | APA91bFyMJx4b0ddI........ Emulator
40 | APA91bFhwEhHOClkg........ Phone
The phone is running Gingerbread and the program registers and runs correctly on it except for not displaying the notification upon message receipt.
mDisplay = (TextView) findViewById(R.id.display);
registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
Log.d("registrationID", "::" + regId);
if (regId.equals("")) {
// automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
}
Any help would be greatly appreciated.
Thanks
Thank you for everyone that responded to this question.
I have resolved the issue:
On my phone under Accounts & Sync, General sync settings, I found that the Background data sync box was not ticked. When set all works fine.
I should have figured this out before asking the question, my apologies.
However I hope this answer can be of assistance to others.
HI~everyone!
I have gotten the registration_id for the phone and an auth token from google for my gmail account that is performing a push.
But When I send my auth token and registration id to Ubuntu and try to post it by php , php's curl and only curl to request to C2DM to get a message. And I always get the 401 Unauthorized.
And this is my php code ....
$post_params = array ( "Email" => $MY_GOOGLE_ACC, "Passwd" =>
$MY_GOOGLE_PWD, "accountType"=>"GOOGLE", "source=" . $MY_GOOGLE_SRC, "service=ac2dm" );
$first = true;
$data_msg = "";
foreach ($post_params as $key => $value) {
if ($first)
$first = false;
else
$data_msg .= "&";
$data_msg .= urlencode($key) ."=". urlencode($value);
}
$x = curl_init("https://www.google.com/accounts/ClientLogin");
curl_setopt($x, CURLOPT_HEADER, 1);
curl_setopt($x, CURLOPT_POST, 1);
curl_setopt($x, CURLOPT_POSTFIELDS, $data_msg);
curl_setopt($x, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($x);
curl_close($x);
$response = $data;
$authKey = trim(substr($response, 4+strpos($response, "SID=")));
echo $authKey; $collapse_key = 'something';
$post_params = array ( "registration_id" => $DEVICE_TOKEN, "collapse_key" =>
$collapse_key, "data.payload"=>"cakephp" );
$first = true;
$data_msg = "";
foreach ($post_params as $key => $value) {
if ($first)
$first = false;
else
$data_msg .= "&";
$data_msg .= urlencode($key) ."=". urlencode($value);
}
$size=strlen($data_msg);
$x = curl_init("https://android.apis.google.com/c2dm/send");
curl_setopt($x, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Content-Length:'. $size, 'Authorization: GoogleLogin auth=' . $authKey));
curl_setopt($x, CURLOPT_HEADER, 1);
curl_setopt($x, CURLOPT_POST, 1);
curl_setopt($x, CURLOPT_POSTFIELDS, $data_msg);
curl_setopt($x, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($x);
curl_close($x);
$response = $data;
Am I miss somthing or do something wrong?
AND any help would be much appreciated,thanks!!
It seems you are extracting the SID from the response, not the Auth field.
$authKey = trim(substr($response, 4+strpos($response, "SID=")));
should be
$authKey = trim(substr($response, 5+strpos($response, "Auth=")));
Try printing the whole response, you'll see something like:
SID=DQAAAGgA...7Zg8CTN
LSID=DQAAAGsA...lk8BBbG
Auth=DQAAAGgA...dk3fA5N
It's this last field that you're searching for!