我从新的Google服务开始,通知Firebase Cloud Messaging
。
感谢此代码https://github.com/firebase/quickstart-android/tree/master/messaging,我能够将 Firebase用户控制台的通知发送到我的Android设备。
是否有任何API或方式在不使用Firebase控制台的情况下发送通知?我的意思是,例如,PHP API或类似的东西,直接从我自己的服务器创建通知。
答案 0 :(得分:185)
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}"
答案 1 :(得分:43)
这可以使用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 );
}
?>
$message
是您要发送到设备的消息
$id
是设备注册令牌
YOUR_KEY_HERE
是您的服务器API密钥(或旧版服务器API密钥)
答案 2 :(得分:38)
使用服务API。
网址:request.ContentLength = requestBody.Length;
方法类型:https://fcm.googleapis.com/fcm/send
标题:
POST
车身/有效载荷:
Content-Type: application/json
Authorization: key=your api key
在您的应用中,您可以在要调用的活动中添加以下代码:
{ "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)"
}
同时查看Firebase onMessageReceived not called when app in background
上的答案答案 3 :(得分:34)
使用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
向主题发送消息
这里的主题是:/ 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
向设备组发送消息
向设备组发送消息与向单个设备发送消息非常相似。将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
使用Service API的示例
API网址:https://fcm.googleapis.com/fcm/send
接头
Content-type: application/json
Authorization:key=<Your Api key>
请求方法:POST
请求正文
发送给特定设备的消息
{
"data": {
"score": "5x1",
"time": "15:10"
},
"to": "<registration token>"
}
主题消息
{
"to": "/topics/foo-bar",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!"
}
}
设备组的消息
{
"to": "<aUniqueKey>",
"data": {
"hello": "This is a Firebase Cloud Messaging Device Group Message!"
}
}
答案 4 :(得分:23)
正如Frank所说,您可以使用Firebase云消息传递(FCM)HTTP API从您自己的后端触发推送通知。但你无法
含义:您必须自己存储FCM / GCM注册ID(推送令牌)或使用FCM主题订阅用户。另请注意, FCM不是Firebase通知的API ,它是没有计划或开放式分析的低级API。 Firebase Notifications建立在FCM的顶部。
答案 5 :(得分:4)
首先你需要从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;
}
?>
答案 6 :(得分:4)
this link提供的解决方案对我有很大帮助。您可以检查出来。
具有这些说明的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;
记住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.
答案 7 :(得分:3)
您可以使用例如用于Google Cloud Messaging(GCM)的PHP脚本。 Firebase及其控制台就在GCM之上。
我在github上找到了这个: https://gist.github.com/prime31/5675017
提示:此PHP脚本生成android notification。
因此:如果您想在Android中接收并显示通知,请阅读this answer from Koot。
答案 8 :(得分:2)
我编译了上面的大部分答案,并根据 FCM HTTP Connection Docs 更新了变量,以策划一个在 2021 年与 FCM 配合使用的解决方案。感谢 Hamzah Malik 在上面非常有见地的回答。
首先,确保您已将您的项目与 Firebase 相关联,并为您的应用设置了所有依赖项。如果您还没有,请先前往 FCM Config docs
如果这样做,您还需要从 API 复制项目的服务器响应密钥。前往您的 Firebase Console,点击您正在处理的项目,然后导航至;
Project Settings(Setting wheel on upper left corner) -> Cloud Messaging Tab -> Copy the Server key
我使用 Ankit Adlakha's API call structure 和 FCM Docs 编译了 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;
}
要通过令牌提交通知,请使用 'to' => 'registration token'
我在我的网站后端设置了该功能并在 Postman 上进行了测试。如果您的配置成功,您应该会看到类似于下面的响应;
{"message":"{"message_id":3061657653031348530}"}
答案 9 :(得分:2)
可以使用FCM HTTP v1 API端点将通知或数据消息发送到firebase基础云消息服务器。 https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send
您需要使用Firebase控制台生成和下载服务帐户的私钥,并使用google api客户端库生成访问密钥。使用任何http库将消息发布到上述终点,下面的代码显示使用OkHTTP发布消息。您可以在firebase cloud messaging and sending messages to multiple clients using fcm topic example
找到完整的服务器端和客户端代码如果需要发送特定客户端消息,则需要获取客户端的firebase注册密钥,请参阅sending client or device specific messages to FCM server example
var curLat ='';
var curLon ='';
var weatherAPI='';
$(document).ready(function(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
curLat = "lat=" + position.coords.latitude;
console.log("1_", curLat);
});
}
weatherAPI = getURL(curLat);
console.log("3_", weatherAPI);
});
function getURL(lat){
console.log("2_", lat);
var url = "https://fcc-weather-api.glitch.me/api/current?";
url = url + "&" + lat;
return url;
}
答案 10 :(得分:1)
Go to cloud Messaging select: Server key
function sendGCM($message, $deviceToken) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => array (
$id
),
'data' => array (
"title" => "Notification title",
"body" => $message,
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "YOUR_SERVER_KEY",
'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);
}
答案 11 :(得分:1)
在2020年工作
$response = Http::withHeaders([
'Content-Type' => 'application/json',
'Authorization'=> 'key='. $token,
])->post($url, [
'notification' => [
'body' => $request->summary,
'title' => $request->title,
'image' => 'http://'.request()->getHttpHost().$path,
],
'priority'=> 'high',
'data' => [
'click_action'=> 'FLUTTER_NOTIFICATION_CLICK',
'status'=> 'done',
],
'to' => '/topics/all'
]);
答案 12 :(得分:0)
使用Firebase控制台,您可以根据应用程序包向所有用户发送消息。但不能使用CURL或PHP API。
通过API您可以向特定设备ID或订阅用户发送通知,以选择主题或订阅的主题用户。
free
答案 13 :(得分:0)
或者您可以使用Firebase云功能,这对我来说是实现推送通知的更简单方法。 firebase/functions-samples
答案 14 :(得分:0)
如果您使用的是PHP,建议您使用Firebase的PHP SDK:Firebase Admin SDK。为方便配置,您可以按照以下步骤操作:
从Firebase(Initialize the sdk)获取项目凭证json文件,并将其包含在您的项目中。
在您的项目中安装SDK。我使用作曲家:
composer require kreait/firebase-php ^4.35
尝试使用SDK文档中Cloud Messaging session中的任何示例:
use Kreait\Firebase;
use Kreait\Firebase\Messaging\CloudMessage;
$messaging = (new Firebase\Factory())
->withServiceAccount('/path/to/firebase_credentials.json')
->createMessaging();
$message = CloudMessage::withTarget(/* see sections below */)
->withNotification(Notification::create('Title', 'Body'))
->withData(['key' => 'value']);
$messaging->send($message);
答案 15 :(得分:0)
这是我的项目中使用CURL的工作代码。
<?PHP
// API access key from Google API's Console
( 'API_ACCESS_KEY', 'YOUR-API-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,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/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;
答案 16 :(得分:0)
如果你想从android发送推送通知,请查看我的博客文章
Send Push Notifications from 1 android phone to another with out server.
发送推送通知只不过是对https://fcm.googleapis.com/fcm/send
的帖子请求使用排球的代码段:
JSONObject json = new JSONObject();
try {
JSONObject userData=new JSONObject();
userData.put("title","your title");
userData.put("body","your body");
json.put("data",userData);
json.put("to", receiverFirebaseToken);
}
catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", json, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("onResponse", "" + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorizationey=" + SERVER_API_KEY);
params.put("Content-Typepplication/json");
return params;
}
};
MySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
我建议大家查看我的博文,了解完整的详细信息。