본문 바로가기

Backend/JAVA

[Noti] 알림 전송 방식 4가지 ( SMS, Email, Kakao, Push )

반응형

알림 전송시 사용할 공통 VO선언

import org.apache.commons.lang3.builder.ToStringBuilder;
import com.fasterxml.jackson.annotation.JsonAlias;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class HmsNotiVO {
	@JsonAlias({"noti_type", "notiType"})
	private String notiType;  //1.sms 2. email 3.kakao 4.push
	@JsonAlias("msg")
	private String msg;
	@JsonAlias({"mobile_number", "mobileNumber"})
	private String mobileNumber;
	private String email;
	private String subject;
	private String templateCode;
	private String fcmToken;
	
	private String url;
	
	
	/**
	* 알림 발송 템플릿 vo 추가
	*
	* alarm_id	알림발송ID
	*/
	
	private String alarmId;	
	
	@JsonAlias({"err_code", "errCode"})
	private String errCode;
	@JsonAlias({"err_msg", "errMsg"})
	private String errMsg;
	private String title;
	private String body;
	@JsonAlias({"askakao_temple", "askakaoTemple"})
	private String askakaoTemple;
	
	@JsonAlias({"replace_text1", "replace1"})
	private String replace1;
	@JsonAlias({"replace_text2", "replace2"})
	private String replace2;

	@JsonAlias({"tr_num", "trNum"})
	private String trNum;

	private String sendState;

	private String umsType;

	
	
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }		
    
}

 

 

Controller구성

/**
 * 인증번호 SMS 발송
 *
 * @param request
 * @param obj
 * @return
 * @throws IOException, Exception
 */
@PostMapping(value = "/main/sendSms")
@ResponseBody
public ResponseEntity<?> requestSendSms(HttpServletRequest request, @Valid @RequestBody MemberDto param) throws IOException, CException, Throwable {
	log.debug("requestSendSms start!");

	CommonResult result = new CommonResult();

	String userId = param.getUserId();
	String mobileNumber = param.getMobileNumber();

	MemberVO memberVO = new MemberVO();
	memberVO.setUserId(userId);
	memberVO.setEmail(userId);
	memberVO.setMobileNumber(mobileNumber);
	memberVO.setVerifyKey(userId);
	memberVO.setIp(getClientIP(request));

	try {

		String authKey = verifyKeyService.insertAuthKey(memberVO, 5);

		HmsNotiVO hmsNotiVO = new HmsNotiVO();
		hmsNotiVO.setReplace1(authKey);
		hmsNotiVO.setMobileNumber(mobileNumber);
		hmsNotiVO.setAlarmId("000000");

		indexService.sendSmsUser(hmsNotiVO);

	} catch (Throwable e) {
		errorLog(e, request);
		throw new CException();
	}

	String csrf = getCsrfToken(request);
	result.setNewToken(csrf);

	return ResponseEntity.ok(result);
}


/**
 * 인증번호 이메일 발송
 * 
 * @param request
 * @param obj
 * @return
 * @throws IOException, Exception
 */
@PostMapping(value = "/main/member/requestSendEmail")
@ResponseBody
public ResponseEntity<?> requestSendEmail(HttpServletRequest request, @RequestBody JSONObject obj, Locale locale) throws IOException, CException, Throwable {
	log.debug("requestSendEmail start!");

	CommonResult result = new CommonResult();
	String email = obj.get("email") == null ? "" : obj.get("email").toString();
	//String verifyKey = obj.get("verifyKey") == null ? "" : obj.get("verifyKey").toString();
	String verifyKey = email;
	Boolean rs = true;
	if (email.equals("")) {
		result.setResultCode(-1);
		result.setResultMsg("입력 정보가 올바르지않습니다.");
		rs = false;
	}
        
	log.info("locale.getLanguage(): " + locale.getLanguage());

	if (rs) {
		MemberVO memberVO = new MemberVO();
		memberVO.setEmail(email);
		memberVO.setVerifyKey(verifyKey);

		indexService.sendEmailUser(memberVO);
	}

	String csrf = getCsrfToken(request);
	result.setNewToken(csrf);

	return ResponseEntity.ok(result);
}

 

 

