capacitor-wechat

January 31, 2026 ยท View on GitHub

Capgo - Instant updates for capacitor

โžก๏ธ Get Instant updates for your App with Capgo

Missing a feature? We'll build the plugin for you ๐Ÿ’ช

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

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

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

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.

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.