更新记录

1.0.0(2025-04-30)

支持iOS、安卓APP调用微信SDK功能


平台兼容性

uni-app x(4.36)

Chrome Safari Android Android插件版本 iOS iOS插件版本 鸿蒙 微信小程序
- - 5.0 1.0.0 12 1.0.0 - -

tt-wechat-pro

🚀 专业版微信SDK插件,为 uni-app x 提供完整的微信集成解决方案,包含登录、分享、支付、小程序等全功能

📖 目录

SDK版本信息

平台 版本
iOS 2.0.4
Android 6.8.0
HarmonyOS - ❌ 不支持

📚 推荐阅读: 微信官方集成文档

🚨 重要提示

⚠️ 必须使用自定义基座运行,否则无法找到插件方法

环境配置

前置条件

  1. 微信开放平台申请移动应用
  2. 获取 AppID
  3. 配置应用包名和签名

iOS平台配置

1. 配置 URL Scheme

在项目根目录的 Info.plist 文件中添加以下配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
      <!-- 允许查询微信应用 -->
      <key>LSApplicationQueriesSchemes</key>
      <array>
        <string>weixin</string>
        <string>weixinULAPI</string>
      </array>

      <!-- URL Scheme 配置 -->
      <key>CFBundleURLTypes</key>
      <array>
        <dict>
            <key>CFBundleURLName</key>
            <string>WeChat</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <!-- 这里填写您在微信开放平台申请的 AppID -->
                <string>您的微信AppID</string>
            </array>
        </dict>
      </array>
    </dict>
</plist>

2. 配置通用链接 (Universal Link)

📖 详细配置请参考: uni官方文档-通用链接

Android平台配置

Android平台会自动完成相关配置,确保在微信开放平台正确配置应用包名和签名即可。

快速开始

1. 导入插件

import * as wxsdk from "@/uni_modules/tt-wechat-pro";

export default {
    data() {
        return {
            weChat: null as wxsdk.TTWeChatSDK | null,
        }
    },
    onLoad() {
        // 初始化微信SDK实例
        this.weChat = wxsdk.getTTWeChatSDK()
        // 注册微信SDK
        this.initWeChatSDK()
    },
    methods: {
        // 初始化微信SDK
        initWeChatSDK() {
            // SDK初始化代码见下方
        }
    }
}

2. 初始化 SDK

initWeChatSDK() {
    if (!this.weChat) {
        console.error('微信SDK初始化失败')
        return
    }

    this.weChat.register({
        appid: "您的微信AppID",           // 必填:微信开放平台申请的AppID
        universalLink: "您的通用链接",     // iOS必填:通用链接
        success: (e) => {
            console.log("✅ 微信SDK初始化成功");
            // 可以在这里进行后续操作,如检测微信是否安装
            this.checkWeChatInstalled()
        },
        fail: (err) => {
            console.error("❌ 微信SDK初始化失败:", err);
            uni.showToast({
                title: '微信SDK初始化失败',
                icon: 'error'
            })
        }
    } as wxsdk.TTWeChatRegisterOptions);
}

基础使用

检测微信是否安装

checkWeChatInstalled() {
    const isInstalled = this.weChat?.isInstall()
    if (!isInstalled) {
        uni.showModal({
            title: '提示',
            content: '请先安装微信客户端',
            showCancel: false
        })
        return false
    }
    return true
}

功能介绍

微信授权登录

💡 微信登录是一个两步过程:先获取code,再通过后端接口换取用户信息

第一步:获取授权码 (code)

参数说明

TTWeChatLoginOptions

参数 类型 必填 说明
state string 请求唯一标识,原样返回,长度不超过1K

返回值 TTWeChatLoginSuccess

参数 类型 说明
code string 用于换取access_token的授权码
state string 原样返回的标识符

示例代码

// 微信授权登录
handleWeChatLogin() {
    // 先检查微信是否安装
    if (!this.checkWeChatInstalled()) {
        return
    }

    this.weChat?.login({
        state: Date.now().toString(), // 使用时间戳作为唯一标识
        success: (result) => {
            console.log("✅ 获取授权码成功:", result.code);
            // 将code发送到后端服务器
            this.sendCodeToServer(result.code)
        },
        fail: (error) => {
            console.error("❌ 微信授权失败:", error);
            uni.showToast({
                title: '授权失败',
                icon: 'error'
            })
        }
    } as wxsdk.TTWeChatLoginOptions)
}

