close

 

Error Message:

1.FirebaseError: Messaging: Notifications have been blocked. (messaging/notifications-blocked).

開啟Chrome的通知允許 

 

使用POSTMAN 測試 送推播給Firebase

POST URL :

https://fcm.googleapis.com/fcm/send

Header :

Content-Type : application/json
Authorization : key=<Your Cloud Messaging Key>

Body:

{ "notification": {
    "title": "Your Title",
    "text": "Your Text",
     "click_action": "OPEN_ACTIVITY_1"
  },
  "to" : "<Token>"

POST 回傳正常訊息:

{
    "multicast_id": 71607338..158701,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [
        {
            "message_id": "0:1524194..f9fd7ecd"
        }
    ]
}

 

POST 回傳錯誤訊息

Could not get any response
There was an error connecting to https://fcm.googleapis.com/fcm/send.
Why this might have happened:
  • The server couldn't send a response:
    Ensure that the backend is working properly
  • Self-signed SSL certificates are being blocked:
    Fix this by turning off 'SSL certificate verification' in Settings > General
  • Proxy configured incorrectly
    Ensure that proxy is configured correctly in Settings > Proxy
  • Request timeout:
    Change request timeout in Settings > General

解決方法: 從Firebase 複製 Key 貼上時,會有一個斷行符號,要注意清除

完整 Client 端 index.html

<html>
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Firebase Cloud Messaging Example</title>
<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script>
<script>
// Initialize Firebase
// TODO: Replace with your project's customized code snippet
var config = {
apiKey: "AIzaSyBVmCa0dkPpVwB-rq7p5-meE0wvnswoAT8",
authDomain: "testfcm-31d35.firebaseapp.com",
databaseURL: "https://testfcm-31d35.firebaseio.com",
projectId: "testfcm-31d35",
storageBucket: "testfcm-31d35.appspot.com",
messagingSenderId: "991319139484"
};
firebase.initializeApp(config);
</script>
<!--jquery CDN-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.js" integrity="sha256-fNXJFIlca05BIO2Y5zh1xrShK3ME+/lYZ0j+ChxX2DA=" crossorigin="anonymous"></script>
</header>
<body>
<div id="notification">
<div id="title"></div>
<div id="message"></div>
</div>
</body>
<script>
//Initialize
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function() {
console.log('Have Permission');
getToken();
})
.catch(function(err) {
console.log('Errr Occured' + err);
})
 
function getToken() {
messaging.getToken()
.then(function(currentToken) {
if (currentToken) {
console.log('Token:' + currentToken);
} else {
console.log('No Instance ID token available. Request permission to generate one.');
}
})
.catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
});
}
 
messaging.onMessage(function (payload) {
console.log('onMessage:', payload);
$("#title").text(payload.notification.title);
$("#message").text(payload.notification.body);
});
</script>
</html>

根目錄的 Service Worker : firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');

var config = {
    apiKey: "AIzaSyBVmC...0wvnswoAT8",
    authDomain: "testfcm-31d35.firebaseapp.com",
    databaseURL: "https://testfcm-31d35.firebaseio.com",
    projectId: "testfcm-31d35",
    storageBucket: "testfcm-31d35.appspot.com",
    messagingSenderId: "99269484"
    };
firebase.initializeApp({
  'messagingSenderId': '991319139484'
});

 

PHP Service 發送

$fcm_api_key = 'AAAA5s85pJw:APA91bE0...6E81W';
$msg = array(
'body' => $this->message,
'title' => $this->title,
);
 
$fields = array(
'to' => $token,
'notification' => $msg,
);
 
$headers = array(
'Authorization: key=' . $fcm_api_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($fields));
$result = json_decode(curl_exec($ch));
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpcode != 200) {
return false;
}

 

參考網站:

http://blog.changyy.org/2017/10/firebase-firebase-fcm-web-app-debug.html

https://stackoverflow.com/questions/37371990/how-can-i-send-a-firebase-cloud-messaging-notification-without-use-the-firebase

arrow
arrow
    文章標籤
    FCM javascript
    全站熱搜

    allblue1928 發表在 痞客邦 留言(0) 人氣()