SMS서비스

@Override
public HmsNotiVO sendSmsUser(HmsNotiVO vo) throws IOException, CException, Throwable {
	// TODO Auto-generated method stub
	log.info("send sms!");

	// wiseU솔루션 이용
	RestApiWiseUUtil wiseUUtil = new RestApiWiseUUtil();
	JSONObject jObj = null;
	StringBuilder sb = null;
	BufferedReader br = null;
	BufferedWriter bw = null;
	HttpURLConnection conn = null;
	String notiType = "";
	String msgType = "";

	String line = "";
	String sendId = "H" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + UUID.randomUUID().toString().substring(0, 4);

	jObj = new JSONObject();

	Map<String, Object> model = new HashMap<>();

	String subject = "[SMS] 알림이 발송되었습니다.";

	model.put("authKey", vo.getReplace1());

	String sendMsg = "";
	sendMsg += "테스트번호 [" + vo.getReplace1() + "]\n\n";
	sendMsg += "번호 입력 후 인증하기";

	jObj = new JSONObject();

	try {
		jObj.put("SEQ", sendId);
		jObj.put("RECEIVER", vo.getMobileNumber() == null ? "" : vo.getMobileNumber());
		jObj.put("SENDER", "0212345678");
		jObj.put("SUBJECT", subject);
		jObj.put("CONTENT", sendMsg);
		conn = wiseUUtil.jsonHttpUrlConn("rest/v1.0/lms/send", "POST");

		notiType = "2";
		msgType = "LMS";

		bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));

		requestLog(jObj.toString());

		bw.write(jObj.toString());

		bw.flush();

		int status = conn.getResponseCode();
		if (status == HttpURLConnection.HTTP_OK) {
			sb = new StringBuilder();
			br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

			while ((line = br.readLine()) != null) {
				responseLog(line);
				sb.append(line);
			}
		}
		conn.disconnect();

		NotificationVO notiVO = new NotificationVO();
		notiVO.setSendMsg(sendMsg);
		notiVO.setMsg(sendMsg);
		notiVO.setMsgType(msgType);
		notiVO.setNotiType(notiType);
		notiVO.setPhoneNumber(vo.getMobileNumber());
		notificationService.insertNotiDataByHmsTemplate(notiVO);
	
	} catch (Throwable e) {
		log.error("IndexServiceImpl/sendSmsUser -ExceptionError!");
	} finally {
		if (bw != null) {
			bw.close();
		}
		if (br != null) {
			br.close();
		}
	}

	return null;
}

 

Email 서비스

@Override
public void sendEmailUser(MemberVO memberVO) throws IOException, CException, Throwable {
	// TODO Auto-generated method stub
	try {
		log.info("send email!");

		String authKey = verifyKeyService.insertAuthKey(memberVO, 5);
		Map<String, Object> model = new HashMap<>();
		String eventNumber = "";
		String subject = "[Email]이메일 제목";
		String template = "sampleTemplate";

		model.put("eventNumber", eventNumber);
		model.put("authKey", authKey);

		// Eamil 템플릿 지정
		var MailSenderVO = new MailSenderVO();
		MailSenderVO.setSubject(subject);
		MailSenderVO.setToEmail(memberVO.getEmail());
		MailSenderVO.setModel(model);
		MailSenderVO.setTemplate(template);

		emailService.sendEmail(MailSenderVO);
        
	} catch (InterruptedIOException e) {
		log.info("sendAuthKeyMail -InterruptedIOException!");
		throw new InterruptedIOException("member");
	} catch (Throwable e) {
		log.info("sendAuthKeyMail -ExceptionError!");
		throw new Exception();
	}

}

