入门
-
安装软件包
Terminal window npm i @capgo/capacitor-wechatTerminal window pnpm add @capgo/capacitor-wechatTerminal window yarn add @capgo/capacitor-wechatTerminal window bun add @capgo/capacitor-wechat -
与原生项目同步
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync
微信小程序注册
Section titled “微信小程序注册”使用本插件前,您必须在【微信开放平台】(https://open.weixin.qq.com/)注册您的应用,获取App ID。
iOS 配置
Section titled “iOS 配置”将以下内容添加到您的 Info.plist 中:
<key>LSApplicationQueriesSchemes</key><array> <string>weixin</string> <string>weixinULAPI</string></array>
<key>CFBundleURLTypes</key><array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLName</key> <string>weixin</string> <key>CFBundleURLSchemes</key> <array> <string>YOUR_WECHAT_APP_ID</string> </array> </dict></array>您需要将微信SDK集成到您的iOS项目中。将微信SDK添加到您的Podfile中或从【微信开放平台】(https://developers.weixin.qq.com/doc/oplatform/en/Mobile_App/Access_Guide/iOS.html)下载。
Android 配置
Section titled “Android 配置”将以下内容添加到您的 AndroidManifest.xml 中:
<manifest> <application> <!-- WeChat callback activity --> <activity android:name=".wxapi.WXEntryActivity" android:exported="true" android:label="@string/app_name" android:launchMode="singleTask" android:theme="@android:style/Theme.Translucent.NoTitleBar"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application></manifest>您需要将微信SDK集成到您的Android项目中。将微信SDK依赖添加到您的build.gradle中,或者从【微信开放平台】(https://developers.weixin.qq.com/doc/oplatform/en/Mobile_App/Access_Guide/Android.html)下载。
检查微信安装情况
Section titled “检查微信安装情况”import { CapacitorWechat } from '@capgo/capacitor-wechat';
const checkWeChat = async () => { const { installed } = await CapacitorWechat.isInstalled(); if (installed) { console.log('WeChat is installed'); } else { console.log('WeChat is not installed'); }};const loginWithWeChat = async () => { try { const { code, state } = await CapacitorWechat.auth({ scope: 'snsapi_userinfo', // or 'snsapi_login' state: 'my_random_state' });
// Send code to your backend to exchange for access token const response = await fetch('https://yourapi.com/auth/wechat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }) });
const { access_token, openid } = await response.json(); console.log('Logged in with WeChat:', openid); } catch (error) { console.error('WeChat auth failed:', error); }};const shareText = async () => { await CapacitorWechat.share({ scene: 0, // 0 = Chat, 1 = Moments, 2 = Favorite type: 'text', text: 'Hello from Capacitor WeChat!' });};const shareLink = async () => { await CapacitorWechat.share({ scene: 1, // Share to Moments type: 'link', title: 'Check out this awesome app!', description: 'Built with Capacitor and WeChat SDK', link: 'https://capacitorjs.com', thumbUrl: 'https://capacitorjs.com/icon.png' });};const shareImage = async () => { await CapacitorWechat.share({ scene: 0, type: 'image', imageUrl: 'https://example.com/image.png', // or base64 data thumbUrl: 'https://example.com/thumb.png' });};###微信支付
const payWithWeChat = async () => { // First, get payment parameters from your server const paymentParams = await fetchPaymentParamsFromServer();
try { await CapacitorWechat.sendPaymentRequest({ partnerId: paymentParams.partnerId, prepayId: paymentParams.prepayId, nonceStr: paymentParams.nonceStr, timeStamp: paymentParams.timeStamp, package: paymentParams.package, // Usually 'Sign=WXPay' sign: paymentParams.sign });
console.log('Payment successful!'); } catch (error) { console.error('Payment failed:', error); }};const openMiniProgram = async () => { await CapacitorWechat.openMiniProgram({ username: 'gh_xxxxxxxxxxxxx', // Mini program original ID path: 'pages/index/index', // Path within mini program type: 0 // 0 = Release, 1 = Test, 2 = Preview });};API 参考
Section titled “API 参考”isInstalled()
Section titled “isInstalled()”检查设备上是否安装了微信应用。
const result = await CapacitorWechat.isInstalled();// Returns: { installed: boolean }身份验证(选项)
Section titled “身份验证(选项)”使用微信OAuth验证用户身份。
interface WechatAuthOptions { scope: string; // 'snsapi_userinfo' or 'snsapi_login' state?: string; // Optional state parameter for CSRF protection}
const result = await CapacitorWechat.auth(options);// Returns: { code: string, state?: string }分享(选项)
Section titled “分享(选项)”分享内容到微信。
interface WechatShareOptions { scene: number; // 0 = Session (chat), 1 = Timeline (moments), 2 = Favorite type: 'text' | 'image' | 'link' | 'music' | 'video' | 'miniprogram'; text?: string; // For type 'text' title?: string; // For type 'link', 'music', 'video', 'miniprogram' description?: string; // For type 'link', 'music', 'video', 'miniprogram' link?: string; // For type 'link' imageUrl?: string; // Image URL or base64 data thumbUrl?: string; // Thumbnail URL or base64 data mediaUrl?: string; // For type 'music' or 'video' miniProgramUsername?: string; // For type 'miniprogram' miniProgramPath?: string; // For type 'miniprogram' miniProgramType?: number; // For type 'miniprogram': 0 = Release, 1 = Test, 2 = Preview miniProgramWebPageUrl?: string; // Fallback URL for type 'miniprogram'}
await CapacitorWechat.share(options);发送付款请求(选项)
Section titled “发送付款请求(选项)”向微信支付发送支付请求。
interface WechatPaymentOptions { partnerId: string; // Merchant ID prepayId: string; // Prepay ID from unified order API nonceStr: string; // Random string timeStamp: string; // Timestamp package: string; // Usually 'Sign=WXPay' sign: string; // Signature}
await CapacitorWechat.sendPaymentRequest(options);openMiniProgram(选项)
Section titled “openMiniProgram(选项)”打开微信小程序。
interface WechatMiniProgramOptions { username: string; // Mini-program username (original ID) path?: string; // Path to open in mini-program type?: number; // 0 = Release, 1 = Test, 2 = Preview}
await CapacitorWechat.openMiniProgram(options);选择发票(选项)
Section titled “选择发票(选项)”选择微信发票(适用于商业应用)。
interface WechatInvoiceOptions { appId: string; signType: string; cardSign: string; timeStamp: string; nonceStr: string;}
const result = await CapacitorWechat.chooseInvoice(options);// Returns: { cards: string[] }getPluginVersion()
Section titled “getPluginVersion()”获取本机插件版本。
const result = await CapacitorWechat.getPluginVersion();// Returns: { version: string }import { CapacitorWechat } from '@capgo/capacitor-wechat';
export class WeChatService { async init() { const { installed } = await CapacitorWechat.isInstalled(); if (!installed) { throw new Error('WeChat is not installed'); } }
async login() { const { code } = await CapacitorWechat.auth({ scope: 'snsapi_userinfo', state: Math.random().toString(36).substring(7) });
// Exchange code for access token on your backend const response = await fetch('/api/auth/wechat', { method: 'POST', body: JSON.stringify({ code }) });
return response.json(); }
async shareToChat(title: string, description: string, link: string, imageUrl: string) { await CapacitorWechat.share({ scene: 0, // Chat type: 'link', title, description, link, thumbUrl: imageUrl }); }
async shareToMoments(title: string, description: string, link: string, imageUrl: string) { await CapacitorWechat.share({ scene: 1, // Moments type: 'link', title, description, link, thumbUrl: imageUrl }); }}-
微信SDK集成:该插件提供了Capacitor接口,但您需要将官方微信SDK集成到您的原生项目中。
-
应用注册:您必须在【微信开放平台】(https://open.weixin.qq.com/)上注册您的应用才能获得应用ID。
-
通用链接(iOS):对于iOS 13+,您需要配置微信回调通用链接。
-
后端集成:身份验证和支付功能需要后端集成,以将代码交换为令牌并准备支付参数。
-
测试:微信功能需要在物理设备上进行测试 - 它们无法在模拟器中运行。
- 在尝试使用功能之前,请务必检查是否安装了微信。
- 使用 try-catch 块优雅地处理错误。
- 在身份验证请求中使用状态参数以实现 CSRF 保护。
- 在授予访问权限之前在后端验证付款响应。
- 在共享之前压缩图像以减少数据使用。
- 需要 iOS 10.0+
- iOS使用官方微信SDK
- 需要 iOS 13+ 的通用链接配置### Android
- 需要 Android 5.0 (API 21)+
- Android使用官方微信SDK
- 需要WXEntryActivity配置
- 不支持网络平台