How can I get Device token to send notification?

Viewed 437

I have built web version in Codeigniter and have been working in mobile version with react Native. To make new order notification, I am going to use firebase clouding message. how , where can I get this device token ?

public function sendFCMNotification($registration_ids, $message){

        $SERVER_API_KEY ='my server api key';
        // payload data, it will vary according to requirement
        $data = [
            "registration_ids" => $registration_ids, 
            "data" => $message
        ];
        $dataString = json_encode($data);
    
        $headers = [
            'Authorization: key=' . $SERVER_API_KEY,
            'Content-Type: application/json',
        ];
    
        $ch = curl_init();
      
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
               
        $response = curl_exec($ch);
      
        curl_close($ch);
      
        return $response;
    }
2 Answers

In your React-Native app, you can get the token like this:

messaging().getToken().then(token => { saveTokenToDatabase(token);});

then listen for any token change

messaging().onTokenRefresh(token => {saveTokenToDatabase(token);});

The method saveTokenToDatabase is used to save the token to your backend so that you can access it later to send messages

In android you need to use this class to get device token

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onNewToken(String token) {
    super.onNewToken(token);
    Log.e("newToken", token);
    //Add your token in your sharefpreferences.
    SharedPreferenceManager app_sp = new SharedPreferenceManager(this);
    app_sp.putString(Constants.FIREBASE_TOKEN, token);

this service request which update device token on to your server // updatetokenAPI.updateToken(token);

Related