HOME
회사소개
포트폴리오
커뮤니티
고객평가
갤러리
무료봉사
온라인마케팅
최근 신기술
제작/컨설팅
솔루션

fcm topic 전송 방식 > 자료실

본문 바로가기

홈페이지

어플

프로그램

오늘 방문자

제작상담

■ 어떠한 것이든 설명이 가능하시면 제작이 가능합니다.
■ 저희는 거의 임진왜란 직후부터 개발해온 회사입니다.
■ 저희가 개발한 플랫폼 = 평생 무료 하자보수.
■ 요청고객께 6개월마다 홍보용 홈페이지를 무료제작
AI 인공지능,AR,VR 개발 가능합니다.
유지보수를 원하시는 모든형태로 가능합니다.
■ 고객의 아이디어가 저희 포트폴리오에 있을 확률 80%

고객평가

  • 니즈가 명확하지 않아 ...
  • 기획 단계부터 먼저 여...
  • 저희 앱이 일본어 사전...
  • 과격한 표현으로 말하자...
  • 앱 쪽에 정보가 많이 ...
  • 디몬스터를 처음 만났을...
  • 처음했던 외주 개발인데...

궁금해요

  • AI 전반정리

    AI 전반정리

  • 단말기, 이용료, 유지비 없는 POS…

    단말기, 이용료, 유지비 없는 POS…

  • POS 연동에 대한 오해와 진실

    POS 연동에 대한 오해와 진실

고객리뷰

  • (주)**경매  정**대표님

    (주)**경매 정**대표님

  • (주)타이어핏 홍** 대표님

    (주)타이어핏 홍** 대표님

  • (주)아토비엔 임** 대표님

    (주)아토비엔 임** 대표님

숏츠/릴스

  • 인공지능 카메라 하나로 모든 문제를 …

    인공지능 카메라 하나로 모든 문제를 …

  • 효율적인 공간 관리를 위한 매핑 기능

    효율적인 공간 관리를 위한 매핑 기능

자료실

웹 | fcm topic 전송 방식

페이지 정보

작성자 최고관리자 조회414회 댓글0건

본문

FCM  Topic  관련 내용 입니다.

 

푸시 업데이트 이후에 전송은 전체적으로 3가지를 이용하게 될거 라고 예상 될것 같습니다.

 

1. 폰 token을 이용해서 전송하는 방식   (FCM 기존방식)

: 특정 토큰을 가진 회원에게만 전송하는 방식 

 

바로 푸시를 받아야할 경우 topic으로는 전송시간이 1분까지도 걸릴 수 있으므로 회원에게

토큰으로 전송하는 방법도 적극 활용해야합니다. (채팅 알림 등..)

(해당 토큰방식은 올라온 내용이 많아서 기술에 대해서 제외 하겠습니다.)

 

2.[Topic]구독하고 있는 전체 회원에게 전송하는방식 (topic)

: 모든 채널에게 전송하는 방식

(전체 회원에게 전송하는 방식입니다.)  - 특정회원은 못 받게 할 수는 없습니다.

 

3.[Topic]특정 채널에게만 보내는 방식 (condition)

: condition에 조건을 걸어서 특정 채널에게만 전송 할수 있습니다.

(조건이 걸려서 그런지 전송 시간 소요가 있습니다 ,1분이내) - 다소 소요시간이 있습니다.

 

 

3번의 경우 예를 들어, 

-채팅알림 

-공지알림 

- 마케팅 푸시 알림

 

위와 같이 3개의 알림 체크 설정이 있다면,

 3개의 topic 채널이 필요하게 됩니다.

 

 

2. [Topic]구독하고 있는 전체 회원에게 전송하는방식 (topic)

 

- php (전송단)

function send_notification($title, $msg,$idx,$topic)
{
      global $DB;



      $url = 'https://fcm.googleapis.com/v1/projects/프로젝트-id/messages:send';
      putenv('GOOGLE_APPLICATION_CREDENTIALS='.$_SERVER['DOCUMENT_ROOT'].'/lib/발급 받은 프로젝트_key.json');
      $scope = 'https://www.googleapis.com/auth/firebase.messaging';
      $client = new Google_Client();
      $client->useApplicationDefaultCredentials();
      $client->setScopes($scope);
      $auth_key = $client->fetchAccessTokenWithAssertion();
      $ch = curl_init();
      $notification_opt = array (
          'title'     => $title,
          'body'      => $msg,
      );

      $datas = array (
          'title'    => $title,
          'body'     => $msg,
          'idx'      => (string)$idx,
      );

      $android_opt = array (
          'notification' => array(
              'default_sound' => true,
              "channel_id"    =>  'default',
          ),
          'priority' => 'high',
          'data' => $datas,
      );

      $message = array
      (
          'notification' => $notification_opt,
          'data'        => $datas,
          'android'   => $android_opt,
          'topic'       => $topic
      ); 

 

     // 해당 부분에 전체 메세지 전송할 topic의 명을 배열에 추가 해줍니다.

      $last_msg = array (
          "message" => $message
      );

      $headers = array
      (
          'Authorization: Bearer ' . $auth_key['access_token'],
          'Content-Type: application/json'
      );

      $last_msg = array (
          "message" => $message
      );
      $headers = array
      (
          'Authorization: Bearer ' . $auth_key['access_token'],
          'Content-Type: application/json'
      );
      curl_setopt($ch, CURLOPT_HEADER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($last_msg));
      $result = curl_exec($ch);
      if($result === FALSE){


      }


}
 

 

 

3. [Topic] 특정 topic 채널에게만 전송 하는 방식 (condition)

 