// 发送code到后端服务器
sendCodeToServer(code: string) {
    uni.request({
        url: 'https://your-server.com/api/wechat/login',
        method: 'POST',
        data: { code },
        success: (res) => {
            // 处理登录成功逻辑
            console.log('登录成功:', res.data)
        },
        fail: (err) => {
            console.error('登录请求失败:', err)
        }
    })
}

第二步:后端换取用户信息

📖 详细流程请参考: 微信授权后接口调用文档

后端需要完成的步骤:

  1. 使用code换取access_token
  2. 使用access_token获取用户信息
  3. 返回用户信息给前端

微信分享功能

💡 支持分享文本、图片、视频、网页、小程序和音乐到微信好友、朋友圈和收藏

分享类型和场景

分享类型 (type)

  • 0 - 文本分享
  • 1 - 图片分享
  • 2 - 视频分享
  • 3 - 网页分享
  • 4 - 小程序分享
  • 5 - 音乐分享

分享场景 (scene)

  • 0 - 分享到聊天界面
  • 1 - 分享到朋友圈
  • 2 - 分享到收藏

参数说明

TTWeChatShareOptions

参数 类型 必填 说明
type number 分享类型,见上表
scene number 分享场景,见上表
title string 条件 分享标题(文本分享时必填)
desc string 分享描述
imageUrl string 条件 图片地址(图片分享时必填,仅支持本地路径)
videoUrl string 条件 视频地址(视频分享时必填)
musicUrl string 条件 音乐地址(音乐分享时必填)
href string 条件 网页链接(网页分享时必填)
miniProgram TTWeChatShareMiniProgramOptions 条件 小程序信息(小程序分享时必填)

TTWeChatShareMiniProgramOptions

参数 类型 必填 说明
userName string 小程序原始ID
path string 小程序页面路径
webpageUrl string 兼容低版本的网页URL
miniProgramType number 版本类型:0-正式版,1-开发版,2-体验版(默认0)

使用示例

1. 分享文本

shareText() {
    this.weChat?.share({
        type: 0,
        scene: 0, // 分享到聊天
        title: '这是分享的文本内容',
        desc: '分享描述信息',
        success: (res) => {
            console.log('✅ 文本分享成功')
            uni.showToast({ title: '分享成功' })
        },
        fail: (error) => {
            console.error('❌ 分享失败:', error)
            uni.showToast({ title: '分享失败', icon: 'error' })
        }
    } as wxsdk.TTWeChatShareOptions)
}

2. 分享图片

shareImage() {
    this.weChat?.share({
        type: 1,
        scene: 1, // 分享到朋友圈
        imageUrl: '/static/share-image.png', // 本地图片路径
        success: (res) => {
            console.log('✅ 图片分享成功')
        },
        fail: (error) => {
            console.error('❌ 图片分享失败:', error)
        }
    } as wxsdk.TTWeChatShareOptions)
}

3. 分享网页

shareWebPage() {
    this.weChat?.share({
        type: 3,
        scene: 0,
        title: '网页标题',
        desc: '网页描述信息',
        href: 'https://www.example.com',
        imageUrl: '/static/webpage-thumb.png', // 缩略图
        success: (res) => {
            console.log('✅ 网页分享成功')
        },
        fail: (error) => {
            console.error('❌ 网页分享失败:', error)
        }
    } as wxsdk.TTWeChatShareOptions)
}

4. 分享小程序

shareMiniProgram() {
    this.weChat?.share({
        type: 4,
        scene: 0,
        title: '小程序标题',
        desc: '小程序描述',
        miniProgram: {
            userName: 'gh_xxxxxxxxxxxx', // 小程序原始ID
            path: 'pages/index/index',   // 小程序页面路径
            webpageUrl: 'https://www.example.com', // 兼容网页
            miniProgramType: 0 // 正式版
        } as wxsdk.TTWeChatShareMiniProgramOptions,
        success: (res) => {
            console.log('✅ 小程序分享成功')
        },
        fail: (error) => {
            console.error('❌ 小程序分享失败:', error)
        }
    } as wxsdk.TTWeChatShareOptions)
}

微信支付功能

💡 调用微信客户端进行支付,支付参数需要从后端服务器获取

参数说明

TTWeChatPayOptions

参数 类型 必填 说明
partnerId string 商家向财付通申请的商家ID
prepayId string 预支付订单ID
nonceStr string 随机字符串,不超过32位
timeStamp number 时间戳,防重发
package string 扩展字段,统一下单接口返回的prepay_id参数值
sign string 签名,根据微信开放平台文档生成

