Getting Started
Este contenido aún no está disponible en tu idioma.
-
Install the package
Ventana de terminal npm i @capgo/capacitor-wechatVentana de terminal pnpm add @capgo/capacitor-wechatVentana de terminal yarn add @capgo/capacitor-wechatVentana de terminal bun add @capgo/capacitor-wechat -
Sync with native projects
Ventana de terminal npx cap syncVentana de terminal pnpm cap syncVentana de terminal yarn cap syncVentana de terminal bunx cap sync
Configuration
Section titled “Configuration”WeChat App Registration
Section titled “WeChat App Registration”Before using this plugin, you must register your app on the WeChat Open Platform to obtain an App ID.
iOS Configuration
Section titled “iOS Configuration”Add the following to your 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>You’ll need to integrate the WeChat SDK into your iOS project. Add the WeChat SDK to your Podfile or download it from the WeChat Open Platform.
Android Configuration
Section titled “Android Configuration”Add the following to your 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>You’ll need to integrate the WeChat SDK into your Android project. Add the WeChat SDK dependency to your build.gradle or download it from the WeChat Open Platform.
Check WeChat Installation
Section titled “Check WeChat Installation”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'); }};Authentication
Section titled “Authentication”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); }};Share Content
Section titled “Share Content”Share Text
Section titled “Share Text”const shareText = async () => { await CapacitorWechat.share({ scene: 0, // 0 = Chat, 1 = Moments, 2 = Favorite type: 'text', text: 'Hello from Capacitor WeChat!' });};Share Link
Section titled “Share Link”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' });};Share Image
Section titled “Share Image”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' });};WeChat Pay
Section titled “WeChat Pay”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); }};Open Mini Program
Section titled “Open Mini Program”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 Reference
Section titled “API Reference”isInstalled()
Section titled “isInstalled()”Check if WeChat app is installed on the device.
const result = await CapacitorWechat.isInstalled();// Returns: { installed: boolean }auth(options)
Section titled “auth(options)”Authenticate user with WeChat 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 }share(options)
Section titled “share(options)”Share content to WeChat.
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);sendPaymentRequest(options)
Section titled “sendPaymentRequest(options)”Send payment request to WeChat Pay.
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(options)
Section titled “openMiniProgram(options)”Open WeChat mini-program.
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);chooseInvoice(options)
Section titled “chooseInvoice(options)”Choose invoice from WeChat (for business apps).
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()”Get the native plugin version.
const result = await CapacitorWechat.getPluginVersion();// Returns: { version: string }Complete Example
Section titled “Complete Example”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 }); }}Important Notes
Section titled “Important Notes”-
WeChat SDK Integration: This plugin provides the Capacitor interface, but you need to integrate the official WeChat SDK into your native projects.
-
App Registration: You must register your app on the WeChat Open Platform to get an App ID.
-
Universal Links (iOS): For iOS 13+, you need to configure Universal Links for WeChat callbacks.
-
Backend Integration: Authentication and payment features require backend integration to exchange codes for tokens and prepare payment parameters.
-
Testing: WeChat features require testing on physical devices - they will not work in simulators.
Best Practices
Section titled “Best Practices”- Always check if WeChat is installed before attempting to use features.
- Handle errors gracefully with try-catch blocks.
- Use state parameter in auth requests for CSRF protection.
- Validate payment responses on your backend before granting access.
- Compress images before sharing to reduce data usage.
Platform Notes
Section titled “Platform Notes”- Requires iOS 10.0+
- Uses official WeChat SDK for iOS
- Requires Universal Links configuration for iOS 13+
Android
Section titled “Android”- Requires Android 5.0 (API 21)+
- Uses official WeChat SDK for Android
- Requires WXEntryActivity configuration
- Not supported on web platform