Getting Started
Konten ini belum tersedia dalam bahasa Anda.
-
Install the package
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 -
Sync with native projects
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window 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