使用 Laravel 颤振 FCM
Posted
技术标签:
【中文标题】使用 Laravel 颤振 FCM【英文标题】:Flutter FCM with Laravel 【发布时间】:2020-11-19 18:09:51 【问题描述】:我正在为我的应用后端使用 Laravel,并希望按主题向我的 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)。
【问题讨论】:
能否分享您的代码,目前我正面临类似的问题 【参考方案1】:我们在乔布斯中这样做。我分享我们的服务器端代码。您可以根据需要安排。
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();
【讨论】:
【参考方案2】:如果您设置了控制器,那么从前端/视图发送通知就不会那么困难了。这是我的完整示例。
在您的视图 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;
【讨论】:
非常感谢您的回答。请告诉我 form.blade.php 文件中的 id 是什么。 这是您要与通知有效负载一起传递的 ID。如果你不想通过它,你可以让它保持不变。只需将 $res->id 替换为 bulksend 函数中的任何值即可。 非常感谢您提供示例。它正在按我的需要工作。 @AnubhavAnand 我使用了你的代码,但 curl 似乎不起作用是否有库或我需要安装的东西?以上是关于使用 Laravel 颤振 FCM的主要内容,如果未能解决你的问题,请参考以下文章
Flutter FutureBuilder 在调用 Rest API(Backend Laravel)时显示数据然后消失