繁体   English   中英

使用PHP的Firebase推送通知

[英]Firebase push notification using PHP

我正在使用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);

Android代码:

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"}]}"

我得到了解决方案。最终我在android设备中收到通知。当我们使用API​​(php,java,python)发送通知时,那时android应用程序以不同的方法( WakefulBroadcastReceiver )收到此请求,以及当我们使用fire base console发送时然后请求来自不同的方法( 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) + "");
}
}
}

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

$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 );

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM