Zum Inhalt springen

Erste Schritte

  1. Paket installieren

    Terminal-Fenster
    npm i @capgo/capacitor-wechat
  2. Mit nativen Projekten synchronisieren

    Terminal-Fenster
    npx cap sync

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.

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.

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.

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
});
};

Überprüfen Sie, ob die WeChat-App auf dem Gerät installiert ist.

const result = await CapacitorWechat.isInstalled();
// Returns: { installed: boolean }

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 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);

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);

Ö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);

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[] }

Holen Sie sich die native Plugin-Version.

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
});
}
}
  1. WeChat SDK-Integration: Dieses Plugin stellt die Capacitor-Schnittstelle bereit, Sie müssen jedoch das offizielle WeChat SDK in Ihre nativen Projekte integrieren.

  2. App-Registrierung: Sie müssen Ihre App auf der [Offenen WeChat-Plattform] (https://open.weixin.qq.com/) registrieren, um eine App-ID zu erhalten.

  3. Universelle Links (iOS): Für iOS 13+ müssen Sie universelle Links für WeChat-Rückrufe konfigurieren.

  4. Backend-Integration: Authentifizierungs- und Zahlungsfunktionen erfordern eine Backend-Integration, um Codes gegen Token auszutauschen und Zahlungsparameter vorzubereiten.

  5. Testen: WeChat-Funktionen müssen auf physischen Geräten getestet werden – sie funktionieren nicht in Simulatoren.

  1. Überprüfen Sie immer, ob WeChat installiert ist, bevor Sie versuchen, Funktionen zu nutzen.
  2. Fehler elegant behandeln mit Try-Catch-Blöcken.
  3. Statusparameter verwenden in Authentifizierungsanfragen für den CSRF-Schutz.
  4. Überprüfen Sie Zahlungsantworten in Ihrem Backend, bevor Sie Zugriff gewähren.
  5. Komprimieren Sie Bilder vor dem Teilen, um den Datenverbrauch zu reduzieren.
  • 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