はじめに
-
パッケージのインストール
Terminal window npm i @capgo/capacitor-wechatTerminal window pnpm add @capgo/capacitor-wechatTerminal window yarn add @capgo/capacitor-wechatTerminal window bun add @capgo/capacitor-wechat -
ネイティブプロジェクトと同期
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync
WeChatアプリ登録
Section titled “WeChatアプリ登録”このプラグインを使用する前に、WeChat Open Platformでアプリを登録して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>iOSプロジェクトにWeChat SDKを統合する必要があります。PodfileにWeChat SDKを追加するか、WeChat Open Platformからダウンロードしてください。
Android設定
Section titled “Android設定”AndroidManifest.xmlに以下を追加します:
<manifest> <application> <!-- WeChatコールバックアクティビティ --> <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>AndroidプロジェクトにWeChat SDKを統合する必要があります。build.gradleにWeChat SDK依存関係を追加するか、WeChat Open Platformからダウンロードしてください。
WeChatインストール確認
Section titled “WeChatインストール確認”import { CapacitorWechat } from '@capgo/capacitor-wechat';
const checkWeChat = async () => { const { installed } = await CapacitorWechat.isInstalled(); if (installed) { console.log('WeChatがインストールされています'); } else { console.log('WeChatがインストールされていません'); }};const loginWithWeChat = async () => { try { const { code, state } = await CapacitorWechat.auth({ scope: 'snsapi_userinfo', // または 'snsapi_login' state: 'my_random_state' });
// バックエンドにコードを送信してアクセストークンと交換 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('WeChatでログイン:', openid); } catch (error) { console.error('WeChat認証失敗:', error); }};コンテンツ共有
Section titled “コンテンツ共有”テキスト共有
Section titled “テキスト共有”const shareText = async () => { await CapacitorWechat.share({ scene: 0, // 0 = チャット, 1 = モーメント, 2 = お気に入り type: 'text', text: 'Capacitor WeChatからこんにちは!' });};const shareLink = async () => { await CapacitorWechat.share({ scene: 1, // モーメントに共有 type: 'link', title: 'この素晴らしいアプリをチェック!', description: 'Capacitorと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', // またはbase64データ thumbUrl: 'https://example.com/thumb.png' });};WeChat Pay
Section titled “WeChat Pay”const payWithWeChat = async () => { // まず、サーバーから支払いパラメータを取得 const paymentParams = await fetchPaymentParamsFromServer();
try { await CapacitorWechat.sendPaymentRequest({ partnerId: paymentParams.partnerId, prepayId: paymentParams.prepayId, nonceStr: paymentParams.nonceStr, timeStamp: paymentParams.timeStamp, package: paymentParams.package, // 通常は 'Sign=WXPay' sign: paymentParams.sign });
console.log('支払い成功!'); } catch (error) { console.error('支払い失敗:', error); }};ミニプログラムを開く
Section titled “ミニプログラムを開く”const openMiniProgram = async () => { await CapacitorWechat.openMiniProgram({ username: 'gh_xxxxxxxxxxxxx', // ミニプログラムのオリジナルID path: 'pages/index/index', // ミニプログラム内のパス type: 0 // 0 = リリース, 1 = テスト, 2 = プレビュー });};APIリファレンス
Section titled “APIリファレンス”isInstalled()
Section titled “isInstalled()”デバイスにWeChatアプリがインストールされているか確認します。
const result = await CapacitorWechat.isInstalled();// 戻り値: { installed: boolean }auth(options)
Section titled “auth(options)”WeChat OAuthでユーザーを認証します。
interface WechatAuthOptions { scope: string; // 'snsapi_userinfo' または 'snsapi_login' state?: string; // CSRF保護用のオプションのstateパラメータ}
const result = await CapacitorWechat.auth(options);// 戻り値: { code: string, state?: string }share(options)
Section titled “share(options)”WeChatにコンテンツを共有します。
interface WechatShareOptions { scene: number; // 0 = セッション(チャット), 1 = タイムライン(モーメント), 2 = お気に入り type: 'text' | 'image' | 'link' | 'music' | 'video' | 'miniprogram'; text?: string; // タイプ 'text'の場合 title?: string; // タイプ 'link', 'music', 'video', 'miniprogram'の場合 description?: string; // タイプ 'link', 'music', 'video', 'miniprogram'の場合 link?: string; // タイプ 'link'の場合 imageUrl?: string; // 画像URLまたはbase64データ thumbUrl?: string; // サムネイルURLまたはbase64データ mediaUrl?: string; // タイプ 'music' または 'video'の場合 miniProgramUsername?: string; // タイプ 'miniprogram'の場合 miniProgramPath?: string; // タイプ 'miniprogram'の場合 miniProgramType?: number; // タイプ 'miniprogram'の場合: 0 = リリース, 1 = テスト, 2 = プレビュー miniProgramWebPageUrl?: string; // タイプ 'miniprogram'のフォールバックURL}
await CapacitorWechat.share(options);sendPaymentRequest(options)
Section titled “sendPaymentRequest(options)”WeChat Payに支払いリクエストを送信します。
interface WechatPaymentOptions { partnerId: string; // マーチャントID prepayId: string; // 統一注文APIからのプリペイID nonceStr: string; // ランダム文字列 timeStamp: string; // タイムスタンプ package: string; // 通常は 'Sign=WXPay' sign: string; // 署名}
await CapacitorWechat.sendPaymentRequest(options);openMiniProgram(options)
Section titled “openMiniProgram(options)”WeChatミニプログラムを開きます。
interface WechatMiniProgramOptions { username: string; // ミニプログラムのユーザー名(オリジナルID) path?: string; // ミニプログラムで開くパス type?: number; // 0 = リリース, 1 = テスト, 2 = プレビュー}
await CapacitorWechat.openMiniProgram(options);chooseInvoice(options)
Section titled “chooseInvoice(options)”WeChatから請求書を選択します(ビジネスアプリ用)。
interface WechatInvoiceOptions { appId: string; signType: string; cardSign: string; timeStamp: string; nonceStr: string;}
const result = await CapacitorWechat.chooseInvoice(options);// 戻り値: { cards: string[] }getPluginVersion()
Section titled “getPluginVersion()”ネイティブプラグインのバージョンを取得します。
const result = await CapacitorWechat.getPluginVersion();// 戻り値: { version: string }import { CapacitorWechat } from '@capgo/capacitor-wechat';
export class WeChatService { async init() { const { installed } = await CapacitorWechat.isInstalled(); if (!installed) { throw new Error('WeChatがインストールされていません'); } }
async login() { const { code } = await CapacitorWechat.auth({ scope: 'snsapi_userinfo', state: Math.random().toString(36).substring(7) });
// バックエンドでコードをアクセストークンと交換 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, // チャット type: 'link', title, description, link, thumbUrl: imageUrl }); }
async shareToMoments(title: string, description: string, link: string, imageUrl: string) { await CapacitorWechat.share({ scene: 1, // モーメント type: 'link', title, description, link, thumbUrl: imageUrl }); }}重要な注意事項
Section titled “重要な注意事項”-
WeChat SDK統合: このプラグインはCapacitorインターフェースを提供しますが、公式WeChat SDKをネイティブプロジェクトに統合する必要があります。
-
アプリ登録: WeChat Open Platformでアプリを登録してApp IDを取得する必要があります。
-
ユニバーサルリンク(iOS): iOS 13以降では、WeChatコールバック用にユニバーサルリンクを設定する必要があります。
-
バックエンド統合: 認証と支払い機能は、コードをトークンと交換し、支払いパラメータを準備するためのバックエンド統合が必要です。
-
テスト: WeChat機能は物理デバイスでのテストが必要です - シミュレーターでは動作しません。
ベストプラクティス
Section titled “ベストプラクティス”- 常にWeChatのインストールを確認 - 機能を使用する前に確認してください。
- エラーを適切に処理 - try-catchブロックを使用してください。
- 認証リクエストでstateパラメータを使用 - CSRF保護のために。
- バックエンドで支払い応答を検証 - アクセスを許可する前に。
- 画像を圧縮 - 共有前にデータ使用量を削減するために。
プラットフォームに関する注意事項
Section titled “プラットフォームに関する注意事項”- iOS 10.0以降が必要
- iOS用公式WeChat SDKを使用
- iOS 13以降ではユニバーサルリンク設定が必要
Android
Section titled “Android”- Android 5.0(API 21)以降が必要
- Android用公式WeChat SDKを使用
- WXEntryActivity設定が必要
- Webプラットフォームではサポートされていません