การแจ้งเตือนแบบพุช
คู่มือการเชื่อมต่อการแจ้งเตือนแบบพุช
ส่งการแจ้งเตือนไปยัง iOS, Android และเบราว์เซอร์ด้วย Hibira Push API เข้ากันได้กับ Beams: Beams server SDK อย่างเป็นทางการใช้ได้เมื่อชี้ไปที่ endpoint ของคุณ และ client SDK ของเราแยกมาจากของ Beams โดยกำหนดโฮสต์ได้
ลงชื่อเข้าใช้เพื่อดูโค้ดตัวอย่างเหล่านี้พร้อม endpoint ของคุณเอง และหน้าแอปจะกรอก instance ID ให้ ลงชื่อเข้าใช้
วิธีการทำงาน
- เปิดการแจ้งเตือนแบบพุชในหน้าแอปบนพอร์ทัล คุณจะได้ instance ID, secret key และ endpoint
- อุปกรณ์หรือเบราว์เซอร์แต่ละเครื่องลงทะเบียนด้วย client SDK และสมัครรับ interest ซึ่งเป็นหัวข้อ เช่น news หรือ order-1024 เซิร์ฟเวอร์ของคุณเผยแพร่ไปยัง interest หรือไปยัง user ID เมื่ออุปกรณ์เชื่อมโยงกับผู้ใช้ที่ลงชื่อเข้าใช้แล้ว
- Instance ID และ endpoint ใส่ไว้ในแอปของคุณ secret key เผยแพร่ไปยังทุกอุปกรณ์ได้ จึงต้องเก็บไว้บนเซิร์ฟเวอร์ในตัวแปรสภาพแวดล้อม HIBIRA_PUSH_SECRET_KEY และห้ามใส่ไว้ในแอปหรือ repository
- พุชรวมอยู่ในทุกแพ็กเกจ แพ็กเกจกำหนดจำนวนอุปกรณ์และเบราว์เซอร์ที่ลงทะเบียนได้ และความเร็วในการเผยแพร่
1. อัปโหลดข้อมูลรับรอง
- Apple (APNs)
- ใน Apple Developer ให้เปิด Certificates, Identifiers & Profiles › Keys สร้างคีย์ที่มี Apple Push Notifications service (APNs) แล้วดาวน์โหลดไฟล์ .p8 ในหน้าแอป ใต้ Push notifications › Apple (APNs) ให้ป้อน Key ID, Team ID และ bundle ID ของแอป เลือกสภาพแวดล้อม แล้วอัปโหลดไฟล์ .p8 เลือก Development (sandbox) สำหรับบิลด์ที่รันจาก Xcode และ Production สำหรับบิลด์ TestFlight และ App Store
- Android (FCM)
- ในคอนโซล Firebase ให้เปิด Project settings › Service accounts แล้วคลิก Generate new private key อัปโหลดไฟล์ JSON ใต้ Push notifications › Android (FCM) และเพิ่ม google-services.json ของโปรเจกต์เดียวกันลงในแอป Android ของคุณ
- Web Push
- ไม่ต้องอัปโหลดอะไร: คีย์ VAPID จะถูกสร้างเมื่อคุณเปิดพุช เว็บไซต์ของคุณต้องให้บริการผ่าน HTTPS (localhost ใช้ได้ระหว่างพัฒนา)
คีย์และ service account จัดเก็บแบบเข้ารหัสและจะไม่แสดงอีก
2. ลงทะเบียนอุปกรณ์และเบราว์เซอร์
Client SDK
Chrome, Edge, Firefox, Opera และ Safari 16.4+ ด้วย Web Push มาตรฐานและ service worker @hibira-io/push-web ↗
ติดตั้ง
npm install @hibira-io/push-webเพิ่ม 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';ลงทะเบียนเบราว์เซอร์
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'); });เชื่อมโยงผู้ใช้ที่ลงชื่อเข้าใช้
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();
พรอมต์สำหรับเอเจนต์ของ Web
วางข้อความนี้ใน Claude Code, Cursor, GitHub Copilot หรือเอเจนต์เขียนโค้ด AI อื่น ข้อความนี้มี instance ID และ endpoint ส่วน secret key ยังคงเป็นตัวแปรสภาพแวดล้อม
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();
```
แอป Android 7.0+ ด้วย Kotlin หรือ Java ส่งผ่าน Firebase Cloud Messaging hibira-push-android ↗
เพิ่ม dependency ของ Gradle
// settings.gradle.kts dependencyResolutionManagement { repositories { google() mavenCentral() maven("https://jitpack.io") } } // app/build.gradle.kts (google-services.json from Firebase goes in app/) plugins { id("com.android.application") id("com.google.gms.google-services") } dependencies { implementation("com.google.firebase:firebase-messaging:23.4.0") implementation("com.github.hibira-io:hibira-push-android:1.0.0") }เริ่มใช้ SDK
import android.app.Application import io.hibira.push.PushNotifications class App : Application() { override fun onCreate() { super.onCreate() PushNotifications.setEndpoint(this, "https://ws.hibira.io") PushNotifications.start(this, "YOUR_INSTANCE_ID") PushNotifications.addDeviceInterest("hello") } }ขอสิทธิ์การแจ้งเตือน
// AndroidManifest.xml: <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> // Android 13+ shows nothing until the user allows notifications. if (Build.VERSION.SDK_INT >= 33) { requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1) }เชื่อมโยงผู้ใช้ที่ลงชื่อเข้าใช้
import io.hibira.push.PushCallback import io.hibira.push.PushCallbackError import io.hibira.push.auth.AuthData import io.hibira.push.auth.AuthDataGetter import io.hibira.push.auth.PushTokenProvider val tokenProvider = PushTokenProvider( "https://api.your-app.example/push/user-token", object : AuthDataGetter { override fun getAuthData() = AuthData( headers = hashMapOf("Authorization" to "Bearer $sessionToken"), ) }, ) PushNotifications.setUserId(userId, tokenProvider, object : PushCallback<Void, PushCallbackError> { override fun onSuccess(vararg values: Void) {} override fun onFailure(error: PushCallbackError) { Log.w("push", error.message) } }) // On sign-out: PushNotifications.stop()
พรอมต์สำหรับเอเจนต์ของ Android
วางข้อความนี้ใน Claude Code, Cursor, GitHub Copilot หรือเอเจนต์เขียนโค้ด AI อื่น ข้อความนี้มี instance ID และ endpoint ส่วน secret key ยังคงเป็นตัวแปรสภาพแวดล้อม
Add Hibira push notifications to this Android 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-push-android, https://github.com/hibira-io/hibira-push-android).
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. Add the JitPack repository and com.github.hibira-io:hibira-push-android (package io.hibira.push; it replaces com.pusher:push-notifications-android). The app needs the Google services Gradle plugin and its google-services.json from the same Firebase project whose service account is uploaded in the portal.
3. Call PushNotifications.setEndpoint and then PushNotifications.start in the Application class (create one and register it in AndroidManifest.xml if the app has none); keep the instance ID and endpoint in BuildConfig fields or resources.
4. On Android 13 and later, declare POST_NOTIFICATIONS in the manifest and request it at a sensible moment (for example after the user turns notifications on), using the project's existing permission approach.
5. If the app has signed-in users, call setUserId with a PushTokenProvider pointing at the backend token endpoint (sending the session credentials) after sign-in, and PushNotifications.stop() on sign-out.
6. Read the instance ID and endpoint from the project's config or environment, and add placeholder entries to .env.example (or its equivalent).
7. Always set the endpoint above. The Pusher Beams SDKs and their defaults point at pusher.com.
8. 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.
9. Subscribe test devices to the "hello" interest so the portal's Send a test reaches them.
10. 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):
Add the Gradle dependencies:
```kotlin
// settings.gradle.kts
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven("https://jitpack.io")
}
}
// app/build.gradle.kts (google-services.json from Firebase goes in app/)
plugins {
id("com.android.application")
id("com.google.gms.google-services")
}
dependencies {
implementation("com.google.firebase:firebase-messaging:23.4.0")
implementation("com.github.hibira-io:hibira-push-android:1.0.0")
}
```
Start the SDK:
```kotlin
import android.app.Application
import io.hibira.push.PushNotifications
class App : Application() {
override fun onCreate() {
super.onCreate()
PushNotifications.setEndpoint(this, "https://ws.hibira.io")
PushNotifications.start(this, "YOUR_INSTANCE_ID")
PushNotifications.addDeviceInterest("hello")
}
}
```
Ask for notification permission:
```kotlin
// AndroidManifest.xml: <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
// Android 13+ shows nothing until the user allows notifications.
if (Build.VERSION.SDK_INT >= 33) {
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1)
}
```
Link the signed-in user:
```kotlin
import io.hibira.push.PushCallback
import io.hibira.push.PushCallbackError
import io.hibira.push.auth.AuthData
import io.hibira.push.auth.AuthDataGetter
import io.hibira.push.auth.PushTokenProvider
val tokenProvider = PushTokenProvider(
"https://api.your-app.example/push/user-token",
object : AuthDataGetter {
override fun getAuthData() = AuthData(
headers = hashMapOf("Authorization" to "Bearer $sessionToken"),
)
},
)
PushNotifications.setUserId(userId, tokenProvider, object : PushCallback<Void, PushCallbackError> {
override fun onSuccess(vararg values: Void) {}
override fun onFailure(error: PushCallbackError) { Log.w("push", error.message) }
})
// On sign-out:
PushNotifications.stop()
```
แอป Swift บน iOS 15+ และ macOS 12+ ส่งผ่าน APNs HibiraPush ↗
ติดตั้ง
// Xcode: File › Add Package Dependencies › https://github.com/hibira-io/hibira-push-ios // or in Package.swift: .package(url: "https://github.com/hibira-io/hibira-push-ios", from: "1.0.0") // Then turn on Signing & Capabilities › Push Notifications for the app target.ลงทะเบียนรับการแจ้งเตือน
import HibiraPush import UIKit final class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { PushNotifications.shared.setEndpoint("https://ws.hibira.io") PushNotifications.shared.start(instanceId: "YOUR_INSTANCE_ID") PushNotifications.shared.registerForRemoteNotifications() try? PushNotifications.shared.addDeviceInterest(interest: "hello") return true } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { PushNotifications.shared.registerDeviceToken(deviceToken) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { PushNotifications.shared.handleNotification(userInfo: userInfo) completionHandler(.noData) } }เชื่อมโยงผู้ใช้ที่ลงชื่อเข้าใช้
let tokenProvider = PushTokenProvider(authURL: "https://api.your-app.example/push/user-token") { AuthData(headers: ["Authorization": "Bearer \(sessionToken)"], queryParams: [:]) } PushNotifications.shared.setUserId(userId, tokenProvider: tokenProvider) { error in if let error = error { print("push:", error) } } // On sign-out: PushNotifications.shared.stop { }
พรอมต์สำหรับเอเจนต์ของ iOS / macOS
วางข้อความนี้ใน Claude Code, Cursor, GitHub Copilot หรือเอเจนต์เขียนโค้ด AI อื่น ข้อความนี้มี instance ID และ endpoint ส่วน secret key ยังคงเป็นตัวแปรสภาพแวดล้อม
Add Hibira push notifications to this iOS / macOS 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: HibiraPush, https://github.com/hibira-io/hibira-push-ios).
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. Add the Swift package https://github.com/hibira-io/hibira-push-ios (product HibiraPush; it replaces pusher/push-notifications-swift and PushNotifications keeps its name) and turn on the Push Notifications capability for the app target.
3. In a SwiftUI app, add a UIApplicationDelegateAdaptor for the AppDelegate in the reference; keep the instance ID and endpoint in an xcconfig or Info.plist entry (the HibiraPushEndpoint Info.plist key also sets the endpoint).
4. Call setEndpoint before start, forward the device token from didRegisterForRemoteNotificationsWithDeviceToken, and pass received notifications to handleNotification.
5. If the app has signed-in users, call setUserId with a PushTokenProvider pointing at the backend token endpoint (sending the session credentials) after sign-in, and stop on sign-out.
6. Remind me that the APNs environment chosen in the portal must match the build: Development (sandbox) for Xcode builds, Production for TestFlight and the App Store.
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:
```swift
// Xcode: File › Add Package Dependencies › https://github.com/hibira-io/hibira-push-ios
// or in Package.swift:
.package(url: "https://github.com/hibira-io/hibira-push-ios", from: "1.0.0")
// Then turn on Signing & Capabilities › Push Notifications for the app target.
```
Register for notifications:
```swift
import HibiraPush
import UIKit
final class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
PushNotifications.shared.setEndpoint("https://ws.hibira.io")
PushNotifications.shared.start(instanceId: "YOUR_INSTANCE_ID")
PushNotifications.shared.registerForRemoteNotifications()
try? PushNotifications.shared.addDeviceInterest(interest: "hello")
return true
}
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
PushNotifications.shared.registerDeviceToken(deviceToken)
}
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
PushNotifications.shared.handleNotification(userInfo: userInfo)
completionHandler(.noData)
}
}
```
Link the signed-in user:
```swift
let tokenProvider = PushTokenProvider(authURL: "https://api.your-app.example/push/user-token") {
AuthData(headers: ["Authorization": "Bearer \(sessionToken)"], queryParams: [:])
}
PushNotifications.shared.setUserId(userId, tokenProvider: tokenProvider) { error in
if let error = error { print("push:", error) }
}
// On sign-out:
PushNotifications.shared.stop { }
```
3. เผยแพร่จากเซิร์ฟเวอร์ของคุณ
Server SDK
เผยแพร่จาก Node.js ด้วย Beams server SDK อย่างเป็นทางการ โดยชี้ไปที่ endpoint ของคุณ @pusher/push-notifications-server ↗
ติดตั้ง
npm install @pusher/push-notifications-serverเผยแพร่ไปยัง 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/' } }, });เพิ่ม endpoint สำหรับโทเค็นผู้ใช้
// 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: '...' } });เผยแพร่ไปยังผู้ใช้ที่ลงชื่อเข้าใช้
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.' } }, });
พรอมต์สำหรับเอเจนต์ของ Node.js
วางข้อความนี้ใน Claude Code, Cursor, GitHub Copilot หรือเอเจนต์เขียนโค้ด AI อื่น ข้อความนี้มี instance ID และ endpoint ส่วน secret key ยังคงเป็นตัวแปรสภาพแวดล้อม
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.' } },
});
```
เผยแพร่จากแอป PHP ใดก็ได้ด้วย Beams server SDK อย่างเป็นทางการ โดยชี้ไปที่ endpoint ของคุณ pusher/pusher-push-notifications ↗
ติดตั้ง
composer require pusher/pusher-push-notificationsเผยแพร่ไปยัง interest
use Pusher\PushNotifications\PushNotifications; $beams = new PushNotifications([ 'instanceId' => 'YOUR_INSTANCE_ID', 'secretKey' => getenv('HIBIRA_PUSH_SECRET_KEY'), 'endpoint' => 'https://ws.hibira.io', ]); $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!']], ]);เพิ่ม endpoint สำหรับโทเค็นผู้ใช้
// GET /push/user-token?user_id=..., for a signed-in user only $userId = (string) $currentUser->id; if (($_GET['user_id'] ?? '') !== $userId) { http_response_code(401); exit; } header('Content-Type: application/json'); echo json_encode($beams->generateToken($userId)); // {"token": "..."}เผยแพร่ไปยังผู้ใช้ที่ลงชื่อเข้าใช้
$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.']], ]);
พรอมต์สำหรับเอเจนต์ของ PHP
วางข้อความนี้ใน Claude Code, Cursor, GitHub Copilot หรือเอเจนต์เขียนโค้ด AI อื่น ข้อความนี้มี instance ID และ endpoint ส่วน secret key ยังคงเป็นตัวแปรสภาพแวดล้อม
Add Hibira push notifications to this PHP 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/pusher-push-notifications, https://github.com/pusher/push-notifications-php).
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 small factory or service that builds PushNotifications from environment variables, always with the endpoint option (without it the SDK talks to pusher.com), and use it wherever the app publishes.
3. If the app has signed-in users, add the token endpoint behind the project's existing session check; it must refuse a user_id that is not the signed-in user's.
4. 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.
5. Always set the endpoint above. The Pusher Beams SDKs and their defaults point at pusher.com.
6. 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.
7. Subscribe test devices to the "hello" interest so the portal's Send a test reaches them.
8. 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
composer require pusher/pusher-push-notifications
```
Publish to an interest:
```php
use Pusher\PushNotifications\PushNotifications;
$beams = new PushNotifications([
'instanceId' => 'YOUR_INSTANCE_ID',
'secretKey' => getenv('HIBIRA_PUSH_SECRET_KEY'),
'endpoint' => 'https://ws.hibira.io',
]);
$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!']],
]);
```
Add the user token endpoint:
```php
// GET /push/user-token?user_id=..., for a signed-in user only
$userId = (string) $currentUser->id;
if (($_GET['user_id'] ?? '') !== $userId) {
http_response_code(401);
exit;
}
header('Content-Type: application/json');
echo json_encode($beams->generateToken($userId)); // {"token": "..."}
```
Publish to a signed-in user:
```php
$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.']],
]);
```
แอป Laravel: binding ใน container พร้อม endpoint ของคุณ route สำหรับโทเค็น และการเผยแพร่จาก job pusher/pusher-push-notifications ↗
ติดตั้ง
composer require pusher/pusher-push-notificationsตั้งค่าข้อมูลรับรองของพุช
HIBIRA_PUSH_INSTANCE_ID=YOUR_INSTANCE_ID HIBIRA_PUSH_SECRET_KEY= HIBIRA_PUSH_ENDPOINT=https://ws.hibira.ioBind ไคลเอนต์
// config/services.php 'hibira_push' => [ 'instance_id' => env('HIBIRA_PUSH_INSTANCE_ID'), 'secret_key' => env('HIBIRA_PUSH_SECRET_KEY'), 'endpoint' => env('HIBIRA_PUSH_ENDPOINT'), ], // app/Providers/AppServiceProvider.php, in register() $this->app->singleton(\Pusher\PushNotifications\PushNotifications::class, fn () => new \Pusher\PushNotifications\PushNotifications([ 'instanceId' => config('services.hibira_push.instance_id'), 'secretKey' => config('services.hibira_push.secret_key'), 'endpoint' => config('services.hibira_push.endpoint'), ]));เพิ่ม endpoint สำหรับโทเค็นผู้ใช้
// routes/web.php (or routes/api.php with your API guard) use Illuminate\Http\Request; use Pusher\PushNotifications\PushNotifications; Route::middleware('auth')->get('/push/user-token', function (Request $request, PushNotifications $beams) { $userId = (string) $request->user()->id; abort_unless($request->query('user_id') === $userId, 401); return $beams->generateToken($userId); // {"token": "..."} });เผยแพร่ไปยังผู้ใช้ที่ลงชื่อเข้าใช้
app(\Pusher\PushNotifications\PushNotifications::class)->publishToUsers([(string) $order->user_id], [ 'apns' => ['aps' => ['alert' => ['title' => 'Order shipped', 'body' => "Order #{$order->id} is on its way."]]], 'fcm' => ['notification' => ['title' => 'Order shipped', 'body' => "Order #{$order->id} is on its way."]], 'web' => ['notification' => ['title' => 'Order shipped', 'body' => "Order #{$order->id} is on its way."]], ]);
พรอมต์สำหรับเอเจนต์ของ Laravel
วางข้อความนี้ใน Claude Code, Cursor, GitHub Copilot หรือเอเจนต์เขียนโค้ด AI อื่น ข้อความนี้มี instance ID และ endpoint ส่วน secret key ยังคงเป็นตัวแปรสภาพแวดล้อม
Add Hibira push notifications to this Laravel 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/pusher-push-notifications, https://github.com/pusher/push-notifications-php).
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. Add the HIBIRA_PUSH_* entries to .env and .env.example, the hibira_push block to config/services.php, and the singleton binding in AppServiceProvider::register, always passing the endpoint (without it the SDK talks to pusher.com).
3. If the project uses laravel-notification-channels/pusher-push-notifications, also bind PushNotifications for its PusherChannel with the same options, because the package builds its own client without an endpoint.
4. Add the token route behind the project's existing auth middleware (web session or API guard, whichever the mobile and web clients use); it must refuse a user_id that is not the signed-in user's.
5. Publish from queued jobs or notifications rather than inside the request where possible.
6. 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.
7. Always set the endpoint above. The Pusher Beams SDKs and their defaults point at pusher.com.
8. 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.
9. Subscribe test devices to the "hello" interest so the portal's Send a test reaches them.
10. 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
composer require pusher/pusher-push-notifications
```
Set your push credentials:
```ini
HIBIRA_PUSH_INSTANCE_ID=YOUR_INSTANCE_ID
HIBIRA_PUSH_SECRET_KEY=
HIBIRA_PUSH_ENDPOINT=https://ws.hibira.io
```
Bind the client:
```php
// config/services.php
'hibira_push' => [
'instance_id' => env('HIBIRA_PUSH_INSTANCE_ID'),
'secret_key' => env('HIBIRA_PUSH_SECRET_KEY'),
'endpoint' => env('HIBIRA_PUSH_ENDPOINT'),
],
// app/Providers/AppServiceProvider.php, in register()
$this->app->singleton(\Pusher\PushNotifications\PushNotifications::class, fn () => new \Pusher\PushNotifications\PushNotifications([
'instanceId' => config('services.hibira_push.instance_id'),
'secretKey' => config('services.hibira_push.secret_key'),
'endpoint' => config('services.hibira_push.endpoint'),
]));
```
Add the user token endpoint:
```php
// routes/web.php (or routes/api.php with your API guard)
use Illuminate\Http\Request;
use Pusher\PushNotifications\PushNotifications;
Route::middleware('auth')->get('/push/user-token', function (Request $request, PushNotifications $beams) {
$userId = (string) $request->user()->id;
abort_unless($request->query('user_id') === $userId, 401);
return $beams->generateToken($userId); // {"token": "..."}
});
```
Publish to a signed-in user:
```php
app(\Pusher\PushNotifications\PushNotifications::class)->publishToUsers([(string) $order->user_id], [
'apns' => ['aps' => ['alert' => ['title' => 'Order shipped', 'body' => "Order #{$order->id} is on its way."]]],
'fcm' => ['notification' => ['title' => 'Order shipped', 'body' => "Order #{$order->id} is on its way."]],
'web' => ['notification' => ['title' => 'Order shipped', 'body' => "Order #{$order->id} is on its way."]],
]);
```
เผยแพร่จาก Django, Flask, FastAPI หรือสคริปต์ด้วย Beams server SDK อย่างเป็นทางการ pusher_push_notifications ↗
ติดตั้ง
pip install pusher_push_notificationsเผยแพร่ไปยัง interest
import os from pusher_push_notifications import PushNotifications beams = PushNotifications( instance_id='YOUR_INSTANCE_ID', secret_key=os.environ['HIBIRA_PUSH_SECRET_KEY'], endpoint='ws.hibira.io', # host only; the SDK always uses https ) beams.publish_to_interests( interests=['hello'], publish_body={ 'apns': {'aps': {'alert': {'title': 'Hello', 'body': 'Hello, world!'}}}, 'fcm': {'notification': {'title': 'Hello', 'body': 'Hello, world!'}}, 'web': {'notification': {'title': 'Hello', 'body': 'Hello, world!'}}, }, )เพิ่ม endpoint สำหรับโทเค็นผู้ใช้
# Flask: GET /push/user-token?user_id=..., for a signed-in user only def push_user_token(): user_id = str(current_user.id) if request.args.get('user_id') != user_id: abort(401) return beams.generate_token(user_id) # {'token': '...'}เผยแพร่ไปยังผู้ใช้ที่ลงชื่อเข้าใช้
beams.publish_to_users( user_ids=['user-1'], publish_body={ '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.'}}, }, )
พรอมต์สำหรับเอเจนต์ของ Python
วางข้อความนี้ใน Claude Code, Cursor, GitHub Copilot หรือเอเจนต์เขียนโค้ด AI อื่น ข้อความนี้มี instance ID และ endpoint ส่วน secret key ยังคงเป็นตัวแปรสภาพแวดล้อม
Add Hibira push notifications to this Python 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, https://github.com/pusher/push-notifications-python).
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 module that builds PushNotifications from environment variables (or the framework's settings), always with endpoint set to the host from the reference (without it the SDK talks to pusher.com).
3. If the app has signed-in users, add the token view or route in the project's framework behind its existing login check; it must refuse a user_id that is not the signed-in user's.
4. 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.
5. Always set the endpoint above. The Pusher Beams SDKs and their defaults point at pusher.com.
6. 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.
7. Subscribe test devices to the "hello" interest so the portal's Send a test reaches them.
8. 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
pip install pusher_push_notifications
```
Publish to an interest:
```python
import os
from pusher_push_notifications import PushNotifications
beams = PushNotifications(
instance_id='YOUR_INSTANCE_ID',
secret_key=os.environ['HIBIRA_PUSH_SECRET_KEY'],
endpoint='ws.hibira.io', # host only; the SDK always uses https
)
beams.publish_to_interests(
interests=['hello'],
publish_body={
'apns': {'aps': {'alert': {'title': 'Hello', 'body': 'Hello, world!'}}},
'fcm': {'notification': {'title': 'Hello', 'body': 'Hello, world!'}},
'web': {'notification': {'title': 'Hello', 'body': 'Hello, world!'}},
},
)
```
Add the user token endpoint:
```python
# Flask: GET /push/user-token?user_id=..., for a signed-in user only
def push_user_token():
user_id = str(current_user.id)
if request.args.get('user_id') != user_id:
abort(401)
return beams.generate_token(user_id) # {'token': '...'}
```
Publish to a signed-in user:
```python
beams.publish_to_users(
user_ids=['user-1'],
publish_body={
'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.'}},
},
)
```
เผยแพร่จากบริการ Go ด้วย Beams server SDK อย่างเป็นทางการและ base URL ที่กำหนดเอง push-notifications-go ↗
ติดตั้ง
go get github.com/pusher/push-notifications-goเผยแพร่ไปยัง interest
import ( "os" pushnotifications "github.com/pusher/push-notifications-go" ) beams, err := pushnotifications.New("YOUR_INSTANCE_ID", os.Getenv("HIBIRA_PUSH_SECRET_KEY"), pushnotifications.WithCustomBaseURL("https://ws.hibira.io")) if err != nil { return err } publishID, err := beams.PublishToInterests([]string{"hello"}, map[string]interface{}{ "apns": map[string]interface{}{"aps": map[string]interface{}{ "alert": map[string]interface{}{"title": "Hello", "body": "Hello, world!"}}}, "fcm": map[string]interface{}{ "notification": map[string]interface{}{"title": "Hello", "body": "Hello, world!"}}, "web": map[string]interface{}{ "notification": map[string]interface{}{"title": "Hello", "body": "Hello, world!"}}, })เพิ่ม endpoint สำหรับโทเค็นผู้ใช้
// GET /push/user-token?user_id=..., behind your session middleware http.HandleFunc("/push/user-token", func(w http.ResponseWriter, r *http.Request) { userID := currentUserID(r) if userID == "" || r.URL.Query().Get("user_id") != userID { http.Error(w, "unauthorized", http.StatusUnauthorized) return } token, err := beams.GenerateToken(userID) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(token) // {"token": "..."} })เผยแพร่ไปยังผู้ใช้ที่ลงชื่อเข้าใช้
publishID, err := beams.PublishToUsers([]string{"user-1"}, map[string]interface{}{ "fcm": map[string]interface{}{ "notification": map[string]interface{}{"title": "Order shipped", "body": "Order #1024 is on its way."}}, "apns": map[string]interface{}{"aps": map[string]interface{}{ "alert": map[string]interface{}{"title": "Order shipped", "body": "Order #1024 is on its way."}}}, })
พรอมต์สำหรับเอเจนต์ของ Go
วางข้อความนี้ใน Claude Code, Cursor, GitHub Copilot หรือเอเจนต์เขียนโค้ด AI อื่น ข้อความนี้มี instance ID และ endpoint ส่วน secret key ยังคงเป็นตัวแปรสภาพแวดล้อม
Add Hibira push notifications to this Go 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: push-notifications-go, https://github.com/pusher/push-notifications-go).
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. Build one pushnotifications client at startup from environment variables, always with pushnotifications.WithCustomBaseURL (without it the SDK talks to pusher.com), and pass it to the code that publishes.
3. If the service has signed-in users, add the token handler behind the existing session or auth middleware; it must refuse a user_id that is not the signed-in user's.
4. 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.
5. Always set the endpoint above. The Pusher Beams SDKs and their defaults point at pusher.com.
6. 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.
7. Subscribe test devices to the "hello" interest so the portal's Send a test reaches them.
8. 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
go get github.com/pusher/push-notifications-go
```
Publish to an interest:
```go
import (
"os"
pushnotifications "github.com/pusher/push-notifications-go"
)
beams, err := pushnotifications.New("YOUR_INSTANCE_ID", os.Getenv("HIBIRA_PUSH_SECRET_KEY"),
pushnotifications.WithCustomBaseURL("https://ws.hibira.io"))
if err != nil {
return err
}
publishID, err := beams.PublishToInterests([]string{"hello"}, map[string]interface{}{
"apns": map[string]interface{}{"aps": map[string]interface{}{
"alert": map[string]interface{}{"title": "Hello", "body": "Hello, world!"}}},
"fcm": map[string]interface{}{
"notification": map[string]interface{}{"title": "Hello", "body": "Hello, world!"}},
"web": map[string]interface{}{
"notification": map[string]interface{}{"title": "Hello", "body": "Hello, world!"}},
})
```
Add the user token endpoint:
```go
// GET /push/user-token?user_id=..., behind your session middleware
http.HandleFunc("/push/user-token", func(w http.ResponseWriter, r *http.Request) {
userID := currentUserID(r)
if userID == "" || r.URL.Query().Get("user_id") != userID {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
token, err := beams.GenerateToken(userID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(token) // {"token": "..."}
})
```
Publish to a signed-in user:
```go
publishID, err := beams.PublishToUsers([]string{"user-1"}, map[string]interface{}{
"fcm": map[string]interface{}{
"notification": map[string]interface{}{"title": "Order shipped", "body": "Order #1024 is on its way."}},
"apns": map[string]interface{}{"aps": map[string]interface{}{
"alert": map[string]interface{}{"title": "Order shipped", "body": "Order #1024 is on its way."}}},
})
```
ภาษาใดก็ได้ หรือทดสอบเร็วๆ จากเทอร์มินัล: API การเผยแพร่เป็น HTTPS และ JSON ธรรมดา REST API ↗
เผยแพร่ไปยัง interest
curl -X POST "https://ws.hibira.io/publish_api/v1/instances/YOUR_INSTANCE_ID/publishes/interests" \ -H "Authorization: Bearer $HIBIRA_PUSH_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "interests": ["hello"], "apns": {"aps": {"alert": {"title": "Hello", "body": "Hello, world!"}}}, "fcm": {"notification": {"title": "Hello", "body": "Hello, world!"}}, "web": {"notification": {"title": "Hello", "body": "Hello, world!"}} }' # {"publishId":"pubid-..."}เผยแพร่ไปยังผู้ใช้ที่ลงชื่อเข้าใช้
curl -X POST "https://ws.hibira.io/publish_api/v1/instances/YOUR_INSTANCE_ID/publishes/users" \ -H "Authorization: Bearer $HIBIRA_PUSH_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"users": ["user-1"], "fcm": {"notification": {"title": "Order shipped", "body": "Order #1024 is on its way."}}}'ลบผู้ใช้
# Unlinks every device of the user, for example when their account is deleted. curl -X DELETE "https://ws.hibira.io/customer_api/v1/instances/YOUR_INSTANCE_ID/users/user-1" \ -H "Authorization: Bearer $HIBIRA_PUSH_SECRET_KEY"
พรอมต์สำหรับเอเจนต์ของ curl / HTTP
วางข้อความนี้ใน Claude Code, Cursor, GitHub Copilot หรือเอเจนต์เขียนโค้ด AI อื่น ข้อความนี้มี instance ID และ endpoint ส่วน secret key ยังคงเป็นตัวแปรสภาพแวดล้อม
Add Hibira push notifications to this curl / HTTP 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: REST API, https://hibira.io/guides/push-notifications).
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. Use the HTTP client the project already has; send JSON with Authorization: Bearer and the secret key from the environment.
3. A publish takes up to 100 interests or 1,000 user IDs; split larger audiences across several requests and retry a 429 response after the Retry-After delay.
4. User tokens for the client SDKs are HS256 JWTs signed with the secret key, with sub set to the user ID, iss set to https://<instance ID>.pushnotifications.pusher.com and exp in the future; prefer a maintained JWT library to build them.
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):
Publish to an interest:
```shell
curl -X POST "https://ws.hibira.io/publish_api/v1/instances/YOUR_INSTANCE_ID/publishes/interests" \
-H "Authorization: Bearer $HIBIRA_PUSH_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{
"interests": ["hello"],
"apns": {"aps": {"alert": {"title": "Hello", "body": "Hello, world!"}}},
"fcm": {"notification": {"title": "Hello", "body": "Hello, world!"}},
"web": {"notification": {"title": "Hello", "body": "Hello, world!"}}
}'
# {"publishId":"pubid-..."}
```
Publish to a signed-in user:
```shell
curl -X POST "https://ws.hibira.io/publish_api/v1/instances/YOUR_INSTANCE_ID/publishes/users" \
-H "Authorization: Bearer $HIBIRA_PUSH_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"users": ["user-1"], "fcm": {"notification": {"title": "Order shipped", "body": "Order #1024 is on its way."}}}'
```
Delete a user:
```shell
# Unlinks every device of the user, for example when their account is deleted.
curl -X DELETE "https://ws.hibira.io/customer_api/v1/instances/YOUR_INSTANCE_ID/users/user-1" \
-H "Authorization: Bearer $HIBIRA_PUSH_SECRET_KEY"
```
4. ผู้ใช้ที่ลงชื่อเข้าใช้
หากต้องการส่งถึงบุคคลหนึ่งบนทุกอุปกรณ์ที่เขาใช้ ให้เชื่อมโยงแต่ละอุปกรณ์กับ user ID ของคุณเอง client SDK จะเรียก endpoint สำหรับโทเค็นของคุณด้วย ?user_id=… endpoint ตรวจสอบว่าคำขอมาจากผู้ใช้ที่ลงชื่อเข้าใช้คนนั้น แล้วตอบกลับด้วยโทเค็นที่ generateToken สร้างจาก secret key ของคุณ (Beams server SDK ทุกตัวมีฟังก์ชันนี้) จากนั้นเผยแพร่ไปยัง user ID แทน interest การลบผู้ใช้จะยกเลิกการเชื่อมโยงอุปกรณ์ทั้งหมดของผู้ใช้นั้น
เรียก stop เมื่อผู้ใช้ออกจากระบบ เพื่อไม่ให้คนถัดไปบนอุปกรณ์นั้นได้รับการแจ้งเตือนของเขา
5. ส่งทดสอบ
ในหน้าแอป ใต้ Push notifications › Send a test ให้ป้อน interest (hello ในโค้ดตัวอย่างด้านบน) หัวข้อ และเนื้อหา แล้วคลิกส่งทดสอบ อุปกรณ์ที่สมัครรับ interest นั้นจะได้รับภายในไม่กี่วินาที และมาตรวัดผู้สมัครรับข้อมูลจะแสดงจำนวนอุปกรณ์และเบราว์เซอร์ที่ลงทะเบียนแล้ว
การแก้ปัญหา
- อุปกรณ์หรือเบราว์เซอร์ไม่ปรากฏในผู้สมัครรับข้อมูลเลย
- ตรวจสอบว่าไคลเอนต์เรียก start ด้วย instance ID และ endpoint ของแอปนี้ และผู้ใช้อนุญาตการแจ้งเตือนแล้ว บน Android ไฟล์ google-services.json ต้องมาจากโปรเจกต์ Firebase เดียวกับ service account ที่คุณอัปโหลด
- iPhone และ iPad ไม่ได้รับอะไรเลย
- สภาพแวดล้อม APNs ต้องตรงกับบิลด์: Development (sandbox) สำหรับบิลด์ที่รันจาก Xcode และ Production สำหรับ TestFlight และ App Store bundle ID ต้องตรงกับแอปทุกตัวอักษร และ target ของแอปต้องมีความสามารถ Push Notifications
- start() ล้มเหลวพร้อมข้อความ “service worker missing”
- ให้บริการ /service-worker.js จากรากของเว็บไซต์ผ่าน HTTPS พร้อมบรรทัด importScripts จากคู่มือเว็บ service worker ในโฟลเดอร์ย่อยจะควบคุมได้เฉพาะโฟลเดอร์นั้น
- Safari บน iPhone ไม่ขอสิทธิ์เลย
- Web Push บน iOS และ iPadOS 16.4+ ใช้ได้หลังจากเพิ่มเว็บไซต์ลงในหน้าจอโฮมแล้วเท่านั้น และการขอสิทธิ์ต้องเกิดจากการแตะ
- Server SDK ยังเรียก pusher.com หรือล้มเหลวผ่าน http
- ตั้งค่าตัวเลือก endpoint SDK ของ Node.js ต้องใช้ beams.protocol = 'https' ด้วย และ SDK ของ Go ใช้ WithCustomBaseURL
- การเผยแพร่ได้รับ 401
- เซิร์ฟเวอร์ใช้ secret key ผิด หรือ key ที่ถูกเปลี่ยนนานเกินช่วงผ่อนผันแล้ว คัดลอก key ปัจจุบันจากหน้าแอป
- การเผยแพร่ได้รับ 429
- คุณเผยแพร่เร็วกว่าที่แพ็กเกจอนุญาต รอตามระยะเวลา Retry-After และกำหนดเป้าหมายสูงสุด 100 interest หรือ 1,000 ผู้ใช้ในการเผยแพร่ครั้งเดียว แทนที่จะส่งทีละคำขอ
- การลงทะเบียนอุปกรณ์ได้รับ 402
- แอปถึงขีดจำกัดผู้สมัครรับข้อมูลของแพ็กเกจแล้ว อัปเกรดแพ็กเกจ หรือลบผู้ใช้ที่ออกไปแล้วเพื่อลบอุปกรณ์ของพวกเขา
- setUserId ล้มเหลว
- Endpoint สำหรับโทเค็นของคุณต้องตอบกลับ 200 พร้อม JSON ที่ generateToken ส่งกลับสำหรับ user_id ที่ถูกถาม โดยใช้ secret key ของแอปนี้ อุปกรณ์ที่เชื่อมโยงกับผู้ใช้อื่นต้องเรียก stop ก่อน
ย้ายมาจาก Pusher Beams ใช่ไหม? เปลี่ยนแพ็กเกจ client SDK มาใช้ของเรา ตั้งค่า endpoint ใน server SDK อัปโหลดคีย์ APNs และ service account ของ FCM แล้วเผยแพร่ไปยังทั้งสองบริการจนกว่าผู้ใช้จะอัปเดต อุปกรณ์จะลงทะเบียนใหม่เมื่อเริ่มใช้งานครั้งแรก ย้ายจาก Pusher →