示例代码

// 微信支付
handleWeChatPay() {
    // 先检查微信是否安装
    if (!this.checkWeChatInstalled()) {
        return
    }

    // 从后端获取支付参数
    this.getPaymentParams().then(params => {
        this.weChat?.pay({
            partnerId: params.partnerId,
            prepayId: params.prepayId,
            nonceStr: params.nonceStr,
            package: params.package,
            timeStamp: params.timeStamp,
            sign: params.sign,
            success: (res) => {
                console.log("✅ 支付成功");
                uni.showToast({
                    title: '支付成功',
                    icon: 'success'
                })
                // 处理支付成功逻辑
                this.handlePaymentSuccess(res)
            },
            fail: (error) => {
                console.error("❌ 支付失败:", error);
                uni.showToast({
                    title: '支付失败',
                    icon: 'error'
                })
                // 处理支付失败逻辑
                this.handlePaymentFail(error)
            }
        } as wxsdk.TTWeChatPayOptions);
    })
}

// 从后端获取支付参数
getPaymentParams() {
    return new Promise((resolve, reject) => {
        uni.request({
            url: 'https://your-server.com/api/wechat/pay',
            method: 'POST',
            data: {
                orderId: 'your_order_id',
                amount: 100, // 支付金额(分)
            },
            success: (res) => {
                if (res.data.success) {
                    resolve(res.data.payParams)
                } else {
                    reject(res.data.message)
                }
            },
            fail: (err) => {
                reject(err)
            }
        })
    })
}

重要注意事项

⚠️ 安全提示

  • 支付参数必须从服务器端获取,绝不可在客户端生成
  • 签名算法严格按照微信支付文档执行
  • 支付前建议先检测微信是否安装
  • 支付结果需要通过服务器回调验证,不能仅依赖客户端返回

打开微信小程序

💡 从您的应用直接跳转到指定的微信小程序

参数说明

TTWeChatLaunchMiniProgramOptions

参数 类型 必填 说明
userName string 小程序原始ID (以 gh_ 开头)
path string 小程序页面路径
miniProgramType number 版本类型:0-正式版,1-开发版,2-体验版(默认0)

示例代码

// 打开微信小程序
openMiniProgram() {
    // 先检查微信是否安装
    if (!this.checkWeChatInstalled()) {
        return
    }

    this.weChat?.launchMiniProgram({
        userName: "gh_xxxxxxxxxxxx", // 小程序原始ID
        path: "pages/index/index?param=value", // 可以带参数
        miniProgramType: 0, // 正式版
        success: (e) => {
            console.log("✅ 成功打开小程序");
        },
        fail: (err) => {
            console.error("❌ 打开小程序失败:", err);
            uni.showToast({
                title: '打开失败',
                icon: 'error'
            })
        }
    } as wxsdk.TTWeChatLaunchMiniProgramOptions);
}

打开微信客服

💡 打开企业微信客服功能,为用户提供在线客服支持

参数说明

TTWeChatOpenCustomerServiceOptions

参数 类型 必填 说明
corpId string 企业微信的企业ID
url string 客服会话URL

示例代码

// 打开微信客服
openCustomerService() {
    // 先检查微信是否安装
    if (!this.checkWeChatInstalled()) {
        return
    }

    this.weChat?.openCustomerService({
        corpId: 'your_corp_id', // 企业微信ID
        url: 'https://work.weixin.qq.com/kf/xxx', // 客服URL
        success: (e) => {
            console.log("✅ 成功打开客服");
        },
        fail: (err) => {
            console.error("❌ 打开客服失败:", err);
            uni.showToast({
                title: '打开客服失败',
                icon: 'error'
            })
        }
    } as wxsdk.TTWeChatOpenCustomerServiceOptions);
}

错误处理

错误码说明

错误码 错误信息 适用场景 解决方案
基础错误
101 未安装微信 所有功能 提示用户安装微信客户端
102 SDK未初始化或初始化失败 所有功能 检查SDK初始化参数,重新注册
分享错误
301 type参数非法 分享功能 检查分享类型参数(0-5)
302 scene参数非法 分享功能 检查分享场景参数(0-2)
303 imageUrl不能为空 图片分享 提供有效的本地图片路径
304 图片类型的分享imageUrl参数异常 图片分享 检查图片路径和文件格式
305 title不能为空 文本分享 提供分享标题
306 videoUrl不能为空 视频分享 提供有效的视频链接
307 href不能为空 网页分享 提供有效的网页链接
308 miniProgram不能为空 小程序分享 提供完整的小程序信息
309 musicUrl不能为空 音乐分享 提供有效的音乐链接
小程序相关
401 userName不能为空 打开小程序 提供小程序原始ID
402 path不能为空 打开小程序 提供小程序页面路径
客服相关
501 corpId不能为空 打开客服 提供企业微信ID
502 url不能为空 打开客服 提供客服会话URL
其他错误
999 其他错误 所有功能 查看微信原始错误码和详细信息

