@capgo/capacitor-wechat

中文文档
8.0.56发布于 2026/11/02MPL-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 2381

WeChat SDK for Capacitor - enables authentication, sharing, payments, and mini-programs

原始使用文档
文档目录33 节
  1. ➡️ Get started for free
  2. Key features
  3. Documentation
  4. Compatibility
  5. Install
  6. Configuration
  7. Capacitor config
  8. iOS
  9. Android
  10. Setup
  11. API
  12. initialize(...)
  13. isInstalled()
  14. auth(...)
  15. share(...)
  16. sendPaymentRequest(...)
  17. openMiniProgram(...)
  18. chooseInvoice(...)
  19. getPluginVersion()
  20. Interfaces
  21. Usage Examples
  22. Check Installation
  23. Authentication
  24. Share Content
  25. Payment
  26. Open Mini Program
  27. Important Notes
  28. Troubleshooting
  29. iOS: App crashes with NSException on startup
  30. iOS: Build errors with WechatOpenSDK
  31. Credits
  32. License
  33. Contributing

capacitor-wechat

Add WeChat login, sharing, payments and mini-programs to your Capacitor app with the official WeChat Open SDK.

Capgo - Build Capacitor apps with AI, ship updates instantly

Capgo: push fixes to your Capacitor users in minutes, build signed iOS and Android apps without a Mac, and roll back in one click.

➡️ Get started for free

14-day unlimited free trial. No credit card required

🤖 Building with an AI coding agent? Install Capgo skills so Claude Code, Codex, Cursor, Copilot, or Gemini CLI know how to install and use @capgo/capacitor-wechat in your Capacitor app: npx skills add Cap-go/capgo-skills. Then ask your agent: "Add @capgo/capacitor-wechat to my Capacitor app and wire it up." Agent setup guides · Hosted MCP

@capgo/capacitor-wechat for Capacitor apps

Key features

  • Setup: initialize() with your WeChat app ID and isInstalled() to check for the app.
  • Login: auth() runs the WeChat OAuth flow.
  • Sharing: share() to a chat, Moments or Favorites.
  • Payments: sendPaymentRequest() for WeChat Pay.
  • Mini-programs and invoices: openMiniProgram() and chooseInvoice().
  • Platforms: iOS and Android. Not available on web.

Documentation

The most complete doc is available here: https://capgo.app/docs/plugins/wechat/

Compatibility

Plugin versionCapacitor compatibilityMaintained
v8.*.*v8.*.*✅
v7.*.*v7.*.*On demand
v6.*.*v6.*.*❌
v5.*.*v5.*.*❌

Note: The major version of this plugin follows the major version of Capacitor. Use the version that matches your Capacitor installation (e.g., plugin v8 for Capacitor 8). Only the latest major version is actively maintained.

Install

You can use our AI-Assisted Setup to install the plugin. Add the Capgo skills to your AI tool using the following command:

npx skills add https://github.com/cap-go/capacitor-skills --skill capacitor-plugins

Then use the following prompt:

Use the `capacitor-plugins` skill from `cap-go/capacitor-skills` to install the `@capgo/capacitor-wechat` plugin in my project.

If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:

npm install @capgo/capacitor-wechat
npx cap sync

Configuration

Capacitor config

Add your WeChat credentials to capacitor.config.ts (or .json). You can override them at runtime by calling CapacitorWechat.initialize(...).

const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'Example',
  webDir: 'dist',
  plugins: {
    CapacitorWechat: {
      appId: 'wx1234567890abcdef',
      universalLink: 'https://your-universal-link.example.com/'
    }
  }
};

iOS

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.

Important: iOS requires a valid Universal Link to be configured. You must set the universalLink parameter either in your capacitor.config (as shown above) or when calling initialize(). Without a valid Universal Link, the app will crash during WeChat SDK initialization. Learn more about configuring Universal Links in the WeChat iOS documentation.

Android

The plugin ships an AndroidManifest.xml with the Android 11+ package visibility query for WeChat (com.tencent.mm). That is required for isInstalled() / isWXAppInstalled() to work on Android 11 and newer. If you maintain a custom manifest merge setup, add:

<queries>
  <package android:name="com.tencent.mm" />
</queries>

Also add the WeChat callback activity to your app 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.

Create WXEntryActivity and WXPayEntryActivity inside your application's package (your.package.name.wxapi). Both activities should extend ee.forgr.plugin.capacitor_wechat.WechatResponseActivity so the plugin can receive callbacks from WeChat:

package your.package.name.wxapi;

import ee.forgr.plugin.capacitor_wechat.WechatResponseActivity;

public class WXEntryActivity extends WechatResponseActivity {}

public class WXPayEntryActivity extends WechatResponseActivity {}

Register these activities in your app manifest just like the snippet above (WeChat requires both for general SDK + Pay callbacks).

Setup

Before using any WeChat functionality, you need to register your app with a WeChat App ID from the WeChat Open Platform. Once you have the credentials, either place them in capacitor.config or call CapacitorWechat.initialize before making other calls:

import { CapacitorWechat } from '@capgo/capacitor-wechat';

await CapacitorWechat.initialize({
  appId: 'wx1234567890abcdef',
  universalLink: 'https://your-universal-link.example.com/'
});

API

Capacitor WeChat Plugin - WeChat SDK integration for authentication, sharing, payments, and mini-programs.

initialize(...)

initialize(options: WechatInitializationOptions) => Promise<void>

Initialize the WeChat SDK with your application credentials.

You can also set these values in capacitor.config.ts under the CapacitorWechat plugin configuration. Calling this method overrides any bundled configuration at runtime.

ParamTypeDescription
optionsWechatInitializationOptions- Initialization options including the required WeChat App ID

Since: 1.1.0


isInstalled()

isInstalled() => Promise<{ installed: boolean; }>

Check if WeChat app is installed on the device.

Returns: Promise<{ installed: boolean; }>

Since: 1.0.0


auth(...)

auth(options: WechatAuthOptions) => Promise<WechatAuthResponse>

Authenticate user with WeChat OAuth.

ParamTypeDescription
optionsWechatAuthOptions- Authentication options including scope

Returns: Promise<WechatAuthResponse>

Since: 1.0.0


share(...)

share(options: WechatShareOptions) => Promise<void>

Share content to WeChat.

ParamTypeDescription
optionsWechatShareOptions- Share options including type, scene, and content

Since: 1.0.0


sendPaymentRequest(...)

sendPaymentRequest(options: WechatPaymentOptions) => Promise<void>

Send payment request to WeChat Pay.

ParamTypeDescription
optionsWechatPaymentOptions- Payment request options from server

Since: 1.0.0


openMiniProgram(...)

openMiniProgram(options: WechatMiniProgramOptions) => Promise<{ extMsg?: string; }>

Open WeChat mini-program.

ParamTypeDescription
optionsWechatMiniProgramOptions- Mini-program options including username and path

Returns: Promise<{ extMsg?: string; }>

Since: 1.0.0


chooseInvoice(...)

chooseInvoice(options: WechatInvoiceOptions) => Promise<WechatInvoiceResponse>

Choose invoice from WeChat.

ParamTypeDescription
optionsWechatInvoiceOptions- Invoice selection options

Returns: Promise<WechatInvoiceResponse>

Since: 1.0.0


getPluginVersion()

getPluginVersion() => Promise<{ version: string; }>

Get the native Capacitor plugin version.

Returns: Promise<{ version: string; }>

Since: 1.0.0


Interfaces

WechatInitializationOptions

WeChat initialization options.

PropTypeDescription
appIdstringRequired WeChat application ID.
universalLinkstringiOS universal link that is associated with your WeChat application.

WechatAuthResponse

WeChat authentication response.

PropTypeDescription
codestringAuthorization code to exchange for access token.
statestringState parameter if provided in request.

WechatAuthOptions

WeChat authentication options.

PropTypeDescription
scopestringOAuth scope. Use 'snsapi_userinfo' for user info or 'snsapi_login' for login only.
statestringOptional state parameter for CSRF protection.

WechatShareOptions

WeChat share options.

PropTypeDescription
scenenumberShare scene: 0 = Session (chat), 1 = Timeline (moments), 2 = Favorite.
type'text' | 'image' | 'link' | 'music' | 'video' | 'miniprogram'Share type: 'text', 'image', 'link', 'music', 'video', 'miniprogram'.
textstringText content (for type 'text').
titlestringTitle (for type 'link', 'music', 'video', 'miniprogram').
descriptionstringDescription (for type 'link', 'music', 'video', 'miniprogram').
linkstringLink URL (for type 'link').
imageUrlstringImage URL or base64 data.
thumbUrlstringThumbnail URL or base64 data (for type 'link', 'music', 'video').
mediaUrlstringMusic or video URL (for type 'music', 'video').
miniProgramUsernamestringMini-program username (for type 'miniprogram').
miniProgramPathstringMini-program path (for type 'miniprogram').
miniProgramTypenumberMini-program type: 0 = Release, 1 = Test, 2 = Preview (for type 'miniprogram').
miniProgramWebPageUrlstringMini-program web page URL fallback (for type 'miniprogram').

WechatPaymentOptions

WeChat payment options.

PropTypeDescription
partnerIdstringPartner ID (merchant ID).
prepayIdstringPrepay ID from unified order API.
nonceStrstringRandom string.
timeStampstringTimestamp.
packagestringPackage value, typically 'Sign=WXPay'.
signstringSignature.

WechatMiniProgramOptions

WeChat mini-program options.

PropTypeDescription
usernamestringMini-program username (original ID).
pathstringPath to open in mini-program.
typenumberMini-program type: 0 = Release, 1 = Test, 2 = Preview.

WechatInvoiceResponse

WeChat invoice response.