해당 전송방식은 특정 채널 topic에게만 전송하는 방식이므로,

조건을 겁니다.

 

fcm message 에 topic 이나 token대신에 condition 이 추가됩니다.

 

'토픽채널명1' in topics || '토픽채널명2' in topics

 

다음과 같이 구성됩니다

 

php 예시

 

 

function send_notification($title, $msg,$idx,$condition)
{
      global $DB;
      //토픽 채널은 다음과 같이 조건을 추가할 수 있음

      $url = 'https://fcm.googleapis.com/v1/projects/프로젝트-id/messages:send';
      putenv('GOOGLE_APPLICATION_CREDENTIALS='.$_SERVER['DOCUMENT_ROOT'].'/lib/구글에서발급받은fcm키.json');
      $scope = 'https://www.googleapis.com/auth/firebase.messaging';
      $client = new Google_Client();
      $client->useApplicationDefaultCredentials();
      $client->setScopes($scope);
      $auth_key = $client->fetchAccessTokenWithAssertion();
      $ch = curl_init();
      $notification_opt = array (
          'title'     => $title,
          'body'      => $msg,
      );

      $datas = array (
          'title'    => $title,
          'body'     => $msg,
          'idx'      => (string)$idx,
      );

      $android_opt = array (
          'notification' => array(
              'default_sound' => true,
              "channel_id"    =>  'default',
          ),
          'priority' => 'high',
          'data' => $datas,
      );

      $message = array
      (
          'notification' => $notification_opt,
          'data'         => $datas,
          'android'      => $android_opt,
          'condition'    => $condition // 해당 부분에 다음과 같이 조건으로 들어갑니다. ('토픽채널명1' in topics || '토픽채널명2' in topics)  구분자 - (||)
      );

      $last_msg = array (
          "message" => $message
      );

      $headers = array
      (
          'Authorization: Bearer ' . $auth_key['access_token'],
          'Content-Type: application/json'
      );

      $last_msg = array (
          "message" => $message
      );
      $headers = array
      (
          'Authorization: Bearer ' . $auth_key['access_token'],
          'Content-Type: application/json'
      );
      curl_setopt($ch, CURLOPT_HEADER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

      // curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 요청 타임아웃 설정
      // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // 연결 타임아웃 설정

      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($last_msg));
      $result = curl_exec($ch);
      if($result === FALSE){


      }

}

 

 

4. react-native 소스단  클라이언트 에는 topic 채널 구독여부에 따라서  해당 채널로 전송된 푸시를 받거나 안받을 수 있습니다.

 

푸시의 기본설정과 동일하며 추가된 함수는 해당부분 밖에 없습니다.

import messaging from '@react-native-firebase/messaging';
const subscribeToTopic_ = async (topic:string=> {
console.log("구독 : " + topic)
await messaging().subscribeToTopic(topic);
};

const unsubscribeToTopic_ = async (topic:string=> {
console.log("구독 해제 :" + topic)
await messaging().unsubscribeFromTopic(topic);
};

 

 

topic 채널을 두개 쓰는경우의 예시 (topic_channel1,topic_channel2)

ifresponse.data.topic_channel1 == "Y"){
subscribeToTopic_("topic_channel1");
}else{
unsubscribeToTopic_("topic_channel1");
}

if(response.data.topic_channel2 == "Y"){
subscribeToTopic_("topic_channel2");
}else{
unsubscribeToTopic_("topic_channel2");
}

 

 

해당방법과 동일하게 앱 실행시에 유저의 알림 수신여부 값을 서버로 부터 가져와서 구독하거나 구독하지 않도록 설정 해줍니다.

 

당연한 부분이지만, 앱에서 알림 설정 페이지가 있다면 알림을 ON,OFF할때마다 구독여부를 변경 해주어야합니다.

 

 

const checkList = [
// {id: 0, title: '전체', : '', type: checkAll},
{id: 1title: '공지사항'topic_channel: 'topic_channel1'type: true},
{id: 2title: '마케팅 메세지'topic_channel: 'topic_channel2'type: true},
{id: 3title: '채팅알림'topic_channel: 'topic_channel3'type: true},
];

 

해당과 같은 체크박스가 변경후 저장했을시 동일 구독함수를 넘겨와서 처리하였습니다.

checkList.forEach(item => {
// item.type : true (구독중) , false (구독아님)
if(item.type){
subscribeToTopic(item.topic_channel)
}else//topic 구독 해제하기
unsubscribeToTopic(item.topic_channel);
}
});

 

토큰을  이용하는 방식이나,

topic방식이나

topic의 condition 경우 

전송을 어떻게 할지에 따라서 해당 방법중 에 채택을 하여 구성 해야해야 할듯 합니다. 

 


| 디몬스터 | TEL : 070-7621-0572 / 070-5022-0572 | HP : 010-7574-0572 | E-mail : jackee@naver.com
| 메타몬스터 - 서울 구로구 구로동 235-3 대륭포스트타워 8차 L동 805, 806호 | 부천시 길주로 272 2001호(중동 코스모폴리탄) | 부산시 금정구 금정로 225 4층,5층 | 몽골사무실- Ulaannaatar.mongola bayangol district 3-khoroo agro center 9-02
당사의 어플방식은 저작권 및 특허출원중입니다. 복제,모방,변용 및 유사 상행위 적발시,경고,통보없이 민형사상 책임을 진행합니다
Copyright © www.dmonster.co.kr All rights reserved.Since 2008 (주)세미콜론즈 · 사업자번호: 801-88-00338