跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客我的书AI学习GitHub 精选镜像AI 生图工具UI配色美学关于
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
JavaScriptRNReact NativeWeChatPay

专为 Expo React Native 项目设计的微信 SDK 封装库

专为 Expo React Native 项目设计的微信 SDK 封装库,集成分享、支付、登陆、跳转、发票等接口, SDK使用微信官方:WechatSDK.XCFramework

Tesfly发布于 2026/4/2更新于 2026/9/1152K 浏览
专为 Expo React Native 项目设计的微信 SDK 封装库

expo-react-native-wechat-v2

npm version license platform expo

专为 Expo React Native 项目设计的微信 SDK 封装库,集成分享、支付、登陆、跳转、发票等接口, SDK使用微信官方:WechatSDK.XCFramework

📋 目录

  • ✨ 特性
  • 📦 安装
  • 🚀 快速开始
  • ⚙️ 配置指南
  • 📚 API 文档
  • 🔄 事件处理
  • 🛠️ 错误处理
  • 📱 使用示例
  • 📋 注意事项
  • 🤝 贡献
  • 📄 许可证

✨ 特性

功能描述支持平台
🔐
微信登录授权
支持 OAuth2 授权登录
iOS / Android
📤 内容分享支持文本、图片、音乐、视频、网页、小程序分享iOS / Android
💰 微信支付完整的支付流程集成iOS / Android
🚀 小程序跳转支持跳转到微信小程序iOS / Android
📝 TypeScript完整的类型定义支持全平台
🎯 Expo 友好专为 Expo 项目优化Expo
🔄 Promise API现代化的异步处理方式全平台
📱 跨平台支持同时支持 iOS 和 AndroidiOS / Android
📱 SDK版本Android SDK: 6.8.23 + ; iOS SDK: 2.0.2 +iOS / Android

📦 安装

使用 Expo CLI(推荐)

npx expo install expo-react-native-wechat-v2

使用 yarn

yarn add expo-react-native-wechat-v2

使用 npm

npm install expo-react-native-wechat-v2 --save

🚀 快速开始

1. 基础配置

Expo 项目配置

在项目根目录的 app.json 中添加配置:

{
  "expo": {
    "ios": {
      "infoPlist": {
        "LSApplicationQueriesSchemes": ["weixin", "weixinULAPI", "weixinURLParamsAPI"],
        "CFBundleURLTypes": [
          {
            "CFBundleTypeRole": "Editor",
            "CFBundleURLName": "weixin",
            "CFBundleURLSchemes": ["wx5555555555555555"]
          }
        ]
      }
    }
  }
}
执行预构建
  • 生成./ios 和 ./android 项目文件夹
npx expo prebuild

2. 基础使用

import * as WeChat from 'expo-react-native-wechat-v2';

// 注册微信应用
// 项目中只需要全局注册一次, 多次注册可能会导致意想不到的问题发生;
await WeChat.registerApp('wx5555555555555555', 'https://your-domain.com/');

// 检查微信是否安装
const isInstalled = await WeChat.isWXAppInstalled();

// 分享文本
await WeChat.shareText({
  text: 'Hello from React Native!',
  scene: 0, // 0: 会话, 1: 朋友圈, 2: 收藏
});

⚙️ 配置指南

iOS Universal Links 配置

1. 苹果开发者后台配置
  1. 登录 Apple Developer
  2. 开启 Associated Domains 功能
  3. 记录项目的 Team ID
2. 创建 apple-app-site-association 文件
{
   "applinks": {
       "apps": [],
       "details": [
           {
               "appID": "com.douyin.sample",
               "paths": [ "*" ]
           }
       ]
   }
}

重要注意事项:

项目说明
文件命名apple-app-site-association(无后缀名)
appID 格式TeamID.BundleID
文件位置网站根目录或 .well-known 目录
域名要求必须支持 HTTPS
验证地址https://app-site-association.cdn-apple.com/a/v1/your-domain.com
生效时间因苹果更新机制,可能需要 1-2 天生效
3. Xcode 配置

在 Xcode 中设置 Associated Domains:

  • Targets → Signing & Capabilities → Associated Domains
  • 添加:applinks:your-domain.com

Set Associated Domains Set Associated Domains

Expo 一键配置

  1. 在项目根目录的 app.json 中添加配置:
{
    "expo": {
        "ios": {
          "infoPlist": {
            "LSApplicationQueriesSchemes": ["weixin", "weixinULAPI", "weixinURLParamsAPI"],
            "CFBundleURLTypes": [
              {
                "CFBundleTypeRole": "Editor",
                "CFBundleURLName": "wexin",
                "CFBundleURLSchemes": ["wx5555555555555555"]
              }
            ]
          }
        }
    }
}
  1. 执行命令:
