【问题标题】:Firebase push notification using PHP使用 PHP 的 Firebase 推送通知
【发布时间】:2017-09-15 20:50:04
【问题描述】:

我正在使用 Firebase 推送通知。我的 PHP 代码运行良好。我收到成功消息,但在我的 Android 应用程序中没有收到单设备和多设备的推送通知。但是使用 Firebase 控制台发送通知它工作正常。我在 Android 设备上收到了通知。我需要添加任何服务器配置吗?

PHP 代码:

$yourApiSecret = "AIzaSyDY";
$androidAppId = "traasasadad";
$data = array(
    "tokens" => "AAAA_kFbSQ4:APA91bQuMV-nRuTnVNFg0HD2C9PBnWWad",
    "notification" => "Hello World!"
);
$data_string = json_encode($data);
$ch = curl_init('https://push.ionic.io/api/v1/push');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'X-Ionic-Application-Id: '.$androidAppId,
        'Content-Length: ' . strlen($data_string),
        'Authorization: Basic '.base64_encode($yourApiSecret)
    )
);

$result = curl_exec($ch);
var_dump($result);

安卓代码:

package com.seven77Trades.notification;

/**  * Created by ist on 21/3/17.  */ import
android.app.NotificationManager; import android.app.PendingIntent;
import android.content.Context; import android.content.Intent; import
android.media.RingtoneManager; import android.net.Uri; import
android.support.v4.app.NotificationCompat; import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService; import
com.google.firebase.messaging.RemoteMessage; import
com.seven77Trades.HomeActivity; import com.seven77Trades.R;

public class FirebaseMsgService 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
        // messages. For more see: 
        // [END_EXCLUDE]

        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be: 
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        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());
            /*Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getColor());
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getSound());
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getTag());
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getClickAction());*/


            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.
    }
    // [END receive_message]

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, HomeActivity.class);
        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.mipmap.ic_logo)
                .setContentTitle("Firebase")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    } }

输出:

"{"multicast_id":8295856130292351869,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1492611205996022%0296efeff9fd7ecd"}]}"

【问题讨论】:

  • 您的通知数据是否需要alert 字段? This documentation 似乎表明确实如此。
  • 另请参见此处的示例:legacy.docs.ionic.io/v1.0/docs/push-api-examples
  • 为什么不直接使用 FCM (https://fcm.googleapis.com/fcm/send) 发送?
  • @AL 我已经在使用这个 URL,并且我收到了成功消息,但在 android 应用程序中没有收到。是否有服务器白名单
  • AFAIK,FCM 中没有服务器白名单。你能发布你的 Android 端代码吗?

标签: php android firebase ionic-framework firebase-cloud-messaging


【解决方案1】:

我得到了解决方案。终于我在 android 设备中收到了通知。当我们使用 API(php、java、python)发送通知时,android 应用程序以不同的方法获取此请求(WakefulBroadcastReceiver) 并且当我们使用 fire base 控制台发送请求时,请求来自不同的方法 (FirebaseMessagingService)。

这里是 BrackPul​​lBroadCastReceiver:

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());

// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));

setResultCode(Activity.RESULT_OK);
}
}




public class GcmIntentService extends IntentService {

private Context context;

public GcmIntentService() {
super("GcmIntentService");
}

String imageUrl = "";

@Override
protected void onHandleIntent(Intent intent) {

context = this;
Bundle extras = intent.getExtras();
for (String key: extras.keySet())
{
Log.d (TAG, key + " is a key in the bundle");
Log.d(TAG, extras.get(key) + "");
}
}
}

【讨论】:

    【解决方案2】:

    我认为目标 url 有一些错误,您可以尝试像这样发送通知:

    $url = 'http://fcm.googleapis.com/fcm/send';
    
          $fields =array(
            "notification"=> array(
                           "title" => 'sometitle',
                           "body" => $message, //Can be any message you want to send
                           "icon" => $image,
                           "click_action" => "http://google.com"
    
                           ),
                       "registration_ids"=> 'Your android app fcm token',
                       "data"=> array(
                         "data" => "something",
                       )
                   );
    
          $fields = json_encode ( $fields );
          $headers = array (
                'Authorization: key=' . "your firebase app 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_POSTFIELDS, $fields );
    
          $result = curl_exec ( $ch );
          curl_close ( $ch );
    

    您还可以在有效负载中传递自定义数据

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 2018-09-17
      • 2019-01-30
      • 2017-03-05
      • 2018-09-19
      相关资源
      最近更新 更多