跳转到内容

入门

  1. 安装软件包

    Terminal window
    npm i @capgo/capacitor-wechat
  2. 与原生项目同步

    Terminal window
    npx cap sync

使用本插件前,您必须在【微信开放平台】(https://open.weixin.qq.com/)注册您的应用,获取App ID。

将以下内容添加到您的 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)下载。

将以下内容添加到您的 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)下载。

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

检查设备上是否安装了微信应用。

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

使用微信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 }

分享内容到微信。

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

向微信支付发送支付请求。

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

打开微信小程序。

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

选择微信发票(适用于商业应用)。

interface WechatInvoiceOptions {
appId: string;
signType: string;
cardSign: string;
timeStamp: string;
nonceStr: string;
}
const result = await CapacitorWechat.chooseInvoice(options);
// Returns: { cards: string[] }

获取本机插件版本。

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. 微信SDK集成:该插件提供了Capacitor接口,但您需要将官方微信SDK集成到您的原生项目中。

  2. 应用注册:您必须在【微信开放平台】(https://open.weixin.qq.com/)上注册您的应用才能获得应用ID。

  3. 通用链接(iOS):对于iOS 13+,您需要配置微信回调通用链接。

  4. 后端集成:身份验证和支付功能需要后端集成,以将代码交换为令牌并准备支付参数。

  5. 测试:微信功能需要在物理设备上进行测试 - 它们无法在模拟器中运行。

  1. 在尝试使用功能之前,请务必检查是否安装了微信
  2. 使用 try-catch 块优雅地处理错误
  3. 在身份验证请求中使用状态参数以实现 CSRF 保护。
  4. 在授予访问权限之前在后端验证付款响应
  5. 在共享之前压缩图像以减少数据使用。
  • 需要 iOS 10.0+
  • iOS使用官方微信SDK
  • 需要 iOS 13+ 的通用链接配置### Android
  • 需要 Android 5.0 (API 21)+
  • Android使用官方微信SDK
  • 需要WXEntryActivity配置
  • 不支持网络平台