### Start Example App Packager Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/CONTRIBUTING.md Starts the Metro server for the example application. Changes in JavaScript code will be reflected without a rebuild. ```sh yarn example start ``` -------------------------------- ### Bootstrap Project Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/CONTRIBUTING.md Installs all project dependencies and pods. This is a comprehensive setup script for the development environment. ```sh yarn bootstrap ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/CONTRIBUTING.md Run this command in the root directory to install all necessary dependencies for the project packages. ```sh yarn ``` -------------------------------- ### Run Example App on Android Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/CONTRIBUTING.md Builds and runs the example application on an Android device or emulator. Native code changes require a rebuild. ```sh yarn example android ``` -------------------------------- ### Check WeChat Installation and Support Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/README.md Provides methods to check if WeChat is installed on the device and if the installed version supports the required APIs. ```APIDOC ## GET /isWXAppInstalled ### Description Checks if the WeChat application is installed on the device. ### Method GET ### Endpoint /isWXAppInstalled ### Parameters None ### Response #### Success Response (200) - **isInstalled** (Boolean) - True if WeChat is installed, false otherwise. ## GET /isWXAppSupportApi ### Description Checks if the installed WeChat version supports opening URLs via the SDK. ### Method GET ### Endpoint /isWXAppSupportApi ### Parameters None ### Response #### Success Response (200) - **isSupported** (Boolean) - True if the WeChat API is supported, false otherwise. ``` -------------------------------- ### Run Example App on iOS Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/CONTRIBUTING.md Builds and runs the example application on an iOS simulator or device. Native code changes require a rebuild. ```sh yarn example ios ``` -------------------------------- ### Check WeChat Installation Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Verifies if the WeChat application is installed on the device. ```APIDOC ## Check WeChat Installation ### Description Checks if the WeChat application is installed on the user's device. Useful for conditionally showing WeChat-related features. ### Method `isWXAppInstalled` ### Endpoint `/isWXAppInstalled` ### Parameters None ### Request Example ```javascript import * as WeChat from 'react-native-wechat-lib'; async function checkWeChatAvailability() { const isInstalled = await WeChat.isWXAppInstalled(); if (isInstalled) { console.log('WeChat is installed, show WeChat login button'); } else { console.log('WeChat not installed, hide WeChat features'); } return isInstalled; } ``` ### Response #### Success Response (200) - **isInstalled** (boolean) - True if WeChat is installed, false otherwise. #### Response Example ```json { "isInstalled": true } ``` ``` -------------------------------- ### Source Installation for Specific Version Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/README.md Clone the repository and checkout a specific branch (e.g., '1.1.x') before linking for local use. ```sh git clone https://github.com/little-snow-fox/react-native-wechat-lib cd react-native-wechat-lib git checkout 1.1.x npm link cd ../my-project npm link react-native-wechat-lib ``` -------------------------------- ### Source Installation for React Native WeChat Library Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/README.md Clone the repository and link the library locally for development or testing purposes. ```sh git clone https://github.com/little-snow-fox/react-native-wechat-lib cd react-native-wechat-lib npm link cd ../my-project npm link react-native-wechat-lib ``` -------------------------------- ### Install React Native WeChat Library Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/README.md Use npm to install the library. For version 3.0.x, specify version 3.0.4. Version 3.0.0 and above deprecate 'react-native link'. ```sh npm install react-native-wechat-lib --save # 3.0.x 使用3.0.4 npm install react-native-wechat-lib@3.0.4 --save # 3.0.0 开始弃用 react-native link react-native-wechat-lib ``` -------------------------------- ### Check WeChat Installation Status Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Checks if the WeChat application is installed on the user's device. This is useful for conditionally displaying WeChat-related features to the user. ```javascript import * as WeChat from 'react-native-wechat-lib'; async function checkWeChatAvailability() { const isInstalled = await WeChat.isWXAppInstalled(); if (isInstalled) { console.log('WeChat is installed, show WeChat login button'); } else { console.log('WeChat not installed, hide WeChat features'); } return isInstalled; } ``` -------------------------------- ### Get SDK Version Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Retrieves the current version of the WeChat SDK API. ```APIDOC ## Get SDK Version ### Description Returns the current WeChat SDK API version string. Useful for debugging and ensuring compatibility. ### Method `getApiVersion` ### Endpoint `/getApiVersion` ### Parameters None ### Request Example ```javascript import * as WeChat from 'react-native-wechat-lib'; async function displaySDKVersion() { const version = await WeChat.getApiVersion(); console.log('WeChat SDK Version:', version); // e.g., "6.8.20" return version; } ``` ### Response #### Success Response (200) - **version** (string) - The current SDK API version. #### Response Example ```json { "version": "6.8.20" } ``` ``` -------------------------------- ### Handle WeChat Event Listeners Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Listen for WeChat callback events when returning from WeChat to your app. Setup listeners on app initialization to handle requests and responses. ```javascript import * as WeChat from 'react-native-wechat-lib'; import { DeviceEventEmitter } from 'react-native'; // Setup listeners on app initialization function setupWeChatListeners() { // Handle requests from WeChat (e.g., launching from mini program) DeviceEventEmitter.addListener('WeChat_Req', (req) => { console.log('WeChat request received:', req); if (req.type === 'LaunchFromWX.Req') { // App launched from mini program handleMiniProgramData(req.extMsg); } }); // Handle responses from WeChat DeviceEventEmitter.addListener('WeChat_Resp', (resp) => { console.log('WeChat response:', resp); switch (resp.type) { case 'WXLaunchMiniProgramReq.Resp': // Returned from mini program console.log('Mini program data:', resp.extMsg); break; case 'SendMessageToWX.Resp': // Share completed console.log('Share result:', resp.errCode === 0 ? 'success' : 'failed'); break; case 'PayReq.Resp': // Payment completed handlePaymentResult(resp); break; } }); } function handlePaymentResult(resp) { if (resp.errCode === 0) { console.log('Payment successful'); } else if (resp.errCode === -2) { console.log('Payment cancelled'); } else { console.log('Payment failed:', resp.errStr); } } ``` -------------------------------- ### Get API Version and Open WeChat Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/README.md Retrieves the WeChat SDK API version and provides a method to open the WeChat application. ```APIDOC ## GET /getApiVersion ### Description Retrieves the version of the WeChat SDK API. ### Method GET ### Endpoint /getApiVersion ### Parameters None ### Response #### Success Response (200) - **version** (String) - The version string of the WeChat SDK API. ## POST /openWXApp ### Description Opens the WeChat application from your application. ### Method POST ### Endpoint /openWXApp ### Parameters None ### Response #### Success Response (200) - **success** (Boolean) - Indicates if the WeChat app was opened successfully. ``` -------------------------------- ### Get WeChat SDK API Version Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Retrieves the current WeChat SDK API version string. This is helpful for debugging and ensuring compatibility with different WeChat SDK versions. ```javascript import * as WeChat from 'react-native-wechat-lib'; async function displaySDKVersion() { const version = await WeChat.getApiVersion(); console.log('WeChat SDK Version:', version); // e.g., "6.8.20" return version; } ``` -------------------------------- ### Register App Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Initializes the WeChat SDK with your App ID and Universal Link. This must be called before any other WeChat functions. ```APIDOC ## Register App ### Description Registers your application with the WeChat SDK. This method must be called once before using any other WeChat functionality, typically during app initialization. ### Method `registerApp` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **appId** (string) - Required - Your WeChat App ID. - **universalLink** (string) - Required - Universal Link for iOS. ### Request Example ```javascript import * as WeChat from 'react-native-wechat-lib'; async function initializeWeChat() { try { const registered = await WeChat.registerApp( 'wx7973caefdffba1b8', // Your WeChat App ID 'https://your-domain.com/app/' // Universal Link (required for iOS) ); console.log('WeChat registered:', registered); // true on success } catch (error) { console.error('Failed to register WeChat:', error); } } ``` ### Response #### Success Response (200) - **registered** (boolean) - True if registration was successful. #### Response Example ```json { "registered": true } ``` ``` -------------------------------- ### Launch Mini Program API Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt API to launch a WeChat Mini Program directly from your app. ```APIDOC ## POST /launchMiniProgram ### Description Launches a WeChat Mini Program directly from your app. ### Method POST ### Endpoint /launchMiniProgram ### Parameters #### Request Body - **userName** (string) - Required - The Mini Program original ID. - **miniProgramType** (number) - Required - Type of Mini Program: 0 (Release), 1 (Development), 2 (Preview). - **path** (string) - Optional - The target page path within the Mini Program. ### Request Example ```json { "userName": "gh_d39d10000000", "miniProgramType": 0, "path": "/pages/product/detail?id=456" } ``` ### Response #### Success Response (200) - **extMsg** (string) - Optional - Message from the mini program callback. #### Response Example ```json { "extMsg": "Callback message from mini program" } ``` ``` -------------------------------- ### Register App and Handle WeChat Events Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/README.md Register the WeChat app with its ID and universal link. Listen for 'WeChat_Req' and 'WeChat_Resp' events to handle responses from WeChat, including launching mini programs, sending messages, and payment callbacks. Ensure event listeners are added before triggering corresponding methods. ```javascript WeChat.registerApp(Global.APP_ID, Global.UNIVERSAL_LINK); DeviceEventEmitter.addListener('WeChat_Req', req => { console.log('req:', req) if (req.type === 'LaunchFromWX.Req') { // 从小程序回到APP的事件 miniProgramCallback(req.extMsg) } }); DeviceEventEmitter.addListener('WeChat_Resp', resp => { console.log('res:', resp) if (resp.type === 'WXLaunchMiniProgramReq.Resp') { // 从小程序回到APP的事件 miniProgramCallback(resp.extMsg) } else if (resp.type === 'SendMessageToWX.Resp') { // 发送微信消息后的事件 sendMessageCallback(resp.country) } else if (resp.type === 'PayReq.Resp') { // 支付回调 payCallback(resp) } }); ``` -------------------------------- ### Publish New Versions Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/CONTRIBUTING.md Uses release-it to handle the process of publishing new versions to npm. This includes version bumping, tagging, and release creation. ```sh yarn release ``` -------------------------------- ### Share Music (shareMusic) Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Shares music content with a playable link, thumbnail, and description. ```APIDOC ## shareMusic - Share Music ### Description Shares music content with a playable link, thumbnail, and description. ### Method POST (Implied by the function call) ### Endpoint Not explicitly defined, but typically involves a WeChat SDK endpoint. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **title** (string) - Required - The title of the music. - **description** (string) - Optional - The description of the music. - **musicUrl** (string) - Required - The web page URL for the music. - **musicDataUrl** (string) - Required - The direct audio URL for the music. - **musicLowBandUrl** (string) - Optional - The low bandwidth version of the audio URL. - **thumbImageUrl** (string) - Required - The URL of the thumbnail image (auto-compressed to 32KB). - **scene** (number) - Required - The destination scene for the share. 0: Session, 1: Timeline/Moments, 2: Favorites. ### Request Example ```javascript WeChat.shareMusic({ title: 'Amazing Song', description: 'Listen to this great track', musicUrl: 'https://music.example.com/song', musicDataUrl: 'https://music.example.com/song.mp3', musicLowBandUrl: 'https://music.example.com/song-low', thumbImageUrl: 'https://example.com/album-cover.jpg', scene: 0 }); ``` ### Response #### Success Response (200) - **errCode** (number) - Error code indicating the result of the operation. 0 typically means success. #### Response Example ```json { "errCode": 0 } ``` ``` -------------------------------- ### POST /pay Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/README.md Initiates a payment request using the provided payment data. It returns an object indicating the success or failure of the authorization. ```APIDOC ## POST /pay ### Description Sends request for proceeding payment, then returns an object indicating the result. ### Method POST ### Endpoint /pay ### Parameters #### Request Body - **partnerId** (String) - Required - Merchant ID obtained from WeChat Pay. - **prepayId** (String) - Required - Pre-paid order ID. - **nonceStr** (String) - Required - A random string. - **timeStamp** (String) - Required - Timestamp of the transaction. - **package** (String) - Required - Data and signature filled according to WeChat Pay documentation. - **sign** (String) - Required - Signature generated according to WeChat Open Platform documentation. ### Response #### Success Response (200) - **errCode** (Number) - 0 if authorization succeeds. - **errStr** (String) - Error message if any error occurred. #### Response Example ```json { "errCode": 0, "errStr": "Success" } ``` ``` -------------------------------- ### Run Unit Tests Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/CONTRIBUTING.md Executes the unit test suite using Jest. Ensure all tests pass before committing changes. ```sh yarn test ``` -------------------------------- ### Event Subscription and Callbacks Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/README.md Handles callback events when returning to the app from WeChat, such as from mini-programs or after a successful payment. Event listeners should be added before triggering relevant methods. ```APIDOC ## Event Subscription and Callbacks ### Description Handles callback events triggered when returning to the app from WeChat (e.g., from mini-programs or after payment). Event listeners should be registered prior to initiating actions that lead to callbacks. ### Method N/A (Event Listeners) ### Endpoint N/A (Internal Event Handling) ### Event Listeners - **WeChat_Req**: Listens for incoming requests from WeChat. - **LaunchFromWX.Req**: Triggered when returning to the app from a mini-program. Callback receives `extMsg`. - **WeChat_Resp**: Listens for responses from WeChat. - **WXLaunchMiniProgramReq.Resp**: Triggered when returning from a mini-program. Callback receives `extMsg`. - **SendMessageToWX.Resp**: Triggered after sending a message to WeChat. Callback receives `country`. - **PayReq.Resp**: Triggered after a payment is completed. Callback receives the full response object. ### Code Example ```javascript WeChat.registerApp(Global.APP_ID, Global.UNIVERSAL_LINK); DeviceEventEmitter.addListener('WeChat_Req', req => { console.log('req:', req) if (req.type === 'LaunchFromWX.Req') { // From mini-program back to app miniProgramCallback(req.extMsg) } }); DeviceEventEmitter.addListener('WeChat_Resp', resp => { console.log('res:', resp) if (resp.type === 'WXLaunchMiniProgramReq.Resp') { // From mini-program back to app miniProgramCallback(resp.extMsg) } else if (resp.type === 'SendMessageToWX.Resp') { // After sending message to WeChat sendMessageCallback(resp.country) } else if (resp.type === 'PayReq.Resp') { // Payment callback payCallback(resp) } }); ``` ``` -------------------------------- ### Initialize WeChat SDK with RegisterApp Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Registers your application with the WeChat SDK. This must be called once before any other WeChat functionality. Ensure your WeChat App ID and Universal Link are correctly provided. ```javascript import * as WeChat from 'react-native-wechat-lib'; // Register your app on startup async function initializeWeChat() { try { const registered = await WeChat.registerApp( 'wx7973caefdffba1b8', // Your WeChat App ID 'https://your-domain.com/app/' // Universal Link (required for iOS) ); console.log('WeChat registered:', registered); // true on success } catch (error) { console.error('Failed to register WeChat:', error); } } ``` -------------------------------- ### Share Web Page (shareWebpage) Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Shares a webpage link with title, description, and thumbnail image. ```APIDOC ## shareWebpage - Share Web Page ### Description Shares a webpage link with title, description, and thumbnail image. ### Method POST (Implied by the function call) ### Endpoint Not explicitly defined, but typically involves a WeChat SDK endpoint. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **title** (string) - Required - The title of the webpage. - **description** (string) - Optional - The description of the webpage. - **webpageUrl** (string) - Required - The URL of the webpage. - **thumbImageUrl** (string) - Required - The URL of the thumbnail image. - **scene** (number) - Required - The destination scene for the share. 0: Session, 1: Timeline/Moments, 2: Favorites. ### Request Example ```javascript WeChat.shareWebpage({ title: 'Interesting Article', description: 'A fascinating read about technology trends', webpageUrl: 'https://example.com/article/tech-trends', thumbImageUrl: 'https://example.com/article-thumb.jpg', scene: 0 }); ``` ### Response #### Success Response (200) - **errCode** (number) - Error code indicating the result of the operation. 0 typically means success. #### Response Example ```json { "errCode": 0 } ``` ``` -------------------------------- ### Launch WeChat Mini Program Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Launches a WeChat Mini Program directly from your app. Requires the Mini Program's original ID and target page path. Supports specifying the Mini Program type (Release, Development, Preview). ```javascript import * as WeChat from 'react-native-wechat-lib'; async function openMiniProgram() { try { const result = await WeChat.launchMiniProgram({ userName: 'gh_d39d10000000', // Mini Program original ID miniProgramType: 0, // 0: Release, 1: Development, 2: Preview path: '/pages/product/detail?id=456' // Target page path }); // Result may contain extMsg from mini program callback console.log('Mini Program opened, response:', result.extMsg); } catch (error) { if (error.code === -1) { console.error('Invalid miniProgramType'); } else { console.error('Failed to launch mini program:', error); } } } ``` -------------------------------- ### Share Video (shareVideo) Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Shares video content with title, description, and thumbnail. ```APIDOC ## shareVideo - Share Video ### Description Shares video content with title, description, and thumbnail. ### Method POST (Implied by the function call) ### Endpoint Not explicitly defined, but typically involves a WeChat SDK endpoint. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **title** (string) - Required - The title of the video. - **description** (string) - Optional - The description of the video. - **videoUrl** (string) - Required - The URL of the video. - **videoLowBandUrl** (string) - Optional - The low bandwidth version of the video URL. - **thumbImageUrl** (string) - Required - The URL of the thumbnail image. - **scene** (number) - Required - The destination scene for the share. 0: Session, 1: Timeline/Moments, 2: Favorites. ### Request Example ```javascript WeChat.shareVideo({ title: 'Funny Cat Video', description: 'You have to see this!', videoUrl: 'https://video.example.com/watch?v=abc123', videoLowBandUrl: 'https://video.example.com/watch-low?v=abc123', thumbImageUrl: 'https://example.com/video-thumb.jpg', scene: 1 }); ``` ### Response #### Success Response (200) - **errCode** (number) - Error code indicating the result of the operation. 0 typically means success. #### Response Example ```json { "errCode": 0 } ``` ``` -------------------------------- ### Share Mini Program API Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt API for sharing a WeChat Mini Program card to chat sessions, with a fallback webpage for older clients. ```APIDOC ## POST /shareMiniProgram ### Description Shares a WeChat Mini Program card to chat sessions. ### Method POST ### Endpoint /shareMiniProgram ### Parameters #### Request Body - **userName** (string) - Required - The Mini Program original ID. - **path** (string) - Optional - The page path within the Mini Program with parameters. - **title** (string) - Required - The title of the Mini Program card. - **description** (string) - Optional - The description of the Mini Program card. - **thumbImageUrl** (string) - Optional - URL for the thumbnail image. - **hdImageUrl** (string) - Optional - URL for the HD preview image (SDK 6.5.9+). - **webpageUrl** (string) - Optional - Fallback webpage URL for older clients. - **miniProgramType** (number) - Optional - Type of Mini Program: 0 (Release), 1 (Development), 2 (Preview). Defaults to 0. - **withShareTicket** (string) - Optional - Whether to return a share ticket. Use 'true' or 'false'. - **scene** (number) - Required - The scene to share to. Mini programs only share to sessions (value: 0). ### Request Example ```json { "userName": "gh_d39d10000000", "path": "/pages/index/index?id=123", "title": "Check out this Mini Program", "description": "Amazing features await", "thumbImageUrl": "https://example.com/mini-thumb.jpg", "hdImageUrl": "https://example.com/mini-hd.jpg", "webpageUrl": "https://example.com/fallback", "miniProgramType": 0, "withShareTicket": "false", "scene": 0 } ``` ### Response #### Success Response (200) - **result** (object) - Indicates the success of the operation. #### Response Example ```json { "result": "success" } ``` ``` -------------------------------- ### Register App Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/README.md Registers your application with the WeChat SDK. This method should be called once globally. ```APIDOC ## POST /registerApp ### Description Registers your application with the WeChat SDK. This method should be called once globally. ### Method POST ### Endpoint /registerApp ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **appid** (String) - Required - The appid you get from WeChat dashboard - **universalLink** (String) - Optional - The universal link for iOS ### Request Example ```json { "appid": "your_app_id", "universalLink": "your_universal_link" } ``` ### Response #### Success Response (200) - **success** (Boolean) - Indicates if the registration was successful. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Share Mini Program Card to WeChat Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Shares a WeChat Mini Program card to chat sessions with a fallback webpage for older clients. Specify the Mini Program's original ID, path, and preview images. ```javascript import * as WeChat from 'react-native-wechat-lib'; async function shareMiniProgram() { try { const result = await WeChat.shareMiniProgram({ userName: 'gh_d39d10000000', // Mini Program original ID path: '/pages/index/index?id=123', // Page path with parameters title: 'Check out this Mini Program', description: 'Amazing features await', thumbImageUrl: 'https://example.com/mini-thumb.jpg', hdImageUrl: 'https://example.com/mini-hd.jpg', // HD preview (SDK 6.5.9+) webpageUrl: 'https://example.com/fallback', // Fallback for old clients miniProgramType: 0, // 0: Release, 1: Development, 2: Preview withShareTicket: 'false', scene: 0 // Mini programs only share to sessions }); console.log('Mini Program shared'); } catch (error) { console.error('Mini Program share failed:', error); } } ``` -------------------------------- ### Launch WeChat App Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Opens the WeChat application from your React Native app. ```APIDOC ## Launch WeChat Application ### Description Opens the WeChat application from your app. Returns a boolean indicating success. ### Method `openWXApp` ### Endpoint `/openWXApp` ### Parameters None ### Request Example ```javascript import * as WeChat from 'react-native-wechat-lib'; async function launchWeChat() { try { const success = await WeChat.openWXApp(); console.log('WeChat opened:', success); } catch (error) { console.error('Failed to open WeChat:', error); } } ``` ### Response #### Success Response (200) - **success** (boolean) - True if the WeChat app was successfully opened. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Type Check Files Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/CONTRIBUTING.md Verifies the code against TypeScript type definitions. This ensures type safety across the project. ```sh yarn typecheck ``` -------------------------------- ### OAuth Login Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Initiates an OAuth login flow with WeChat, returning an authorization code upon user approval. ```APIDOC ## OAuth Login ### Description Sends an authentication request to WeChat for OAuth login. The user will be redirected to WeChat to authorize, then returned to your app with an authorization code. ### Method `sendAuthRequest` ### Endpoint `/sendAuthRequest` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **scope** (string) - Required - The scope of the request, e.g., 'snsapi_userinfo'. - **state** (string) - Required - A security parameter to prevent CSRF attacks. ### Request Example ```javascript import * as WeChat from 'react-native-wechat-lib'; async function weChatLogin() { try { const response = await WeChat.sendAuthRequest( 'snsapi_userinfo', // Scope: 'snsapi_userinfo' for full profile 'random_state_123' // State parameter for security ); // Response structure: // { // errCode: 0, // 0 = success // code: 'auth_code', // Use this to get access_token from your server // openId: 'user_openid', // lang: 'en', // country: 'US' // } console.log('Auth code:', response.code); // Send response.code to your backend to exchange for access_token return response; } catch (error) { if (error.code === -2) { console.log('User cancelled authorization'); } else { console.error('WeChat login failed:', error.message); } } } ``` ### Response #### Success Response (200) - **errCode** (number) - 0 indicates success. - **code** (string) - The authorization code to be exchanged for an access token. - **openId** (string) - The user's WeChat OpenID. - **lang** (string) - The user's language preference. - **country** (string) - The user's country. #### Response Example ```json { "errCode": 0, "code": "qyX9z8aBcDeFgHiJkLmNopQrStUvWxYz1234567890", "openId": "o6_b2v_xxxxxxxxx", "lang": "en", "country": "CN" } ``` ### Error Handling - **-2**: User cancelled authorization. ``` -------------------------------- ### Initiate WeChat Payment Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Initiates a WeChat Pay transaction. Payment parameters, including partner ID, prepay ID, nonce string, timestamp, package, and signature, must be obtained from your backend server. ```javascript import * as WeChat from 'react-native-wechat-lib'; async function processPayment(orderData) { try { // Payment parameters from your server's unified order API const result = await WeChat.pay({ partnerId: '1900000109', // Merchant ID prepayId: 'wx201410272009395522', // Prepay transaction ID nonceStr: '5K8264ILTKCH16CQ2502', // Random string timeStamp: '1414561699', // Timestamp (string on Android) package: 'Sign=WXPay', // Fixed value sign: '8B26B278BC6B...' // Signature from server }); // errCode: 0 = success, -1 = error, -2 = user cancelled if (result.errCode === 0) { console.log('Payment successful!'); } } catch (error) { if (error.code === -2) { console.log('Payment cancelled by user'); } else { console.error('Payment failed:', error.message); } } } ``` -------------------------------- ### Lint Files Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/CONTRIBUTING.md Checks code for style and potential errors using ESLint. This helps maintain code quality and consistency. ```sh yarn lint ``` -------------------------------- ### Share Local Image (shareLocalImage) Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Shares a local image file to WeChat. Use this for images stored on the device. ```APIDOC ## shareLocalImage - Share Local Image ### Description Shares a local image file to WeChat. Use this for images stored on the device. ### Method POST (Implied by the function call) ### Endpoint Not explicitly defined, but typically involves a WeChat SDK endpoint. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **imageUrl** (string) - Required - The absolute path to the local image file. - **scene** (number) - Required - The destination scene for the share. 0: Session, 1: Timeline/Moments, 2: Favorites. ### Request Example ```javascript WeChat.shareLocalImage({ imageUrl: '/storage/emulated/0/DCIM/photo.jpg', // Absolute path scene: 0 }); ``` ### Response #### Success Response (200) - **errCode** (number) - Error code indicating the result of the operation. 0 typically means success. #### Response Example ```json { "errCode": 0 } ``` ``` -------------------------------- ### Share Local Image Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Shares a local image file from the device's storage to a WeChat chat session. Requires the absolute path to the image file. ```javascript import * as WeChat from 'react-native-wechat-lib'; async function shareLocalPhoto(localPath) { try { const result = await WeChat.shareLocalImage({ imageUrl: '/storage/emulated/0/DCIM/photo.jpg', // Absolute path scene: 0 // Share to chat session }); console.log('Local image shared'); } catch (error) { console.error('Failed to share local image:', error); } } ``` -------------------------------- ### Fix Linting Errors Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/CONTRIBUTING.md Automatically fixes formatting and style issues detected by ESLint. Run this to ensure code adheres to project standards. ```sh yarn lint --fix ``` -------------------------------- ### Send Auth Request Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/README.md Initiates a WeChat authorization login request to obtain user information. ```APIDOC ## POST /sendAuthRequest ### Description Sends an authentication request to WeChat to log in the user. It returns an object containing authorization details. ### Method POST ### Endpoint /sendAuthRequest ### Parameters #### Path Parameters None #### Query Parameters - **scope** (Array|String) - Optional - Scopes of the auth request (e.g., 'snsapi_userinfo'). - **state** (String) - Optional - A string to maintain state between the request and callback. ### Request Body None ### Response #### Success Response (200) - **errCode** (Number) - Error Code. - **errStr** (String) - Error message if any error occurred. - **openId** (String) - The user's WeChat OpenID. - **code** (String) - The authorization code. - **url** (String) - The URL string associated with the request. - **lang** (String) - The user's language preference. - **country** (String) - The user's country. #### Response Example ```json { "errCode": 0, "errStr": "Success", "openId": "o6_b2P_xxxxxxxxx", "code": "auth_code_xxxxxx", "url": "your_redirect_url?code=auth_code_xxxxxx&state=your_state", "lang": "en", "country": "CN" } ``` ``` -------------------------------- ### Share Text Content (shareText) Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Shares plain text to WeChat. The scene parameter controls the destination: 0 for chat session, 1 for Moments, 2 for Favorites. ```APIDOC ## shareText - Share Text Content ### Description Shares plain text to WeChat. Scene parameter controls the destination: 0 for chat session, 1 for Moments, 2 for Favorites. ### Method POST (Implied by the function call) ### Endpoint Not explicitly defined, but typically involves a WeChat SDK endpoint. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **text** (string) - Required - The text content to share. - **scene** (number) - Required - The destination scene for the share. 0: Session, 1: Timeline/Moments, 2: Favorites. ### Request Example ```javascript WeChat.shareText({ text: 'Check out this amazing content!', scene: 0 }); ``` ### Response #### Success Response (200) - **errCode** (number) - Error code indicating the result of the operation. 0 typically means success. #### Response Example ```json { "errCode": 0 } ``` ``` -------------------------------- ### Share Music Content Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Shares music content to a WeChat chat session, including a title, description, playable web URL, direct audio URL, low-bandwidth audio URL, and a thumbnail image. The thumbnail is auto-compressed. ```javascript import * as WeChat from 'react-native-wechat-lib'; async function shareMusic() { try { const result = await WeChat.shareMusic({ title: 'Amazing Song', description: 'Listen to this great track', musicUrl: 'https://music.example.com/song', // Web page URL musicDataUrl: 'https://music.example.com/song.mp3', // Direct audio URL musicLowBandUrl: 'https://music.example.com/song-low', // Low bandwidth version thumbImageUrl: 'https://example.com/album-cover.jpg', // Auto-compressed to 32KB scene: 0 }); console.log('Music shared'); } catch (error) { console.error('Music share failed:', error); } } ``` -------------------------------- ### Share Remote Image (shareImage) Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Shares an image from a URL to WeChat. The image will be downloaded and shared. ```APIDOC ## shareImage - Share Remote Image ### Description Shares an image from a URL to WeChat. The image will be downloaded and shared. ### Method POST (Implied by the function call) ### Endpoint Not explicitly defined, but typically involves a WeChat SDK endpoint. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **imageUrl** (string) - Required - The URL of the image to share. - **scene** (number) - Required - The destination scene for the share. 0: Session, 1: Timeline/Moments, 2: Favorites. ### Request Example ```javascript WeChat.shareImage({ imageUrl: 'https://example.com/photo.jpg', scene: 1 }); ``` ### Response #### Success Response (200) - **errCode** (number) - Error code indicating the result of the operation. 0 typically means success. #### Response Example ```json { "errCode": 0 } ``` ``` -------------------------------- ### Launch WeChat Application Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Opens the WeChat application from your React Native app. Returns a boolean indicating whether the operation was successful. ```javascript import * as WeChat from 'react-native-wechat-lib'; async function launchWeChat() { try { const success = await WeChat.openWXApp(); console.log('WeChat opened:', success); } catch (error) { console.error('Failed to open WeChat:', error); } } ``` -------------------------------- ### WeChat Scan Login Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/README.md Allows users to log in by scanning a QR code displayed by the application. ```APIDOC ## POST /authByScan ### Description Initiates a WeChat login process via QR code scanning. The user scans the QR code displayed by the app, and upon successful login, a callback is triggered with user information. ### Method POST ### Endpoint /authByScan ### Parameters #### Path Parameters None #### Query Parameters - **appId** (String) - Required - The WeChat App ID. - **appSecret** (String) - Required - The WeChat App Secret. - **onQRGet** (Function) - Callback function that receives the QR code string. ### Request Body None ### Response #### Success Response (200) - **errCode** (Number) - Error Code. - **errStr** (String) - Error message if any error occurred. - **nickname** (String) - The user's WeChat nickname. - **headimgurl** (String) - The URL of the user's WeChat profile picture. - **openid** (String) - The user's WeChat OpenID. - **unionid** (String) - The user's WeChat UnionID. #### Response Example ```json { "errCode": 0, "errStr": "Success", "nickname": "WeChat User", "headimgurl": "http://wx.qlogo.cn/mmopen/xxxxxx/0", "openid": "o6_b2P_xxxxxxxxx", "unionid": "o6_b2P_yyyyyyyyy" } ``` ### Example Usage ```javascript const ret = await WeChat.authByScan('YOUR_APP_ID', 'YOUR_APP_SECRET', (qrcode) => { console.log('QR Code received:', qrcode); // Render the QR code using an Image component }); console.log('Login Info:', ret); ``` ``` -------------------------------- ### POST /subscribeMessage Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/README.md Subscribes to a one-time message from WeChat. This function requires metadata including the template ID and other parameters for maintaining state. ```APIDOC ## POST /subscribeMessage ### Description Subscribes to a one-time message from WeChat. ### Method POST ### Endpoint /subscribeMessage ### Parameters #### Request Body - **scene** (Number) - Optional - A numeric value (0-10000) to identify the subscription context after redirection. - **templateId** (String) - Required - The message template ID obtained from the WeChat Open Platform. - **reserved** (String) - Optional - Used to maintain request and callback state, preventing CSRF attacks. Max 128 bytes, URL-encoded. ### Response #### Success Response (200) - **message** (String) - Confirmation message. #### Response Example ```json { "message": "Subscription successful" } ``` ``` -------------------------------- ### Select Invoice via WeChat Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Opens WeChat's invoice selection interface for users to choose electronic invoices. Requires a card signature, sign type, timestamp, and nonce string. The result contains selected invoices with their details. ```javascript import * as WeChat from 'react-native-wechat-lib'; async function selectInvoice() { try { const result = await WeChat.chooseInvoice({ cardSign: 'generated_signature', // Invoice signature signType: 'SHA256', timeStamp: Date.now(), nonceStr: 'random_string_123' }); // result.cards contains selected invoices // [{ // appId: 'wx...', // cardId: 'invoice_card_id', // encryptCode: 'encrypted_invoice_code' // }] result.cards.forEach(invoice => { console.log('Selected invoice:', invoice.cardId); }); } catch (error) { console.error('Invoice selection failed:', error); } } ``` -------------------------------- ### Register WeChat App Source: https://github.com/little-snow-fox/react-native-wechat-lib/blob/master/README.md Register your application with WeChat using your App ID and an optional universal link. This should be called once globally. ```javascript import * as WeChat from 'react-native-wechat-lib'; WeChat.registerApp('appid', 'universalLink'); ``` -------------------------------- ### Share Video Content Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Shares video content to WeChat Moments (Timeline), including a title, description, video URL, low-bandwidth video URL, and a thumbnail image. ```javascript import * as WeChat from 'react-native-wechat-lib'; async function shareVideo() { try { const result = await WeChat.shareVideo({ title: 'Funny Cat Video', description: 'You have to see this!', videoUrl: 'https://video.example.com/watch?v=abc123', videoLowBandUrl: 'https://video.example.com/watch-low?v=abc123', thumbImageUrl: 'https://example.com/video-thumb.jpg', scene: 1 // Share to Moments }); console.log('Video shared'); } catch (error) { console.error('Video share failed:', error); } } ``` -------------------------------- ### Choose Invoice API Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt API to open WeChat's invoice selection interface for users to choose electronic invoices. ```APIDOC ## POST /chooseInvoice ### Description Opens WeChat's invoice selection interface. ### Method POST ### Endpoint /chooseInvoice ### Parameters #### Request Body - **cardSign** (string) - Required - Invoice signature. - **signType** (string) - Required - Signature type (e.g., 'SHA256'). - **timeStamp** (number) - Required - Timestamp. - **nonceStr** (string) - Required - Random string. ### Request Example ```json { "cardSign": "generated_signature", "signType": "SHA256", "timeStamp": 1678886400000, "nonceStr": "random_string_123" } ``` ### Response #### Success Response (200) - **cards** (array) - An array of selected invoice objects. - **appId** (string) - The application ID. - **cardId** (string) - The ID of the selected invoice card. - **encryptCode** (string) - The encrypted code of the invoice. #### Response Example ```json { "cards": [ { "appId": "wx...", "cardId": "invoice_card_id", "encryptCode": "encrypted_invoice_code" } ] } ``` ``` -------------------------------- ### Request One-Time Subscription Message Source: https://context7.com/little-snow-fox/react-native-wechat-lib/llms.txt Requests user permission for a one-time subscription message notification from WeChat. Requires a scene value, template ID, and an optional reserved security parameter. ```javascript import * as WeChat from 'react-native-wechat-lib'; async function requestSubscription() { try { const result = await WeChat.subscribeMessage({ scene: 1, // Scene value (0-10000) templateId: 'template_id_from_wechat_platform', reserved: 'csrf_token_12345' // Optional security parameter }); console.log('Subscription successful'); } catch (error) { console.error('Subscription failed:', error); } } ```