Firebase 콘솔을 사용하지 않고 Firebase 클라우드 메시징 알림을 보내려면 어떻게해야합니까? [닫은]
알림에 대한 새로운 Google 서비스부터 시작하겠습니다 Firebase Cloud Messaging.
이 코드 덕분에 https://github.com/firebase/quickstart-android/tree/master/messaging 내 Firebase 사용자 콘솔 에서 내 Android 기기 로 알림을 보낼 수있었습니다 .
Firebase 콘솔을 사용하지 않고 알림을 보내는 API 또는 방법이 있습니까? 예를 들어 PHP API 또는 이와 유사한 것을 사용하여 내 서버에서 직접 알림을 만듭니다.
Firebase Cloud Messaging에는 메시지를 보내기 위해 호출 할 수있는 서버 측 API가 있습니다. https://firebase.google.com/docs/cloud-messaging/server를 참조 하십시오 .
curlHTTP 엔드 포인트를 호출하는 데 사용 하는 것만 큼 간단하게 메시지를 보낼 수 있습니다 . 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}"
이것은 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는 IS 장치 등록 토큰
YOUR_KEY_HERE 서버 API 키 (또는 레거시 서버 API 키)
서비스 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" // 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)"
}
그리고 이것을 앱에서 사용하면 활동에 아래 코드를 추가하여 호출 할 수 있습니다.
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
또한 백그라운드에서 앱을 사용할 때 Firebase onMessageReceived에서 호출되지 않은 응답을 확인하십시오.
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 : 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!"
}
}
Frank가 언급했듯이 Firebase Cloud Messaging (FCM) HTTP API를 사용하여 자신의 백엔드에서 푸시 알림을 트리거 할 수 있습니다. 그러나 당신은 할 수 없습니다
- Firebase 사용자 식별자 (UID)에 알림을 보내고
- 사용자 세그먼트에 알림을 보냅니다 (사용자 콘솔에서 할 수있는 것처럼 대상 속성 및 이벤트).
의미 : FCM / GCM 등록 ID (푸시 토큰)를 직접 저장하거나 FCM 주제를 사용하여 사용자를 구독해야합니다. 마음에 또한 유지 FCM은 중포 기지 알림에 대한 API 아니다 , 그것은 일정 또는 개방 속도 분석없이 낮은 수준의 API입니다. Firebase 알림은 FCM에 구축되어 있습니다.
먼저 안드로이드에서 토큰을 가져와야 하고이 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;
}
?>
예를 들어 Google 클라우드 메시징 (GCM) 용 PHP 스크립트를 사용할 수 있습니다. Firebase와 콘솔은 GCM의 최상단에 있습니다.
나는 이것을 github에서 발견했다 : https://gist.github.com/prime31/5675017
힌트 :이 PHP 스크립트는 안드로이드 알림을 발생 시킵니다.
Therefore: Read this answer from Koot if you want to receive and show the notification in Android.
Notification or data message can be sent to firebase base cloud messaging server using FCM HTTP v1 API endpoint. https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send.
You need to generate and download private key of service account using Firebase console and generate access key using google api client library. Use any http library to post message to above end point, below code shows posting message using OkHTTP. You can find complete server side and client side code at firebase cloud messaging and sending messages to multiple clients using fcm topic example
If a specific client message needs to sent, you need to get firebase registration key of the client, see sending client or device specific messages to FCM server example
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");
}
If you want to send push notifications from android check out my blog post
Send Push Notifications from 1 android phone to another with out server.
sending push notification is nothing but a post request to https://fcm.googleapis.com/fcm/send
code snippet using 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);
I suggest you all to check out my blog post for complete details.
Using Firebase Console you can send message to all users based on application package.But with CURL or PHP API its not possible.
Through API You can send notification to specific device ID or subscribed users to selected topic or subscribed topic users.
Get a view on following link. It will help you.
https://firebase.google.com/docs/cloud-messaging/send-message
Or you can use Firebase cloud functions, which is for me the easier way to implement your push notifications. firebase/functions-samples
'Programming' 카테고리의 다른 글
| 파이프 완성을 처리하기위한 콜백 (0) | 2020.05.15 |
|---|---|
| 디버깅을 종료 할 때 Visual Studio 2013이 IIS Express 앱을 닫지 못하게하려면 어떻게해야합니까? (0) | 2020.05.15 |
| 요소의 부모 div 얻기 (0) | 2020.05.15 |
| Python에서 Pandas와 NumPy + SciPy의 차이점은 무엇입니까? (0) | 2020.05.15 |
| Swift에서 유형이 지정된 배열을 어떻게 확장 할 수 있습니까? (0) | 2020.05.15 |