react-native-wechat-lib

repository·master·Indexed 20 days ago

https://github.com/little-snow-fox/react-native-wechat-lib

A React Native bridging library for iOS and Android that integrates WeChat SDKs. It provides functionalities for WeChat Login (standard and scan code), sharing (text, image, file, music, video, webpage, and Mini Programs), payments, and launching Mini Programs. Version 3.0.4 supports React Native 70, Android SDK 6.8.20, and iOS SDK 2.0.

Tokens
9K
Snippets
27
Records
38
Agent score
73%

What's inside react-native-wechat-lib

  1. Handle WeChat callback events

    master

    When WeChat returns to your app (e.g., after a successful payment or returning from a Mini Program), it triggers events via DeviceEventEmitter. You should set up listeners before triggering the action that causes the return.

    Listening for Responses (WeChat_Resp)

    Use the WeChat_Resp event to handle results from payments, sharing, or Mini Program interactions.

    Listening for Requests (WeChat_Req)

    Use the WeChat_Req event to handle scenarios where the user returns from a Mini Program to your app.

    Implementation Pattern:

    import { DeviceEventEmitter } from 'react-native';
    import * as WeChat from 'react-native-wechat-lib';
    
    // 1. Register App
    WeChat.registerApp(APP_ID, UNIVERSAL_LINK);
    
    // 2. Setup Listeners
    DeviceEventEmitter.addListener('WeChat_Req', req => {
      if (req.type === 'LaunchFromWX.Req') {
        // Handle return from Mini Program
      }
    });
    
    DeviceEventEmitter.addListener('WeChat_Resp', resp => {
      if (resp.type === 'WXLaunchMiniProgramReq.Resp') {
        // Handle Mini Program response
      } else if (resp.type === 'PayReq.Resp') {
        // Handle Payment response
      }
    });
  2. Configure AppDelegate.h for WeChat Delegate

    master

    Update your AppDelegate.h to import the WeChat SDK and conform to the WXApiDelegate protocol. This allows your AppDelegate to act as the delegate for WeChat events.

    #import <React/RCTBridgeDelegate.h>
    #import <UIKit/UIKit.h>
    #import "WXApi.h"
    
    @interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, WXApiDelegate>
    
    @property (nonatomic, strong) UIWindow *window;
    
    @end
  3. Configure Login and Share callbacks for Android

    master

    If you are integrating login or sharing features, you must create a WXEntryActivity to handle callbacks from WeChat.

    1. Create a package named wxapi within your application's package structure.
    2. Create the WXEntryActivity class inside that package.
    3. Register the activity in your AndroidManifest.xml.

    Note: If you encounter issues where the app cannot return to your application after launching a WeChat Mini Program, ensure you add android:taskAffinity (set to your package name) and android:launchMode="singleTask" to the WXEntryActivity configuration in AndroidManifest.xml.

    // File: your/package/wxapi/WXEntryActivity.java
    package your.package.wxapi;
    
    import android.app.Activity;
    import android.os.Bundle;
    import com.wechatlib.WeChatLibModule;
    
    public class WXEntryActivity extends Activity {
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WeChatLibModule.handleIntent(getIntent());
        finish();
      }
    }
    <!-- File: AndroidManifest.xml -->
    <manifest>
      <application>
        <activity
          android:name=".wxapi.WXEntryActivity"
          android:label="@string/app_name"
          android:exported="true"
          android:taskAffinity="your.package.name"
          android:launchMode="singleTask"
        />
      </application>
    </manifest>
  4. Configure Linker Flags and Frameworks for iOS

    master

    Depending on your SDK version and requirements, you may need to link specific frameworks and configure linker flags in your Xcode project settings.

    For SDK 1.7.4 and later:

    • Link CFNetwork.framework.
    • In "Other Linker Flags", add: -Objc -all_load.
    • Ensure ATS (App Transport Security) is supported.

    For SDK 1.6.x:

    • Link CoreTelephony.framework.

    For SDK 1.6.3:

    • Link Security.framework in the "Build Phases" section.

    For SDK 1.5:

    • Link SystemConfiguration.framework, libz.dylib, and libsqlite3.0.dylib to support user statistics features.
  5. Configure Info.plist for iOS 9+ compatibility

    master

    Due to iOS 9 system policy updates, you must whitelist the weixin URL scheme in your Info.plist to allow the app to check if WeChat is installed. This is required for features like sharing, collection, payment, and login. Additionally, if your app needs to access non-HTTPS resources, you must configure NSAppTransportSecurity.

    <key>LSApplicationQueriesSchemes</key>
    <array>
      <string>weixin</string>
    </array>
    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true/>
    </dict>
  6. Install react-native-wechat-lib via npm

    master

    You can install the library using npm.

    Standard Installation (v1.1.x): Installs the latest stable version available on npm.

    Development Version (v3.0.x): Use this version if you need support for React Native 70, Android SDK 6.8.20, or iOS SDK 2.0. Warning: The 3.0.x branch is currently in development and some features may be untested. Use at your own risk.

    Note for iOS users: If your iOS application requires a WeChat SDK without payment functionality, use the NPM package with the -notpay suffix.

    # Standard installation
    npm install react-native-wechat-lib --save
    
    # Install specific 3.0.x development version
    npm install react-native-wechat-lib@3.0.4 --save
  7. Configure AppDelegate.m for WeChat Callbacks

    master

    You must implement WeChat callback methods in AppDelegate.m. Failure to do so will cause sharing attempts to hang on "connecting" and bounce back to the app.

    Note: Even if you do not use Universal Links, you should implement the continueUserActivity method to ensure you can receive callback events (such as after a successful WeChat Pay transaction).

    - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
        return  [WXApi handleOpenURL:url delegate:self];
    }
    
    - (BOOL)application:(UIApplication *)application
      continueUserActivity:(NSUserActivity *)userActivity
      restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable
      restorableObjects))restorationHandler {
      // Triggers a callback method
      [RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
      return [WXApi handleOpenUniversalLink:userActivity delegate:self];
    }
  8. Configure URL Schemes and LSApplicationQueriesSchemes for iOS

    master

    To allow your app to communicate with WeChat and return to your app after an interaction, you must configure URL schemes.

    1. URL Type: In Targets > info, add your app's ID as a "URL Schema" under "URL type".
    2. LSApplicationQueriesSchemes: To prevent Apple from blocking jumps to WeChat due to security permissions, add weixin, wechat, and weixinULAPI to the LSApplicationQueriesSchemes array in your Info.plist.
    <key>LSApplicationQueriesSchemes</key>
    <array>
      <string>weixin</string>
      <string>wechat</string>
      <string>weixinULAPI</string>
    </array>
  9. Register the WeChatLib module in Android

    master

    To manually register the package in your Android project, add WeChatLibPackage to the getPackages method in either MainApplication.java or MainActivity.java.

    import com.wechatlib.WeChatLibPackage; // Add this line
    
      @Override
      protected List<ReactPackage> getPackages() {
        @SuppressWarnings("UnnecessaryLocalVariable")
        List<ReactPackage> packages = new PackageList(this).getPackages();
        // Packages that cannot be autolinked yet can be added manually here, for example:
        // packages.add(new MyReactNativePackage());
        packages.add(new WeChatLibPackage()); // Add this line
        return packages;
      }