user-notifications

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

User Notifications

用户通知

Prerequisite

前置条件

Load the
user-sign-in
skill first. The sender list below is served from the app's primary origin, which that skill elects.
先加载
user-sign-in
skill。下面的发送方列表由应用的 主 origin 提供,而这个 origin 由该 skill 选定。

How it works

工作原理

Your canister can notify your app's users, on their devices and while the app is closed. The canister addresses a user; Internet Identity holds that user's devices and delivers to them, so there is no push service, no VAPID keys, and no device tokens in the app.
Three pieces, all required. Missing any one of them produces silence rather than an error at the point you left out.
  1. The frontend asks the user's consent, through II.
  2. The origin names the sending canister at
    /.well-known/ii-notification-senders
    .
  3. The canister sends, through the
    identity-notifications
    library.
你的 canister 可以在用户设备上向应用用户发送通知,即使应用已关闭也可以。canister 只需指定用户;Internet Identity 持有该用户注册的设备并向这些设备投递通知,因此应用中无需 push service、VAPID keys 或 device tokens。
需要三个组成部分,缺一不可。缺少其中任何一项时,不会在遗漏处报错,而只会表现为没有任何通知。
  1. frontend 通过 II 请求用户同意。
  2. origin 在
    /.well-known/ii-notification-senders
    中声明用于发送通知的 canister。
  3. canister 通过
    identity-notifications
    library 发送通知。

1. Consent, in the frontend

1. frontend 中的用户同意

Needs
@icp-sdk/auth
11.1.0 or later. Earlier 11.x has none of these methods.
javascript
const { granted } = await authClient.requestNotificationConsent();
const { granted } = await authClient.getNotificationConsentStatus();
await authClient.revokeNotificationConsent();
CallOpens IINeeds a sessionAnswers
requestNotificationConsent()
YesNo; signs the user in if needed
{ granted }
, what II recorded
getNotificationConsentStatus()
NoYes
{ granted }
, uncertified query
revokeNotificationConsent()
NoYesnothing; idempotent
  • All three answer a record, not a bare boolean.
    const granted = await ...requestNotificationConsent()
    type-checks and is always truthy.
  • granted: false
    is the user's refusal, not a failure. Render it; do not throw.
  • Asking a second time when consent is already held returns
    { granted: true }
    without showing a screen, because the answer is read back from the canister rather than reported from the ceremony.
  • getNotificationConsentStatus
    is a query, so the answer is uncertified. Paint a toggle from it; do not gate anything on it.
  • Ask from a click. The ceremony renders, so it cannot run under
    prompt: 'none'
    .
  • Consent is recorded against the identity, and the browser the user answered on is the one registered for delivery. Someone who wants your notifications on a second machine answers again there. The status call reports the consent alone and does not speak for the device in the user's hand.
需要
@icp-sdk/auth
11.1.0 或更高版本。较早的 11.x 版本不包含任何这些方法。
javascript
const { granted } = await authClient.requestNotificationConsent();
const { granted } = await authClient.getNotificationConsentStatus();
await authClient.revokeNotificationConsent();
调用是否打开 II是否需要 session返回
requestNotificationConsent()
是否;必要时会让用户 sign-in
{ granted }
,II 记录的同意结果
getNotificationConsentStatus()
否是
{ granted }
,未经认证的 query 结果
revokeNotificationConsent()
否是无返回值;幂等
  • 这三个调用返回的都是一个 record,而不是单独的 boolean 值。
    const granted = await ...requestNotificationConsent()
    可以通过类型检查,而且结果始终为 truthy。
  • granted: false
    表示用户拒绝,并非失败。应渲染该状态,不要抛出异常。
  • 如果已经获得同意,再次询问会直接返回
    { granted: true }
    ,不会显示界面,因为答案会从 canister 读回,而不是由 ceremony 报告。
  • getNotificationConsentStatus
    是 query,因此结果未经认证。可以据此绘制 toggle,但不要基于它控制任何功能。
  • 必须在用户点击操作中发起询问。ceremony 会进行渲染,因此不能在
    prompt: 'none'
    下运行。
  • 同意结果记录在 identity 上,而用户作出回答时使用的浏览器会被注册为投递设备。如果用户希望在第二台设备上接收通知,需要在该设备上再次作出回答。status 调用只报告同意状态,不能代表用户当前手持的设备。

