如何在不使用Firebase控制台的情况下发送Firebase云消息通知?

我从新的谷歌服务开始通知,Firebase Cloud Messaging

多亏了这个代码https://github.com/firebase/quickstart-android/tree/master/messaging,我才能从我的Firebase用户控制台发送通知到我的Android设备。

有没有什么API或方法可以在不使用Firebase控制台的情况下发送通知?我的意思是,例如,一个PHP API或类似的东西,直接从我自己的服务器创建通知。

420734 次浏览

Firebase云消息传递有一个服务器端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\":{\"title\":\"Hello\",\"body\":\"Yellow\"}}"

你可以在任何环境中使用所有这些REST API,但是有专门的所谓管理sdk用于许多列出在这里的平台。

正如Frank所提到的,您可以使用Firebase Cloud Messaging (FCM) HTTP API从您自己的后端触发推送通知。但是你不能这样做

  1. 发送通知到Firebase用户标识符(UID)和
  2. 向用户群发送通知(目标属性&事件就像你可以在用户控制台)。

意思是:您必须自己存储FCM/GCM注册id(推送令牌)或使用FCM主题订阅用户。还要记住FCM不是Firebase通知的API,它是一个低级API,没有调度或打开率分析。Firebase Notifications是建立在FCM之上的。

例如,您可以使用用于谷歌云消息传递(GCM)的PHP脚本。Firebase及其控制台位于GCM之上。

我在github上找到了这个: https://gist.github.com/prime31/5675017 < / p >

提示:这个PHP脚本的结果是android的通知

因此:如果你想在Android中接收和显示通知,请读取这是库特的回答

使用服务api。

URL: 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"
},
"data": {
"<some_key>": "<some_value>"
},
"to": "<device_token>"
}

在你的应用程序中,你可以添加以下代码在你的活动中被调用:

<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>

也检查当应用程序在后台时,未调用Firebase onmessagerreceived上的答案

首先,你需要从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;
}




?>

使用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

使用服务API的示例

API url: __abc0

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!"
}
}

这是使用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密钥)

如果你想从android发送推送通知,请查看我的博客文章

从一个android手机发送推送通知到另一个没有服务器的android手机

发送推送通知只是一个post请求到https://fcm.googleapis.com/fcm/send

使用volley的代码片段:

    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);

我建议你们都去看看我的博客以获得完整的细节。

可以使用FCM HTTP v1 API端点将通知或数据消息发送到firebase基础云消息服务器。 https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send . < / p >

您需要使用Firebase控制台生成并下载服务账号的私钥,使用谷歌api客户端库生成接入密钥。使用任何http库张贴消息到上面的端点,下面的代码显示张贴消息使用OkHTTP。你可以在Firebase云消息传递和发送消息到多个客户端使用FCM主题示例找到完整的服务器端和客户端代码

如果需要发送特定的客户端消息,则需要获取客户端的firebase注册密钥,参见发送客户端或设备特定的消息到FCM服务器示例

String SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
String FCM_ENDPOINT
= "https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send";


GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream("firebase-private-key.json"))
.createScoped(Arrays.asList(SCOPE));
googleCredential.refreshToken();
String token = googleCredential.getAccessToken();






final MediaType mediaType = MediaType.parse("application/json");


OkHttpClient httpClient = new OkHttpClient();


Request request = new Request.Builder()
.url(FCM_ENDPOINT)
.addHeader("Content-Type", "application/json; UTF-8")
.addHeader("Authorization", "Bearer " + token)
.post(RequestBody.create(mediaType, jsonMessage))
.build();




Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
log.info("Message sent to FCM server");
}

使用Firebase Console可以根据应用程序包向所有用户发送消息。但对于CURL或PHP API,这是不可能的。

通过API可以向指定的设备ID或订阅的用户发送通知给选定的主题或订阅的主题用户。

Get a view on following link. It will help you.
https://firebase.google.com/docs/cloud-messaging/send-message
或者你可以使用Firebase的云功能,对我来说,这是实现推送通知的更简单的方法。 重火力点/ functions-samples < / p >

如果你使用的是PHP,我建议使用Firebase的PHP SDK: Firebase Admin SDK。为了一个简单的配置,您可以按照以下步骤:

从Firebase (初始化sdk)获取项目凭证json文件,并将其包含在项目中。

在项目中安装SDK。我使用composer:

composer require kreait/firebase-php ^4.35

试试SDK文档中的云消息会话中的任何例子:

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);

这个来自这个链接的解决方案对我帮助很大。你可以去看看。

带有这些指令行的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>&nbsp;</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.

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);
}

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'
]);

下面是我使用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;

简介

我编译了上面的大部分答案,并根据FCM HTTP连接文档更新了变量,以制定一个在2021年适用于FCM的解决方案。感谢Hamzah马利克上面非常有见地的回答。

先决条件

首先,确保你已经将你的项目连接到Firebase,并且你已经设置了应用程序上的所有依赖项。如果你还没有,首先前往FCM配置文档

如果这样做了,您还需要从API复制项目的服务器响应键。转到你的重火力点控制台,点击你正在做的项目,然后导航到;

Project Settings(Setting wheel on upper left corner) -> Cloud Messaging Tab -> Copy the Server key

配置PHP后端

我用Ankit Adlakha的API调用结构和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}"}