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

移动端应用分享链接跳转逻辑及Node.js(NestJS)实现方案咨询

基于NestJS的移动端深度链接跳转架构设计

1. 核心组件划分

整个系统拆分为5个核心模块,职责清晰、便于维护:

  • 分享链接生成服务:负责生成带业务参数的唯一跳转链接,关联分享场景与用户信息
  • 跳转路由控制器:作为链接请求的入口,处理设备检测、参数解析与跳转逻辑
  • 设备检测工具:通过请求头判断用户设备平台(iOS/Android/其他)
  • 应用配置中心:统一管理各平台的App唤起协议、应用商店链接等配置
  • 可选:访问统计服务:记录跳转次数、设备类型等数据,用于运营分析

2. 各组件实现细节

2.1 分享链接生成服务

功能:接收业务参数(如用户ID、分享页面类型),生成带唯一标识的跳转链接,并暂存参数信息。

import { Injectable } from '@nestjs/common';
import { v4 as uuidv4 } from 'uuid';
import { RedisService } from './redis.service';

@Injectable()
export class ShareLinkService {
  constructor(private readonly redisService: RedisService) {}

  // 生成用户个人主页分享链接
  async generateUserProfileLink(userId: string, sharerId?: string): Promise<string> {
    // 生成短标识,减少链接长度
    const shareId = `share_${uuidv4().slice(0, 8)}`;
    // 用Redis暂存参数,设置7天过期时间
    await this.redisService.set(
      shareId,
      JSON.stringify({ type: 'user_profile', userId, sharerId }),
      60 * 60 * 24 * 7
    );
    // 返回完整跳转链接
    return `https://your-domain.com/deeplink/${shareId}`;
  }

  // 根据shareId获取暂存的参数
  async getShareParams(shareId: string) {
    const paramsStr = await this.redisService.get(shareId);
    return paramsStr ? JSON.parse(paramsStr) : null;
  }
}

2.2 跳转路由控制器

功能:处理跳转请求,解析参数后根据设备类型返回唤起App或跳转应用商店的逻辑页面。

import { Controller, Get, Param, Res, Headers } from '@nestjs/common';
import { Response } from 'express';
import { ShareLinkService } from './share-link.service';
import { DeviceDetector } from './device-detector';
import { AppConfigService } from './app-config.service';

@Controller('deeplink')
export class DeepLinkController {
  constructor(
    private readonly shareLinkService: ShareLinkService,
    private readonly deviceDetector: DeviceDetector,
    private readonly appConfigService: AppConfigService
  ) {}

  @Get(':shareId')
  async handleDeepLink(
    @Param('shareId') shareId: string,
    @Headers('user-agent') userAgent: string,
    @Res() res: Response
  ) {
    // 1. 验证分享链接有效性
    const shareParams = await this.shareLinkService.getShareParams(shareId);
    if (!shareParams) {
      return res.status(404).send('无效的分享链接');
    }

    // 2. 检测用户设备平台
    const platform = this.deviceDetector.detectPlatform(userAgent);

    // 3. 获取对应平台的跳转配置
    const { appScheme, appStoreUrl } = this.appConfigService.getPlatformConfig(platform);
    // 拼接App内跳转的协议链接
    const deepLinkUrl = `${appScheme}://user/profile?userId=${shareParams.userId}&sharerId=${shareParams.sharerId}`;

    // 4. 返回包含唤起逻辑的HTML页面
    res.send(this.generateRedirectPage(deepLinkUrl, appStoreUrl));
  }

  // 生成自动跳转的HTML页面
  private generateRedirectPage(deepLinkUrl: string, fallbackUrl: string): string {
    return `
      <!DOCTYPE html>
      <html>
        <head>
          <meta charset="UTF-8">
          <title>跳转中...</title>
        </head>
        <body>
          <script>
            // 优先尝试唤起App
            window.location.href = "${deepLinkUrl}";
            // 3秒后未唤起则跳转应用商店
            setTimeout(() => {
              window.location.href = "${fallbackUrl}";
            }, 3000);
          </script>
          若未自动跳转,请<a href="${fallbackUrl}">点击这里</a>
        </body>
      </html>
    `;
  }
}

2.3 设备检测工具

功能:通过请求头的User-Agent字段判断用户设备类型。

import { Injectable } from '@nestjs/common';

export type PlatformType = 'ios' | 'android' | 'other';

@Injectable()
export class DeviceDetector {
  detectPlatform(userAgent: string): PlatformType {
    const lowerAgent = userAgent.toLowerCase();
    if (lowerAgent.includes('iphone') || lowerAgent.includes('ipad')) {
      return 'ios';
    } else if (lowerAgent.includes('android')) {
      return 'android';
    }
    return 'other';
  }
}

2.4 应用配置中心

功能:统一管理各平台的App唤起协议、应用商店链接,便于后续修改配置。

import { Injectable } from '@nestjs/common';
import { PlatformType } from './device-detector';

interface PlatformConfig {
  appScheme: string;
  appStoreUrl: string;
}

@Injectable()
export class AppConfigService {
  private readonly platformConfigs: Record<PlatformType, PlatformConfig> = {
    ios: {
      appScheme: 'yourapp://', // 你的iOS App自定义协议
      appStoreUrl: 'https://apps.apple.com/cn/app/你的应用ID'
    },
    android: {
      appScheme: 'yourapp://', // 你的Android App自定义协议
      appStoreUrl: 'https://play.google.com/store/apps/details?id=你的应用包名'
    },
    other: {
      appScheme: 'yourapp://',
      appStoreUrl: 'https://your-domain.com/download' // 其他设备跳转到官网下载页
    }
  };

  getPlatformConfig(platform: PlatformType): PlatformConfig {
    return this.platformConfigs[platform];
  }
}

3. 关键注意事项

  • 优先使用官方标准链接:iOS推荐用Universal Links,Android用App Links,比自定义Scheme更稳定,避免被浏览器拦截。需要在NestJS服务端配置apple-app-site-association和assetlinks.json文件,放在静态资源目录或通过路由返回。
  • 链接过期与清理:用Redis的自动过期功能处理分享参数,避免无效数据堆积;若用数据库存储,需定时清理过期记录。
  • 异常处理:针对分享参数不存在、设备检测失败等场景,返回友好提示或跳转到默认下载页。
  • 多场景测试:在不同设备、不同浏览器(Safari/Chrome/微信内置浏览器)测试跳转逻辑,确保唤起与降级跳转正常工作。

4. 整体流程梳理

  1. 移动端App调用NestJS的分享链接生成接口,传入用户ID等参数,获取分享链接。
  2. 用户将链接分享至社交平台或聊天工具。
  3. 接收方点击链接,请求到达NestJS的跳转路由控制器。
  4. 控制器解析分享参数,检测设备平台,返回包含唤起逻辑的HTML页面。
  5. 页面优先尝试唤起App,若失败则自动跳转至对应平台的应用商店。
  6. App被唤起后,解析协议链接中的参数,跳转到指定的用户个人主页。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 13:38:32