Asking with the sign-in

在 sign-in 时请求同意

The sign-in button is already a click, so that is the cheapest place to ask. Run both from it and the user signs in and answers in one visit to II rather than two:
javascript
const [identity, { granted }] = await Promise.all([
  authClient.signIn(),
  authClient.requestNotificationConsent(),
]);
Asking at any later moment needs a control of its own.
sign-in 按钮本来就需要用户点击,因此在这里一并请求成本最低。让两个操作都由该按钮触发,用户只需访问 II 一次,就能完成 sign-in 和回答,而不必访问两次:
javascript
const [identity, { granted }] = await Promise.all([
  authClient.signIn(),
  authClient.requestNotificationConsent(),
]);
如果之后再询问同意,则需要为其提供单独的 control。

A toggle, later

之后添加 toggle

To show the user whether your app may notify them, and let them turn it off:
javascript
const { granted } = await authClient.getNotificationConsentStatus();
await authClient.revokeNotificationConsent();
Revoking is scoped to your app. It drops your origin's consent and whatever you still had queued for that user, and leaves their device subscriptions and every other app's consent alone. So dropping someone from your own recipient table revokes nothing, and revoking is not an unsubscribe.
Errors worth branching on:
ErrorMeansRemedy
InteractionRequiredError
Client built with
prompt: 'none'
Ask again from a click
NotificationsUnsupportedError
That II deployment does not notify at allHide the control; nothing to retry
SessionGoneError
No live session (status and revoke only)Sign in again
要显示应用是否获准向用户发送通知,并允许用户将其关闭:
javascript
const { granted } = await authClient.getNotificationConsentStatus();
await authClient.revokeNotificationConsent();
撤销仅作用于你的应用。它会删除你的 origin 上的同意记录,以及你为该用户排队但尚未投递的所有通知,同时保留用户的设备订阅和所有其他应用的同意记录。因此,仅从你自己的收件人表中删除某人不会撤销任何内容,而撤销也不等于取消订阅。
值得区分处理的错误:
错误含义修复方法
InteractionRequiredError
客户端以
prompt: 'none'
构建
在用户点击操作中再次询问
NotificationsUnsupportedError
该 II deployment 完全不支持通知隐藏 control;无需重试
SessionGoneError
没有活动 session(仅 status 和 revoke 操作)重新 sign-in

2. The senders document

2. 发送方文档

Serve from the primary origin, the same origin as
/.well-known/ii-app-metadata
:
json
{ "senders": ["ryjl3-tyaaa-aaaaa-aaaba-cai"] }
  • At most 10 canisters, shared by every app derived from that origin. A longer list is rejected whole, never truncated.
  • II caches what it reads, so a canister added is not accepted instantly and one removed keeps working for a while afterwards.
  • Without this document naming the sending canister, every send is refused. This is the most common cause of "nothing arrives and nothing errors".
必须从 主 origin 提供该文档;它应与
/.well-known/ii-app-metadata
使用同一个 origin:
json
{ "senders": ["ryjl3-tyaaa-aaaaa-aaaba-cai"] }
  • 最多 10 个 canister,由从该 origin 派生的所有应用共享。列表超出长度时会整体拒绝,绝不会截断。
  • II 会缓存读取到的内容,因此新增 canister 不会立即生效,而被移除的 canister 在此后一段时间内仍会继续工作。
  • 如果没有通过该文档声明用于发送通知的 canister,所有发送都会被拒绝。这是“没有任何通知到达,也没有任何报错”最常见的原因。

3. Sending

3. 发送通知

Library:
identity-notifications
, same
send
in both languages, different wiring. Rust is on crates.io, Motoko on Mops (requires moc 2.0.0 or later).
Rust needs
endpoints!()
plus three stable
MemoryId
s handed to
init
(see "Upgrades"). Motoko needs neither: the mixin brings the endpoints and keeps its own state. Do not tell a Motoko user to pass memory ids; there are none.
toml
identity-notifications = "0.1"
rust
use identity_notifications as notifications;
use identity_notifications::{Memories, Notification};

notifications::endpoints!();          // the endpoints II calls back on

#[init]      fn init()         { init_notifications(); }
#[post_upgrade] fn post_upgrade() { init_notifications(); }

