Ask Question Forum:
Model Library:2025-02-08 Updated:A.I. model is online for auto reply question page
C
O
M
P
U
T
E
R
2
8
Show
#
ASK
RECENT
←
- Underline
- Bold
- Italic
- Indent
- Step
- Bullet
- Quote
- Cut
- Copy
- Paste
- Table
- Spelling
- Find & Replace
- Undo
- Redo
- Link
- Attach
- Clear
- Code
Below area will not be traslated by Google,you can input code or other languages
Hint:If find spelling error, You need to correct it,1 by 1 or ignore it (code area won't be checked).
X-position of the mouse cursor
Y-position of the mouse cursor
Y-position of the mouse cursor
Testcursor
caretPos
Attachment:===
Asked by Norton Alex
at 2026-06-10 19:57:39
Point:500 Replies:4 POST_ID:829418USER_ID:12423
Topic:
curl;firebase;php
I follow this article, it doesn't work
The error:
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
Please advise
Accepted Solution
Expert: Wilson Edwards replied at 2026-06-11 10:44:06
500 points Excellent
Solved:
Step-1 Open Firebase console, go to setting-->service account->Generate new key, u will get a new json file, save it then send to the server at ../videoapps/fcmweb, change it other filename for security in order to user can not read it on internet.
Step-2 php file
require_once '/yourdirectoy/fcmweb/vendor/autoload.php';
$ver=$_SERVER['argv'];
$token=$ver[1];//yoursendertoken
$access_token = get_access_token2();
echo $access_token."#############\n\n\n";
sendFCMNotification($access_token, $token);
function get_access_token2(){
putenv('GOOGLE_APPLICATION_CREDENTIALS=yourserviceaccount.json');
$scope = 'https://www.googleapis.com/auth/analytics.readonly';
$scope ='https://www.googleapis.com/auth/firebase.messaging';
$client = new Google_Client();
$client->setScopes($scope);
$client->useApplicationDefaultCredentials();
$token=$client->fetchAccessTokenWithAssertion()["access_token"];
return $token;
}
Step-3: message json format:
$data = [
'message' => [
"data"=> [
"title" => "Title",
"body" => "This is message body.",
"icon" => "https://www.clipscutter.com/image/brand/brand-256.pn>
"image" => "https://images.unsplash.com/photo-1514473776127-61e>
"click_action" => "https://example.com"
],
'token' => $token
],];
Step-4: curl opt:
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer $access_token",
"Content-Type: application/json",
),
Step-5 Run command on linux
php send_subscribe.php "yoursendertoken"
U will see the message on ....../fcmweb/index.html
Author: Norton Alex replied at 2026-06-10 20:21:29
in php curl or on line curl, use "token" or "to" ?
Author: Norton Alex replied at 2026-06-10 20:14:57
I put the code at computer28.com , at directory,
https://computer28.com/data/fcmweb/send_subscribe.php
send_subscribe.php
command:php send_subscribe.php "your-client-fcm-token"
-----------------------
include "./get_access_token.php";
date_default_timezone_set('Asia/Hong_Kong');
$ver=$_SERVER['argv'];
$token=$ver[1];//client fcm token
$access_token= 'your server token';
sendFCMNotification($access_token, $token);
//$token="fNDkdz1JlRYx0kn93pgKJ4:APA91bHgoU1sEJxAXbV0SH_U1wd8Of5AWPo_YWA52HGErz1kHAK2zNwVumAFGs6oBpkOpUSoklwMa0RR87XeT4DPFw5O8dkqj78Qzz2L2Bx0bd4Ln9mvlB2NG-9I1caVf3wNrpcPGkTd";
function sendFCMNotification($access_token, $token) {
$url = "https://fcm.googleapis.com/v1/projects/fcmweb-7b53d/messages:send";
$url = "https://fcm.googleapis.com/fcm/send";
$sender_id='0#1#2#3#4#5';$date=date("Y-m-d, H:i:s");
$message='your message';
$data = [
'data' => ['sender_id'=>$sender_id,"body" => $message,
"title" => "Title",
"icon" => "https://www.clipscutter.com/image/brand/brand-256.png",
"image" => "https://images.unsplash.com/photo-1514473776127-61e2dc1dded3?w=871&q=80",
"click_action" => "https://example.com"
],
'to' => $token,
'priority'=> 'high'
];
echo "===".json_encode($data)."===\n";
$options = array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => array(
"Authorization: key=$access_token",
"Content-Type: application/json",
),
CURLOPT_POSTFIELDS => json_encode($data),
);
$curl = curl_init();
curl_setopt_array($curl, $options);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
and I am using service worker, sw.main.js(has cache) and sw.data2.js(no cache with Push)
just use sw.data2.js is better.
self.addEventListener('push', function(event) {
//console.log('[Service Worker] Push Received');
//console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
var currentdate = new Date();
var hr= currentdate.getHours();if (hr<10)hr="0"+hr;
var min=currentdate.getMinutes();if (min<10)min="0"+min;
var sec=currentdate.getSeconds();if (sec<10)sec="0"+sec;
var calltime = hr + ":"+ min + ":"+ sec +" "
+ currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear();
//console.log("pass");
const title = 'Incoming Call From:';
const options = {
body: `"${event.data.text()}"`,
requireInteraction: true,
icon: '/icon/icon.png',
badge: '/icon/badge.png',
silent:false,
sound:'/music/eid.mp3',
channel_id: getRandomArbitrary(0,100000000)
};
//console.log("msgobj:",msgobj,new Date());
if (msgobj !=null) msgobj.postMessage(event.data.text());
else{
self.removeEventListener("message", function() {}, true);
self.addEventListener("message", (event) => {
// event is an ExtendableMessageEvent msgobject
console.log(`sw.js The client sent me a message-2XXXX: ${event.data}`);
msgobj=event.source;
msgobj.postMessage(event.data.text());
});
}
//console.log("@@@@@@@@@@@@@@@@@@@");
//const audio = new Audio("eid.mp3"); audio.play();
// event.waitUntil(self.registration.showNotification(title, options));
});
Expert: rcschroeder replied at 2026-06-10 20:00:47
The error message indicates that the request is missing proper authentication credentials. To resolve this issue, you need to follow these steps:
1. **Enable the Firebase Cloud Messaging (FCM) API**
* Go to the Firebase Console and navigate to the "Cloud Messaging" section.
* Click on "Get started" and then select your project.
* Click on "Setup" and enable the FCM API.
2. **Generate a Server Key**
* In the Firebase Console, go to the "Cloud Messaging" section and click on the three vertical dots next to your project name.
* Select "Get server key".
* Copy the Server Key.
3. **Install Required Packages**
First, you'll need to install the `firebase/php-sdk` package using Composer:
```bash
composer require firebase/php-sdk
```
This will download and install the Firebase PHP SDK.
4. **Modify Your Code**
Replace your notification code with the following:
```php
require_once __DIR__ . '/vendor/autoload.php';
use FirebaseJWTJWT;
use Firebase MessagingV2Message;
$serverKey = 'your_server_key_here'; // Replace with your Server Key
function sendNotification($token, $message) {
$options = [
'https_options' => [
GuzzleHttpClient::HTTP_AUTH_TOKEN => ['Authorization' => "Bearer $token"],
],
];
$client = new GuzzleHttpClient($options);
$response = $client->post('https://fcm.googleapis.com/fcm/send', [
'headers' => [
'Authorization: key=' . $serverKey,
'Content-Type: application/json',
],
'json' => [
"to" => $message['to'],
"data" => $message['data'],
"notification" => $message['notification']
]
]);
if ($response->getStatusCode() === 200) {
return true;
} else {
return false;
}
}
```
Here's how you can use it:
```php
$token = 'your_fcm_token_here'; // Replace with your FCM Token
$message = [
'to' => 'your_target_device_token_here', // Replace with the device token of the user to send notifications to.
'data' => ['message' => 'Hello, world!'],
'notification' => [
'title' => 'Test Notification',
'body' => 'This is a test notification.'
]
];
if (sendNotification($token, $message)) {
echo "Notification sent successfully.";
} else {
echo "Failed to send notification.";
}
```
**Step 5: Add Error Handling**
To handle errors, you can use try-catch blocks. Here's how you can modify the above code:
```php
try {
if (sendNotification($token, $message)) {
echo "Notification sent successfully.";
} else {
echo "Failed to send notification.";
}
} catch (GuzzleHttpClientException $e) {
echo 'Caught exception: ', $e->getMessage(), "";
}
```
**Step 6: Check Your Code**
Double-check that the `serverKey` is correct and the token and target device tokens are in the expected format.
Here's the complete code:
```php
<?php
require_once __DIR__ . '/vendor/autoload.php';
use FirebaseJWTJWT;
use Firebase MessagingV2Message;
$serverKey = 'your_server_key_here'; // Replace with your Server Key
function sendNotification($token, $message) {
$options = [
'https_options' => [
GuzzleHttpClient::HTTP_AUTH_TOKEN => ['Authorization' => "Bearer $token"],
],
];
$client = new GuzzleHttpClient($options);
$response = $client->post('https://fcm.googleapis.com/fcm/send', [
'headers' => [
'Authorization: key=' . $serverKey,
'Content-Type: application/json',
],
'json' => [
"to" => $message['to'],
"data" => $message['data'],
"notification" => $message['notification']
]
]);
if ($response->getStatusCode() === 200) {
return true;
} else {
return false;
}
}
$token = 'your_fcm_token_here'; // Replace with your FCM Token
$message = [
'to' => 'your_target_device_token_here', // Replace with the device token of the user to send notifications to.
'data' => ['message' => 'Hello, world!'],
'notification' => [
'title' => 'Test Notification',
'body' => 'This is a test notification.'
]
];
try {
if (sendNotification($token, $message)) {
echo "Notification sent successfully.";
} else {
echo "Failed to send notification.";
}
} catch (GuzzleHttpClientException $e) {
echo 'Caught exception: ', $e->getMessage(), "";
}
```
After following these steps and testing your code, you should be able to send notifications using Firebase Cloud Messaging (FCM). If you're still having trouble, make sure that all your tokens are in the correct format.
1. **Enable the Firebase Cloud Messaging (FCM) API**
* Go to the Firebase Console and navigate to the "Cloud Messaging" section.
* Click on "Get started" and then select your project.
* Click on "Setup" and enable the FCM API.
2. **Generate a Server Key**
* In the Firebase Console, go to the "Cloud Messaging" section and click on the three vertical dots next to your project name.
* Select "Get server key".
* Copy the Server Key.
3. **Install Required Packages**
First, you'll need to install the `firebase/php-sdk` package using Composer:
```bash
composer require firebase/php-sdk
```
This will download and install the Firebase PHP SDK.
4. **Modify Your Code**
Replace your notification code with the following:
```php
require_once __DIR__ . '/vendor/autoload.php';
use FirebaseJWTJWT;
use Firebase MessagingV2Message;
$serverKey = 'your_server_key_here'; // Replace with your Server Key
function sendNotification($token, $message) {
$options = [
'https_options' => [
GuzzleHttpClient::HTTP_AUTH_TOKEN => ['Authorization' => "Bearer $token"],
],
];
$client = new GuzzleHttpClient($options);
$response = $client->post('https://fcm.googleapis.com/fcm/send', [
'headers' => [
'Authorization: key=' . $serverKey,
'Content-Type: application/json',
],
'json' => [
"to" => $message['to'],
"data" => $message['data'],
"notification" => $message['notification']
]
]);
if ($response->getStatusCode() === 200) {
return true;
} else {
return false;
}
}
```
Here's how you can use it:
```php
$token = 'your_fcm_token_here'; // Replace with your FCM Token
$message = [
'to' => 'your_target_device_token_here', // Replace with the device token of the user to send notifications to.
'data' => ['message' => 'Hello, world!'],
'notification' => [
'title' => 'Test Notification',
'body' => 'This is a test notification.'
]
];
if (sendNotification($token, $message)) {
echo "Notification sent successfully.";
} else {
echo "Failed to send notification.";
}
```
**Step 5: Add Error Handling**
To handle errors, you can use try-catch blocks. Here's how you can modify the above code:
```php
try {
if (sendNotification($token, $message)) {
echo "Notification sent successfully.";
} else {
echo "Failed to send notification.";
}
} catch (GuzzleHttpClientException $e) {
echo 'Caught exception: ', $e->getMessage(), "";
}
```
**Step 6: Check Your Code**
Double-check that the `serverKey` is correct and the token and target device tokens are in the expected format.
Here's the complete code:
```php
<?php
require_once __DIR__ . '/vendor/autoload.php';
use FirebaseJWTJWT;
use Firebase MessagingV2Message;
$serverKey = 'your_server_key_here'; // Replace with your Server Key
function sendNotification($token, $message) {
$options = [
'https_options' => [
GuzzleHttpClient::HTTP_AUTH_TOKEN => ['Authorization' => "Bearer $token"],
],
];
$client = new GuzzleHttpClient($options);
$response = $client->post('https://fcm.googleapis.com/fcm/send', [
'headers' => [
'Authorization: key=' . $serverKey,
'Content-Type: application/json',
],
'json' => [
"to" => $message['to'],
"data" => $message['data'],
"notification" => $message['notification']
]
]);
if ($response->getStatusCode() === 200) {
return true;
} else {
return false;
}
}
$token = 'your_fcm_token_here'; // Replace with your FCM Token
$message = [
'to' => 'your_target_device_token_here', // Replace with the device token of the user to send notifications to.
'data' => ['message' => 'Hello, world!'],
'notification' => [
'title' => 'Test Notification',
'body' => 'This is a test notification.'
]
];
try {
if (sendNotification($token, $message)) {
echo "Notification sent successfully.";
} else {
echo "Failed to send notification.";
}
} catch (GuzzleHttpClientException $e) {
echo 'Caught exception: ', $e->getMessage(), "";
}
```
After following these steps and testing your code, you should be able to send notifications using Firebase Cloud Messaging (FCM). If you're still having trouble, make sure that all your tokens are in the correct format.