#php #android #firebase #push-notification #firebase-cloud-messaging
#php #Android #firebase #push-уведомление #firebase-облако-обмен сообщениями
Вопрос:
У меня проблема, когда я получаю уведомление от php-кода моего сервера, но оно работает хорошо, когда я отправляю его от администратора firebase.
Я получаю ключ сервера из настроек в проекте firebase и получаю ключ браузера и пытаюсь использовать оба и не работает
вот код php :
function sendToAndroid($DevicesTokens, $ID, $Message) {
// Set POST variables
$url = 'https://fcm.googleapis.com/fcm/send';
$_Message = array(
'id' => $ID,
'message' => $Message
);
$fields = array(
'registration_ids' => array($DevicesTokens),
'data' => $_Message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$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, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
return $result;
}
вот ответ в формате json
{«multicast_id»:4977823335719589401,»success»:1,»failure»:0,»canonical_ids»:0,»results»:[{«message_id»:»0:1475538722422633X4545e6f9fd7ecd»}]}
и код Android :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MessageActivity.class);
intent.putExtra("message",messageBody);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.like_icon)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " refreshedToken);
sendRegistrationToServer(refreshedToken);
}
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("Token",token)
.build();
Request request = new Request.Builder()
.url("http://192.168.1.71/fcm/register.php")
.post(body)
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Я думаю, что проблема в моем php-коде, потому что он отлично работает от администратора firebase для определенного токена и для всех.
Я отправил токен устройства и сохранил в базе данных.
Комментарии:
1. Вы получаете какой-либо ответ об ошибке?
2. нет, я получаю успешный ответ
Ответ №1:
Вы должны использовать код FCM для php и Android в обоих
Вот полный рабочий код php
$msg = "Hello Zamin";
$device_id = 'Your device token';`
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'to' => $device_id,
'notification' => array (
"body" => $msg,
'title' => "iorder",
"icon" => "myicon"
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "Your Server id",
'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_POSTFIELDS, $fields );
echo $result = curl_exec ( $ch );
curl_close ( $ch )