fn init_notifications() {
    MEMORIES.with_borrow(|manager| {
        notifications::init(manager, Memories {
            entries: MemoryId::new(10),
            content: MemoryId::new(11),
            metrics: MemoryId::new(12),
        })
    });
}

notifications::send(to, Notification {
    title: "New message".into(),
    body: text,
    url: Some(format!("https://chat.example.com/chats/{from}")),
    key: Some(format!("chat-{from}")),
    ..Default::default()
});
motoko
import Notifications "mo:identity-notifications";

actor {
  include Notifications<system>();

  notifications.send<system>(to, {
    title = "New message";
    body = text;
    url = ?("https://chat.example.com/chats/" # caller.toText());
    key = ?("chat-" # caller.toText());
    urgency = null;
    expiresAt = null;
    funnel = null;
  })
}
Configuration is environment variables, not init arguments:
yaml
canisters:
  - name: backend
    settings:
      environment_variables:
        notification_sender:      "rdmx6-jaaaa-aaaaa-aaadq-cai"   # the II canister
        notification_origin:      "https://your-app.icp0.io"
        notification_capacity_mb: "1024"   # optional
Library:
identity-notifications
。两种语言使用相同的
send
,但接入方式不同。Rust 版发布于 crates.io,Motoko 版发布于 Mops(需要 moc 2.0.0 或更高版本)。
Rust 需要
endpoints!()
,并且需要把三个稳定的
MemoryId
传给
init
(参见“升级”)。Motoko 两者都不需要:mixin 会提供 endpoints,并自行维护状态。不要让 Motoko 用户传入 memory ids;它没有这些参数。
toml
identity-notifications = "0.1"
rust
use identity_notifications as notifications;
use identity_notifications::{Memories, Notification};

notifications::endpoints!();          // the endpoints II calls back on

#[init]      fn init()         { init_notifications(); }
#[post_upgrade] fn post_upgrade() { init_notifications(); }

fn init_notifications() {
    MEMORIES.with_borrow(|manager| {
        notifications::init(manager, Memories {
            entries: MemoryId::new(10),
            content: MemoryId::new(11),
            metrics: MemoryId::new(12),
        })
    });
}

notifications::send(to, Notification {
    title: "New message".into(),
    body: text,
    url: Some(format!("https://chat.example.com/chats/{from}")),
    key: Some(format!("chat-{from}")),
    ..Default::default()
});
motoko
import Notifications "mo:identity-notifications";

actor {
  include Notifications<system>();

  notifications.send<system>(to, {
    title = "New message";
    body = text;
    url = ?("https://chat.example.com/chats/" # caller.toText());
    key = ?("chat-" # caller.toText());
    urgency = null;
    expiresAt = null;
    funnel = null;
  })
}
配置使用 environment variables,而不是 init arguments:
yaml
canisters:
  - name: backend
    settings:
      environment_variables:
        notification_sender:      "rdmx6-jaaaa-aaaaa-aaadq-cai"   # the II canister
        notification_origin:      "https://your-app.icp0.io"
        notification_capacity_mb: "1024"   # optional

The optional fields

可选字段

FieldDefaultWhat it is for
url
noneWhere acting on it takes the user. Must be the sending origin or one of its alternative origins; II refuses anything else.
key
noneWhat the notification is about. A second send under the same key updates that notification instead of adding another, and it is what
dismiss(recipient, key)
names.
urgency
Normal
VeryLow
,
Low
,
Normal
,
High
. Schedules this notification against the origin's other traffic. Not a rendering hint, and honoured on channels with no tray.
expiresAt
/
expires_at
a short windowHow long this is still worth sending. Set past the default for anything that matters later; short for anything worthless once the moment passes.
funnel
noneWhich funnel to count it in. A label per notification is an unbounded set of rows: use one per campaign or kind, not per send.
字段默认值用途
url
无用户操作后跳转到的位置。必须是用于发送的 origin 或其替代 origin;II 会拒绝其他地址。
key
无通知 所针对的内容。使用同一个
key
再次发送会 更新 原通知,而不是新增一条;
dismiss(recipient, key)
也使用它来标识通知。
urgency
Normal
可设为
VeryLow
、
Low
、
Normal
、
High
。用于根据该 origin 的其他流量安排此通知的调度优先级。这不是渲染提示,即使在没有通知托盘的 channel 上也会生效。
expiresAt
/
expires_at
较短的默认时长此通知还值得发送的时长。对于稍后仍有价值的内容,应设置为超过默认短时长;对于错过当下便没有价值的内容,则应使用较短时长。
funnel
无用于将此通知计入哪个 funnel。每条通知使用一个 label 会产生无限增长的数据行:应为每个 campaign 或类型使用一个,而不是每次发送都使用一个。

Choosing
urgency
and
expiresAt

选择
urgency
和
expiresAt

Different questions:
urgency
is where this sits against the origin's other traffic,
expiresAt
is whether it is still worth showing when it could be. Pick both together.
Unset is a short default, so anything still worth delivering later needs an explicit value. It is not a tray lifetime: a delivered notification stays until the user clears it.
expiresAt
bounds how long the notification is still worth sending at all, and the library does not cap a longer value.
Sending
urgency
expiresAt
Why
Security alert, new sign-in
High
daysAhead of other traffic, and worth seeing late, so set well past the short default.
Direct message
Normal
unsetWorth sending now, noise much later.
"Your driver is outside"
High
minutesAhead of everything, worthless once passed.
Campaign to the whole user base
VeryLow
daysNone is urgent and a large send must not push real notifications behind it, but each should still land. Give the campaign a
funnel
and its conversion rate is readable on its own.
Digest, nudge, streak reminder
Low
hoursYields to anything else, and yesterday's is pointless.
A short expiry does not make something urgent, and
High
does not make it last longer.
High
on everything removes the ordering it was reached for.
两者解决的问题不同:
urgency
决定该通知相对于该 origin 的 其他流量 的调度位置,
expiresAt
决定当通知本可显示时,它是否仍值得显示。两者应结合选择。
未设置时会采用一个较短的默认值,因此较晚仍值得投递的通知需要显式设置该值。它不是通知在托盘中的保留时长:已投递的通知会一直保留,直到用户将其清除。
expiresAt
限定通知在多长时间内仍值得发送,library 不会对更长的值进行上限截断。
发送场景
urgency
expiresAt
原因
安全警报、新 sign-in
High
数天排在其他流量之前,而且稍后查看仍有价值,因此应设置为远长于默认短时长。
私信
Normal
未设置现在值得发送,稍后发送只会造成噪声。
“司机就在外面”
High
数分钟优先于其他所有通知,但一旦错过就毫无价值。
面向全体用户的 campaign
VeryLow
数天没有哪条通知是紧急的,而且大规模发送不能把真正通知的优先级往后挤;但每条仍应送达。为 campaign 设置
funnel
后,就可以单独读取它的 conversion rate。
摘要、nudge、连续记录提醒
Low
数小时应为其他通知让路,而且昨天的摘要或提醒已经没有意义。
较短的有效期不会让通知变得紧急,而
High
也不会延长其有效期。所有通知都设为
High
会失去它本应提供的调度顺序。

key

key

The id is
hash(recipient, key)
, so a key reaches only that recipient's own entry: it cannot touch another user's notification or another app's. What it can do is collide with this app's other pending notification to the same recipient, and the later send wins. Derive
key
from the thing the notification is about, such as the conversation, rather than from whatever a caller passed in.
metrics()
reports the pipeline hour by hour, and is the only place a notification's fate shows up, since
send
returns nothing.
ID 为
hash(recipient, key)
,因此一个
key
只能作用于该收件人自己的条目:它无法影响另一名用户的通知,也无法影响其他应用的通知。但它可能与本应用面向同一收件人的另一条待处理通知发生冲突,此时后发送的通知会胜出。应从通知所针对的内容(例如会话)派生
key
,而不是直接采用调用方传入的任意值。
metrics()
按小时报告 pipeline 的情况。由于
send
不返回任何内容,这里是唯一能查看通知最终处理结果的地方。

What the app does and does not own

应用负责与不负责的部分

  • The app addresses a user, nothing finer. II holds a queue per browser that identity has registered, so one
    send
    can surface on a laptop and a phone at once. Where and how a notification reaches them is II's and the user's to manage, and an app that reasons about it is coupling itself to something it cannot see.
  • II composes what is shown. The user reads your app's name, then the title your canister sent. The name comes from
    /.well-known/ii-app-metadata
    , and falls back to your origin's hostname where you publish none, so do not put your app's name in
    title
    yourself: it arrives twice. Publishing that document is what brands the notifications as well as the sign-in screen: see "App metadata on the sign-in screen" in the
    user-sign-in
    skill.
  • Sending cannot fail the call it is made from.
    send
    neither traps nor awaits, so a recipient who cannot be notified costs the endpoint nothing and returns nothing to branch on. What became of a notification is in
    metrics()
    .
  • iOS needs II added to the Home Screen for web push. The consent ceremony walks the user through it; the app does nothing.
  • 应用只能寻址到用户这一层级。 II 会为该 identity 注册过的每个浏览器维护一个队列,因此一次
    send
    可以同时显示在笔记本电脑和手机上。通知在何处以及如何送达用户,由 II 和用户管理;应用如果围绕这些细节进行设计,就会与自身无法观察的部分产生耦合。
  • 最终显示的内容由 II 组合。 用户会先读到应用名称,然后读到 canister 发送的标题。该名称来自
    /.well-known/ii-app-metadata
    ;如果未发布该文档,则回退到 origin 的 hostname。因此,不要自行在
    title
    中放入应用名称,否则名称会出现两次。发布该文档不仅会为通知添加品牌标识,也会为 sign-in 界面添加品牌标识:参见
    user-sign-in
    skill 中的“sign-in 界面上的 App metadata”。
  • 发送操作不会使发起它的调用失败。
    send
    既不会 trap,也不会 await,因此,无法接收通知的收件人不会给 endpoint 带来任何成本,也不会返回可供分支判断的结果。通知最终的处理结果记录在
    metrics()
    中。
  • 在 iOS 上使用 web push,需要先将 II 添加到主屏幕。 consent ceremony 会引导用户完成此操作;应用无需做任何事情。

Upgrades

升级

Motoko: nothing to do. There is no post-upgrade call to make and no ids to pass back in.
Rust: call
init
again from
post_upgrade
.
No timer survives a canister upgrade, so without that second call anything already queued stays queued and is never sent. It is not optional and it is not a no-op on a canister that was running a moment ago.
Pass the same
MemoryId
s every time. Renumbering them on a running canister points the library at empty memories instead of the ones holding the queue, and whatever was waiting is gone.
Motoko:无需进行任何操作。 不需要调用 post-upgrade,也不需要传回任何 ids。
Rust:在
post_upgrade
中再次调用
init
。
canister 升级后不会保留任何 timer,因此,如果不进行第二次调用,已排队的通知会一直停留在队列中,永远不会被发送。对于刚刚还在运行的 canister,此操作既非可选,也不是 no-op。
每次都应传入相同的
MemoryId
。如果在运行中的 canister 上重新编号,library 将指向空的 memory,而不是保存队列的 memory,其中尚未发送的内容也会丢失。

Mistakes That Break Your Build

会导致构建或运行失败的常见错误

  1. Leaving the senders document out. Without
    /.well-known/ii-notification-senders
    naming the sending canister, every send is refused and nothing anywhere reports it. See "2. The senders document".
  2. Putting your app's name in
    title
    .
    II puts it in front of the title you sent, so the user reads it twice. See "What the app does and does not own".
  3. Deriving
    key
    from whatever a caller passed in.
    Two of your own sends under one key collide in that recipient's tray and the later one wins. See "
    key
    ".
  4. Skipping
    init
    in
    post_upgrade
    , in Rust.
    Anything queued stays queued and is never sent. See "Upgrades".
  1. 遗漏发送方文档。 如果没有通过
    /.well-known/ii-notification-senders
    声明用于发送通知的 canister,所有发送都会被拒绝,而且任何地方都不会报告此错误。参见“2. 发送方文档”。
  2. 把应用名称放进
    title
    。
    II 会把应用名称放在你发送的标题之前,因此用户会看到两次名称。参见“应用负责与不负责的部分”。
  3. 根据调用方传入的任意值派生
    key
    。
    本应用使用同一个
    key
    发出的两条通知会在该收件人的托盘中发生冲突,后发送的通知会胜出。参见“
    key
    ”。
  4. 在 Rust 中跳过
    post_upgrade
    里的
    init
    。
    已排队的通知会一直停留在队列中,永远不会被发送。参见“升级”。