Back/apps/push.js
seonkyu.kim 21762a2d27
All checks were successful
JJ_Back/pipeline/head This commit looks good
[] push 수정
2024-08-20 14:48:02 +09:00

48 lines
1.8 KiB
JavaScript

import apn from 'apn';
import { bundleID, apnKey, apnKeyID, apnTeamID } from '../private/config.js';
// APNs 옵션 설정
const options = {
token: {
// key: `../private/${apnKey}`, // 다운로드한 .p8 파일 경로
key: path.join(__dirname, '../private', apnKey), // 절대 경로로 변경
keyId: apnKeyID, // Apple Developer Console에서 얻은 키 ID
teamId: apnTeamID, // Apple Developer Console에서 얻은 팀 ID
},
production: false, // 프로덕션(실제 배포 환경)인 경우 true로 설정
};
const apnProvider = new apn.Provider(options);
export function HandlePush(req, res) {
// 쿼리 파라미터에서 값 추출
const { id: deviceToken, title, body, parameter, sound = "default", badge = 0 } = req.query;
if (!deviceToken || !title || !body) {
res.status(400).json({ error: 'deviceToken, title, and body are required' });
return;
}
const notification = new apn.Notification();
notification.topic = "your.bundle.id";
notification.expiry = Math.floor(Date.now() / 1000) + 3600;
notification.badge = Number(badge);
notification.sound = sound;
notification.alert = { title, body };
notification.payload = { parameter };
apnProvider.send(notification, deviceToken).then((response) => {
if (response.sent.length > 0) {
console.log('Successfully sent message:', response.sent);
res.status(200).json({ message: 'Successfully sent message' });
} else {
console.error('Failed to send message:', response.failed);
res.status(500).json({ error: 'Failed to send message', details: response.failed });
}
}).catch((error) => {
console.error('Error sending message:', error);
res.status(500).json({ error: `Error sending message: ${error.message}` });
}).finally(() => {
apnProvider.shutdown();
});
}