How to get failed token in FCM using php

105 Views Asked by At

I use the fmcSendToServerAction function to send data to Firebase for sending push notifications to users, and I receive a response from FCM as follows: {"multicast_id":3518989135591430380,"success":1,"failure":2,"canonical_ids":0,"results":[{"error":"NotRegistered"},{"error":"NotRegistered"},{"message_id":"48ccfe8f-b449-491a-b912-fe9cc86ab98e"}]}. How can I retrieve the failure tokens to update the active status in the database? Of course, the tokens generated when users agree to receive notifications have been saved in the database by me (see image).

/**
 *
 * @Route("/fcm/send", name="fmc_send_to_server")
 * @Method("GET")
 * @Template(engine="php")
 */
public function fmcSendToServerAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $fcmTokens = $em->getRepository('VlanceBaseBundle:FcmToken')->findAll();
    $registrationIds = array_map(function ($ft) {
        return $ft->getToken();
    }, $fcmTokens);

    $fcmMessages = $em->getRepository('VlanceBaseBundle:FcmNotifyPush')->getFcmNotifyPush();

    $url = "https://fcm.googleapis.com/fcm/send";
    $server_key = "SERVER_MY_KEY";

    if (count($fcmMessages) <= 0) {
        return new Response('No notifications to send to users', 200);
    }

    foreach ($fcmMessages as $message) {
        $messageData = [
            'data' => [
                'title' => $message->getTitle(),
                'body' => $message->getDiscription(),
                'click_action' => $message->getUrl()
            ],
            'registration_ids' => $registrationIds,
        ];

        $options = [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                "Authorization: Bearer " . $server_key,
                "Content-Type: application/json",
            ],
            CURLOPT_POSTFIELDS => json_encode($messageData),
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_RETURNTRANSFER => true, // Capture the response
        ];

        $curl = curl_init();
        curl_setopt_array($curl, $options);
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); // Get HTTP response code
        curl_close($curl);
    }
    return new Response('All notifications have been sent to users', 200);
}

Database: In which tokens with IDs 37 and 38 are failures.

enter image description here

How can I retrieve the failure tokens to update the active status in the database?

1

There are 1 best solutions below

1
Frank van Puffelen On BEST ANSWER

As CBroe commented, the three items in the results array of the respond correspond to the three tokens that you sent. So sending to the first two tokens failed (because the token is not known in this project and should probably be removed from your token database), and the third token succeeded.