PropTypeDescription
cardsWechatInvoiceCard[]Array of selected card IDs.

WechatInvoiceCard

WeChat invoice card item.

PropTypeDescription
cardIdstringThe selected card identifier.
encryptCodestringEncrypted code returned by WeChat.

WechatInvoiceOptions

WeChat invoice options.

PropTypeDescription
appIdstringApp ID.
signTypestringSignature type.
cardSignstringCard signature.
timeStampstringTimestamp.
nonceStrstringRandom string.

Usage Examples

Check Installation

import { CapacitorWechat } from '@capgo/capacitor-wechat';

const checkWechat = async () => {
  const { installed } = await CapacitorWechat.isInstalled();
  console.log('WeChat installed:', installed);
};

Authentication

const loginWithWechat = async () => {
  try {
    const { code } = await CapacitorWechat.auth({
      scope: 'snsapi_userinfo',
      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',
      body: JSON.stringify({ code })
    });

    const { access_token } = await response.json();
    console.log('Access token:', access_token);
  } catch (error) {
    console.error('WeChat auth failed:', error);
  }
};

Share Content

// 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
const shareLink = async () => {
  await CapacitorWechat.share({
    scene: 1,
    type: 'link',
    title: 'Check out this awesome app!',
    description: 'Built with Capacitor',
    link: 'https://capacitorjs.com',
    thumbUrl: 'https://capacitorjs.com/icon.png'
  });
};

Payment

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,
      sign: paymentParams.sign
    });

    console.log('Payment successful!');
  } catch (error) {
    console.error('Payment failed:', error);
  }
};

Open Mini Program

const openMiniProgram = async () => {
  const { extMsg } = await CapacitorWechat.openMiniProgram({
    username: 'gh_xxxxxxxxxxxxx', // Mini program original ID
    path: 'pages/index/index',
    type: 0 // 0 = Release, 1 = Test, 2 = Preview
  });

  console.log('Mini program returned:', extMsg);
};

Important Notes

  1. WeChat SDK: The plugin pulls the official SDKs via CocoaPods (WechatOpenSDK) and Gradle (com.tencent.mm.opensdk:wechat-sdk-android-without-mta). If you use a custom build setup, ensure those dependencies stay intact.

  2. App Registration: You must register your app on the WeChat Open Platform to get an App ID.

  3. Universal Links (iOS): For iOS 13+, you need to configure Universal Links for WeChat callbacks.

  4. Backend Integration: Authentication and payment features require backend integration to exchange codes for tokens and prepare payment parameters.

Troubleshooting

iOS: App crashes with NSException on startup

Problem: App crashes immediately when WeChat plugin loads with an NSException error.

Solution: This usually happens when the universalLink is not configured or is empty. Ensure you have set the universalLink in your capacitor.config or when calling initialize():

// In capacitor.config.ts
plugins: {
  CapacitorWechat: {
    appId: 'wx1234567890abcdef',
    universalLink: 'https://your-domain.com/universal-link/'  // Required for iOS!
  }
}

// Or in your app initialization
await CapacitorWechat.initialize({
  appId: 'wx1234567890abcdef',
  universalLink: 'https://your-domain.com/universal-link/'
});

Learn how to set up Universal Links for WeChat in the WeChat iOS documentation.

iOS: Build errors with WechatOpenSDK

Problem: Build fails with errors about missing WechatOpenSDK module.

Solution: Make sure the WeChat SDK is properly installed via CocoaPods. Run:

cd ios/App
pod install

Credits

This plugin was inspired by cordova-plugin-wechat and adapted for Capacitor.

License

MIT

Contributing

See CONTRIBUTING.md for details on how to contribute to this plugin.

版本与发布记录

@capgo/capacitor-wechat 共发布 66 个版本,首次发布于 2025/10/27;过去 12 个月发布了 58 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.0.56latest2026/11/027 天前
8.0.552026/10/2614 天前
8.0.542026/10/1921 天前
8.0.532026/10/1525 天前
8.0.522026/10/1327 天前
8.0.512026/10/1228 天前

关于 @capgo/capacitor-wechat 的常见问题

@capgo/capacitor-wechat 是什么?

WeChat SDK for Capacitor - enables authentication, sharing, payments, and mini-programs

如何安装 @capgo/capacitor-wechat?

在项目目录运行 npm install @capgo/capacitor-wechat,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capgo/capacitor-wechat 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@capgo/capacitor-wechat 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@capgo/capacitor-wechat 可以商用吗?

@capgo/capacitor-wechat 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@capgo/capacitor-wechat 的下载量有多少?

根据 npm 官方下载统计,@capgo/capacitor-wechat 在 2026/10/09 – 2026/11/07 这 30 天内被下载 2,381 次,日均约 79 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@capgo/capacitor-wechat 还在维护吗?

最新版本 8.0.56 发布于 2026/11/02(7 天前);至今共发布 66 个版本,其中过去 12 个月发布了 58 个;首次发布于 2025/10/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。