Send Push Notification in FCM v1 API
google-services.json file and firebase-messaging dependency to your Android project, implement a service extending FirebaseMessagingService, request notification permissions for Android 13+, and capture the device registration token. In this project i will Show PHP API CODE with all steps.To send push notifications to the next stage officer when an approval is completed, you need to integrate Firebase Cloud Messaging (FCM) into your app. Here's how to implement it:
🔧 Step 1: Set Up Firebase in Your Project
Add Firebase Dependencies
In your app/build.gradle:
dependencies {
// ... existing dependencies ...
// Firebase Cloud Messaging
implementation 'com.google.firebase:firebase-messaging:23.4.1'
implementation 'com.google.firebase:firebase-analytics:21.5.1'
}
Add google-services.json
Go to Firebase Console → Create a new project (or use existing)
Add your Android app with your package name
Download
google-services.jsonand place it in yourapp/directory
Add this to your root build.gradle:
🔧 Step 2: Add Firebase Service to AndroidManifest.xml
🔧 Step 3: Create Firebase Messaging Service
🔧 Step 4: Save FCM Token on Login
Add this to your login activity to save the token when user logs in:
// In your LoginActivity or DashboardActivity
private void getAndSaveFcmToken() {
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(task -> {
if (!task.isSuccessful()) {
Log.w("FCM_TOKEN", "Fetching FCM token failed", task.getException());
return;
}
String token = task.getResult();
Log.d("FCM_TOKEN", "Token: " + token);
// Save token to your server with employee ID
saveTokenToServer(token);
});
}
private void saveTokenToServer(String token) {
// Call your PHP API to save the token
String url = "https://www.jyotishgher.in/save_fcm_token.php"; //ADD YOUR SERVER SIDE FILE
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
response -> Log.d("FCM_SAVE", "Token saved: " + response),
error -> Log.e("FCM_SAVE", "Error saving token", error)
) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("empno", empNo); // Your employee ID
params.put("fcm_token", token);
return params;
}
};
queue.add(stringRequest);
}
🔧 Step 5: Create Database Table for FCM Tokens
🔧 Step 6: PHP API to Save FCM Token | Use your's server end Code
🔧 Step 7: Send Notification as per your requirement where you need
Fix for Notification Builder Error
The error occurs because the method is setContentText(), not setContentBody(). Here's the corrected code:
📄 How to Get Firebase Server Key
For Legacy API (Solution 1):OLD
Go to Firebase Console
Select your project
Click on ⚙️ Project Settings → Cloud Messaging
Under Project Credentials, copy the Server Key
For FCM v1 API (Solution 2): NEW ADVISED
Go to Firebase Console → Project Settings → Service Accounts
Click Generate New Private Key
Save the JSON file as
service-account.jsonin your serverCopy your Project ID from Project Settings → General
🎯 Common Issues & Solutions
| Issue | Solution |
|---|---|
| 404 Error | Use correct FCM endpoint or check Project ID |
| 401 Unauthorized | Invalid Server Key - regenerate from Firebase Console |
| InvalidRegistration | Token is invalid - refresh token on device |
| NotRegistered | App uninstalled - remove token from database |
Make sure to replace YOUR_FCM_SERVER_KEY with your actual Server Key from Firebase Console!
$serverKey = 'AAAA3xYZ123...'; // Your actual server key
🔧 Step 8: PHP API to Send FCM Notification
send_notification.php
🔑 Important Notes
Project ID: Replace
YOUR_PROJECT_ID_HEREwith your actual Firebase Project ID (found in Firebase Console → Project Settings)Service Account: Download the service account JSON from Firebase Console and place it at
/service-account.jsonPermissions: Make sure the service account has the "Firebase Cloud Messaging Admin" role
Testing: Test by calling the API with a valid employee number
The FCM v1 API is more reliable and will work even if the legacy endpoint is blocked!
Expected Response:
{
"success": true,
"message": "Notification sent to 1 device(s)",
"target_empno": "063",
"total_tokens": 1,
"success_count": 1,
"failed_count": 0,
"results": [
{
"token_id": "1",
"success": true,
"response": "Notification sent successfully",
"httpCode": 200
}
]
}
🔧 Step 2: Add FCM Admin Role to Service Account MOST IMPORTANT
Go to Google Cloud Console
Select your Firebase project
Go to IAM & Admin → IAM also then Go to APIs & Services → Library Then Enable Search for "Firebase Cloud Messaging API"
Find your service account email (from
service-account.json)Click the Edit (pencil) icon
Click Add Another Role
Search and add: Firebase Cloud Messaging Admin
Click Save


Post a Comment
0Comments