npx expo prebuild

React Native 手动配置

iOS 配置
  1. URL Schemes 配置
    • Xcode → Targets → Info → URL Types
    • 添加微信 AppID:wx5555555555555555

Set URL Types in XCode

或者在 Info.plist 文件中添加:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLName</key>
        <string>wexin</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>wx5555555555555555</string>
        </array>
    </dict>
</array>
  1. Queried URL Schemes 配置
    • 添加:weixin、weixinULAPI、weixinURLParamsAPI

Set URL Schemas in XCode

或者在 Info.plist 文件中添加:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>weixin</string>
    <string>weixinULAPI</string>
    <string>weixinURLParamsAPI</string>
</array>
Android 配置

Android 无需额外配置,库会自动处理。

📚 API 文档

本库支持 TypeScript,使用 Promise 或 async/await 来接收返回。

接口名称和参数尽量跟腾讯官网保持一致性,除了嵌套对象变成扁平对象,你可以直接查看腾讯文档来获得更多帮助。

基础功能

registerApp(appId, universalLink?) - 注册应用
参数类型必填说明
appIdString✅微信开放平台获取的 AppID
universalLinkString❌iOS Universal Link

返回值: Promise<Boolean>

import * as WeChat from 'expo-react-native-wechat-v2';

// 注册微信应用(全局调用一次)
await WeChat.registerApp('wx5555555555555555', 'https://your-domain.com/');
isWXAppInstalled() - 检查微信安装状态

返回值: Promise<Boolean>

const isInstalled = await WeChat.isWXAppInstalled();
console.log('微信是否已安装:', isInstalled);
isWXAppSupportApi() - 检查 API 支持

返回值: Promise<Boolean>

const isSupported = await WeChat.isWXAppSupportApi();
console.log('微信 API 是否支持:', isSupported);
getApiVersion() - 获取 SDK 版本

返回值: Promise<String>

const version = await WeChat.getApiVersion();
console.log('微信 SDK 版本:', version);
openWXApp() - 打开微信应用

返回值: Promise<Boolean>

await WeChat.openWXApp();

授权登录

sendAuthRequest(scope?, state?) - 微信授权登录
参数类型必填说明
scopeArray/String❌授权范围
stateString❌OAuth2 状态参数

返回值: Promise<AuthResponse>

字段类型说明
errCodeNumber错误代码
errStrString错误信息
openIdString用户唯一标识
codeString授权码
urlStringURL 字符串
langString用户语言
countryString用户国家
const authResult = await WeChat.sendAuthRequest(['snsapi_userinfo'], 'state123');
console.log('授权结果:', authResult);

分享功能

