PHP - FCM Push

PHP - FCM Push

PHP 方面,撰寫如下

https://gist.github.com/MohammadaliMirhamed/7384b741a5c979eb13633dc6ea1269ce

    public function FCMPush($Title,$Content,$Token) {
        //hotelB2B
        define( 'API_ACCESS_KEY', '<YOUR_API_ACCESS_KEY>' );

        $data = $this->getPostData();
        $registrationIds = $data['Token'];

        $msg = array(
            'body'  =>  $data['Content'],
            'title' =>  $data['Title'],
                'icon'  => 'myicon',/*Default Icon*/
                'sound' => 'mySound'/*Default sound*/
        );

        $fields = array(
            'to' => $registrationIds,
            'notification' => $msg);

        $headers = array(
                'Authorization: key=' . API_ACCESS_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 = curl_exec($ch );
        curl_close( $ch );
    }

而 API_ACCESS_KEY 如何取得呢?

 https://stackoverflow.com/questions/37337512/where-can-i-find-the-api-key-for-firebase-cloud-messaging

https://console.firebase.google.com/

點擊你的專案

在左上角

在頁面,點擊CLOUD MESSAGING

則可以看到伺服器金鑰。

 

------------------

如果要傳送客製化資料,key /value的資料,則fields 欄位加入 data 

        //特殊欄位處理
        $payload = array('test'=>'1234');

        $fields = array(
            'to' => $registrationIds,
            'notification' => $msg,
            'data' =>  $payload);