技術ブログ

プログラミング、IT関連の記事中心

PHPでFirebase Cloud Messaging(FCM)のPush通知を送信する方法【Node.js】

■はじめに

Firebase Cloud Messaging(以降、FCM)でPush通知を送信するため、「Server Key」と、送信先の「Device Token」が取得できている前提として本手順を記載します。

■手順

以下に、PHPでFCMのプッシュ通知を送信する処理を記載します。

<?php

$api_key = "{サーバーキー}";
$base_url = "https://fcm.googleapis.com/fcm/send";

$data = array(
    "to"           => $_POST['token']
    , "priority"     => "high"
    , "notification" => array(
        "title" => $_POST['title']
        , "body"  => $_POST['body']
        , "sound" => "default"
        , "badge" => $_POST['badge']
    )
);
$header = array(
    "Content-Type:application/json"
    , "Authorization:key=".$api_key
);
$context = stream_context_create(array(
    "http" => array(
        'method' => 'POST'
        , 'header' => implode("\r\n", $header)
        , 'content'=> json_encode($data)
    )
));
file_get_contents($base_url, false, $context);

echo "access";
?>