public void sendEmail(MailSenderVO mailData) throws IOException, TemplateException, Throwable {
	NotificationVO notiVO = new NotificationVO(); 
 	
	// 템플릿 불러옴
	var template = configuration.getTemplate(mailData.getTemplate() + ".ftl");
	var content = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailData.getModel());
	
	uploadPathDev = uploadPathDev.replace("upload", "email");
	
	try {
		mailSendProcess_ums(mailData,content);
	} catch (InterruptedIOException e) {
		log.error("mailApiRequest InterruptedIOException! - sendEmail");
		throw new InterruptedIOException("member");
	} catch (Throwable e) {
		log.error("mailApiRequest error! - sendEmail");
		throw new Exception();
	}
    
	notiVO.setMailData(mailData);
    
	try {
		notificationService.insertNotiDataByEmail(notiVO);
	} catch (Throwable e) {
		log.error("sendEmail -ExceptionError!");
		
	}
	
}

 

ftl템플릿 예시

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>단체메일</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;700&display=swap');
    </style>
</head>
<body>
<div style="font-family: 'Noto Sans KR', sans-serif; width: 700px; padding: 64px 32px; font-size: 13px;">
    <div style="padding: 64px; border: 2px solid #eee; border-radius: 4px;">
		<img alt="${compNameEn}" src="cid:logo" style="padding-bottom: 16px;"/>
		${content}
	</div>
	<div style="font-size: 12px; color: #9e9e9e; text-align: center; padding-top: 8px;">
        본 메일은 발신전용입니다. 문의사항이 있으신 경우 고객센터로 연락주시기 바랍니다.
        <div>© ${compNameEn}</div>
    </div>
</div>
</body>
</html>

 

 

ums로 메일 처리

public void mailSendProcess_ums(MailSenderVO mailData , String content ) throws CException, Throwable {
	RestApiWiseUUtil wiseUUtil = new RestApiWiseUUtil();
	JSONObject jObj = null;
	String line = "";
	jObj = new JSONObject();
	
	try {
		String uid = "H"+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + UUID.randomUUID().toString().substring(0, 4);
		jObj.put("SEND_DIV", "mail");
		jObj.put("SEQ", uid);
		jObj.put("RECEIVER_ID", mailData.getToEmail());
		jObj.put("RECEIVER_NM", mailData.getToEmail()); // mailData.getToEmail()
		jObj.put("RECEIVER", mailData.getToEmail());
		
		jObj.put("SENDER_NM", "hotel.members");
		jObj.put("SENDER", "test@test.com");
		jObj.put("SUBJECT", mailData.getSubject() );
		jObj.put("CONTENT", content);
		
		mate.mateUmsCall(jObj);
	} catch (InterruptedIOException e) {
		log.info("mailSendProcess_ums -InterruptedIOException!");
		throw new InterruptedIOException("member");
	} catch (Throwable e) {
		log.info("mailSendProcess_ums -ExceptionError!");
		throw new Exception();
	}
}