shareText(data) - 分享文本
参数类型必填说明
textString✅分享文本内容
sceneNumber❌分享场景(0: 会话, 1: 朋友圈, 2: 收藏)
await WeChat.shareText({
  text: '分享的文本内容',
  scene: 0,
});
shareImage(data) - 分享网络图片
参数类型必填说明
imageUrlString✅图片网络地址
sceneNumber❌分享场景
await WeChat.shareImage({
  imageUrl: 'https://example.com/image.jpg',
  scene: 0,
});
shareLocalImage(data) - 分享本地图片
参数类型必填说明
imageUrlString✅本地图片路径
sceneNumber❌分享场景
await WeChat.shareLocalImage({
  imageUrl: 'file:///path/to/local/image.jpg',
  scene: 0,
});
shareMusic(data) - 分享音乐
参数类型必填说明
titleString❌音乐标题
descriptionString❌音乐描述
thumbImageUrlString❌缩略图(自动压缩到32KB)
musicUrlString✅音乐网页URL
musicLowBandUrlString❌低带宽音乐URL
musicDataUrlString❌音乐数据URL
musicLowBandDataUrlString❌低带宽音乐数据URL
sceneNumber❌分享场景
await WeChat.shareMusic({
  title: '音乐标题',
  description: '音乐描述',
  musicUrl: 'https://example.com/music.mp3',
  thumbImageUrl: 'https://example.com/thumb.jpg',
  scene: 0,
});
shareVideo(data) - 分享视频
参数类型必填说明
titleString❌视频标题
descriptionString❌视频描述
thumbImageUrlString❌缩略图(自动压缩到32KB)
videoUrlString✅视频链接
videoLowBandUrlString❌低带宽视频链接
sceneNumber❌分享场景
await WeChat.shareVideo({
  title: '视频标题',
  description: '视频描述',
  videoUrl: 'https://example.com/video.mp4',
  thumbImageUrl: 'https://example.com/thumb.jpg',
  scene: 0,
});
shareWebpage(data) - 分享网页
参数类型必填说明
titleString❌网页标题
descriptionString❌网页描述
thumbImageUrlString❌缩略图(自动压缩到32KB)
webpageUrlString✅网页链接
sceneNumber❌分享场景
await WeChat.shareWebpage({
  title: '网页标题',
  description: '网页描述',
  webpageUrl: 'https://example.com',
  thumbImageUrl: 'https://example.com/thumb.jpg',
  scene: 0,
});
shareMiniProgram(data) - 分享小程序
参数类型必填说明
titleString❌小程序标题
descriptionString❌小程序描述
thumbImageUrlString❌缩略图(自动压缩到32KB)
userNameString✅小程序原始ID
pathString❌小程序页面路径
hdImageUrlString❌高清预览图(6.5.9+支持)
withShareTicketString❌是否使用带shareTicket的分享
miniProgramTypeNumber❌小程序类型(0:正式版, 1:开发版, 2:体验版)
webpageUrlString❌兼容低版本的网页链接
sceneNumber❌分享场景
await WeChat.shareMiniProgram({
  title: '小程序标题',
  description: '小程序描述',
  userName: 'gh_d39d10000000',
  path: 'pages/index/index',
  webpageUrl: 'https://example.com/fallback.html',
  thumbImageUrl: 'https://example.com/thumb.jpg',
  scene: 0,
});
shareFile(data) - 分享文件
参数类型必填说明
urlString✅文件地址
titleString❌文件标题
extString❌文件扩展名
sceneNumber❌分享场景(仅支持会话)
await WeChat.shareFile({
  url: 'file:///path/to/file.pdf',
  title: '文件标题',
  ext: 'pdf',
  scene: 0,
});

小程序功能

launchMiniProgram(data) - 跳转到小程序
参数类型必填说明
userNameString✅小程序原始ID
miniProgramTypeNumber❌小程序类型(0:正式版, 1:开发版, 2:体验版)
pathString❌小程序页面路径
await WeChat.launchMiniProgram({
  userName: 'gh_d39d10000000',
  miniProgramType: 0,
  path: 'pages/index/index?id=123',
});
subscribeMessage(data) - 订阅消息
参数类型必填说明
sceneNumber❌订阅场景(0-10000)
templateIdString✅订阅消息模板ID
reservedString❌保留参数(防CSRF攻击)
await WeChat.subscribeMessage({
  scene: 0,
  templateId: 'template_id_here',
  reserved: 'reserved_data',
});

支付功能

pay(data) - 微信支付
参数类型必填说明
partnerIdString✅商家ID
prepayIdString✅预支付订单ID
nonceStrString✅随机字符串
timeStampString✅时间戳
packageString✅包名(固定为"Sign=WXPay")
signString✅签名
await WeChat.pay({
  partnerId: 'partner_id',
  prepayId: 'prepay_id',
  nonceStr: 'nonce_str',
  timeStamp: 'timestamp',
  package: 'Sign=WXPay',
  sign: 'signature',
});

发票功能

chooseInvoice(data) - 选择发票
参数类型必填说明
cardSignString❌签名
signTypeString❌签名类型
timeStampNumber❌当前时间戳
nonceStrString❌随机字符串

返回值: Promise<{errCode, errStr, cards: Invoice[]}>

字段类型说明
errCodeNumber错误代码
errStrString错误信息
cardsInvoice[]发票数据数组
const result = await WeChat.chooseInvoice({
  cardSign: 'card_sign',
  signType: 'SHA256',
  timeStamp: Date.now(),
  nonceStr: `${Date.now()}`,
});

console.log('发票数据:', result.cards);

🔄 事件处理

设置事件监听器

从小程序回到 APP,或者支付成功回到 APP 都会触发回调事件来返回相应信息,请在触发相应方法前提前添加事件队列。

import { DeviceEventEmitter } from 'react-native';

// 监听微信请求事件
DeviceEventEmitter.addListener('WeChat_Req', (req) => {
  console.log('微信请求事件:', req);
  if (req.type === 'LaunchFromWX.Req') {
    // 从小程序回到APP
    handleMiniProgramCallback(req.extMsg);
  }
});

// 监听微信响应事件
DeviceEventEmitter.addListener('WeChat_Resp', (resp) => {
  console.log('微信响应事件:', resp);
  if (resp.type === 'WXLaunchMiniProgramReq.Resp') {
    // 小程序跳转回调
    handleMiniProgramCallback(resp.extMsg);
  } else if (resp.type === 'SendMessageToWX.Resp') {
    // 分享消息回调
    handleShareCallback(resp);
  } else if (resp.type === 'PayReq.Resp') {
    // 支付回调
    handlePayCallback(resp);
  }
});

