Dav*_*ral 188 php api android firebase firebase-cloud-messaging
我开始使用新的Google服务进行通知Firebase Cloud Messaging
.
感谢此代码https://github.com/firebase/quickstart-android/tree/master/messaging我能够将Firebase用户控制台的通知发送到我的Android设备.
是否有任何API或方式可以在不使用Firebase控制台的情况下发送通知?我的意思是,例如,PHP API或类似的东西,直接从我自己的服务器创建通知.
Fra*_*len 190
Firebase Cloud Messaging具有服务器端API,您可以调用它们来发送消息.请参阅https://firebase.google.com/docs/cloud-messaging/server.
发送消息可以像使用curl
调用HTTP端点一样简单.请参阅https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol
curl -X POST --header "Authorization: key=<API_ACCESS_KEY>" \
--Header "Content-Type: application/json" \
https://fcm.googleapis.com/fcm/send \
-d "{\"to\":\"<YOUR_DEVICE_ID_TOKEN>\",\"notification\":{\"body\":\"Yellow\"},\"priority\":10}"
Run Code Online (Sandbox Code Playgroud)
Ham*_*lik 48
这适用于CURL
function sendGCM($message, $id) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => array (
$id
),
'data' => array (
"message" => $message
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "YOUR_KEY_HERE",
'Content-Type: application/json'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
echo $result;
curl_close ( $ch );
}
?>
Run Code Online (Sandbox Code Playgroud)
$message
是您要发送到设备的消息
$id
是设备注册令牌
YOUR_KEY_HERE
是您的服务器API密钥(或旧服务器API密钥)
小智 42
使用服务API.
网址: https://fcm.googleapis.com/fcm/send
方法类型: POST
头:
Content-Type: application/json
Authorization: key=your api key
Run Code Online (Sandbox Code Playgroud)
车身/有效载荷:
{ "notification": {
"title": "Your Title",
"text": "Your Text",
"click_action": "OPEN_ACTIVITY_1" // should match to your intent filter
},
"data": {
"keyname": "any value " //you can get this data as extras in your activity and this data is optional
},
"to" : "to_id(firebase refreshedToken)"
}
Run Code Online (Sandbox Code Playgroud)
在您的应用中,您可以在要调用的活动中添加以下代码:
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
Run Code Online (Sandbox Code Playgroud)
同时检查Firebase onMessageReceived上的答案,该应用程序在后台运行时未调用
J.R*_*J.R 36
使用curl的例子
将消息发送到特定设备
要将消息发送到特定设备,请将其设置为特定应用程序实例的注册令牌
curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>" -X POST -d '{ "data": { "score": "5x1","time": "15:10"},"to" : "<registration token>"}' https://fcm.googleapis.com/fcm/send
Run Code Online (Sandbox Code Playgroud)
向主题发送消息
这里的主题是:/ topics/foo-bar
curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>" -X POST -d '{ "to": "/topics/foo-bar","data": { "message": "This is a Firebase Cloud Messaging Topic Message!"}}' https://fcm.googleapis.com/fcm/send
Run Code Online (Sandbox Code Playgroud)
将消息发送到设备组
将消息发送到设备组与将消息发送到单个设备非常相似.将to参数设置为设备组的唯一通知密钥
curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>" -X POST -d '{"to": "<aUniqueKey>","data": {"hello": "This is a Firebase Cloud Messaging Device Group Message!"}}' https://fcm.googleapis.com/fcm/send
Run Code Online (Sandbox Code Playgroud)
使用Service API的示例
API网址: https://fcm.googleapis.com/fcm/send
头
Content-type: application/json
Authorization:key=<Your Api key>
Run Code Online (Sandbox Code Playgroud)
请求方法: POST
请求机构
给特定设备的消息
{
"data": {
"score": "5x1",
"time": "15:10"
},
"to": "<registration token>"
}
Run Code Online (Sandbox Code Playgroud)
消息到主题
{
"to": "/topics/foo-bar",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!"
}
}
Run Code Online (Sandbox Code Playgroud)
发送给设备组的消息
{
"to": "<aUniqueKey>",
"data": {
"hello": "This is a Firebase Cloud Messaging Device Group Message!"
}
}
Run Code Online (Sandbox Code Playgroud)
Ant*_*ard 23
如Frank所述,您可以使用Firebase云消息传递(FCM)HTTP API从您自己的后端触发推送通知.但你无法做到
含义:您必须自己存储FCM/GCM注册ID(推送令牌)或使用FCM主题订阅用户.请记住,FCM不是Firebase Notifications的API,它是没有计划或开放式分析的低级API.Firebase Notifications建立在FCM的顶部.
Ken*_*rwa 12
我编译了上面的大部分答案,并根据FCM HTTP 连接文档更新了变量,以策划一个在 2021 年与 FCM 配合使用的解决方案。感谢Hamzah Malik上面非常有见地的回答。
首先,确保您已将项目与 Firebase 连接,并且已设置应用程序的所有依赖项。如果还没有,请首先访问FCM 配置文档
如果完成,您还需要从 API 复制项目的服务器响应密钥。前往Firebase Console,单击您正在处理的项目,然后导航至;
Project Settings(Setting wheel on upper left corner) -> Cloud Messaging Tab -> Copy the Server key
Run Code Online (Sandbox Code Playgroud)
我使用Ankit Adlakha 的 API 调用结构和 FCM 文档编译了 Hamzah 的答案,得出以下 PHP 函数:
function sendGCM() {
// FCM API Url
$url = 'https://fcm.googleapis.com/fcm/send';
// Put your Server Response Key here
$apiKey = "YOUR SERVER RESPONSE KEY HERE";
// Compile headers in one variable
$headers = array (
'Authorization:key=' . $apiKey,
'Content-Type:application/json'
);
// Add notification content to a variable for easy reference
$notifData = [
'title' => "Test Title",
'body' => "Test notification body",
'click_action' => "android.intent.action.MAIN"
];
// Create the api body
$apiBody = [
'notification' => $notifData,
'data' => $notifData,
"time_to_live" => "600" // Optional
'to' => '/topics/mytargettopic' // Replace 'mytargettopic' with your intended notification audience
];
// Initialize curl with the prepared headers and body
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url );
curl_setopt ($ch, CURLOPT_POST, true );
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ($ch, CURLOPT_POSTFIELDS, json_encode($apiBody));
// Execute call and save result
$result = curl_exec ( $ch );
// Close curl after call
curl_close ( $ch );
return $result;
}
Run Code Online (Sandbox Code Playgroud)
要通过令牌提交通知,请使用'to' => 'registration token'
我在我的网站后端设置了该功能,并在 Postman 上进行了测试。如果您的配置成功,您应该会收到类似于以下内容的响应;
{"message":"{"message_id":3061657653031348530}"}
Run Code Online (Sandbox Code Playgroud)
此链接中的此解决方案对我有很大帮助。你可以看看。
带有这些指令行的 curl.php 文件可以工作。
<?php
// Server key from Firebase Console define( 'API_ACCESS_KEY', 'AAAA----FE6F' );
$data = array("to" => "cNf2---6Vs9", "notification" => array( "title" => "Shareurcodes.com", "body" => "A Code Sharing Blog!","icon" => "icon.png", "click_action" => "http://shareurcodes.com"));
$data_string = json_encode($data);
echo "The Json Data : ".$data_string;
$headers = array ( 'Authorization: key=' . API_ACCESS_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_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
curl_close ($ch);
echo "<p> </p>";
echo "The Result : ".$result;
Run Code Online (Sandbox Code Playgroud)
记住 you need to execute curl.php file using another browser ie not from the browser that is used to get the user token. You can see notification only if you are browsing another website.
首先,您需要从android获取令牌,然后可以调用此php代码,甚至可以发送数据以在应用程序中进行进一步的操作。
<?php
// Call .php?Action=M&t=title&m=message&r=token
$action=$_GET["Action"];
switch ($action) {
Case "M":
$r=$_GET["r"];
$t=$_GET["t"];
$m=$_GET["m"];
$j=json_decode(notify($r, $t, $m));
$succ=0;
$fail=0;
$succ=$j->{'success'};
$fail=$j->{'failure'};
print "Success: " . $succ . "<br>";
print "Fail : " . $fail . "<br>";
break;
default:
print json_encode ("Error: Function not defined ->" . $action);
}
function notify ($r, $t, $m)
{
// API access key from Google API's Console
if (!defined('API_ACCESS_KEY')) define( 'API_ACCESS_KEY', 'Insert here' );
$tokenarray = array($r);
// prep the bundle
$msg = array
(
'title' => $t,
'message' => $m,
'MyKey1' => 'MyData1',
'MyKey2' => 'MyData2',
);
$fields = array
(
'registration_ids' => $tokenarray,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
return $result;
}
?>
Run Code Online (Sandbox Code Playgroud)
这是我的项目中使用 CURL 的工作代码。
<?PHP
//Avoid keys confusions!
//firebase Cloud Messaging have 3 different keys:
//API_KEY, SERVER_KEY and PUSH_KEY ... here we need SERVER_KEY
// SERVER access key from Google firebase Console
define( 'SERVER_ACCESS_KEY', 'YOUR-SERVER-ACCESS-KEY-GOES-HERE' );
$registrationIds = array( $_GET['id'] );
// prep the bundle
$msg = array
(
'message' => 'here is a message. message',
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$fields = array
(
// use this to method if want to send to topics
// 'to' => 'topics/all'
'registration_ids' => $registrationIds,
'notification' => $msg
);
$headers = array
(
'Authorization: key=' . SERVER_ACCESS_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_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
269470 次 |
最近记录: |