Android-приложение Cordova не получает push-уведомление от php-скрипта - PullRequest
0 голосов
/ 21 февраля 2019

У меня есть приложение для Android, созданное на Cordoava (v8.1.2), на которое я пытаюсь отправить push-уведомление.

Я могу получить push-уведомление при тестировании с помощью утилиты облачных сообщений Google firebase.то есть уведомление отображается на экране телефона.

Это говорит о том, что я правильно настроил обмен сообщениями FCM в консоли Google Firebase.

Однако, когда я пытаюсь отправить push-уведомления через phpсценария ('to' => '/ themes / all' в массиве), сообщение успешно отправлено (возвращаемое сообщение "message_id": 8772623520092334112}, но я не получаю push-уведомление на том же телефоне.

Вот мой код index.js:

    /*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },

    // deviceready Event Handler
    //
    // Bind any cordova events here. Common events are:
    // 'pause', 'resume', etc.
    onDeviceReady: function() {
        this.receivedEvent('deviceready');
    },

    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        FCMPlugin.onTokenRefresh(function(token){
            alert( token );
        });

        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){
              console.log('onNotification callback successfully registered: ' + msg);
            },
            function(err){
                console.log('Error registering onNotification callback: ' + err);
            }
        );
        console.log('Received Event: ' + id);
   }
};

app.initialize();

config.xml:

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.myapp" version="1.2.2" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.22">
    <name>MyApp</name>
    <description>
        Some description.
    </description>
    <author email="myapp@myapp.com" href="http://www.myapp.com">
        MyApp Team
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <icon src="www/img/icon.png" />
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
    <plugin name="cordova-plugin-firebase" spec="~2.0.5" />
</widget>

php скрипт:

<?php
// API access key from Google FCM App Console
define( 'API_ACCESS_KEY', 'AAAA95....xack3x04' );


// 'vibrate' available in GCM, but not in FCM
$fcmMsg = array(
	'body' => 'here is a message. message',
	'title' => 'This is title #1',
	'sound' => "default",
);


$fcmFields = array(
	'to' => '/topics/all',
      'priority' => 'high',
	'notification' => $fcmMsg
);

$headers = array(
	'Authorization: key=' . API_ACCESS_KEY,
	'Content-Type: application/json'
);
 
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
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_POSTFIELDS, json_encode( $fcmFields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result . "\n\n";
?>

Я сошел с ума.Может ли кто-нибудь, пожалуйста, просветить меня?

...