2026 年 Expo + React Native 项目接入微信分享完整指南

2026 年 Expo + React Native 项目接入微信分享完整指南

本文基于 Expo SDK 54 + React Native 0.81 + react-native-wechat-lib 1.1.27 的实战经验,详细记录了在 Expo 管理的 React Native 项目中接入微信分享功能的完整流程和踩坑记录。

前言

在 React Native 生态中,react-native-wechat-lib 是目前最常用的微信 SDK 封装库。但由于该库更新较慢,加上 Expo 的特殊性,接入过程中会遇到不少坑。本文将分享我们在生产项目中的完整接入方案。

技术栈

  • Expo SDK: 54.0.30
  • React Native: 0.81.5
  • react-native-wechat-lib: 1.1.27
  • 构建方式: EAS Build

整体流程

arduino 复制代码
准备工作 → 安装依赖 → 创建 Expo 插件 → 配置 app.config.js → 
编写 JS 服务层 → 服务器配置 → 微信开放平台配置 → 构建测试

第一步:准备工作

1.1 微信开放平台配置

  1. 登录 微信开放平台
  2. 创建移动应用,获取 AppID
  3. 配置 iOS 应用信息:
    • Bundle ID: com.yourapp
    • Universal Link: https://yourdomain.com/open/

1.2 Apple Developer 配置

  1. 获取 Team ID(格式如 A1B2C3D4E5
  2. 确认 Bundle ID 与微信开放平台一致

第二步:安装依赖

bash 复制代码
npm install react-native-wechat-lib@1.1.27

⚠️ 注意:在 Expo 管理的项目中,不需要手动执行 pod install,EAS Build 会自动处理。

第三步:创建 Expo Config Plugin

由于 Expo 管理原生代码,我们需要通过 Config Plugin 来配置微信 SDK 所需的原生设置。

创建 plugins/withWechat.js

javascript 复制代码
const { withInfoPlist, withAndroidManifest } = require("expo/config-plugins");

/**
 * 微信 SDK Expo Config Plugin
 * 自动配置 iOS 和 Android 的微信相关设置
 */
function withWechat(config, { appId, universalLink }) {
  if (!appId) {
    throw new Error("withWechat: appId is required");
  }

  // iOS 配置
  config = withInfoPlist(config, (config) => {
    // 添加微信 URL Scheme
    const urlTypes = config.modResults.CFBundleURLTypes || [];
    const wechatScheme = {
      CFBundleURLSchemes: [appId],
      CFBundleURLName: "wechat",
    };

    const hasWechatScheme = urlTypes.some(
      (type) =>
        type.CFBundleURLSchemes &&
        type.CFBundleURLSchemes.includes(appId)
    );

    if (!hasWechatScheme) {
      urlTypes.push(wechatScheme);
    }
    config.modResults.CFBundleURLTypes = urlTypes;

    // 添加 LSApplicationQueriesSchemes
    const queriesSchemes = config.modResults.LSApplicationQueriesSchemes || [];
    const wechatSchemes = ["weixin", "weixinULAPI"];
    wechatSchemes.forEach((scheme) => {
      if (!queriesSchemes.includes(scheme)) {
        queriesSchemes.push(scheme);
      }
    });
    config.modResults.LSApplicationQueriesSchemes = queriesSchemes;

    return config;
  });

  // Android 配置
  config = withAndroidManifest(config, (config) => {
    const mainApplication = config.modResults.manifest.application?.[0];
    if (!mainApplication) return config;

    const packageName = config.android?.package || "com.yourapp";
    const activities = mainApplication.activity || [];
    const wxActivityName = `${packageName}.wxapi.WXEntryActivity`;

    const hasWxActivity = activities.some(
      (activity) => activity.$?.["android:name"] === wxActivityName
    );

    if (!hasWxActivity) {
      activities.push({
        $: {
          "android:name": wxActivityName,
          "android:exported": "true",
          "android:launchMode": "singleTask",
          "android:taskAffinity": packageName,
          "android:theme": "@android:style/Theme.Translucent.NoTitleBar",
        },
      });
    }

    mainApplication.activity = activities;
    return config;
  });

  return config;
}

module.exports = withWechat;

第四步:配置 app.config.js

javascript 复制代码
module.exports = {
  expo: {
    name: "你的应用名",
    slug: "your-app",
    version: "1.0.0",
    
    extra: {
      wechatAppId: "wx你的AppID", // 微信 AppID
    },
    
    ios: {
      bundleIdentifier: "com.yourapp",
      associatedDomains: [
        "applinks:yourdomain.com",
        "webcredentials:yourdomain.com",
      ],
      infoPlist: {
        LSApplicationQueriesSchemes: ["weixin", "weixinULAPI", "wechat"],
      },
    },
    
    android: {
      package: "com.yourapp",
    },
    
    plugins: [
      [
        "./plugins/withWechat",
        {
          appId: "wx你的AppID",
          universalLink: "https://yourdomain.com/open/",
        },
      ],
    ],
  },
};

第五步:编写微信服务层

创建 src/services/wechatService.ts

typescript 复制代码
import { Platform, Alert } from "react-native";
import Constants from "expo-constants";

// 从 Expo 配置中获取微信 AppID
const WECHAT_APP_ID = Constants.expoConfig?.extra?.wechatAppId || "";

// 动态加载微信 SDK
let WeChat: any = null;
let sdkLoadAttempted = false;

const getWechatSDK = () => {
  if (sdkLoadAttempted) return WeChat;
  sdkLoadAttempted = true;
  
  if (Platform.OS === "web") {
    return null;
  }
  
  try {
    const module = require("react-native-wechat-lib");
    WeChat = module.default || module;
    
    if (!WeChat || typeof WeChat.registerApp !== "function") {
      WeChat = null;
    }
    
    return WeChat;
  } catch (error) {
    console.warn("微信 SDK 加载失败:", error);
    return null;
  }
};

class WechatService {
  private isRegistered = false;

  // 检查 SDK 是否可用
  isAvailable(): boolean {
    if (Platform.OS === "web") return false;
    const sdk = getWechatSDK();
    return sdk !== null && typeof sdk.registerApp === "function";
  }

  // 注册微信 SDK
  async register(): Promise<boolean> {
    if (this.isRegistered) return true;
    
    const sdk = getWechatSDK();
    if (!sdk) return false;
    
    try {
      const result = await sdk.registerApp(WECHAT_APP_ID);
      this.isRegistered = result;
      return result;
    } catch (error) {
      console.error("微信 SDK 注册失败:", error);
      return false;
    }
  }

  // 检查微信是否已安装
  async isWechatInstalled(): Promise<boolean> {
    const sdk = getWechatSDK();
    if (!sdk) return false;
    
    try {
      return await sdk.isWXAppInstalled();
    } catch (error) {
      return false;
    }
  }

  // 分享网页到微信
  async shareWebpage(params: {
    title: string;
    description: string;
    thumbImageUrl?: string;
    webpageUrl: string;
    scene?: "session" | "timeline" | "favorite";
  }): Promise<{ success: boolean; message: string }> {
    
    if (!this.isAvailable()) {
      return { 
        success: false, 
        message: Platform.OS === "web" 
          ? "Web 端暂不支持微信分享" 
          : "微信分享功能需要在正式构建版本中使用"
      };
    }

    try {
      const registered = await this.register();
      if (!registered) {
        return { success: false, message: "微信 SDK 初始化失败" };
      }

      const isInstalled = await this.isWechatInstalled();
      if (!isInstalled) {
        return { success: false, message: "请先安装微信" };
      }

      const sceneMap = {
        session: 0,   // 聊天界面
        timeline: 1,  // 朋友圈
        favorite: 2,  // 收藏
      };

      const sdk = getWechatSDK();
      await sdk.shareWebpage({
        title: params.title,
        description: params.description,
        thumbImageUrl: params.thumbImageUrl || "",
        webpageUrl: params.webpageUrl,
        scene: sceneMap[params.scene || "session"],
      });

      return { success: true, message: "分享成功" };
    } catch (error: any) {
      if (error?.errCode === -2) {
        return { success: false, message: "已取消分享" };
      }
      return { success: false, message: error?.message || "分享失败" };
    }
  }

  // 分享图片到微信
  async shareImage(params: {
    imageUrl?: string;
    imageBase64?: string;
    scene?: "session" | "timeline" | "favorite";
  }): Promise<{ success: boolean; message: string }> {
    if (!this.isAvailable()) {
      return { success: false, message: "微信分享不可用" };
    }

    try {
      await this.register();
      
      const isInstalled = await this.isWechatInstalled();
      if (!isInstalled) {
        return { success: false, message: "请先安装微信" };
      }

      const sceneMap = { session: 0, timeline: 1, favorite: 2 };
      const sdk = getWechatSDK();
      
      await sdk.shareImage({
        imageUrl: params.imageBase64 || params.imageUrl,
        scene: sceneMap[params.scene || "session"],
      });

      return { success: true, message: "分享成功" };
    } catch (error: any) {
      if (error?.errCode === -2) {
        return { success: false, message: "已取消分享" };
      }
      return { success: false, message: "分享失败" };
    }
  }
}

export const wechatService = new WechatService();

第六步:服务器配置 (Universal Link)

在你的服务器上创建 apple-app-site-association 文件。

文件路径

arduino 复制代码
https://yourdomain.com/.well-known/apple-app-site-association

文件内容

json 复制代码
{
  "applinks": {
    "apps": [],
    "details": [
      {
        "appIDs": ["TEAMID.com.yourapp"],
        "components": [
          { "/": "/open/*" },
          { "/": "/topic/*" }
        ]
      }
    ]
  },
  "webcredentials": {
    "apps": ["TEAMID.com.yourapp"]
  }
}

⚠️ 将 TEAMID 替换为你的 Apple Team ID,com.yourapp 替换为你的 Bundle ID。

服务器配置要求

  1. 必须通过 HTTPS 访问
  2. Content-Type 应为 application/json
  3. 文件名不能有 .json 后缀
  4. 不能有重定向

Nginx 配置示例

nginx 复制代码
location /.well-known/apple-app-site-association {
    default_type application/json;
}

第七步:在组件中使用

tsx 复制代码
import React from "react";
import { Button, Alert } from "react-native";
import { wechatService } from "@/services/wechatService";

export function ShareButton() {
  const handleShare = async () => {
    const result = await wechatService.shareWebpage({
      title: "分享标题",
      description: "分享描述",
      thumbImageUrl: "https://example.com/thumb.jpg",
      webpageUrl: "https://example.com/share-page",
      scene: "session", // 或 "timeline" 分享到朋友圈
    });

    if (result.success) {
      Alert.alert("成功", "分享成功");
    } else {
      Alert.alert("提示", result.message);
    }
  };

  return <Button title="分享到微信" onPress={handleShare} />;
}

第八步:构建和测试

使用 EAS Build

bash 复制代码
# 构建 iOS 生产版本
eas build -p ios --profile production

# 构建并自动提交到 TestFlight
eas build -p ios --profile production --auto-submit

测试注意事项

  1. Expo Go 不支持:微信 SDK 是原生模块,必须使用 EAS Build 构建的版本测试
  2. 重启手机:安装新版本后建议重启手机,让 iOS 刷新 Associated Domains 缓存
  3. 验证 Universal Link :访问 https://app-site-association.cdn-apple.com/a/v1/yourdomain.com 确认 Apple 已缓存配置

常见问题排查

问题 1:分享时微信没有被唤起

可能原因:

  • Universal Link 配置不一致(微信开放平台、App 代码、服务器三端必须完全一致)
  • apple-app-site-association 文件内容错误或无法访问
  • Apple 还未缓存你的配置

排查步骤:

  1. 确认三端域名完全一致(注意 www 和非 www 的区别)
  2. 直接访问 https://yourdomain.com/.well-known/apple-app-site-association 确认可以下载
  3. 检查 Apple CDN 缓存:https://app-site-association.cdn-apple.com/a/v1/yourdomain.com

问题 2:SDK 注册失败

可能原因:

  • AppID 配置错误
  • 在 Expo Go 中运行(不支持)

解决方案:

  • 确认 app.config.js 中的 AppID 与微信开放平台一致
  • 使用 EAS Build 构建的版本测试

问题 3:提示"请先安装微信"

可能原因:

  • LSApplicationQueriesSchemes 未正确配置

解决方案: 确认 app.config.js 中包含:

javascript 复制代码
infoPlist: {
  LSApplicationQueriesSchemes: ["weixin", "weixinULAPI", "wechat"],
}

调试技巧

在开发阶段,可以添加调试弹窗来追踪问题:

typescript 复制代码
const DEBUG_MODE = true;

const debugAlert = (title: string, message: string) => {
  if (DEBUG_MODE) {
    Alert.alert(`[调试] ${title}`, message);
  }
};

// 在关键步骤添加调试
debugAlert("开始分享", `AppID: ${WECHAT_APP_ID}`);
debugAlert("注册结果", `registered: ${registered}`);
debugAlert("微信安装检查", `isInstalled: ${isInstalled}`);

总结

在 Expo 项目中接入微信分享的关键点:

  1. 使用 Config Plugin 配置原生设置,而不是手动修改原生代码
  2. 三端配置一致 是成功的关键(微信开放平台、App、服务器)
  3. Universal Link 配置正确且可访问
  4. 必须使用 EAS Build 构建的版本测试,Expo Go 不支持原生模块

希望这篇文章能帮助你顺利接入微信分享功能!如有问题欢迎评论区交流。


参考资料:

相关推荐
崔庆才丨静觅6 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60616 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅7 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅7 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
未来侦察班7 小时前
一晃13年过去了,苹果的Airdrop依然很坚挺。
macos·ios·苹果vision pro
崔庆才丨静觅7 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment7 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅8 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊8 小时前
jwt介绍
前端