我正在尝试使用 PHP 向 Android 设备发送 FCM 通知。我的代码适用于 Android O 之前的设备。
在Android O中,我们还需要在请求中设置通道ID来接收通知,我不知道该怎么做。
我已在应用程序中完成了必要的设置,并使用 Firebase 控制台我可以收到通知,但当我尝试通过 PHP 脚本发送通知时,通知失败。
我还查看了下面的链接,但它对我不起作用。
Android FCM定义通道ID并通过PHP向该通道发送通知 https://stackoverflow.com/questions/54246893/android-fcm-define-channel-id-and-send-notification-to-this-channel-through-php
我的 PHP 代码:
$notification = new Notification();
$notification->setTitle("startSession");
$notification->setBody($_POST['child_id']);
$notification->setNotificationChannel('my_channel_id');
$requestData = $notification->getNotification();
$firebase_token = $_POST['token'];
$firebase_api = 'my_value';
$fields = array(
'to' => $firebase_token,
'data' => $requestData,
);
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . $firebase_api,
'Content-Type: application/json'
);
$ch = curl_init();
// Set the url, number of POST vars, POST data
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, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if($result === FALSE){
die('Curl failed: ' . curl_error($ch));
$return_obj = array('responseCode'=>'0' , 'responseMsg'=> 'Error inserting, please try
again.', 'errorCode'=>'1');
}else{
$return_obj = array('responseCode'=>'1' , 'responseMsg'=> 'Successfully inserted.',
'errorCode'=>'0');
}
// Close connection
echo json_encode($return_obj);
curl_close($ch);
我的通知类代码是:
<?php
class Notification{
private $title;
private $body;
private $answer_value;
private $android_channel_id;
function __construct(){
}
public function setTitle($title){
$this->title = $title;
}
public function setBody($body){
$this->body = $body;
}
public function setAnswer($answer){
$this->answer_value = $answer;
}
public function setNotificationChannel($channel){
$this->android_channel_id = $channel;
}
public function getNotificatin(){
$notification = array();
$notification['title'] = $this->title;
$notification['body'] = $this->body;
$notification['answer'] = $this->answer_value;
$notification['android_channel_id'] = $this->android_channel_id;
return $notification;
}
}
?>
我确信语法是正确的,因为通知仍然适用于 Android
任何帮助将不胜感激。谢谢!