Jak mogę wysłać powiadomienie Firebase Cloud Messaging bez korzystania z konsoli Firebase? [zamknięte]

Zaczynam od nowej usługi Google dla powiadomień, Firebase Cloud Messaging.

Dzięki temu kodowi https://github.com/firebase/quickstart-android/tree/master/messaging udało mi się wysyłać powiadomienia z mojej konsoli użytkownika Firebase na Moje urządzenie z Androidem.

Czy istnieje jakieś API lub sposób na wysłanie powiadomienia bez użycia konsoli Firebase? Mam na myśli, na przykład, PHP API lub coś w tym stylu, do tworzenia powiadomień z własnego serwera bezpośrednio.

Author: Alexander Farber, 2016-05-22

11 answers

Firebase Cloud Messaging ma interfejsy API po stronie serwera, które można wywołać, aby wysyłać wiadomości. Zobacz https://firebase.google.com/docs/cloud-messaging/server .

Wysłanie wiadomości może być tak proste, jak użycie curl do wywołania punktu końcowego HTTP. Zobacz też 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}"
 168
Author: Frank van Puffelen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-05 22:42:03

To działa przy użyciu 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 jest twoją wiadomością do wysłania na urządzenie

$id jest tokenem rejestracji urządzeń

YOUR_KEY_HERE jest kluczem API serwera (lub starszym kluczem API serwera)

 37
Author: Hamzah Malik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-20 19:04:18

Użyj API usługi.

URL: https://fcm.googleapis.com/fcm/send

Typ Metody: POST

Nagłówki:

Content-Type: application/json
Authorization: key=your api key

Ciało / Ładunek:

{ "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)"
} 

I dzięki temu w aplikacji możesz dodać poniższy kod w swojej aktywności do wywołania:

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

Sprawdź również odpowiedź na Firebase onmessagerecapes not called when app in background

 34
Author: Ankit Adlakha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-20 16:01:41

Przykłady użycia curl

Wysyłanie wiadomości do określonych urządzeń

Aby wysyłać wiadomości do określonych urządzeń, Ustaw token do rejestracji dla konkretnej instancji aplikacji

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

Wysyłanie wiadomości do tematów

Oto temat: / 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

Wysyłanie wiadomości do grup urządzeń

Wysyłanie wiadomości do grupy urządzeń jest bardzo podobne do wysyłania wiadomości do jednostki urządzenie. Ustaw parametr to na unikalny klucz powiadomień dla grupy urządzeń

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

Przykłady użycia Service API

URL API: https://fcm.googleapis.com/fcm/send

Nagłówki

Content-type: application/json
Authorization:key=<Your Api key>

Metoda Zapytania: POST

Request Body

Komunikaty do konkretnych urządzeń

{
  "data": {
    "score": "5x1",
    "time": "15:10"
  },
  "to": "<registration token>"
}

Wiadomości do tematów

{
  "to": "/topics/foo-bar",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!"
  }
}

Wiadomości do grup urządzeń

{
  "to": "<aUniqueKey>",
  "data": {
    "hello": "This is a Firebase Cloud Messaging Device Group Message!"
  }
}
 28
Author: J.R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-15 09:34:40

Jak wspomniał Frank, możesz użyć Firebase Cloud Messaging (FCM) HTTP API, aby wyzwalać powiadomienia push z własnego zaplecza. Ale nie będziesz w stanie

  1. wysyłanie powiadomień do identyfikatora użytkownika Firebase (UID) oraz
  2. wysyłanie powiadomień do segmentów użytkowników(kierowanie właściwości i zdarzeń, jak można na konsoli użytkownika).

Znaczenie: będziesz musiał przechowywać identyfikatory rejestracji FCM / GCM (push tokeny) samodzielnie lub używać tematów FCM do subskrybowania użytkowników. Keep also in pamiętaj, że FCM nie jest API dla powiadomień Firebase , jest to API niższego poziomu bez planowania i analizy otwartej stopy. Firebase Notifications jest zbudowany na FCM.

 22
Author: Antoine Guénard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-26 20:42:13

Najpierw musisz pobrać token z Androida, a następnie możesz wywołać ten kod php, a nawet wysłać dane do dalszych działań w aplikacji.

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


?>
 4
Author: Sandi Horvat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-08 10:40:41

Możesz użyć na przykład skryptu PHP dla Google Cloud Messaging (GCM). Firebase, a jego konsola, znajduje się tuż nad GCM.

Znalazłem ten na GitHubie: https://gist.github.com/prime31/5675017

Podpowiedź: ten skrypt PHP powoduje powiadomienie Androida .

Dlatego: przeczytaj tę odpowiedź z Koot Jeśli Chcesz otrzymać i pokazać powiadomienie w Androidzie.

 3
Author: P-Zenker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:03:08

Jeśli chcesz wysyłać powiadomienia push z Androida sprawdź mój wpis na blogu

Wysyłaj powiadomienia Push z 1 telefonu z Androidem na inny serwer bez wyjścia.

Wysyłanie powiadomień push to nic innego jak żądanie post do https://fcm.googleapis.com/fcm/send

Fragment kodu za pomocą 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);

Proponuję wszystkim zajrzeć do mojego wpisu na blogu, aby uzyskać szczegółowe informacje.

 0
Author: Redman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-27 10:47:21

Powiadomienie lub wiadomość z danymi mogą być wysyłane do serwera firebase base cloud messaging server przy użyciu punktu końcowego API FCM HTTP V1. https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send .

Musisz wygenerować i pobrać klucz prywatny konta usługi za pomocą konsoli Firebase oraz wygenerować klucz dostępu za pomocą biblioteki klienta google api. Użyj dowolnej biblioteki http, aby wysłać wiadomość do powyższego punktu końcowego, poniższy kod pokazuje wysyłanie wiadomości za pomocą OkHTTP. Można znaleźć pełną stronę serwera i kod po stronie klienta w firebase cloud messaging i wysyłanie wiadomości do wielu klientów za pomocą przykładu tematu fcm

Jeśli chcesz wysłać konkretną wiadomość klienta, musisz uzyskać klucz rejestracyjny firebase klienta, Zobacz wysyłanie wiadomości specyficznych dla klienta lub urządzenia do serwera FCM przykład
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");
}
 0
Author: Arnav Rao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-16 05:15:46

Za pomocą konsoli Firebase można wysyłać wiadomości do wszystkich użytkowników na podstawie pakietu aplikacji.Ale z CURL lub PHP API nie jest to możliwe.

Poprzez API możesz wysyłać powiadomienia do określonego identyfikatora urządzenia lub subskrybowanych użytkowników do wybranego tematu lub subskrybowanych użytkowników tematu.

Get a view on following link. It will help you.
https://firebase.google.com/docs/cloud-messaging/send-message
 0
Author: Prateek Bhardwaj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-26 16:05:06

LUB możesz skorzystać z funkcji Firebase cloud, co jest dla mnie łatwiejszym sposobem implementacji powiadomień push. firebase / functions-samples

 0
Author: Laurent Maquet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-19 13:36:17