使用事件发射器

import * as WeChat from 'expo-react-native-wechat-v2';

// 添加事件监听器
WeChat.addListener('SendMessageToWX.Resp', (resp) => {
  console.log('分享结果:', resp);
});

// 一次性监听器
WeChat.once('PayReq.Resp', (resp) => {
  console.log('支付结果:', resp);
});

// 移除所有监听器
WeChat.removeAllListeners('SendMessageToWX.Resp');

🛠️ 错误处理

WechatError 类

所有 API 调用失败时会抛出 WechatError 异常:

import * as WeChat from 'expo-react-native-wechat-v2';

try {
  await WeChat.shareText({ text: 'Hello' });
} catch (error) {
  if (error instanceof WeChat.WechatError) {
    console.log('错误代码:', error.code);
    console.log('错误信息:', error.message);
  }
}

常见错误代码

错误代码说明处理建议
-1通用错误检查参数和网络连接
-2用户取消用户主动取消操作
-3发送失败检查微信是否安装
-4授权失败检查AppID配置
-5微信不支持检查微信版本

📱 使用示例

基础调用示例

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import * as WeChat from 'expo-react-native-wechat-v2';

export default function App() {
    return (
        <View style={styles.container}>
            <Text onPress={()=>{
                WeChat.registerApp('wx5555555555555555', 'https://www.baidu.com/').then((a)=>{
                    console.log("==registerApp==>",a);
                });
            }}>registerApp</Text>
            <Text onPress={()=>{
                WeChat.isWXAppInstalled().then((a)=>{
                    console.log("==isWXAppInstalled==>",a);
                });
            }}>isWXAppInstalled</Text>
            <Text onPress={()=>{
                WeChat.getApiVersion().then((a)=>{
                    console.log("==getApiVersion==>",a);
                });
            }}>getApiVersion</Text>
            <Text onPress={()=>{
                WeChat.openWXApp().then((a)=>{
                    console.log("==openWXApp==>",a);
                });
            }}>openWXApp</Text>
            <Text onPress={()=>{
                WeChat.shareText({
                    text: 'Text content.',
                    scene: 0,
                }).then((a)=>{
                    console.log("==shareText==>",a);
                });
            }}>shareText</Text>
            <StatusBar style="auto" />
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
});

现代化应用示例

import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import * as WeChat from 'expo-react-native-wechat-v2';

