【问题标题】:How to send FCM notification using PHP?如何使用 PHP 发送 FCM 通知?
【发布时间】:2016-12-06 01:55:37
【问题描述】:

我尝试使用 PHP 代码/网络浏览器发送 FCM。

但问题是当我使用 PHP 网络浏览器发送它时:

  • FCM 通知仅显示在虚拟设备上。
  • FCM 通知不会出现在真实的手机设备上。

而且我只能使用 Firebase 控制台向真实手机设备发送 FCM 通知。

有人可以帮忙吗?代码如下。

<?php
require "init.php";
global $con;
    if(isset($_POST['Submit'])){
        $message     = $_POST['message'];
        $title       = $_POST['title'];
        $path_to_fcm = 'https://fcm.googleapis.com/fcm/send'; 
        $server_key  = "AAAA2gV_U_I:APA91bHA28EUGmA3BrDXFInGy-snx8wW6eZ_RUE7EtOyM99pbfrVZU_ME-FU0O9_dUxYpM30OYF8KWYlixod_PfwbgLNoovzdkdJ4F-30vY8X_tBz0CMrajCIAgbNVRfw203YdRGli";    
        $sql     = "SELECT fcm_token FROM fcm_table";
        $result  = mysqli_query($con, $sql);
        $row     = mysqli_fetch_row($result);
            $key = $row[0];
        $headers = array('Authorization:key=' .$server_key, 'Content-Type:application/json');
        $fields  = array('to' => $key, 'notification' => array('title' => $title, 'body'=> $message));
        $payload = json_encode($fields);
        $curl_session = curl_init();
        curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
        curl_setopt($curl_session, CURLOPT_POST, true);
        curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);
        $result = curl_exec($curl_session);
        curl_close($curl_session);
        mysqli_close($con);
    }   
?>
<!DOCTYPE html>
<html>
<head>
    <title>FCM Notification</title>
</head>
<body>
    <form action='fcm_notification.php' method="POST">
        <table>
            <tr>
                <td>Title : </td>
                <td><input type="text" name="title" required="required" /></td>
            </tr>
            <tr>
                <td>Message : </td>
                <td><input type="text" name="message"  required="required" /></td>
            </tr>
            <tr>
                <td><input type="submit" name="Submit" value="Send notification"></td>

            </tr>
        </table> 
    </form>
</body>
</html>

谢谢。

【问题讨论】:

  • 设备是指Android,对吧?
  • 是的。安卓设备
  • 您能否正确获取模拟器的注册令牌?您是否尝试过使用简单的 cURL 响应发送消息并查看 iut 是否仍然没有收到任何消息?
  • 是的。注册令牌从模拟器工作到数据库。
  • 你能检查一下这个link.

标签: php android curl firebase firebase-cloud-messaging


【解决方案1】:

通过以下方式,您可以使用 google FCM 向手机发送推送通知。对我来说,它的作品符合预期。添加密钥'priority' =&gt; 'high'

function sendPushNotification($fields = array())
{
    $API_ACCESS_KEY = 'YOUR KEY';
    $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 );
    return $result;
}

$title = 'Whatever';
$message = 'Lorem ipsum';
$fields = array
(
    'registration_ids'  => ['deviceID'],
    'data'          => '',
    'priority' => 'high',
    'notification' => array(
        'body' => $message,
        'title' => $title,
        'sound' => 'default',
        'icon' => 'icon'
    )
);

sendPushNotification($fields);

【讨论】:

  • 设备ID ?与 FCM 的发件人 ID 相同吗?
  • 当您尝试连接 google FCM 时,它会从移动设备向您发送一个registration_id/deviceID,无论您如何称呼它。如下图fxRKtQfyP5Y:APA91bGkjkerOGAVCdZFy6f9G-gmXHJwRNAeKELIWMgddDKQW34MZw0LQPPluM1hKCzYsfcVVnuwbSJEjctAKs2JAaCLUEeSM6QEW7qVZ281O9TUOa8mJ4Hb8qNo_qHoc9eSNvsGjrKY
