2
5

More than 3 years have passed since last update.

Firebase Cloud Messaging API をPHPで叩いてみた

Posted at

Firebase Cloud Messaging API をPHPで叩いてみた

仕事でFirebaseを使ってモバイルアプリのプッシュ通知機能を実装することになったため、0から一人でネットの海を彷徨いながら調べたことをつらつらと書いていきます。

とりあえずAPI叩くには

自分の環境にcurlコマンドをインストールし、それぞれ必要な値を入力した下記コマンドをターミナルで叩いてみてください。

curl -X POST --header "Authorization: key={SERVER_KEY}" \
--Header "Content-Type: application/json" \
https://fcm.googleapis.com/fcm/send \
-d @- << EOF
{
    "registration_ids": ["{DEVICE_TOKEN}"],
    "notification": {
        "title": "{TITLE}",
        "body": "{MESSAGE}"
    },
    "priority": 10
}
EOF

{SERVER_KEY} = Firebaseコンソールを開き、プロジェクトの設定>クラウド メッセージング>プロジェクト認証情報 に記載されているサーバーキーの値を入力してください。

{DEVICE_TOKEN} = 対象のアプリから取得したデバイストークの値を入力してください。

{TITLE} = プッシュ通知に表示するタイトルを文字列で入力してください。

{MESSAGE} = プッシュ通知に表示するボディ部分のメッセージを文字列で入力してください。

コマンドを叩くと下記のようにmessage_idが返ってくれば成功です。

$ curl -X POST --header "Authorization: key=**********" \
> --Header "Content-Type: application/json" \
> https://fcm.googleapis.com/fcm/send \
> -d @- << EOF
> {
>     "registration_ids": ["**********"],
>     "notification": {
>         "title": "TEST",
>         "body": "This is test push."
>     },
>     "priority": "high"
> }
> EOF
{"multicast_id":**********,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"**********"}]}

PHPで書いてみた

curlコマンドだけではシステムに組み込む際に面倒だと思うので、続いてPHPで上記一連の処理を下記のように実装してみました。

<?php
define( 'FCM_API_SEVER_KEY', '{SEVER_KEY}');
define( 'FCM_API_URL', 'https://fcm.googleapis.com/fcm/send' );
$data = [
        "registration_ids" => ["{DEVICE_TOKEN}"],
        "notification" => [
                "title" => "{TITLE}",
                "body" => "{MESSAGE}"
        ],
        "priority" => "high"
];

$header = [
        'Authorization: key=' . FCM_API_SEVER_KEY,
        'Content-Type: application/json',
];
$context = stream_context_create(array(
        'http' => array(
                'method' => 'POST',
                'header' => implode(PHP_EOL,$header),
                'content'=>  json_encode($data),
                'ignore_errors' => true
        )
));

$response = file_get_contents(
        FCM_API_URL,
        false,
        $context
);

$result = json_decode($response,true);

// 返却値を確認
var_dump($result);

このファイルを下記のように実行すれば先ほどのcurlコマンドと同じようにプッシュ通知を送信できます。

$ php fcmReq.php
array(5) {
  ["multicast_id"]=>
  int(**********)
  ["success"]=>
  int(1)
  ["failure"]=>
  int(0)
  ["canonical_ids"]=>
  int(0)
  ["results"]=>
  array(1) {
    [0]=>
    array(1) {
      ["message_id"]=>
      string(16) "**********"
    }
  }
}

参考記事

https://qiita.com/nkmrh/items/e964d916f9a2620a1b80
https://qiita.com/re-24/items/542f39220a606e319fa1

2
5
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
2
5