programing

CURL을 통해 모든 장치에 Firebase 알림을 보내는 방법은 무엇입니까?

iphone6s 2023. 7. 6. 21:58
반응형

CURL을 통해 모든 장치에 Firebase 알림을 보내는 방법은 무엇입니까?

Firebase 관리 콘솔을 통해 알림이 전송될 때 발생하는 작업을 기본적으로 복제하여 모든 앱 사용자(Android)에게 알림을 보내려고 합니다.다음은 CURL 명령으로 시작하는 방법입니다.

curl --curl --curl "인증: key=AIzaSyBidmyauthkey isfineL-6NcJxj-1JUVEEM" -- 머리글 "Content-Type:application/json" -d "{\"알림\":{\title\":\"note-Title\",\"body\":\"note-Body\"}}" https://fcm.googleapis.com/fcm/send

여기 JSON이 당신의 눈에 더 편안함을 표현했습니다.

{
"notification":{
    "title":"note-Title",
    "body":"note-Body"
    }
}

돌아오는 응답은 두 가지 문자뿐입니다.

로.

바로 그거예요. "to"라는 단어입니다. (Headers report a 400) 저는 이것이 제 JSON에 "to"가 없는 것과 관련이 있다고 생각합니다."to"를 위해 무엇을 넣을까요?정의된 항목이 없으며 장치가 아무것도 등록되지 않았습니다.그러나 여전히 Firebase 관리 패널에서 알림을 받을 수 있습니다.

