feat(push-notification): 添加用户登录后自动更新推送token绑定功能

- 新增updateTokenUserId方法用于更新设备令牌的用户ID绑定关系
- 添加onUserLogin方法在用户登录成功后自动更新token绑定
- 优化checkAndRegisterToken逻辑,确保每次应用启动都更新用户ID绑定
- 修改UpdateTokenRequest接口,将appVersion和osVersion设为可选参数
- 在用户登录成功后自动触发推送token用户ID绑定更新
This commit is contained in:
richarjiang
2025-11-03 17:58:17 +08:00
parent 635d835a50
commit fbffa07f74
4 changed files with 74 additions and 4 deletions

View File

@@ -161,6 +161,7 @@ export class PushNotificationManager {
/**
* 检查并注册设备令牌
* 每次应用启动都会上报token更新用户ID绑定关系
*/
private async checkAndRegisterToken(token: string): Promise<void> {
try {
@@ -171,7 +172,8 @@ export class PushNotificationManager {
if (!isRegistered || storedToken !== token) {
await this.registerDeviceToken(token);
} else {
console.log('设备令牌已注册,无需重复注册');
// 令牌已注册且未变化更新用户ID绑定关系
await this.updateTokenUserId(token);
}
} catch (error) {
console.error('检查和注册设备令牌失败:', error);
@@ -179,6 +181,47 @@ export class PushNotificationManager {
}
}
/**
* 更新设备令牌的用户ID绑定关系
* 用户ID从服务端通过header中的token解析获取
*/
private async updateTokenUserId(token: string): Promise<boolean> {
try {
logger.info('更新设备令牌用户ID绑定:', token.substring(0, 20) + '...');
// 调用服务端API更新token用户ID绑定关系
const response = await pushNotificationService.updateTokenUserId(token);
console.log('设备令牌用户ID绑定更新成功:', response.tokenId);
return true;
} catch (error) {
console.error('更新设备令牌用户ID绑定失败:', error);
// 如果更新用户ID绑定失败尝试重新注册token
console.log('尝试重新注册设备令牌...');
return this.registerDeviceToken(token);
}
}
/**
* 用户登录成功后调用此方法更新token用户ID绑定
*/
async onUserLogin(): Promise<boolean> {
try {
const token = this.currentToken || await this.getDeviceToken();
if (!token) {
console.warn('未找到设备令牌无法更新用户ID绑定');
return false;
}
return await this.updateTokenUserId(token);
} catch (error) {
console.error('用户登录后更新token用户ID绑定失败:', error);
this.config.onError?.(error as Error);
return false;
}
}
/**
* 注册设备令牌到后端
*/

View File

@@ -19,8 +19,8 @@ export interface DeviceTokenRequest {
export interface UpdateTokenRequest {
currentDeviceToken: string;
newDeviceToken: string;
appVersion: string;
osVersion: string;
appVersion?: string;
osVersion?: string;
}
// 设备令牌注销请求参数
@@ -125,6 +125,27 @@ export class PushNotificationService {
}
}
/**
* 更新设备令牌的用户ID绑定关系
* 用户ID从服务端通过header中的token解析获取
*/
async updateTokenUserId(deviceToken: string): Promise<PushNotificationResponse> {
try {
logger.info('更新设备令牌用户ID绑定:', deviceToken.substring(0, 20) + '...');
const response = await api.put<PushNotificationResponse>(
'/push-notifications/update-token-user-id',
{ deviceToken }
);
logger.info('设备令牌用户ID绑定更新成功:', response.tokenId);
return response;
} catch (error) {
logger.error('更新设备令牌用户ID绑定失败:', error);
throw error;
}
}
/**
* 获取本地存储的设备令牌
*/