← Tất cả hướng dẫn

Thông báo đẩy

Hướng dẫn tích hợp thông báo đẩy

Gửi thông báo tới iOS, Android và trình duyệt với Hibira Push. API tương thích Beams: các SDK máy chủ Beams chính thức hoạt động khi trỏ tới endpoint của bạn, và SDK client của chúng tôi là bản fork từ Beams với host có thể cấu hình.

Đăng nhập để xem các đoạn mã này với endpoint của riêng bạn, và trang ứng dụng sẽ điền instance ID. Đăng nhập

Cách hoạt động

  • Bật thông báo đẩy trên trang ứng dụng trong cổng thông tin. Bạn nhận được instance ID, secret key và endpoint.
  • Mỗi thiết bị hoặc trình duyệt đăng ký bằng SDK client và theo dõi các interest, là chủ đề như news hoặc order-1024. Máy chủ của bạn gửi tới interest, hoặc tới user ID khi thiết bị đã liên kết với người dùng đăng nhập.
  • Instance ID và endpoint được đưa vào ứng dụng. Secret key có thể gửi tới mọi thiết bị: hãy giữ nó trên máy chủ, trong biến môi trường HIBIRA_PUSH_SECRET_KEY, không bao giờ trong ứng dụng hay repository.
  • Thông báo đẩy có trong mọi gói. Gói quy định số thiết bị và trình duyệt có thể đăng ký và tốc độ gửi.

1. Tải lên thông tin xác thực

Apple (APNs)
Trong Apple Developer, mở Certificates, Identifiers & Profiles › Keys, tạo một khóa có Apple Push Notifications service (APNs) và tải tệp .p8. Trên trang ứng dụng, mục Push notifications › Apple (APNs), nhập Key ID, Team ID và bundle ID của ứng dụng, chọn môi trường và tải tệp .p8 lên. Chọn Development (sandbox) cho bản build chạy từ Xcode, và Production cho bản TestFlight và App Store.
Android (FCM)
Trong Firebase console, mở Project settings › Service accounts và bấm Generate new private key. Tải tệp JSON lên mục Push notifications › Android (FCM), và thêm google-services.json của cùng dự án vào ứng dụng Android.
Web Push
Không cần tải lên gì: khóa VAPID được tạo khi bạn bật push. Trang của bạn phải chạy qua HTTPS (localhost dùng được khi phát triển).

Khóa và service account được lưu dạng mã hóa và không bao giờ hiển thị lại.

2. Đăng ký thiết bị và trình duyệt

SDK client

Nền tảng

Chrome, Edge, Firefox, Opera và Safari 16.4+ với Web Push tiêu chuẩn và một service worker. @hibira-io/push-web ↗

  1. Cài đặt

    npm install @hibira-io/push-web
  2. Thêm service worker

    // public/service-worker.js, served at https://your-site/service-worker.js
    importScripts('https://cdn.jsdelivr.net/npm/@hibira-io/push-web@1/dist/service-worker.js');
    self.HibiraPush.endpoint = 'https://ws.hibira.io';
  3. Đăng ký trình duyệt

    import { Client } from '@hibira-io/push-web';
    
    const push = new Client({
      instanceId: 'YOUR_INSTANCE_ID',
      endpoint: 'https://ws.hibira.io',
    });
    
    // Browsers only show the permission prompt after a click or tap.
    document.querySelector('#enable-notifications').addEventListener('click', async () => {
      await push.start();
      await push.addDeviceInterest('hello');
    });
  4. Liên kết người dùng đã đăng nhập

    import { TokenProvider } from '@hibira-io/push-web';
    
    // After sign-in. Your backend answers GET /push/user-token?user_id=... (see the server guide).
    await push.setUserId(currentUser.id, new TokenProvider({ url: '/push/user-token' }));
    
    // On sign-out, so the next person on this browser doesn't get their notifications.
    await push.stop();
Prompt cho agent cho Web

Dán nội dung này vào Claude Code, Cursor, GitHub Copilot hoặc một AI agent lập trình khác. Nó chứa instance ID và endpoint; secret key vẫn là biến môi trường.