앱이 포그라운드에 있으면 알림이 핸들러에 의해 처리되지만 앱이 백그라운드에 있으면 Firebase 서비스에 의해 내부적으로 처리되고 알림 핸들러에 전달되지 않는 Firebase 알림 처리의 놀라운 한계 때문에 "데이터 전용" JSON 패키지를 시도하고 싶습니다.API를 통해 알림 요청을 제출하면 해결할 수 있지만, 데이터만 사용하는 경우에만 해결할 수 있습니다. (그러면 iOS와 Android를 동일한 메시지로 처리하는 기능이 중단됩니다.JSON에서 "알림"을 "데이터"로 대체해도 아무런 영향이 없습니다.

좋습니다. 그리고 여기서 해결책을 시도했습니다. Firebase Java Server는 푸시 알림을 모든 장치에 전송합니다. 이 알림은 "관리 콘솔을 통해 모두에게 알림이 가능하지만...API를 통해 실제로 가능한 것은 아닙니다."해결 방법은 각 클라이언트가 주제를 구독하도록 한 다음 해당 주제에 대한 통지를 발송하는 것입니다.먼저 Create의 코드를 입력합니다.

FirebaseMessaging.getInstance().subscribeToTopic("allDevices");

그리고 내가 보내는 새로운 JSON:

{
"notification":{
    "title":"note-Title",
    "body":"note-Body"
    },
"to":"allDevices"
}

그래서 이제는 서버로부터 진정한 응답을 받고 있습니다.

{
"multicast_id":463numbersnumbers42000,
"success":0,
"failure":1,
"canonical_ids":0,
"results":
    [
    {
    "error":"InvalidRegistration"
    }
    ]
}

그리고 그것은 HTTP 코드 200과 함께 나옵니다.https://firebase.google.com/docs/cloud-messaging/http-server-ref 에 따르면 "Invalid Registration"이 있는 200 코드는 등록 토큰에 문제가 있음을 의미합니다.아마도요? 문서의 그 부분은 메시징 서버를 위한 것이기 때문입니다.알림 서버가 동일합니까?불분명한.다른 곳에서는 주제가 활성화되기까지 몇 시간이 걸릴 수 있습니다.그렇게 하면 새로운 채팅방을 만드는 데 쓸모가 없을 것 같아서, 그것도 잘못된 것 같습니다.

저는 파이어베이스를 사용해 본 적이 없는 몇 시간 만에 알림을 받은 앱을 처음부터 코딩할 수 있을 때 매우 흥분했습니다.예를 들어, Stripe.com 문서 수준에 도달하기까지는 아직 갈 길이 먼 것 같습니다.

결론: 관리 콘솔 기능을 미러링하기 위해 앱을 실행하는 모든 장치에 메시지를 보내기 위해 어떤 JSON을 제공해야 하는지 아는 사람이 있습니까?

Firebase 알림에는 메시지를 보낼 API가 없습니다.다행히도 그것은 정확히 그러한 API를 가진 Firebase Cloud Messaging 위에 구축되었습니다.

Firebase 알림 및 클라우드 메시징을 사용하면 다음과 같은 세 가지 방법으로 장치에 다운스트림 메시지를 보낼 수 있습니다.

  1. 장치 ID를 알고 있는 경우 특정 장치에
  2. 장치 그룹(그룹의 등록 ID를 알고 있는 경우)
  3. 장치에서 구독할 수 있는 키인 항목으로

모든 장치에 명시적으로 보낼 수 있는 방법은 없습니다.될 때 예 예들어예써, 앱시때주가로에으입함제이있수구다습, 니이될한축기할러을능작를예▁when▁you있ing(수:▁to습니다▁app▁topice▁subscribality,▁the▁a구,▁with▁such)에 가입함으로써 을 구축할 수 ./topics/all또는 모든 장치 ID 목록을 유지한 다음 모든 장치 ID에 메시지를 전송합니다.

항목으로 보내기 위해 명령에 구문 오류가 있습니다.는 다으로시주식제별다니합으로 하여 합니다./topics/코드에 해당 코드가 없기 때문에 서버는 다음과 같이 해석합니다.allDevices장치 ID로 표시됩니다.장치 등록 토큰의 형식이 잘못되었기 때문에 오류가 발생합니다.

다음 항목으로 메시지 보내기에 대한 문서:

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

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

모든 장치에 푸시 알림을 보내는 가장 쉬운 방법은 "모두" 항목에 가입한 다음 이 항목에 알림을 보내는 것입니다.기본 활동에 복사

FirebaseMessaging.getInstance().subscribeToTopic("all");

이제 요청을 다음과 같이 보냅니다.

{
    "to": "/topics/all",
    "data":
    {
        "title":"Your title",
        "message":"Your message"
        "image-url":"your_image_url"
    }
}

이것은 비효율적이거나 비표준적인 방법일 수 있지만, 위에서 언급했듯이 가장 쉽습니다.모든 기기에 푸시 알림을 보낼 수 있는 더 좋은 방법이 있다면 게시하십시오.

FCM 설명서를 확인했습니다. 이 방법이 모든 장치알림보낼있는 유일한 방법입니다(2022년 7월 8일 기준).

댓글에 언급된 것처럼 알림이 자동으로 표시되지 않습니다. 다음에서 파생된 클래스를 정의해야 합니다.FirebaseMessagingService기능을 오버라이드합니다.onMessageReceived.

먼저 앱 매니페스트에 서비스를 등록합니다.

<!-- AndroidManifest.xml -->

<service
    android:name=".java.MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

내부에 다음 행을 추가application사용자 지정 기본 아이콘 및 사용자 지정 색상을 설정하는 태그:

<!-- AndroidManifest.xml -->

<!-- Set custom default icon. This is used when no icon is set 
for incoming notification messages. -->
<meta-data
    android:name="com.google.firebase.messaging.default_notification_icon"
    android:resource="@drawable/ic_stat_ic_notification" />
<!-- Set color used with incoming notification messages. This is used 
when no color is set for the incoming notification message. -->
<meta-data
    android:name="com.google.firebase.messaging.default_notification_color"
    android:resource="@color/colorAccent" />

이제 푸시 알림을 받을 서비스를 만듭니다.

// MyFirebaseMessagingService.java

package com.google.firebase.example.messaging;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use WorkManager.
                scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

    }
    // [END receive_message]

    // [START on_new_token]
    /**
     * There are two scenarios when onNewToken is called:
     * 1) When a new token is generated on initial app startup
     * 2) Whenever an existing token is changed
     * Under #2, there are three scenarios when the existing token is changed:
     * A) App is restored to a new device
     * B) User uninstalls/reinstalls the app
     * C) User clears app data
     */
    @Override
    public void onNewToken(@NonNull String token) {
        Log.d(TAG, "Refreshed token: " + token);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // FCM registration token to your app server.
        sendRegistrationToServer(token);
    }
    // [END on_new_token]

    private void scheduleJob() {
        // [START dispatch_job]
        OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(MyWorker.class)
                .build();
        WorkManager.getInstance(this).beginWith(work).enqueue();
        // [END dispatch_job]
    }

    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }

    public static class MyWorker extends Worker {

        public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
            super(context, workerParams);
        }

        @NonNull
        @Override
        public Result doWork() {
            // TODO(developer): add long running task here.
            return Result.success();
        }
    }
}

Firebase Cloud Messaging Tutorial - FCM을 사용한 Push Notifications and Send to multiple device - Firebase Documentation을 사용하여 푸시 알림을 보내는 것이 처음인 경우 이 튜토리얼을 따를 수 있습니다.


여러 항목으로 메시지를 보내려면 대상 항목을 지정하는 부울식인 조건을 지정합니다.예를 들어, 다음 조건은 가입한 장치에 메시지를 보냅니다.TopicA어느 쪽이든TopicB또는TopicC:

{
   "data":
   {
      "title": "Your title",
      "message": "Your message"
      "image-url": "your_image_url"
   },
   "condition": "'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
}

조건 및 항목에 대한 자세한 내용은 여기에서 FCM 문서를 참조하십시오.

편집: 이 메서드는 더 이상 지원되지 않습니다(thx에서 @FernandoZamperin).다른 답들도 한번 봐주세요!

