You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于PHP Curl与AngularJS 1.x的推送通知:如何获取注册ID?

嘿,我来帮你理清楚怎么获取注册ID用于推送~结合你现有的AngularJS 1.x + PHP Curl架构,核心思路是「客户端获取→后端存储→推送时取出」,具体步骤如下:

1. 客户端(AngularJS 1.x)获取注册ID

注册ID本质是推送服务(比如FCM、Web Push)给客户端分配的唯一标识,不同推送场景的获取方式略有不同:

场景A:Web Push(浏览器通知)

需要借助Service Worker来获取推送订阅信息,其中的endpoint就是我们要的注册ID:

angular.module('yourNotificationApp')
.controller('AdminNotificationCtrl', function($http) {
  // 先检查浏览器支持情况
  if ('serviceWorker' in navigator && 'PushManager' in window) {
    // 注册Service Worker
    navigator.serviceWorker.register('/sw.js')
    .then(reg => reg.pushManager.subscribe({
      userVisibleOnly: true, // 要求通知必须对用户可见
      applicationServerKey: urlBase64ToUint8Array('你的VAPID公钥')
    }))
    .then(subscription => {
      // 提取注册ID(endpoint)
      const registrationId = subscription.endpoint;
      // 传给后端存储,记得带上当前用户ID(方便后续定向推送)
      $http.post('/save-reg-id.php', {
        regId: registrationId,
        userId: '当前登录管理员/用户的ID'
      }).then(res => {
        console.log('注册ID已成功保存');
      });
    });
  }
});

// 辅助工具函数:把VAPID公钥转换为Uint8Array格式
function urlBase64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
  const rawData = window.atob(base64);
  return Uint8Array.from([...rawData].map(char => char.charCodeAt(0)));
}

场景B:FCM(Firebase云消息推送,支持Web/移动端)

如果用FCM,直接调用官方SDK获取token(即注册ID):

// 先在页面引入FCM SDK,再初始化
firebase.initializeApp({
  apiKey: "你的FCM API密钥",
  projectId: "你的Firebase项目ID"
});

const messaging = firebase.messaging();
// 先请求用户通知权限
messaging.requestPermission()
.then(() => messaging.getToken())
.then(token => {
  // token就是注册ID,传给后端存储
  $http.post('/save-reg-id.php', {
    regId: token,
    userId: '当前用户ID'
  });
});
2. 后端(PHP)存储注册ID

写一个接口接收客户端传的注册ID,存入数据库(这里以MySQL+PDO为例):

<?php
// 数据库连接配置
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'db_username', 'db_password');
header('Content-Type: application/json');

// 接收前端传的JSON数据
$input = json_decode(file_get_contents('php://input'), true);
$regId = $pdo->quote($input['regId']);
$userId = $pdo->quote($input['userId']);

// 插入或更新:同一个用户可能有多个设备,保留多条或更新旧条目都可以
$sql = "INSERT INTO user_registrations (user_id, reg_id, created_at) 
        VALUES ($userId, $regId, NOW()) 
        ON DUPLICATE KEY UPDATE reg_id = $regId, updated_at = NOW()";

if ($pdo->exec($sql)) {
  echo json_encode(['status' => 'success']);
} else {
  echo json_encode(['status' => 'error']);
}
?>
3. 推送时获取注册ID并调用Curl

当管理员在AngularJS里点击「发送通知」时,先从后端取出目标用户的注册ID,再传给你的curl-service.php发送推送:

AngularJS点击事件逻辑

$scope.sendAdminNotification = function() {
  // 示例:获取所有用户的注册ID,也可以根据需求传指定用户ID获取
  $http.get('/get-reg-ids.php')
  .then(res => {
    const targetRegIds = res.data;
    // 把通知内容和注册ID传给推送接口
    return $http.post('/curl-service.php', {
      regIds: targetRegIds,
      title: '管理员通知',
      body: $scope.notificationContent // 从输入框获取的通知内容
    });
  })
  .then(res => {
    alert('通知已成功发送!');
  })
  .catch(err => {
    console.error('发送失败:', err);
  });
};

后端获取注册ID接口(get-reg-ids.php)

<?php
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'db_username', 'db_password');
header('Content-Type: application/json');

// 示例:获取所有注册ID,也可以加WHERE条件筛选特定用户
$sql = "SELECT reg_id FROM user_registrations";
$stmt = $pdo->query($sql);
$regIds = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);

echo json_encode($regIds);
?>

最后在curl-service.php里用注册ID发送推送

以FCM为例,修改你的现有Curl脚本:

<?php
header('Content-Type: application/json');
$input = json_decode(file_get_contents('php://input'), true);

$apiKey = '你的FCM服务器密钥';
$url = 'https://fcm.googleapis.com/fcm/send';

$headers = [
  'Authorization: key=' . $apiKey,
  'Content-Type: application/json'
];

// 构造推送 payload
$payload = [
  'registration_ids' => $input['regIds'], // 传入获取到的注册ID数组
  'notification' => [
    'title' => $input['title'],
    'body' => $input['body'],
    'click_action' => 'https://你的网站地址' // 用户点击通知跳转的链接
  ]
];

// 执行Curl请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

$result = curl_exec($ch);
curl_close($ch);

echo $result;
?>
关键注意事项
  • 用户关联:一定要把注册ID和用户ID绑定,这样才能实现定向推送(比如推给某个特定用户),而不是全量广播。
  • 过期清理:注册ID可能会过期(比如用户卸载App、清除浏览器数据),后端要处理推送失败的响应,把无效的注册ID从数据库中删除。
  • 权限前置:不管是Web还是移动端,都必须先获得用户的通知权限,否则无法获取注册ID。

内容的提问来源于stack exchange,提问作者neomat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:46:43