Add Hibira push notifications to this Web project. Hibira Push sends to iOS (APNs), Android (FCM) and browsers (Web Push) through a Beams-compatible API, so it works with the Hibira client SDK (here: @hibira-io/push-web, https://github.com/hibira-io/hibira-push-web).

Connection details:
- Instance ID: YOUR_INSTANCE_ID
- Endpoint: https://ws.hibira.io
- No secret key: it belongs on the server, never in this app

What to do:
1. Look at the project first (framework version, package manager, config and env conventions, where similar integrations live) and follow what it already does.
2. Install @hibira-io/push-web (it replaces @pusher/push-notifications-web; the API is the same apart from the import and the endpoint option).
3. Serve service-worker.js from the site root (for example public/service-worker.js in Vite, Next.js or Create React App) with the importScripts line and the endpoint from the reference.
4. Create one shared push client module and call start() from a user action such as an "Enable notifications" button, never on page load: browsers block permission prompts that are not triggered by a click.
5. If the app has signed-in users, call setUserId with a TokenProvider pointing at the backend token endpoint after sign-in, and stop() on sign-out.
6. Web Push needs HTTPS (localhost is fine for development); on iPhone and iPad it works only once the site is added to the Home Screen.
7. Read the instance ID and endpoint from the project's config or environment, and add placeholder entries to .env.example (or its equivalent).
8. Always set the endpoint above. The Pusher Beams SDKs and their defaults point at pusher.com.
9. If YOUR_INSTANCE_ID above is still a placeholder, keep it as a config placeholder and tell me where to fill it in rather than inventing a value.
10. Subscribe test devices to the "hello" interest so the portal's Send a test reaches them.
11. When you are done, list the files you changed and tell me how to check it works: on the Hibira portal app page, Push notifications › Send a test to the hello interest.

Reference setup from the Hibira push notifications guide (adapt it to the project's structure):

Install:

```shell
npm install @hibira-io/push-web
```

Add the service worker:

```js
// public/service-worker.js, served at https://your-site/service-worker.js
importScripts('https://cdn.jsdelivr.net/npm/@hibira-io/push-web@1/dist/service-worker.js');
self.HibiraPush.endpoint = 'https://ws.hibira.io';
```

Register the browser:

```js
import { Client } from '@hibira-io/push-web';

const push = new Client({
  instanceId: 'YOUR_INSTANCE_ID',
  endpoint: 'https://ws.hibira.io',
});

// Browsers only show the permission prompt after a click or tap.
document.querySelector('#enable-notifications').addEventListener('click', async () => {
  await push.start();
  await push.addDeviceInterest('hello');
});
```

Link the signed-in user:

```js
import { TokenProvider } from '@hibira-io/push-web';

// After sign-in. Your backend answers GET /push/user-token?user_id=... (see the server guide).
await push.setUserId(currentUser.id, new TokenProvider({ url: '/push/user-token' }));

// On sign-out, so the next person on this browser doesn't get their notifications.
await push.stop();
```

3. Gửi từ máy chủ của bạn

SDK máy chủ

Ngôn ngữ

Gửi từ Node.js với SDK máy chủ Beams chính thức, trỏ tới endpoint của bạn. @pusher/push-notifications-server ↗

  1. Cài đặt

    npm install @pusher/push-notifications-server
  2. Gửi tới một interest

    const PushNotifications = require('@pusher/push-notifications-server');
    
    const beams = new PushNotifications({
      instanceId: 'YOUR_INSTANCE_ID',
      secretKey: process.env.HIBIRA_PUSH_SECRET_KEY,
      endpoint: 'ws.hibira.io',
    });
    beams.protocol = 'https'; // the SDK switches to http when an endpoint is set
    
    await beams.publishToInterests(['hello'], {
      apns: { aps: { alert: { title: 'Hello', body: 'Hello, world!' } } },
      fcm: { notification: { title: 'Hello', body: 'Hello, world!' } },
      web: { notification: { title: 'Hello', body: 'Hello, world!', deep_link: 'https://your-site.example/' } },
    });
  3. Thêm endpoint cấp mã người dùng

    // Express: the client SDKs call GET /push/user-token?user_id=...
    app.get('/push/user-token', requireLogin, (req, res) => {
      if (req.query.user_id !== String(req.user.id)) return res.sendStatus(401);
      res.json(beams.generateToken(String(req.user.id))); // { token: '...' }
    });
  4. Gửi tới người dùng đã đăng nhập

    await beams.publishToUsers(['user-1'], {
      apns: { aps: { alert: { title: 'Order shipped', body: 'Order #1024 is on its way.' } } },
      fcm: { notification: { title: 'Order shipped', body: 'Order #1024 is on its way.' } },
      web: { notification: { title: 'Order shipped', body: 'Order #1024 is on its way.' } },
    });
Prompt cho agent cho Node.js

Dán nội dung này vào Claude Code, Cursor, GitHub Copilot hoặc một AI agent lập trình khác. Nó chứa instance ID và endpoint; secret key vẫn là biến môi trường.

Add Hibira push notifications to this Node.js project. Hibira Push sends to iOS (APNs), Android (FCM) and browsers (Web Push) through a Beams-compatible API, so it works with the official Beams server SDKs pointed at the Hibira endpoint (here: @pusher/push-notifications-server, https://github.com/pusher/push-notifications-node).

Connection details:
- Instance ID: YOUR_INSTANCE_ID
- Endpoint: https://ws.hibira.io
- Secret key: read it from the HIBIRA_PUSH_SECRET_KEY environment variable (server-side only)

What to do:
1. Look at the project first (framework version, package manager, config and env conventions, where similar integrations live) and follow what it already does.
2. Create one shared module that builds the PushNotifications client from environment variables, with the endpoint option and beams.protocol set as in the reference (without them the SDK talks to pusher.com, or to the endpoint over plain http).
3. If the app has signed-in users, add the token route behind the project's existing authentication middleware; it must refuse a user_id that is not the signed-in user's.
4. Publish from the places that should notify (jobs, controllers, event handlers) through the shared module, and log the publish ID it returns.
5. Read the instance ID and endpoint from the project's config or environment, and add placeholder entries to .env.example (or its equivalent). Never commit the secret key or send it to a browser or mobile app.
6. Always set the endpoint above. The Pusher Beams SDKs and their defaults point at pusher.com.
7. If YOUR_INSTANCE_ID above is still a placeholder, keep it as a config placeholder and tell me where to fill it in rather than inventing a value.
8. Subscribe test devices to the "hello" interest so the portal's Send a test reaches them.
9. When you are done, list the files you changed and tell me how to check it works: on the Hibira portal app page, Push notifications › Send a test to the hello interest.

Reference setup from the Hibira push notifications guide (adapt it to the project's structure):

Install:

```shell
npm install @pusher/push-notifications-server
```

Publish to an interest:

```js
const PushNotifications = require('@pusher/push-notifications-server');

const beams = new PushNotifications({
  instanceId: 'YOUR_INSTANCE_ID',
  secretKey: process.env.HIBIRA_PUSH_SECRET_KEY,
  endpoint: 'ws.hibira.io',
});
beams.protocol = 'https'; // the SDK switches to http when an endpoint is set

await beams.publishToInterests(['hello'], {
  apns: { aps: { alert: { title: 'Hello', body: 'Hello, world!' } } },
  fcm: { notification: { title: 'Hello', body: 'Hello, world!' } },
  web: { notification: { title: 'Hello', body: 'Hello, world!', deep_link: 'https://your-site.example/' } },
});
```

Add the user token endpoint:

```js
// Express: the client SDKs call GET /push/user-token?user_id=...
app.get('/push/user-token', requireLogin, (req, res) => {
  if (req.query.user_id !== String(req.user.id)) return res.sendStatus(401);
  res.json(beams.generateToken(String(req.user.id))); // { token: '...' }
});
```

Publish to a signed-in user:

```js
await beams.publishToUsers(['user-1'], {
  apns: { aps: { alert: { title: 'Order shipped', body: 'Order #1024 is on its way.' } } },
  fcm: { notification: { title: 'Order shipped', body: 'Order #1024 is on its way.' } },
  web: { notification: { title: 'Order shipped', body: 'Order #1024 is on its way.' } },
});
```

4. Người dùng đã đăng nhập

Để gửi tới một người trên mọi thiết bị họ dùng, hãy liên kết từng thiết bị với user ID của bạn. SDK client gọi endpoint cấp mã của bạn với ?user_id=…; endpoint kiểm tra yêu cầu đến từ đúng người dùng đã đăng nhập đó và trả về mã mà generateToken tạo từ secret key (mọi SDK máy chủ Beams đều có). Sau đó gửi tới user ID thay vì interest. Xóa một người dùng sẽ hủy liên kết mọi thiết bị của họ.

Gọi stop khi người dùng đăng xuất, để người tiếp theo trên thiết bị đó không nhận thông báo của họ.

5. Gửi thử

Trên trang ứng dụng, mục Push notifications › Send a test, nhập một interest (hello trong các đoạn mã ở trên), tiêu đề và nội dung, rồi bấm Gửi thử. Các thiết bị theo dõi interest đó nhận được trong vài giây, và đồng hồ Người đăng ký cho biết có bao nhiêu thiết bị và trình duyệt đã đăng ký.

Khắc phục sự cố

Thiết bị hoặc trình duyệt không bao giờ xuất hiện trong Người đăng ký
Kiểm tra client gọi start với instance ID và endpoint của ứng dụng này, và người dùng đã cho phép thông báo. Trên Android, google-services.json phải đến từ cùng dự án Firebase với service account bạn đã tải lên.
iPhone và iPad không nhận được gì
Môi trường APNs phải khớp với bản build: Development (sandbox) cho bản chạy từ Xcode, Production cho TestFlight và App Store. Bundle ID phải khớp chính xác với ứng dụng, và target của ứng dụng cần capability Push Notifications.
start() lỗi với “service worker missing”
Phục vụ /service-worker.js từ thư mục gốc của trang qua HTTPS, với dòng importScripts trong hướng dẫn Web. Service worker trong thư mục con chỉ kiểm soát thư mục đó.
Safari trên iPhone không bao giờ xin quyền
Web Push trên iOS và iPadOS 16.4+ chỉ hoạt động sau khi trang được thêm vào Màn hình chính, và lời nhắc xin quyền phải đến từ một lần chạm.
SDK máy chủ vẫn gọi pusher.com, hoặc lỗi qua http
Đặt tùy chọn endpoint. SDK Node.js còn cần beams.protocol = 'https', và SDK Go dùng WithCustomBaseURL.
Gửi trả về 401
Máy chủ đang dùng sai secret key, hoặc khóa đã bị đổi quá thời gian ân hạn. Hãy sao chép khóa hiện tại từ trang ứng dụng.
Gửi trả về 429
Bạn đang gửi nhanh hơn mức gói cho phép. Hãy đợi theo Retry-After, và nhắm tới tối đa 100 interest hoặc 1.000 người dùng trong một lần gửi thay vì mỗi yêu cầu một đối tượng.
Đăng ký thiết bị trả về 402
Ứng dụng đã đạt giới hạn người đăng ký của gói. Hãy nâng cấp gói, hoặc xóa người dùng đã rời đi để gỡ thiết bị của họ.
setUserId lỗi
Endpoint cấp mã của bạn phải trả về 200 với JSON mà generateToken trả cho user_id được hỏi, dùng secret key của ứng dụng này. Thiết bị đang liên kết với người dùng khác phải gọi stop trước.

Chuyển từ Pusher Beams? Đổi các gói SDK client sang của chúng tôi, đặt endpoint trong SDK máy chủ, tải lên khóa APNs và service account FCM, và gửi tới cả hai dịch vụ cho đến khi người dùng đã cập nhật. Thiết bị đăng ký lại ở lần khởi động đầu tiên. Chuyển từ Pusher →