使用 Laravel 颤动 FCM
Flutter FCM with Laravel
我正在为我的应用程序后端使用 Laravel,并希望按主题向我的 flutter 应用程序发送推送通知。现在我在我的 flutter 应用程序中实现了 firebase 消息传递。作为
_registerOnFirebase() {
_firebaseMessaging.subscribeToTopic('all');
_firebaseMessaging.getToken().then((token) => print(token));
}
void getMessage() {
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print('received message');
}, onResume: (Map<String, dynamic> message) async {
print('on resume $message');
}, onLaunch: (Map<String, dynamic> message) async {
print('on launch $message');
});
}
我正在通过 Postman 将通知发送到应用程序,它正在运行。
enter image description here
现在请告诉我如何从我的 Laravel 表单(来自视图目录)发送通知。
我在资源目录中创建了一个名为 PushNotification 的控制器和一个视图目录(\resources\views\notification\create.blade)。
如果您设置了控制器,那么从 frontend/views 发送通知就不会那么困难了。这是我的完整示例。
在您的视图中创建一个表单 form.blade.php 文件 (resources/views/form.blade.php)
<form method="POST" action="{{route('bulksend')}}">
<label>Title</label>
<input type="text" hint="Title" name="title">
<br>
<label>Body</label>
<input type="text" hint="Body" name="body">
<br>
<label>Image URL</label>
<input type="text" hint="Image URL" name="img">
<br>
<label>ID</label>
<input type="text" hint="Image URL" name="id">
<br>
<input type="submit"/>
</form>
创建网络路由(routes/web.php)
Route::get('form', function () {
return view('form');
});
Route::post('send','MyController@bulksend')->name('bulksend');
在app/Http/Controller中创建一个名为MyController的控制器,并向其中添加这个函数。
public function bulksend(Request $req){
$url = 'https://fcm.googleapis.com/fcm/send';
$dataArr = array('click_action' => 'FLUTTER_NOTIFICATION_CLICK', 'id' => $req->id,'status'=>"done");
$notification = array('title' =>$req->title, 'text' => $req->body, 'image'=> $req->img, 'sound' => 'default', 'badge' => '1',);
$arrayToSend = array('to' => "/topics/all", 'notification' => $notification, 'data' => $dataArr, 'priority'=>'high');
$fields = json_encode ($arrayToSend);
$headers = array (
'Authorization: key=' . "YOUR_FCM_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, $fields );
$result = curl_exec ( $ch );
//var_dump($result);
curl_close ( $ch );
return $result;
}
乔布斯就是这么做的。我分享我们的服务器端代码。可以根据自己的需要来安排。
class SendFCM implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $FcmLog;
protected $regids;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($token,$payload,$incident_action_id=0)
{
$FcmLog = new FcmLog();
$FcmLog->incident_action_id = $incident_action_id;
$FcmLog->user_fcm_token_ids = $token->pluck('id')->toArray();
$FcmLog->payload = $payload;
$FcmLog->response = '';
$FcmLog->save();
$this->regids = $token->pluck('token')->toArray();
$this->FcmLog = $FcmLog;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
try {
$regids = UserFcmToken::whereIn('id',$this->FcmLog->user_fcm_token_ids)->get();
$targets = [
'android' => [],
'ios' => []
];
foreach($regids as $regid) {
$identifier = $regid->device_info['os'];
if($regid->device_info['os']==='android'&&$regid->device_info['framework']==='flutter') {
$identifier = 'android_flutter';
}
$targets[$identifier][] = $regid->token;
}
$headers = array(
'Authorization'=>'key = ******YOUR FIREBASE KEY*****',
'Content-Type'=>'application/json'
);
$client = new Client([
'base_uri' => 'https://fcm.googleapis.com/',
'timeout' => 30,
'connect_timeout' => 15,
'headers' => $headers
]);
$response = [
'ios'=>null,
'android'=>null,
'android_flutter'=>null
];
if(!empty($targets['ios'])) {
if ($this->FcmLog->payload['notification_type'] == 'incident_action') {
$incident = new Incident();
$incidents = $incident->ofUser([
'request' => (object) [
'resource' => 'pending',
'count' => 10,
'internal_user_id' => $this->FcmLog->payload['notification_body']['user_id']
]
]);
$badgeCount = intval($incidents['total']) ?: 1;
}
$fields = array(
'registration_ids' => $targets['ios'],
'notification' => []
);
if($this->FcmLog->payload['notification_type']=='announcement') {
$fields['notification'] = [
'body'=> $this->FcmLog->payload['notification_body']['announcement']['text'],
'title'=> $this->FcmLog->payload['notification_body']['announcement']['title'],
'sound'=> "default",
'badge'=> $badgeCount,
'id'=> $this->FcmLog->payload['notification_body']['announcement']['id'],
];
} else {
$fields['notification'] = [
'body'=> $this->FcmLog->payload['notification_body']['message'],
'title'=> 'Bildirim!',
'sound'=> "default",
'badge'=> $badgeCount,
'notification_type'=>$this->FcmLog->payload['notification_type'],
'id'=> $this->FcmLog->payload['notification_body']['incident_number'],
'token'=> $this->FcmLog->payload['notification_body']['public_token'],
];
}
$request = $client->post('fcm/send', [
'body' => json_encode($fields),
]);
$response['ios'] = (string) $request->getBody();
}
if(!empty($targets['android'])) {
$fields = array(
'registration_ids' => $targets['android'],
'data' => $this->FcmLog->payload
);
$request = $client->post('fcm/send', [
'body' => json_encode($fields),
]);
$response['android'] = (string) $request->getBody();
}
if(!empty($targets['android_flutter'])) {
if($this->FcmLog->payload['notification_type']=='announcement') {
$notificationBody = $this->FcmLog->payload['notification_body']['announcement']['text'];
$notificationTitle = $this->FcmLog->payload['notification_body']['announcement']['title'];
} else {
$notificationBody = $this->FcmLog->payload['notification_body']['message'];
$notificationTitle = 'Bildirim!';
}
$fields = array(
'registration_ids' => $targets['android_flutter'],
'data' => $this->FcmLog->payload,
'notification' => [
'body'=>$notificationBody,
'title'=>$notificationTitle
]
);
$fields['data']['click_action'] = 'FLUTTER_NOTIFICATION_CLICK';
$request = $client->post('fcm/send', [
'body' => json_encode($fields),
]);
$response['android_flutter'] = (string) $request->getBody();
}
}
catch (\Exception $e) {
$response = [ mb_substr($e->getMessage(),0,200) ];
}
$this->FcmLog->response = $response;
$this->FcmLog->save();
}
}
我正在为我的应用程序后端使用 Laravel,并希望按主题向我的 flutter 应用程序发送推送通知。现在我在我的 flutter 应用程序中实现了 firebase 消息传递。作为
_registerOnFirebase() {
_firebaseMessaging.subscribeToTopic('all');
_firebaseMessaging.getToken().then((token) => print(token));
}
void getMessage() {
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print('received message');
}, onResume: (Map<String, dynamic> message) async {
print('on resume $message');
}, onLaunch: (Map<String, dynamic> message) async {
print('on launch $message');
});
}
我正在通过 Postman 将通知发送到应用程序,它正在运行。 enter image description here 现在请告诉我如何从我的 Laravel 表单(来自视图目录)发送通知。 我在资源目录中创建了一个名为 PushNotification 的控制器和一个视图目录(\resources\views\notification\create.blade)。
如果您设置了控制器,那么从 frontend/views 发送通知就不会那么困难了。这是我的完整示例。
在您的视图中创建一个表单 form.blade.php 文件 (resources/views/form.blade.php)
<form method="POST" action="{{route('bulksend')}}"> <label>Title</label> <input type="text" hint="Title" name="title"> <br> <label>Body</label> <input type="text" hint="Body" name="body"> <br> <label>Image URL</label> <input type="text" hint="Image URL" name="img"> <br> <label>ID</label> <input type="text" hint="Image URL" name="id"> <br> <input type="submit"/> </form>
创建网络路由(routes/web.php)
Route::get('form', function () { return view('form'); }); Route::post('send','MyController@bulksend')->name('bulksend');
在app/Http/Controller中创建一个名为MyController的控制器,并向其中添加这个函数。
public function bulksend(Request $req){ $url = 'https://fcm.googleapis.com/fcm/send'; $dataArr = array('click_action' => 'FLUTTER_NOTIFICATION_CLICK', 'id' => $req->id,'status'=>"done"); $notification = array('title' =>$req->title, 'text' => $req->body, 'image'=> $req->img, 'sound' => 'default', 'badge' => '1',); $arrayToSend = array('to' => "/topics/all", 'notification' => $notification, 'data' => $dataArr, 'priority'=>'high'); $fields = json_encode ($arrayToSend); $headers = array ( 'Authorization: key=' . "YOUR_FCM_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, $fields ); $result = curl_exec ( $ch ); //var_dump($result); curl_close ( $ch ); return $result; }
乔布斯就是这么做的。我分享我们的服务器端代码。可以根据自己的需要来安排。
class SendFCM implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $FcmLog;
protected $regids;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($token,$payload,$incident_action_id=0)
{
$FcmLog = new FcmLog();
$FcmLog->incident_action_id = $incident_action_id;
$FcmLog->user_fcm_token_ids = $token->pluck('id')->toArray();
$FcmLog->payload = $payload;
$FcmLog->response = '';
$FcmLog->save();
$this->regids = $token->pluck('token')->toArray();
$this->FcmLog = $FcmLog;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
try {
$regids = UserFcmToken::whereIn('id',$this->FcmLog->user_fcm_token_ids)->get();
$targets = [
'android' => [],
'ios' => []
];
foreach($regids as $regid) {
$identifier = $regid->device_info['os'];
if($regid->device_info['os']==='android'&&$regid->device_info['framework']==='flutter') {
$identifier = 'android_flutter';
}
$targets[$identifier][] = $regid->token;
}
$headers = array(
'Authorization'=>'key = ******YOUR FIREBASE KEY*****',
'Content-Type'=>'application/json'
);
$client = new Client([
'base_uri' => 'https://fcm.googleapis.com/',
'timeout' => 30,
'connect_timeout' => 15,
'headers' => $headers
]);
$response = [
'ios'=>null,
'android'=>null,
'android_flutter'=>null
];
if(!empty($targets['ios'])) {
if ($this->FcmLog->payload['notification_type'] == 'incident_action') {
$incident = new Incident();
$incidents = $incident->ofUser([
'request' => (object) [
'resource' => 'pending',
'count' => 10,
'internal_user_id' => $this->FcmLog->payload['notification_body']['user_id']
]
]);
$badgeCount = intval($incidents['total']) ?: 1;
}
$fields = array(
'registration_ids' => $targets['ios'],
'notification' => []
);
if($this->FcmLog->payload['notification_type']=='announcement') {
$fields['notification'] = [
'body'=> $this->FcmLog->payload['notification_body']['announcement']['text'],
'title'=> $this->FcmLog->payload['notification_body']['announcement']['title'],
'sound'=> "default",
'badge'=> $badgeCount,
'id'=> $this->FcmLog->payload['notification_body']['announcement']['id'],
];
} else {
$fields['notification'] = [
'body'=> $this->FcmLog->payload['notification_body']['message'],
'title'=> 'Bildirim!',
'sound'=> "default",
'badge'=> $badgeCount,
'notification_type'=>$this->FcmLog->payload['notification_type'],
'id'=> $this->FcmLog->payload['notification_body']['incident_number'],
'token'=> $this->FcmLog->payload['notification_body']['public_token'],
];
}
$request = $client->post('fcm/send', [
'body' => json_encode($fields),
]);
$response['ios'] = (string) $request->getBody();
}
if(!empty($targets['android'])) {
$fields = array(
'registration_ids' => $targets['android'],
'data' => $this->FcmLog->payload
);
$request = $client->post('fcm/send', [
'body' => json_encode($fields),
]);
$response['android'] = (string) $request->getBody();
}
if(!empty($targets['android_flutter'])) {
if($this->FcmLog->payload['notification_type']=='announcement') {
$notificationBody = $this->FcmLog->payload['notification_body']['announcement']['text'];
$notificationTitle = $this->FcmLog->payload['notification_body']['announcement']['title'];
} else {
$notificationBody = $this->FcmLog->payload['notification_body']['message'];
$notificationTitle = 'Bildirim!';
}
$fields = array(
'registration_ids' => $targets['android_flutter'],
'data' => $this->FcmLog->payload,
'notification' => [
'body'=>$notificationBody,
'title'=>$notificationTitle
]
);
$fields['data']['click_action'] = 'FLUTTER_NOTIFICATION_CLICK';
$request = $client->post('fcm/send', [
'body' => json_encode($fields),
]);
$response['android_flutter'] = (string) $request->getBody();
}
}
catch (\Exception $e) {
$response = [ mb_substr($e->getMessage(),0,200) ];
}
$this->FcmLog->response = $response;
$this->FcmLog->save();
}
}