dimanche 26 août 2018

Send push notifications to ionic using laravel

I have an ionic mobile app that links to a laravel web app using APIs. Now the backend is setup in such a way that when an admin sends a message to a mobile user or group of users, a push notification should show on registered devices with tokens. I am using this Laravel FCM package. The code is part of the system:

app.js (ionic part)

...
FCMPlugin.getToken(
            function (token) {
                //alert('Token: ' + token);
                console.log('Token: ' + token);
                localStorage.setItem("device_token", token);
            },
            function (err) {
                //alert('error retrieving token: ' + token);
                console.log('error retrieving token: ' + err);
            }
        );

        FCMPlugin.onNotification(
            function(data){

                if(data.wasTapped){
        //Notification was received on device tray and tapped by the user.

                  alert("Tapped: " +  JSON.stringify(data) );

                }else{
        //Notification was received in foreground. Maybe the user needs to be notified.
                    console.log("Not tapped: " + JSON.stringify(data) );


                }
 ...

ProcessMessage.php (laravel)

public function send()
{

    $message = $this->message;

    //Get message subscribers
    $subscribers = Subscriber::whereHas('groups', function ($query) use ($message) {
        $query->whereIn('groups.id', $message->groups()->get()->pluck('id')->toArray());
    })->get();

    if($this->message->type=='notification'){
        foreach ($subscribers as $subscriber) {
            if ($subscriber->user->status == 'active') {
                $subscriber->messageReads()->save(new MessageRead(['message_id' => $message->id, 'status' => '0']));
            }
        }
    $this->updateSendMessage($this->message);

    private function updateSendMessage($message){
    $message->status = '1';
    $message->authorized = '1';
    $message->save();
}

FCMService.php

    namespace App\Services;

    use App\Models\Message;
    use App\Models\SubscriberToken; // need help with this model
    use LaravelFCM\Message\OptionsBuilder;
    use LaravelFCM\Message\PayloadDataBuilder;
    use LaravelFCM\Message\PayloadNotificationBuilder;
    use FCM;

    class FCMService
   {
    public function sendFCMNotification(Message $message){


    $downstreamResponse = $this->sendMessageToTokens($message, $message->tokensArray());

    $downstreamResponse->numberSuccess();
    $downstreamResponse->numberFailure();
    $downstreamResponse->numberModification();

    $tokens_to_update = $downstreamResponse->tokensToModify();
    foreach ($tokens_to_update as $item=>$value){
        $entry = SubscriberToken::where('token', $item)->first(); // Not sure about this part. How to create SubscriberToken model
        $entry->token = $value;
        $entry->save();
    }

    $tokens_to_retry = $downstreamResponse->tokensToRetry();

    if(!empty($tokens_to_retry)){
        $downstreamResponse = $this->sendMessageToTokens($message, $tokens_to_retry);
    }

    return;
}

public function sendMessageToTokens(Message $message, $tokens){
    $optionBuilder = new OptionsBuilder();
    $optionBuilder->setTimeToLive(60*20);

    $notificationBuilder = new PayloadNotificationBuilder($message->title);
    $notificationBuilder->setBody($message->short_content)->setSound('default');

    $dataBuilder = new PayloadDataBuilder();
    $dataBuilder->addData(['message' => $message]);

    $option = $optionBuilder->build();
    $notification = $notificationBuilder->build();
    $data = $dataBuilder->build();

    return $downstreamResponse = FCM::sendTo($tokens, $option,  $notification, $data);
     }
    }

MessageController.php

...
public function update($id, Request $request)
{
    $message = Message::findOrFail($id);
    if(!$this->clientHelper()->hasMessage($id)){
        flash()->error('You cant view that message');
        return back();
    }
    if($message->status=='1' or $message->authorize=='1'){
        flash()->error('Action not allowed, message already sent!!');
        return back();
    }

    if($request->authorize){
        if(auth()->user()->can('authorizeSend', $this->message_class)){
            $this->sendMessage($message);
            flash()->message("Message sent!");
            return back();
        }
    }
    ...
    public function sendMessage($message)
    {
    $messageProcessor = new ProcessMessage($message);
    $messageProcessor->send();
    }

I have setup the Firebase console configs with server keys and placed them in the laravel app according to the docs. The messages are being received by the registered users, but push notifications are not working. Please help.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2MLvKtl
via IFTTT

Aucun commentaire:

Enregistrer un commentaire