시작하기
-
패키지 설치
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 오픈 플랫폼에 앱을 등록하여 앱 ID를 받아야 합니다.
iOS 구성
Section titled “iOS 구성”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 오픈 플랫폼에서 다운로드하세요.
Android 구성
Section titled “Android 구성”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>Android 프로젝트에 WeChat SDK를 통합해야 합니다. build.gradle에 WeChat SDK 종속성을 추가하거나 WeChat 오픈 플랫폼에서 다운로드하세요.
WeChat 설치 확인
Section titled “WeChat 설치 확인”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); }};콘텐츠 공유
Section titled “콘텐츠 공유”텍스트 공유
Section titled “텍스트 공유”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' });};이미지 공유
Section titled “이미지 공유”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' });};WeChat Pay
Section titled “WeChat Pay”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); }};미니 프로그램 열기
Section titled “미니 프로그램 열기”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 });};API 참조
Section titled “API 참조”isInstalled()
Section titled “isInstalled()”기기에 WeChat 앱이 설치되어 있는지 확인합니다.
const result = await CapacitorWechat.isInstalled();// Returns: { installed: boolean }auth(options)
Section titled “auth(options)”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 }share(options)
Section titled “share(options)”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);sendPaymentRequest(options)
Section titled “sendPaymentRequest(options)”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);openMiniProgram(options)
Section titled “openMiniProgram(options)”WeChat 미니 프로그램을 엽니다.
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);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);// Returns: { cards: string[] }getPluginVersion()
Section titled “getPluginVersion()”네이티브 플러그인 버전을 가져옵니다.
const result = await CapacitorWechat.getPluginVersion();// Returns: { version: string }완전한 예제
Section titled “완전한 예제”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 }); }}중요 참고사항
Section titled “중요 참고사항”-
WeChat SDK 통합: 이 플러그인은 Capacitor 인터페이스를 제공하지만, 네이티브 프로젝트에 공식 WeChat SDK를 통합해야 합니다.
-
앱 등록: 앱 ID를 받으려면 WeChat 오픈 플랫폼에 앱을 등록해야 합니다.
-
Universal Links (iOS): iOS 13+의 경우, WeChat 콜백을 위해 Universal Links를 구성해야 합니다.
-
백엔드 통합: 인증 및 결제 기능은 코드를 토큰으로 교환하고 결제 매개변수를 준비하기 위해 백엔드 통합이 필요합니다.
-
테스팅: WeChat 기능은 물리적 기기에서 테스트해야 하며, 시뮬레이터에서는 작동하지 않습니다.
- WeChat 설치 확인: 기능을 사용하기 전에 WeChat이 설치되어 있는지 항상 확인하세요.
- 오류를 우아하게 처리: try-catch 블록을 사용하세요.
- state 매개변수 사용: CSRF 보호를 위해 인증 요청에 state 매개변수를 사용하세요.
- 결제 응답 검증: 액세스 권한을 부여하기 전에 백엔드에서 결제 응답을 검증하세요.
- 이미지 압축: 데이터 사용량을 줄이기 위해 공유하기 전에 이미지를 압축하세요.
플랫폼 참고사항
Section titled “플랫폼 참고사항”- iOS 10.0+ 필요
- iOS용 공식 WeChat SDK 사용
- iOS 13+를 위한 Universal Links 구성 필요
Android
Section titled “Android”- Android 5.0 (API 21)+ 필요
- Android용 공식 WeChat SDK 사용
- WXEntryActivity 구성 필요
- 웹 플랫폼에서 지원되지 않음