我正在尝试弄清楚如何使用 PHP 向 Android 设备发送推送通知。
我已在多个网站上查找过它,这是我最后一次尝试:
function sendFCM($registrationIds, $notifTitle, $notifDesc, $notifChannel, $data) {
$client = new Google_Client();
$client->setAuthConfig('bla.json');
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$client->refreshTokenWithAssertion();
$token = $client->getAccessToken();
$accessToken = $token['access_token'];
$headers = array (
'Authorization: Bearer ' . $accessToken,
'Content-Type:application/json'
);
$notification = array
(
"title" => $notifTitle,
"body" => $notifDesc,
"icon" => "ic_logo_circle",
"android_channel_id" => $notifChannel
);
$fields = array
(
'notification' => $notification,
'data' => $data,
'registration_ids' => $registrationIds
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/v1/projects/projectname/messages: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);
print($result);
curl_close($ch);
}
$notifData = array(
"title" => "this is the title",
"msg" => "the desc",
"image" => "whatever.jpg"
);
sendFCM($registrationIds, "Antwort auf Kommentar", "Cornholio hat dir geantwortet", "channel_reply_comment", $notifData);
$registrationIds
包含多个 Android 设备令牌的数组
{ “错误”:{ “代码”:400,“消息”:“收到无效的 JSON 负载。未知名称“通知”:找不到字段。\ n收到无效的 JSON 负载。未知名称“数据”:找不到字段。\ n收到无效的 JSON 负载。未知名称“registration_ids”:找不到字段。“,”status“:“INVALID_ARGUMENT”,“详细信息”:[{“@type”:“type.googleapis.com/google.rpc.BadRequest”,“fieldViolations”:[{“描述”:“收到无效的 JSON 负载。未知名称“通知”:找不到字段。“},{“描述”:“收到无效的 JSON 负载。未知名称“数据”:找不到字段。“},{“描述”:“收到无效的 JSON 负载。未知名称“registration_ids”:找不到字段。“}]}]}
FCM v1 API 不需要
registration_ids
字段。您需要的是tokens
字段。为了实现这一点以及更多目的,请准备好有关发送消息的文档