【解决方案2】:

您可以创建为设备发送推送通知的功能。

// firebase access key
define( 'API_ACCESS_KEY', 'AAAAAG78XmM:APA91bFRHpzuEIgiQRmPUm4uRy8bygNGr1h2Oq3ydc5WtKbrfJA8NVAaGIAxbQELfcOWwN2OR4pf5NzSRuuWOYj_P-XXXXXXXX');        
// target device 'fcm' id
$device[0]='JI8YHo7GEo:APA9-aGWOU3U3CXXXXXXXXXXX';
$device[1]='JI8YHo7GEo:APA9-aGWOU3U3CXXXXXXXXXXX';

    $url = 'https://fcm.googleapis.com/fcm/send';

    // "to": "e1w6hEbZn-8:APA91bEUIb2JewYCIiApsMu5JfI5Ak...",   // for single device (insted of "registration_ids"=>"$device"  )
    $data = array("registration_ids" => $device,            // for multiple devices 
        "notification" => array( 
        "title" => "Party Night", 
        "body" => "Invitation for pool party!",
        "message"=>"Come at evening...",
        'icon'=>'https://www.example.com/images/icon.png'
    ),
        "data"=>array(
        "name"=>"xyz",
        'image'=>'https://www.example.com/images/minion.jpg'
        ) 
    ); 

    $data_string = json_encode($data); 
    $headers = array ( 'Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json' ); 
    $ch = curl_init(); 
    curl_setopt( $ch,CURLOPT_URL,$url ); 
    curl_setopt( $ch,CURLOPT_POST, true ); 
    curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers ); 
    curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true ); 
    curl_setopt( $ch,CURLOPT_POSTFIELDS, $data_string); 
    $result = curl_exec($ch); 

更多详情请参考这里

to – 类型字符串 –(可选)[消息的收件人] 该值必须是单个注册令牌、通知键或主题。发送到多个主题时不要设置此字段

registration_ids – 类型字符串数组 –(可选)[消息的收件人] 多个注册令牌,最少 1 个,最多 1000 个。

priority– 类型字符串–(可选)[默认正常] 允许值正常和高。

delay_while_idle - 布尔类型 - (可选)[默认值 false] true 表示在设备激活之前不应发送消息。

time_to_live – 输入 JSON 数字 –(可选)[默认值 4 周 最长 4 周] 此参数指定设备离线时消息应在 FCM 存储中保留多长时间(以秒为单位)

data – 类型 JSON 对象 指定消息有效负载的自定义键值对。 例如。 {“post_id”:”1234″,”post_title”:”博客文章标题”}

【讨论】:

    【解决方案3】:

    在 Android 中,您可以在 onMessageReceived() 中将其作为地图数据接收...

    在后台时 - 应用在通知托盘中接收通知负载,并且仅在用户点击通知时处理数据负载。

    在前台时 – 应用收到一个消息对象,其中包含两个可用的有效负载。

    public class FcmMessageService extends FirebaseMessagingService{
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //onMessageReceived will be called when ever you receive new message from server.. (app in background and foreground )
        Log.d("FCM", "From: " + remoteMessage.getFrom());
    
        if(remoteMessage.getNotification()!=null){
        Log.d("FCM", "Notification Message Body: " + remoteMessage.getNotification().getBody());
        }
    
        if(remoteMessage.getData().containsKey("post_id") && remoteMessage.getData().containsKey("post_title")){
            Log.d("Post ID",remoteMessage.getData().get("id").toString());
            Log.d("Post Title",remoteMessage.getData().get("post_title").toString());
            // eg. Server Send Structure data:{"post_id":"12345","post_title":"A Blog Post"}
        }
    }}
    

    【讨论】:

      猜你喜欢
      • 2020-11-27
      • 2016-12-20
      • 2018-05-05
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多