问题
I am Using Laravel for my App backend and want to send push notification to my flutter app by topic. Now I implemented firebase messaging into my flutter app. as
_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');
});
}
and I am sending the notification to the app by Postman and It's working. enter image description here Now please tell me How can I send the notification from my Laravel Forms(From Views Directory). I have created a controller Named PushNotification and a views directory in the resource directory as (\resources\views\notification\create.blade).
回答1:
If you have the controller setup then it won't be that tough to send notification from the frontend/views. Here is my complete example.
Create a form in your view form.blade.php file (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>
Create a web route (routes/web.php)
Route::get('form', function () { return view('form'); }); Route::post('send','MyController@bulksend')->name('bulksend');
Create a controller named MyController in app/Http/Controller and add this function to it.
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; }
回答2:
We do this in Jobs. I share our server side code. you can arrange according to your need.
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();
}
}
来源:https://stackoverflow.com/questions/63165683/flutter-fcm-with-laravel