public void mateUmsCall(JSONObject reqObj) throws IOException, CException, Throwable {
	// TODO Auto-generated method stub
	log.info("send mateUmsCall !");
	RestApiWiseUUtil wiseUUtil = new RestApiWiseUUtil();

	JSONArray reqArray = new JSONArray();
	StringBuilder sb = null;
	BufferedReader br = null;
	BufferedWriter bw = null;
	//JSONObject responseJson = null;
	HttpURLConnection conn = null;
	String line = "";
	reqArray.add(reqObj);

	HttpHeaders headers = new HttpHeaders();
	try {
	    restTemplate = makeRestTemplateWithConnectTimeout(true, 10 * 1000);

	    headers.setContentType(new MediaType(MediaType.APPLICATION_JSON, Charset.forName("utf-8")));

	    MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
	    // 필수
	    params.add("", reqObj.toString());
	    JSONArray reqArr = new JSONArray();
	    reqArr.add(reqObj);

	    log.info("############################ params" + params);

	    HttpEntity<String> reqString = new HttpEntity<>(reqArr.toString(), headers);

	    log.info("############################ HttpEntity" + reqString);

	    ResponseEntity<String> response = restTemplate.postForEntity(infums, reqString, String.class);

	    log.debug("#####" + URLDecoder.decode(response.getBody(), "utf-8"));

	    if (response.getBody() != null) {

		JSONObject json2 = new JSONObject();
		JSONParser parser = new JSONParser();

		JSONArray jar = new JSONArray();
		Object obj = parser.parse(URLDecoder.decode(response.getBody(), "utf-8"));
		jar = (JSONArray) obj;
		if (jar.size() > 0) {
		    for (int i = 0; i < jar.size(); i++) {
			JSONObject jsonObj = (JSONObject) jar.get(i);
			log.info("########## " + jar.get(i));
			if(jsonObj.get("code") == null || !"0".equals(jsonObj.get("code").toString())) {
			    if(jsonObj.get("msg") != null) {
				log.error("mateUmsCall error!!!! - {}", jsonObj.get("msg"));
			    }
			    throw new Exception();
			}
		    }
		}
		log.info("json2 : " + json2);
		log.info("obj : " + obj);
		log.info("jar : " + jar);

	    }

	} catch (ResourceAccessException e) {
	    log.info("mateUmsCall -ResourceAccessException!");
	    throw new InterruptedIOException("member");
	} catch (RestClientException e) {
	    log.info("mateUmsCall -RestClientExceptionError!");
	    throw new Exception();
	} catch (UnsupportedEncodingException e) {
	    log.info("mateUmsCall -UnsupportedEncodingExceptionError!");
	    throw new Exception();
	} catch (Throwable e) {
	    log.info("mateUmsCall -ExceptionError!");
	    throw new Exception();
	}

}

 

 

Kakao서비스 (템플릿 승인 이후 사용 가능)

private HmsNotiVO hmsSendKakaoTemplate(HmsNotiVO vo) throws Throwable {
	log.info("send hmsSend{}!", vo.getAlarmId());
	RestApiWiseUUtil wiseUUtil = new RestApiWiseUUtil();

	JSONObject jObj = null;
	StringBuilder sb = null;
	BufferedReader br = null;
	BufferedWriter bw = null;
	HttpURLConnection conn = null;
	String notiType = "";
	String msgType = "";

	String line = "";
	String sendId = "H" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + UUID.randomUUID().toString().substring(0, 4);

	HmsNotiVO sendVO = mate.call_inf1300(vo);

	log.info("##########   HmsNotiVO sendvo  : " + sendVO);

	jObj = new JSONObject();
	try {
		jObj.put("SEQ", sendId);
		jObj.put("RECEIVER", vo.getMobileNumber());
		jObj.put("SENDER", "testSend");
		jObj.put("SUBJECT", sendVO.getTitle());

		if (sendVO.getAskakaoTemple() != null && !sendVO.getAskakaoTemple().equals("")) {
			JSONObject kakao = new JSONObject();
			kakao.put("SENDER_KEY", kakaoKey);
			kakao.put("TMPL_CD", sendVO.getAskakaoTemple());
			kakao.put("SND_MSG", sendVO.getBody());
			kakao.put("SMS_SND_YN", "Y");
			jObj.put("JONMUN", kakao);
			conn = wiseUUtil.jsonHttpUrlConn("rest/v1.0/at/send", "POST");
			notiType = "3";
			msgType = "KAKAO";
		} else {
			jObj.put("JONMUN", sendVO.getBody());
			conn = wiseUUtil.jsonHttpUrlConn("rest/v1.0/lms/send", "POST");
			notiType = "2";
			msgType = "LMS";
		}


		bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
		log.info("**********************************");
		log.info("RestApiWiseUSglLmsSendJob request JSON : " + jObj.toString());
		log.info("**********************************");
		bw.write(jObj.toString());

		bw.flush();

		int status = conn.getResponseCode();
		if (status == HttpURLConnection.HTTP_OK) {
		sb = new StringBuilder();
		br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

		while ((line = br.readLine()) != null) {
			log.info("**********************************");
			log.info("RestApiWiseUSglLmsSendJob response JSON : " + line);
			log.info("**********************************");
			sb.append(line);
		}
		}
		conn.disconnect();

	} catch (Throwable e) {
		log.error("IndexServiceImpl/hmsSend{}} -ExceptionError!", vo.getAlarmId());
	} finally {
		if (bw != null) {
		bw.close();
		}
		if (br != null) {
		br.close();
		}
	}

	NotificationVO notiVO = new NotificationVO();
	notiVO.setSendMsg(sendVO.getBody());
	notiVO.setMsg(sendVO.getBody());

	notiVO.setMsgType(msgType);
	notiVO.setNotiType(notiType);
	notificationService.insertNotiDataByHmsTemplate(notiVO);

	return null;
}


