首页 > 解决方案 > 如何使用 PHP cURL 和 FCM 向移动设备发送通知?

问题描述

如何使用 PHP cURL 和 FCM 向移动设备发送通知?

$ch = curl_init(); //init
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');//Fire URL
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);//send 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); //.json_encode($fields);
return $result;
curl_close( $ch );

标签: phpcurlpush-notification

解决方案


$to - 设备 ID

$title - 通知标题

$message - 通知消息

$img - 完整的图片链接

$datapayload - 自定义值的数组。

用法:

发送通知($to, $title, $message, $img, $datapayload = "");

带有演示值:

sendnotification("Device_ID","测试通知","测试消息","https://www.google.co.in/images/branding/googleg/1x/googleg_standard_color_128dp.png",array("ID"=>1 ));

function sendnotification($to, $title, $message, $img = "", $datapayload = ""){
$msg = urlencode($message);
$data = array(
    'title'=>$title,
    'sound' => "default",
    'msg'=>$msg,
    'data'=>$datapayload,
    'body'=>$message,
    'color' => "#79bc64"
);
if($img){
    $data["image"] = $img;
    $data["style"] = "picture";
    $data["picture"] = $img;
}
$fields = array(
    'to'=>$to,
    'notification'=>$data,
    'data'=>$datapayload,
    "priority" => "high",
);
$headers = array(
    'Authorization: key=GOOGLE_API_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;

}


推荐阅读