export default function App() {
  const [isRegistered, setIsRegistered] = React.useState(false);

  React.useEffect(() => {
    // 注册微信应用
    WeChat.registerApp('wx5555555555555555', 'https://your-domain.com/')
      .then(() => setIsRegistered(true))
      .catch(console.error);
  }, []);

  const handleShareText = async () => {
    try {
      await WeChat.shareText({
        text: 'Hello from React Native!',
        scene: 0,
      });
      console.log('分享成功');
    } catch (error) {
      console.error('分享失败:', error);
    }
  };

  const handleWeChatLogin = async () => {
    try {
      const result = await WeChat.sendAuthRequest(['snsapi_userinfo']);
      console.log('登录成功:', result);
    } catch (error) {
      console.error('登录失败:', error);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>微信 SDK 示例</Text>
      
      <TouchableOpacity style={styles.button} onPress={handleShareText}>
        <Text style={styles.buttonText}>分享文本</Text>
      </TouchableOpacity>
      
      <TouchableOpacity style={styles.button} onPress={handleWeChatLogin}>
        <Text style={styles.buttonText}>微信登录</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 30,
  },
  button: {
    backgroundColor: '#07C160',
    padding: 15,
    borderRadius: 8,
    marginVertical: 10,
    width: 200,
    alignItems: 'center',
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

📋 注意事项

项目说明
AppID 配置确保使用正确的微信 AppID
Universal LinksiOS 需要正确配置 Universal Links
图片大小缩略图会自动压缩到 32KB 以内
权限检查使用前检查微信是否安装
错误处理始终处理可能的异常情况
回调处理正确设置事件监听器处理回调
版本兼容支持 Android SDK 6.8.23+ 和 iOS SDK 2.0.2+
网络要求确保网络连接正常
签名验证支付功能需要正确的签名算法

🤝 贡献

欢迎提交 Issue 和 Pull Request!

贡献指南

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 打开 Pull Request

📄 许可证

MIT License - 详见 LICENSE 文件

🔗 相关链接

资源链接
微信开放平台https://open.weixin.qq.com/
微信开发者文档https://developers.weixin.qq.com/doc/
Expo 文档https://docs.expo.dev/
React Native 文档https://reactnative.dev/

📞 支持

如有问题,请通过以下方式联系:

  • 📧 邮箱: [email protected]
  • 🐛 提交 Issue: GitHub Issues
  • 📖 文档: 查看本文档的 API 文档 部分

Made with ❤️ by Zeeklog

Thanks zeng-zhiming

目录

  1. expo-react-native-wechat-v2
  2. 📋 目录
  3. ✨ 特性
  4. 📦 安装
  5. 使用 Expo CLI(推荐)
  6. 使用 yarn
  7. 使用 npm
  8. 🚀 快速开始
  9. 1. 基础配置
  10. Expo 项目配置
  11. 执行预构建
  12. 2. 基础使用
  13. ⚙️ 配置指南
  14. iOS Universal Links 配置
  15. 1. 苹果开发者后台配置
  16. 2. 创建 apple-app-site-association 文件
  17. 3. Xcode 配置
  18. Expo 一键配置
  19. React Native 手动配置
  20. iOS 配置
  21. Android 配置
  22. 📚 API 文档
  23. 基础功能
  24. registerApp(appId, universalLink?) - 注册应用
  25. isWXAppInstalled() - 检查微信安装状态
  26. isWXAppSupportApi() - 检查 API 支持
  27. getApiVersion() - 获取 SDK 版本
  28. openWXApp() - 打开微信应用
  29. 授权登录
  30. sendAuthRequest(scope?, state?) - 微信授权登录
  31. 分享功能
  32. shareText(data) - 分享文本
  33. shareImage(data) - 分享网络图片
  34. shareLocalImage(data) - 分享本地图片
  35. shareMusic(data) - 分享音乐
  36. shareVideo(data) - 分享视频
  37. shareWebpage(data) - 分享网页
  38. shareMiniProgram(data) - 分享小程序
  39. shareFile(data) - 分享文件
  40. 小程序功能
  41. launchMiniProgram(data) - 跳转到小程序
  42. subscribeMessage(data) - 订阅消息
  43. 支付功能
  44. pay(data) - 微信支付
  45. 发票功能
  46. chooseInvoice(data) - 选择发票
  47. 🔄 事件处理
  48. 设置事件监听器
  49. 使用事件发射器
  50. 🛠️ 错误处理
  51. WechatError 类
  52. 常见错误代码
  53. 📱 使用示例
  54. 基础调用示例
  55. 现代化应用示例
  56. 📋 注意事项
  57. 🤝 贡献
  58. 贡献指南
  59. 📄 许可证
  60. 🔗 相关链接
  61. 📞 支持

更多推荐文章

查看全部
  • NoneBot 与 Lagrange 搭建 QQ 机器人教程
  • FunASR 离线文件转写服务开发指南
  • 队列详解:从概念到 C 语言实战
  • Android Framework 源码解析:AI 时代的挑战与学习路径
  • Midscene.js跨语言调用教程:Python与Java SDK集成
  • CCF-GESP 六级 C++ 真题解析:道具商店
  • 华为昇腾 910B 使用 LLaMA-Factory 微调 Qwen3.5-32B 模型指南
  • Android Framework 源码解析与核心原理详解
  • WhisperX 语音识别工具:为何比传统方案更具优势
  • 即梦数字人视频生成 API 调用示例
  • IDEA 集成 AI 辅助工具推荐及选型指南
  • 2025 大模型行业现状与方向调研:LLM、MLLM 及 AIGC 赛道分析
  • 代码生成 Prompt:从自然语言描述到完整函数
  • Flask 框架从入门到实战完整指南
  • GitHub Copilot 安装与使用指南
  • Llama-Factory 微调中 Batch Size 的设置与性能调优
  • C++11 核心新特性实战:Lambda、移动语义与模板
  • 基于本地大语言模型与 LangChain 构建免费 AI 搜索问答助手
  • OpenClaw 安装部署全流程:搭建自托管 AI 助手网关
  • 算法实战:模幂、构造、背包、贪心等六题精析

相关免费在线工具

  • 随机加州地址生成器

    随机生成加州地址(街道、城市、州CA、邮编),支持数量快捷选择、显示全部与下载。 在线工具,随机加州地址生成器在线工具,online

  • Keycode 信息

    查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online

  • Escape 与 Native 编解码

    JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online

  • JavaScript / HTML 格式化

    使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online

  • JavaScript 压缩与混淆

    Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online