/**
 * mate - 알림 발송 내용 가져오기
 *
 * @param JSONObject, 미정
 * @return 미정
 * @throws IOException, Exception
 */
public HmsNotiVO call_inf1300(HmsNotiVO vo) {

	HttpHeaders headers = new HttpHeaders();
	HashMap<String, Object> rsMap = new HashMap<>();
	List<HmsNotiVO> rsList = new ArrayList<>();
	HmsNotiVO rsVO = new HmsNotiVO();
	try {
		restTemplate = makeRestTemplate(true);

		headers.setContentType(new MediaType(MediaType.APPLICATION_FORM_URLENCODED, Charset.forName("utf-8")));

		//MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
		log.info("request vo === " + vo);
        
		//	-- alarm_id	알림발송ID
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(inf1300)
			.queryParam("alarm_id", vo.getAlarmId());

		HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
		httpRequestFactory.setConnectTimeout(30000); // 연결시간 초과
		//Rest template setting

		// 담아줄 header
		HttpEntity entity = new HttpEntity<>(headers); // http entity에 header 담아줌

		ResponseEntity<String> response = restTemplate.exchange(URLDecoder.decode(builder.toUriString(), "utf-8"), HttpMethod.GET, entity, String.class);


		log.info("#################" + response);

		if (response.getBody() != null) {

			JSONObject json2 = new JSONObject();
			JSONParser parser = new JSONParser();

			JSONArray jar = new JSONArray();

			Object obj = parser.parse(URLDecoder.decode(response.getBody().replace("%", "%25"), "utf-8"));

			JSONObject jsonObj = (JSONObject) parser.parse(URLDecoder.decode(response.getBody().replace("%", "%25"), "utf-8"));

			log.info("########### jsonObj  " + jsonObj);
			rsVO = (HmsNotiVO) objectMapper.readValue(jsonObj.toJSONString(), HmsNotiVO.class);

			log.info("########### rsVO  " + rsVO);
			log.info("json2 : " + json2);
			log.info("obj : " + obj);
			log.info("jar : " + jar);
		}

	} catch (RestClientException e) {
		log.error("call_inf1300 -RestClientExceptionError!");
	} catch (UnsupportedEncodingException e) {
		log.error("call_inf1300 -UnsupportedEncodingExceptionError!");
	} catch (Throwable e) {

		log.error("call_inf1300 -ExceptionError!");
	}
	return rsVO;
}

 

Push 서비스

@Slf4j
@Service
public class PushNotificationService {
	private static final String PROJECT_ID = "hotelmembership-995d6"; /* your project id */
	private static final String BASE_URL = "https://fcm.googleapis.com";
	private static final String FCM_SEND_ENDPOINT = "/v1/projects/" + PROJECT_ID + "/messages:send";
	//private static final String MESSAGING_SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
	//private static final String[] SCOPES = { MESSAGING_SCOPE };
	public static final String MESSAGE_KEY = "message";

	@Autowired
	NotificationService notificationService;

	@Autowired
	CommonService commonService;


	private HttpURLConnection getConnection() throws IOException {
		URL url = new URL(BASE_URL + FCM_SEND_ENDPOINT);
		//	URL url = new URL("https://oauth2.googleapis.com/token");
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection.setRequestProperty("Authorization", "Bearer " + getAccessToken2());
		httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
		return httpURLConnection;
	}

