指南
如何在 Capacitor 中使用 Notifications
使用 @capgo/capacitor-notifications
通过 Capgo 发送原生 iOS 和 Android 推送通知,支持用户查询、角标、前台/打开追踪、后台回调以及静默 Capgo Live Update 检查。
该插件专为 Capgo 通知流水线构建。Capgo 在 Postgres 中存储平台凭据元数据和营销控制数据,而活跃设备状态和送达事件则写入 Cloudflare Analytics Engine。
安装
使用 Capgo CLI 进行引导式安装:
npx @capgo/cli@latest notifications setup com.example.app
手动安装:
npm install @capgo/capacitor-notifications @capgo/capacitor-updater
npx cap sync
配置
import { CapgoNotifications } from '@capgo/capacitor-notifications'
await CapgoNotifications.configure({
appId: 'com.example.app',
autoUpdater: true,
updateInstallMode: 'next',
})
注册已认证用户
Mint identityProof 通过您的后端使用 POST /notifications/recipients/proof,然后在您的登录成功后注册设备。
await CapgoNotifications.register({
externalId: 'customer-user-123',
identityProof,
tags: ['paid'],
attributes: { plan: 'team' },
consent: true,
})
监听事件
await CapgoNotifications.addListener('notificationReceived', (notification) => {
console.log('Received', notification)
})
await CapgoNotifications.addListener('notificationOpened', (event) => {
console.log('Opened', event.notification.id)
})
await CapgoNotifications.addListener('backgroundNotification', async (event) => {
try {
console.log('Background payload', event.notification.data)
} finally {
await event.finish()
}
})
iOS 配置
启用 推送通知 以及 Background Modes > Remote notifications 在 Xcode 中。
从以下来源转发远程通知: ios/App/App/AppDelegate.swift:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
NotificationCenter.default.post(name: Notification.Name("CapgoNotificationsRemoteNotification"), object: userInfo)
completionHandler(.newData)
}
Android 配置
运行 npx cap sync android在 Capgo 中配置 Android 平台凭据,在 Android 13+ 上请求通知权限,并在带有 Google Play services 的设备或模拟器上进行测试。
调试检查清单
- 运行
npx @capgo/cli@latest notifications setup com.example.app从包含……的文件夹中capacitor.config.*. - 按外部客户 ID 在 Capgo 中搜索收件人。
- 确认设备已具备平台
android或ios且已授予权限。 - 为以下内容添加临时监听器:
registrationChanged,notificationReceived,notificationOpened,以及backgroundNotification. - 从 dashboard 发送测试通知。
- 查看排队中、已发送、已接收和已打开事件的统计数据。
- 对于静默更新检查,请确认
@capgo/capacitor-updater已安装且autoUpdater已启用。
完整参考
- 文档:/docs/plugins/notifications/
- 调试:/docs/plugins/notifications/debugging/
- 来源: https://github.com/Cap-go/capgo/tree/main/packages/capacitor-notifications/
继续阅读《使用 @capgo/capacitor-notifications》
如果你正在使用 使用 @capgo/capacitor-notifications 要规划原生推送消息,请将其与 @capgo/capacitor-notifications 了解实现细节, 调试 排查问题, @capgo/capacitor-updater 进行静默更新检查,以及 Capgo 插件目录 用于其他原生插件。