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

如何在Expo/Laravel中向特定用户推送通知

Expo + Laravel 定向推送通知实现指南

核心工作机制

Expo推送的逻辑很直白:

  1. 前端Expo应用向Expo服务器申请推送令牌(Push Token),这个令牌是用户设备的唯一标识
  2. 前端把令牌传给Laravel后端,关联到对应用户存入数据库
  3. 后端需要推送时,调用Exponent Notifications库,将通知内容+目标用户令牌发给Expo服务器
  4. Expo服务器负责把通知投递到指定设备

前端(Expo)监听通知&获取令牌

1. 申请权限并获取令牌

先请求用户授权通知权限,再拿到令牌传给后端:

import * as Notifications from 'expo-notifications';
import axios from 'axios';

// 请求通知权限
async function requestPerms() {
  const { status } = await Notifications.requestPermissionsAsync();
  if (status !== 'granted') {
    alert('得开通知权限才能收推送哦');
    return;
  }
}

// 获取令牌并传给后端
async function sendTokenToBackend() {
  const token = (await Notifications.getExpoPushTokenAsync()).data;
  await axios.post('/api/save-push-token', { token });
}

// 初始化时执行
useEffect(() => {
  requestPerms();
  sendTokenToBackend();
}, []);

2. 监听通知接收/点击

不管App在前台后台,都能监听通知事件:

// 监听前台收到通知(可自定义弹窗)
Notifications.addNotificationReceivedListener(notification => {
  console.log('前台收到通知:', notification);
  // 这里可以写自定义弹窗逻辑
});

// 监听用户点击通知(前台/后台都触发)
Notifications.addNotificationResponseReceivedListener(response => {
  console.log('用户点了通知:', response);
  // 比如跳转到对应页面
});

后端(Laravel)发送定向通知

1. 基础配置

在.env里可配置Expo密钥(公开Expo项目可不填,专属项目按需添加):

EXPONENT_PUSH_KEY=你的Expo密钥(可选)

如果需要自定义配置,发布库的配置文件:

php artisan vendor:publish --provider="Alymosul\ExponentPushNotifications\ExponentPushNotificationsServiceProvider"

2. 存储用户推送令牌

先建push_tokens表,字段包含user_id(关联用户)、token(Expo令牌)。

在User模型里定义关联:

public function pushTokens()
{
    return $this->hasMany(PushToken::class);
}

写API接口接收前端传的令牌:

// routes/api.php
Route::post('/save-push-token', [PushTokenController::class, 'store']);

// PushTokenController.php
public function store(Request $request)
{
    $request->validate(['token' => 'required|string']);

    // 给当前登录用户绑定令牌(已存在则更新)
    auth()->user()->pushTokens()->updateOrCreate(
        ['token' => $request->token],
        ['token' => $request->token]
    );

    return response()->json(['msg' => '令牌保存成功']);
}

3. 给特定用户发通知

创建Laravel通知类:

// app/Notifications/ExpoPush.php
namespace App\Notifications;

use Alymosul\ExponentPushNotifications\ExpoChannel;
use Alymosul\ExponentPushNotifications\ExpoMessage;
use Illuminate\Notifications\Notification;

class ExpoPush extends Notification
{
    protected $title;
    protected $content;

    public function __construct($title, $content)
    {
        $this->title = $title;
        $this->content = $content;
    }

    public function via($notifiable)
    {
        return [ExpoChannel::class];
    }

    public function toExpo($notifiable)
    {
        return ExpoMessage::create()
            ->title($this->title)
            ->body($this->content)
            ->sound('default'); // 可选,设置通知音效
    }
}

在控制器里给特定用户发送:

// 给ID为1的用户发通知
$user = User::find(1);
$user->notify(new ExpoPush('新消息提醒', '你有一条未读私信'));

// 给多个特定用户发通知
$users = User::whereIn('id', [1,3,5])->get();
Notification::send($users, new ExpoPush('系统通知', '今晚服务器维护'));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:09:15