	public String getAccessToken2() throws IOException {
		//   String firebaseConfigPath2 = "src/main/resources/static/firebase/fcm.json";
		String firebaseConfigPath2 = "static/firebase/fcm.json";

		GoogleCredentials googleCredentials = GoogleCredentials.
				fromStream(new ClassPathResource(firebaseConfigPath2).getInputStream())
//			   .createScoped(Arrays.asList(SCOPES));
//	   .createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
//	   .createScoped(Arrays.asList("https://www.googleapis.com/auth/firebase"));
				.createScoped(Arrays.asList("https://www.googleapis.com/auth/firebase.messaging"));

		log.info("FCM LOG == " + googleCredentials);
		log.info("FCM LOG == " + googleCredentials.getAuthenticationType());
		
		googleCredentials.refreshIfExpired();
		log.info("FCM LOG == " + googleCredentials.getAccessToken());
		log.info("FCM LOG == " + googleCredentials.getAccessToken().getTokenValue());

		return googleCredentials.getAccessToken().getTokenValue();


	}


	private String inputstreamToString(InputStream inputStream) throws IOException {
		StringBuilder stringBuilder = new StringBuilder();
		Scanner scanner = new Scanner(inputStream);
		while (scanner.hasNext()) {
			stringBuilder.append(scanner.nextLine());
		}
		return stringBuilder.toString();
	}

	public void sendMessage(JSONObject fcmMessage, String trNum) throws IOException {
		HttpURLConnection connection = getConnection();
		connection.setDoOutput(true);
		DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
		log.info("###### send fush #### : " + fcmMessage);
		try {
			// outputStream.writeUTF(fcmMessage.toString());
			outputStream.writeBytes(fcmMessage.toString());
			outputStream.flush();
			outputStream.close();

			int responseCode = connection.getResponseCode();

			HmsNotiVO vo = new HmsNotiVO();
			vo.setTrNum(trNum);

			if (responseCode == 200) {

				String response = inputstreamToString(connection.getInputStream());
				log.info("{} - Message sent to Firebase for delivery, response : {}", trNum, ((JSONObject)fcmMessage.get(MESSAGE_KEY)).get("token"));
				log.info(response);

				try {
					vo.setSendState("Y");
					commonService.updateCmmMediaLog(vo);
				} catch (SQLException e) {
					log.error("updateCmmMediaLog -SQLExceptionError!");
				}

			} else {

				String token = ((JSONObject)fcmMessage.get(MESSAGE_KEY)).get("token").toString();
				log.info("{} - Unable to send message to Firebase : {}", trNum, token);
				String response = inputstreamToString(connection.getErrorStream());
				log.info(response);

				JsonNode responseNode = new ObjectMapper().readTree(response);
				String resultMsg = responseNode.get("error").get("status").textValue() + " / " + responseNode.get("error").get("message").textValue();

				try {
					vo.setSendState("F");
					vo.setErrCode(String.valueOf(responseCode));
					vo.setErrMsg(resultMsg);
					commonService.updateCmmMediaLog(vo);

					if (responseCode == 404) {
						vo.setFcmToken(token);
						log.info("{} - init fcm_id - {}", trNum, token);
						commonService.updateInitFcmId(vo);
					}

				} catch (SQLException e) {
					log.error("updateCmmMediaLog -SQLExceptionError!");
				}

				throw new IOException();
			}

		} finally {
			outputStream.close();
		}

	}

	public void sendCommonMessage(String title, String body, String FcmToken, String url, String trNum) throws IOException {
		JSONObject notificationMessage = buildNotificationMessage(title, body, FcmToken, url);
		log.info("FCM request body for message using common notification object:");
//		prettyPrint(notificationMessage);
		sendMessage(notificationMessage, trNum);
	}

//	private  void prettyPrint(JSONObject jsonObject) {
//		Gson gson = new GsonBuilder().setPrettyPrinting().create();
//		log.info(gson.toJson(jsonObject) + "\n");
//	}


