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

React Native集成AWS Pinpoint:为已登录Cognito用户设置EndpointId并推送通知

解决Pinpoint关联Cognito用户并推送通知的问题

嘿,我来帮你搞定这个问题!核心逻辑其实很清晰:Pinpoint的Endpoint是和设备绑定的实体,你只需要把已登录的Cognito用户ID关联到设备对应的Endpoint上,之后就能通过用户ID直接找到所有关联的设备,不用手动存令牌到DynamoDB啦。下面分步骤给你讲:

一、在React Native端关联Endpoint与Cognito用户ID

当你用AWS Amplify集成Push Notifications后,Amplify会自动为每个注册推送的设备创建一个Pinpoint Endpoint。用户登录后,你需要把Cognito的用户ID更新到这个Endpoint的User属性里,完成关联。

import { PushNotifications } from 'aws-amplify';
import { Auth } from 'aws-amplify';

// 用户登录成功后调用这个函数
const linkUserToEndpoint = async () => {
  try {
    // 获取当前登录的Cognito用户信息
    const currentUser = await Auth.currentAuthenticatedUser();
    const userId = currentUser.attributes.sub; // 这里用sub作为用户唯一标识,也可以用你自定义的用户ID字段

    // 获取当前设备对应的Pinpoint Endpoint信息
    const currentEndpoint = await PushNotifications.getEndpoint();

    // 更新Endpoint,把用户ID关联进去
    await PushNotifications.updateEndpoint({
      Address: currentEndpoint.Address, // 设备的推送令牌
      EndpointId: currentEndpoint.EndpointId,
      User: {
        UserId: userId,
        // 可选:添加其他用户属性,方便后续精准推送
        UserAttributes: {
          email: currentUser.attributes.email
        }
      }
    });

    console.log('用户与Endpoint关联成功!');
  } catch (error) {
    console.error('关联失败:', error);
  }
};

二、在Lambda中根据用户ID获取所有关联的Endpoints

你之前用的getEndpoint是根据单个Endpoint ID查询,但其实Pinpoint提供了listEndpointsByUser方法,可以直接通过用户ID获取该用户所有绑定的设备Endpoint。修改你的Lambda代码如下:

const AWS = require('aws-sdk');
const pinpoint = new AWS.Pinpoint();
const APP_ID_PINPOINT = '你的Pinpoint应用ID';

app.post('/asdf/get/user-endpoints', async (req, res) => {
  try {
    const { userId } = req.body;
    const params = {
      ApplicationId: APP_ID_PINPOINT,
      UserId: userId
    };

    // 查询该用户所有关联的Endpoints
    const response = await pinpoint.listEndpointsByUser(params).promise();
    // 返回用户的所有Endpoint列表
    res.json({ data: response.EndpointsResponse.Item });
  } catch (err) {
    res.json({ error: err.message || err });
  }
});

三、推送方式的选择建议

  • 推荐用Pinpoint自带的用户关联机制:这种方式下,Pinpoint会自动帮你管理Endpoint的状态(比如设备卸载APP后,令牌失效会被标记为Disabled),你只需要调用sendMessages或者sendUsersMessages接口,传入用户ID就能推送到该用户的所有设备,不用自己维护令牌列表。
  • 手动存令牌到DynamoDB:这种方式需要你自己处理令牌的新增、删除、失效逻辑,比较繁琐,除非你有特殊的业务需求,否则不推荐。

举个推送的例子,在Lambda中给指定用户发通知:

const sendNotificationToUser = async (userId, messageContent) => {
  const params = {
    ApplicationId: APP_ID_PINPOINT,
    SendUsersMessageRequest: {
      Users: {
        [userId]: {}
      },
      MessageConfiguration: {
        APNSMessage: { // iOS平台,安卓用GCMMessage
          Title: '通知标题',
          Body: messageContent,
          Sound: 'default'
        }
      }
    }
  };

  await pinpoint.sendUsersMessages(params).promise();
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:17:43