주제를 구독하는 대신 사용할 수 있습니다.condition그룹에 없는 인스턴스에 메시지를 보내고 키를 누릅니다.데이터는 다음과 같이 표시될 수 있습니다.

{
    "data": {
        "foo": "bar"
    },
    "condition": "!('anytopicyoudontwanttouse' in topics)"
}

https://firebase.google.com/docs/cloud-messaging/send-message#send_messages_to_topics_2 을 참조하십시오.

한 가지 방법은 모든 사용자의 장치를 주제에 가입시키는 것입니다.그런 식으로 특정 주제에 메시지를 지정하면 모든 장치가 메시지를 수신합니다.Firebase 콘솔의 Notifications 섹션은 다음과 같이 수행합니다.

저는 제 아이오닉 코르도바 앱 푸시 알림을 위한 해결책을 찾고 있었습니다.

Syed Rafay의 답변에 감사합니다.

app.component.ts에서

const options: PushOptions = {
  android: {
    topics: ['all']
  },

서버 파일에

"to" => "/topics/all",

Firebase 콘솔에서 주제 목록을 확인합니다.

  1. Firebase 콘솔로 이동

  2. 사이드 메뉴에서 Grow(성장) 클릭

  3. 클라우드 메시징 클릭

  4. 번째 메시지 보내기를 클릭합니다.

  5. 알림 섹션에서 알림 제목 및 알림 텍스트를 입력합니다.

  6. 다음 클릭

  7. 대상 섹션에서 항목 클릭

  8. 메시지 항목 텍스트 상자를 클릭하면 항목을 볼 수 있습니다(안드로이드 또는 iOS라는 항목은 만들지 않았지만 두 항목을 볼 수 있습니다).

  9. 푸시 알림을 보낼 때 조건으로 추가합니다.

    "condition"=> "주제에 있는 모든 것" || 주제에 있는 'eos' || 주제에 있는 'ios'",

전신

array(
    "notification"=>array(
        "title"=>"Test",
        "body"=>"Test Body",
    ),
    "condition"=> "'all' in topics || 'android' in topics || 'ios' in topics",
);

더 많은 주제가 있을 경우 || (또는) 조건이 있는 항목을 추가할 수 있습니다. 그러면 모든 사용자가 알림을 받게 됩니다.날 위해 테스트하고 일했어요

로그인한 모든 사용자가 특정 항목에 가입하도록 한 다음 해당 항목에 알림을 보냅니다.

코르도바 하이브리드 앱에서 어떻게 하는지 궁금해하는 사람들을 위해:

  • index.js 파일로 합니다.->DeviceReady에 :DeviceReady()를

      subscribe();
    

(기능의 맨 위에 쓰는 것이 중요합니다!

  • 그런 다음 동일한 파일(index.js)에서 다음을 찾습니다.

    함수 구독 (){

     FirebasePlugin.subscribe("write_here_your_topic", function(){
    
     },function(error){
    
         logError("Failed to subscribe to topic", error);
     });
     }
    

여기에 .-> """" "write_here_your_here""

PHP Admin-SDK 예제는 사용자를 주제에 가입시키고 장치 토큰 또는 주제에 의해 장치에 메시지를 보내는 것입니다.항목은 사용자를 등록할 때 자동으로 작성됩니다.

$testTokens = ['device token 1', 'device token 2', ....]

// CREDENTIALS, YOU HAVE TO DOWNLOAD IT FROM FIREBASE CONSOLE.
$factory = (new Factory())->withServiceAccount('credentials.json');

$messaging = $factory->createMessaging();

// Subscribe a token or a group of tokens to a topic (this topic is created automatically if not exists)
// YOU CAN DO THIS IN THE MOBILE APP BUT IS BETTER DO IT IN THE API.
$result = $messaging->subscribeToTopic('all', $testTokens); // 'all' is the topic name

// Send a message to a specific Topic (Channel) 
$message = CloudMessage::withTarget('topic', 'all')
    ->withNotification(Notification::create('Global message Title', 'Global message Body'))
    ->withData(['key' => 'value']); // optional
$messaging->send($message);

// Send a message to a token or a grup of tokens (ONLY!!!)
 foreach($testTokens as $i=>$token){
     $message = CloudMessage::withTarget('token', $token)
         ->withNotification(Notification::create('This is the message Title', 'This is the message Body'))
         ->withData(['custom_index' => $i]); // optional
     $messaging->send($message);

자세한 내용은 이 보고서를 참조하십시오. firebase-php-admin-sdk

"/topics/all"을 사용하여 모든 장치에 알림을 보낼 수 있습니다.

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to": "/topics/all",
  "notification":{ "title":"Notification title", "body":"Notification body", "sound":"default", "click_action":"FCM_PLUGIN_ACTIVITY", "icon":"fcm_push_icon" },
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",
   }
}

언급URL : https://stackoverflow.com/questions/38237559/how-do-you-send-a-firebase-notification-to-all-devices-via-curl

반응형