【问题标题】:FCM received notification from php didn't work from my server and work from adminFCM 从 php 收到的通知在我的服务器上不起作用,从管理员那里工作
【发布时间】:2016-10-01 14:05:01
【问题描述】:

从我的服务器 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:1475538722422633%584545e6f9fd7ecd\"}]}

安卓代码是:

         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 管理员中对特定令牌和所有人都可以正常工作。

我发送了设备令牌并保存在数据库中。

【问题讨论】:

  • 您是否收到任何错误响应?
  • 不,我得到了成功响应

标签: php android firebase push-notification firebase-cloud-messaging


【解决方案1】:

你必须在 php 和 android 中都使用 FCM 代码

这里是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 )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 2019-07-04
    • 2020-03-25
    • 2019-08-07
    • 1970-01-01
    相关资源
    最近更新 更多