错误处理最佳实践

// 统一错误处理函数
handleWeChatError(error: any, action: string) {
    console.error(`❌ ${action}失败:`, error)

    // 获取错误码和错误信息
    const errCode = error.errCode || error.code
    const errMsg = error.errMsg || error.message

    switch(errCode) {
        case 101:
            uni.showModal({
                title: '微信未安装',
                content: '请先安装微信客户端后再试',
                showCancel: false,
                confirmText: '知道了'
            })
            break

        case 102:
            uni.showModal({
                title: 'SDK初始化失败',
                content: '请检查微信AppID配置是否正确',
                showCancel: false
            })
            break

        case 301:
        case 302:
            uni.showToast({
                title: '分享参数错误',
                icon: 'error'
            })
            break

        case 303:
        case 304:
            uni.showToast({
                title: '分享图片无效',
                icon: 'error'
            })
            break

        case 305:
            uni.showToast({
                title: '请输入分享标题',
                icon: 'error'
            })
            break

        case 306:
        case 307:
        case 308:
        case 309:
            uni.showToast({
                title: '分享内容不完整',
                icon: 'error'
            })
            break

        case 401:
        case 402:
            uni.showToast({
                title: '小程序信息不完整',
                icon: 'error'
            })
            break

        case 501:
        case 502:
            uni.showToast({
                title: '客服信息不完整',
                icon: 'error'
            })
            break

        case 999:
            // 其他错误,显示具体错误信息
            uni.showToast({
                title: errMsg || '操作失败',
                icon: 'error'
            })
            break

        default:
            // 微信SDK原始错误,可能是用户取消等
            if (errMsg && errMsg !== '用户取消') {
                uni.showToast({
                    title: errMsg,
                    icon: 'error'
                })
            }
            break
    }
}

// 使用示例
this.weChat?.login({
    state: Date.now().toString(),
    success: (result) => {
        console.log('登录成功:', result)
    },
    fail: (error) => {
        this.handleWeChatError(error, '微信登录')
    }
} as wxsdk.TTWeChatLoginOptions)

调试技巧

// 开发环境下打印详细错误信息
debugWeChatError(error: any) {
    if (process.env.NODE_ENV === 'development') {
        console.group('🐛 微信SDK错误详情')
        console.log('错误码:', error.errCode || error.code)
        console.log('错误信息:', error.errMsg || error.message)
        console.log('错误主体:', error.errSubject)
        console.log('原始错误:', error.cause)
        console.groupEnd()
    }
}

常见问题

1. 找不到插件方法?

解决方案: 确保使用自定义基座运行,标准基座不包含原生插件。

2. iOS平台分享/登录无响应?

解决方案:

  • 检查 Info.plist 中的 URL Scheme 配置
  • 确认通用链接配置正确
  • 验证微信开放平台的 iOS 应用配置

3. Android平台功能异常?

解决方案:

  • 确认应用签名与微信开放平台配置一致
  • 检查包名是否正确
  • 确保微信客户端版本支持相关功能

4. 分享图片失败?

解决方案:

  • 确保图片路径为本地路径
  • 检查图片文件是否存在
  • 图片大小不要超过限制(建议小于32KB)

5. 小程序跳转失败?

解决方案:

  • 确认小程序原始ID正确(以 gh_ 开头)
  • 检查小程序是否已发布
  • 验证跳转路径是否存在

6. 支付功能失败?

解决方案:

  • 确保支付参数从服务器正确获取
  • 检查签名算法是否正确
  • 验证商户配置是否完整
  • 确认微信客户端支持支付功能

📞 技术支持

如果在使用过程中遇到问题,请:

  1. 查阅上方常见问题
  2. 参考微信官方开发文档
  3. 检查配置是否正确
  4. 确认微信客户端版本

祝您开发愉快! 🎉

隐私、权限声明

1. 需要申请的系统权限列表:

2. 采集的数据、发送的服务器地址、以及数据用途说明:

3. 是否包含广告,如包含需详细说明广告表达方式、展示频率: