如果您不想使用Firebase来发送推送通知,您可以考虑使用其他的推送服务提供商,例如OneSignal或Pusher。下面是使用OneSignal和Pusher发送推送通知的代码示例:
使用OneSignal发送推送通知的示例代码:
npm install onesignal-node
const OneSignal = require('onesignal-node');
const oneSignalClient = new OneSignal.Client({
userAuthKey: 'YOUR_USER_AUTH_KEY',
app: { appAuthKey: 'YOUR_APP_AUTH_KEY', appId: 'YOUR_APP_ID' }
});
const notification = new OneSignal.Notification({
contents: {
en: 'Hello, this is a push notification!'
}
});
notification.postBody['included_segments'] = ['All'];
oneSignalClient.sendNotification(notification)
.then(response => {
console.log('Push notification sent successfully!');
})
.catch(error => {
console.error('Error sending push notification:', error);
});
使用Pusher发送推送通知的示例代码:
npm install @pusher/push-notifications-web
const PusherPushNotifications = require('@pusher/push-notifications-web');
const pusherBeamsClient = new PusherPushNotifications.Client({
instanceId: 'YOUR_INSTANCE_ID',
secretKey: 'YOUR_SECRET_KEY',
});
pusherBeamsClient
.publishToInterests(['hello'], {
apns: {
aps: {
alert: 'Hello, this is a push notification!'
}
},
fcm: {
notification: {
title: 'Hello',
body: 'This is a push notification!'
}
}
})
.then(response => {
console.log('Push notification sent successfully!');
})
.catch(error => {
console.error('Error sending push notification:', error);
});
请注意,以上代码示例中的“YOUR_USER_AUTH_KEY”、“YOUR_APP_AUTH_KEY”、“YOUR_APP_ID”、“YOUR_INSTANCE_ID”和“YOUR_SECRET_KEY”需要根据您的OneSignal和Pusher账户信息进行替换。