我正在尝试弄清楚如何使用 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 设备令牌的数组
{“error”:{“code”:400,“message”:“收到无效的 JSON 负载。未知名称“notification”:找不到字段。 收到无效的 JSON 负载。未知名称“数据”:找不到字段。 收到无效的 JSON 负载。未知名称“registration_ids”:找不到字段。”,“状态”:“INVALID_ARGUMENT”,“详细信息”:[ {“@type”:“type.googleapis.com/google.rpc.BadRequest”,“fieldViolations”:[ {“description”:“收到无效的 JSON 负载。未知名称“通知”:找不到字段。" }, { "描述":"收到无效的 JSON 负载。未知名称“数据”:找不到字段。" }, { "description": "收到无效的 JSON 有效负载。未知名称“registration_ids”:找不到字段。” } ] } ] } }