	private JSONObject buildNotificationMessage(String title, String body, String FcmToken, String url) throws UnsupportedEncodingException {
		JSONObject jNotification = new JSONObject();
		//	  jNotification.addProperty("title", title);
		//	 jNotification.addProperty("body", body);

		JSONObject json = new JSONObject();
		JSONObject dataInfo = new JSONObject();
		JSONObject ios = new JSONObject();
		JSONObject headersinfo = new JSONObject();
		JSONObject aps = new JSONObject();
		JSONObject headers = new JSONObject();
		JSONObject android = new JSONObject();
		JSONObject webpush = new JSONObject();
		JSONObject webpush_h = new JSONObject();

		//webpush_h.put("TTL", "4500" );
		//webpush.put("headers" , webpush_h);

		//dataInfo.put("priority", "high");
		JSONObject var1 = new JSONObject();
		JSONObject var2 = new JSONObject();
		JSONObject var3 = new JSONObject();
		JSONObject var4 = new JSONObject();
		JSONObject var5 = new JSONObject();



		//"sound":"default",
		dataInfo.put("url", url);
		dataInfo.put("sender", "hmsw");
		dataInfo.put("title", URLEncoder.encode(title, "utf-8"));
		dataInfo.put("body", URLEncoder.encode(body, "utf-8"));

//		headers.put("apns-priority" , "10");
//		headers.put("mutable-content" , "1");
//		//headers.put("apns-expiration" , "1604750400");
//		aps.put("headers" , headers);
//		//aps.put("mutable-content" , "1");

		android.put("priority", "high");
		//android.put("ttl", "4500s");

		JSONObject jMessage = new JSONObject();
	   // jMessage.put("apns", aps);

		jMessage.put("android", android);
		//jMessage.put("webpush", webpush);

		jNotification.put("title", URLEncoder.encode(title, "UTF-8"));
		jNotification.put("body", URLEncoder.encode(body, "UTF-8"));

		var1.put("title", URLEncoder.encode(title, "UTF-8") );
		var1.put("body", URLEncoder.encode(body, "UTF-8"));
		var2.put("alert", var1);
		var2.put("category", "var1");
		var2.put("thread-id", "var1");
		var2.put("mutable-content", 1);
		var2.put("sound", "default");
		//var2.put("notification", jNotification);
		var2.put("content-available", 1);
		var3.put("aps", var2);
		var4.put("payload" , var3);

		jMessage.put("apns", var4);

		//android.put("notification" , jNotification);

		/* 레거시코드 적용시 오류남 */
		//	json.put("mutable-content", "1");
		//	json.put("content_available", true);
		//	 json.put("badge", "1");
		//	aps.put("aps", json);
		//	  ios.put("mutable_content",  true);
		//	ios.put("content_available",  true);
		//	  ios.put("payload", aps);
		//	json.put("payload", ios);

		jMessage.put("data", dataInfo);

		//jMessage.put("notification", jNotification);
		//	jMessage.put("apns", ios);

		jMessage.put("token", FcmToken);
		// jMessage.put("content-available", true);

		//jMessage.put("priority", "high");

		JSONObject jFcm = new JSONObject();
		jFcm.put(MESSAGE_KEY, jMessage);

		NotificationVO notiVO = new NotificationVO();
		try {
			log.info("title   " + title);
			log.info("body   " + body);
			notiVO.setSendMsg(body);
			notiVO.setMsg(body);
			notiVO.setPhoneNumber(FcmToken);
			log.info("notiVO   " + notiVO);
			notificationService.insertNotiDataByFcmPush(notiVO);

		} catch (IOException e) {
			log.error("sendCommonMessage -IOExceptionError!");
		} catch (SQLException e) {
			log.error("sendCommonMessage -SQLExceptionError!");
		}

		return jFcm;
	}
}

		/*
			firebase
			1. topic
			2. token
			3. condition -> multiple topic
		 */

//그룹발송
//   jMessage.put("topic", "news");
//개인발송
//	jMessage.addProperty("token", /* your test device token */);
반응형

'Backend > JAVA' 카테고리의 다른 글

[Algorithm] 데일리 백준  (0) 2024.05.17
[Algorithm] 데일리 백준  (0) 2024.05.14
[Algorithm] 데일리 백준  (0) 2024.05.10
[Algorithm] 데일리 백준  (0) 2024.05.08
[JAVA] Enum을 String으로 사용하기  (0) 2024.05.07