iT邦幫忙

0

FCM php後台發送Notification

GCM即將快要被淘汰,由FCM取代了,所以就急忙著先看後台怎麼弄!
至於為什麼被淘汰,可以看一下官方說明

這是php轉送至firebase的後台,稍微做一些修改可以搭配帳號搭配device token(如iOS,Android或是Web)來接收Notification的內容。

主要運作程式的部分

<?php
    define( 'API_SERVER_ACCESS_KEY', '你的伺服器金鑰(圖一取得)' );
	
    $token 	 = $_GET['id'];/*FCM 接收端的token*/
	$message = $_GET['message'];/*要接收的內容*/
	$title 	 = $_GET['title'];  /*要接收的標題*/
	
    /*
    notification組成格式 官方範例
    {
      "message":{
        "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
        "notification":{
          "title":"Portugal vs. Denmark",
          "body":"great match!"
        }
      }
    }
    */
    
    $content = array
    (
        'title'	=> $title,
		'body' 	=> $message
    );
	$fields = array
	(
        'to'		    => $token,
		'notification'	=> $content
	);
	
	//firebase認證 與 傳送格式
	$headers = array
	(
		'Authorization: key='. API_SERVER_ACCESS_KEY,
		'Content-Type: application/json'
	);
	
	/*curl至firebase server發送到接收端*/
	$ch = curl_init();//建立CURL連線
	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 );//關閉CURL連線
	//result 是firebase server的結果
	echo $result;

伺服器金鑰取得
[firebase控制台]https://console.firebase.google.com/project/fc-asustor-test/settings/cloudmessaging/)
https://ithelp.ithome.com.tw/upload/images/20180703/20110514cs7LYQmrNC.png

如果正常運作,會收到firebase server的結果
{"multicast_id":6000000490349296195,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1540674978003134%e609af1cf9ad4ecd"}]}

接下來有空再分享html的部分


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言