LoginSignup
1
1

More than 5 years have passed since last update.

動いた、FirebaseのCloud Messaging(FCM) for ウェブ(Javascript)

Posted at

概要

FCMなんとか動いた。忘備録。

環境

  • Apache (Amazon Linux)
  • Chrome (ver 70)

とにかく試す

手順

  • Firebaseプロジェクトの作成
  • サンプルコードの設置
  • 送信処理の実行

Firebaseプロジェクトの作成

Firebase Console (https://console.firebase.google.com) にアクセスして、Googleアカウントでログイン。
プロジェクトの追加。Sparkプランにしておくと月額無料。
プロジェクトのクラウドメッセージングにある、サーバーキーのトークンと、送信者IDを次で使う。
firebase-messaging.png

サンプルコードの設置

ServiceWorkerとしてWebブラウザのバックグラウンドで動くJavascriptを利用するので、httpsなWebサーバに設置する。
SENDER_ID(2箇所)とSERVER_KEYを上記で取得したものに置き換える。
firebase-messaging-sw.js だけはWebルートに設置する、ファイル名も固定。

送信処理の実行

FCMのAPIにポストする。下記phpでポストした。

サンプルコード

  • test.html
  • firebase-messaging-sw.js
  • send.php
test.html
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-messaging.js"></script>
<script>
  // Initialize Firebase
  var config = {
    messagingSenderId: SENDER_ID
  };
  firebase.initializeApp(config);

  // Retrieve Firebase Messaging object.
  const messaging = firebase.messaging();

  function initFirebaseMessagingRegistration() {
      return messaging
          .requestPermission()
          .then(function () {
              console.log("Got notification permission");
              return messaging.getToken(); // これがServiceWorkerを登録(firebase-messaging-sw.js)
          })
          .catch(function (err) {
              console.log("Didn't get notification permission", err);
          });
  }
</script>
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/5.7.0/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/5.7.0/firebase-messaging.js')

var config = {
  messagingSenderId: SENDER_ID
};
firebase.initializeApp(config);

self.addEventListener('push', event => {
  if (event.data) {
    console.log('This push event has data: ', event.data.text());
  } else {
    console.log('This push event has no data.');
  }

  const dataJson = event.data.json();
  const notification = dataJson.notification; 
  event.waitUntil(
    self.registration.showNotification(
      notification.title,
      {
        body: notification.body,
        icon: notification.icon
      }));
});
send.php
$httpHeader = [];
$httpHeader[] = 'Authorization: key='.SERVER_KEY;
$httpHeader[] = 'Content-Type: application/json';

$notification = [
    'title' => "メッセージサンプル",
    'body' => "サンプルメッセージです。",
    'icon' => '/logo.png',
];

$to = $toToken;
$url = 'https://fcm.googleapis.com/fcm/send';

$options = [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => $httpHeader,
    CURLOPT_POSTFIELDS => json_encode(compact('notification', 'to')),
];
$curl = curl_init($url);
curl_setopt_array($curl, $options);
$exec = curl_exec($curl);
if (empty($exec)) {
    $info = curl_getinfo($curl);
    curl_close($curl);
    echo "Error !!".PHP_EOL;
    var_dump($info);
}
else {
    curl_close($curl);
    var_dump($notification);
    echo "Success !!".PHP_EOL;
}
1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1