LoginSignup
39
36

More than 5 years have passed since last update.

Firebaseを利用して特定端末へのpush通知

Posted at

Android + PHP でテスト

Android

ここを見て実装
https://firebase.google.com/docs/notifications/android/console-device

sendRegistrationToServerメソッドで自サーバにpush通知用のトークン送信する処理書けばok。
もちろんサーバ側ではトークンを格納する処理を書く

サーバからの特定端末への通知

Ruby使えたらgemとかありそうだったんですがPHPしか使えないサーバだったので。
こんな感じでクラス作ってNotification::sendで通知。
$pushTokensに対象となる複数のトークン(配列)を設定してメッセージ設定したら送信できる。

notification.php
class Notification {
  private static $apiKey = "hoge";  // Firebase console:Overview > プロジェクトの設定 > クラウドメッセージング > サーバーキー
  private static $url = "https://fcm.googleapis.com/fcm/send";

  static public function send($pushTokens, $message) {
    $headers = [
      "Authorization: key=".self::$apiKey,
      "Content-Type: application/json"
    ];

    $fields = [
      "registration_ids" => is_array($pushTokens) ? $pushTokens : [$pushTokens],
      "notification" => [
        "text" => $message
      ]
    ];

    $handle = curl_init();
    curl_setopt($handle, CURLOPT_URL, self::$url);
    curl_setopt($handle, CURLOPT_POST, true);
    curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($handle);
    curl_close($handle);
    return $result;
}

簡単でした。

39
36
0

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
39
36