Erste Schritte
-
Paket installieren
Terminal-Fenster npm i @capgo/capacitor-wechatTerminal-Fenster pnpm add @capgo/capacitor-wechatTerminal-Fenster yarn add @capgo/capacitor-wechatTerminal-Fenster bun add @capgo/capacitor-wechat -
Mit nativen Projekten synchronisieren
Terminal-Fenster npx cap syncTerminal-Fenster pnpm cap syncTerminal-Fenster yarn cap syncTerminal-Fenster bunx cap sync
Konfiguration
Section titled “Konfiguration”WeChat-App-Registrierung
Section titled “WeChat-App-Registrierung”Bevor Sie dieses Plugin verwenden, müssen Sie Ihre App auf der [WeChat Open Platform] (https://open.weixin.qq.com/) registrieren, um eine App-ID zu erhalten.
iOS Konfiguration
Section titled “iOS Konfiguration”Fügen Sie Folgendes zu Ihrem Info.plist hinzu:
<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>Sie müssen WeChat SDK in Ihr iOS-Projekt integrieren. Fügen Sie WeChat SDK zu Ihrem Podfile hinzu oder laden Sie es von der [WeChat Open Platform] (https://developers.weixin.qq.com/doc/oplatform/en/Mobile_App/Access_Guide/iOS.html) herunter.
Android Konfiguration
Section titled “Android Konfiguration”Fügen Sie Folgendes zu Ihrem AndroidManifest.xml hinzu:
<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>Sie müssen WeChat SDK in Ihr Android-Projekt integrieren. Fügen Sie die WeChat-Abhängigkeit SDK zu Ihrem build.gradle hinzu oder laden Sie sie von der [WeChat Open Platform] (https://developers.weixin.qq.com/doc/oplatform/en/Mobile_App/Access_Guide/Android.html) herunter.
Nutzung
Section titled “Nutzung”Überprüfen Sie die WeChat-Installation
Section titled “Überprüfen Sie die 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'); }};Authentifizierung
Section titled “Authentifizierung”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); }};Inhalte teilen
Section titled “Inhalte teilen”Text teilen
Section titled “Text teilen”const shareText = async () => { await CapacitorWechat.share({ scene: 0, // 0 = Chat, 1 = Moments, 2 = Favorite type: 'text', text: 'Hello from Capacitor WeChat!' });};Link teilen
Section titled “Link teilen”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' });};Bild teilen
Section titled “Bild teilen”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-Bezahlung
Section titled “WeChat-Bezahlung”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); }};Öffnen Sie das Miniprogramm
Section titled “Öffnen Sie das Miniprogramm”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 Referenz
Section titled “API Referenz”isInstalled()
Section titled “isInstalled()”Überprüfen Sie, ob die WeChat-App auf dem Gerät installiert ist.
const result = await CapacitorWechat.isInstalled();// Returns: { installed: boolean }auth(Optionen)
Section titled “auth(Optionen)”Authentifizieren Sie den Benutzer mit 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 }teilen(Optionen)
Section titled “teilen(Optionen)”Teilen Sie Inhalte mit 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(Optionen)
Section titled “sendPaymentRequest(Optionen)”Senden Sie eine Zahlungsanfrage an 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(Optionen)
Section titled “openMiniProgram(Optionen)”Öffnen Sie das WeChat-Miniprogramm.
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);ChooseRechnung(Optionen)
Section titled “ChooseRechnung(Optionen)”Wählen Sie Rechnung von WeChat (für 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()”Holen Sie sich die native Plugin-Version.
const result = await CapacitorWechat.getPluginVersion();// Returns: { version: string }Vollständiges Beispiel
Section titled “Vollständiges Beispiel”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 }); }}Wichtige Hinweise
Section titled “Wichtige Hinweise”-
WeChat SDK-Integration: Dieses Plugin stellt die Capacitor-Schnittstelle bereit, Sie müssen jedoch das offizielle WeChat SDK in Ihre nativen Projekte integrieren.
-
App-Registrierung: Sie müssen Ihre App auf der [Offenen WeChat-Plattform] (https://open.weixin.qq.com/) registrieren, um eine App-ID zu erhalten.
-
Universelle Links (iOS): Für iOS 13+ müssen Sie universelle Links für WeChat-Rückrufe konfigurieren.
-
Backend-Integration: Authentifizierungs- und Zahlungsfunktionen erfordern eine Backend-Integration, um Codes gegen Token auszutauschen und Zahlungsparameter vorzubereiten.
-
Testen: WeChat-Funktionen müssen auf physischen Geräten getestet werden – sie funktionieren nicht in Simulatoren.
Bewährte Methoden
Section titled “Bewährte Methoden”- Überprüfen Sie immer, ob WeChat installiert ist, bevor Sie versuchen, Funktionen zu nutzen.
- Fehler elegant behandeln mit Try-Catch-Blöcken.
- Statusparameter verwenden in Authentifizierungsanfragen für den CSRF-Schutz.
- Überprüfen Sie Zahlungsantworten in Ihrem Backend, bevor Sie Zugriff gewähren.
- Komprimieren Sie Bilder vor dem Teilen, um den Datenverbrauch zu reduzieren.
Plattformhinweise
Section titled “Plattformhinweise”- Erfordert iOS 10.0+
- Verwendet den offiziellen WeChat SDK für iOS
- Erfordert Universal Links-Konfiguration für iOS 13+### Android
- Erfordert Android 5.0 (API 21)+
- Verwendet den offiziellen WeChat SDK für Android – Erfordert die WXEntryActivity-Konfiguration
– Wird auf der Webplattform nicht unterstützt