1. 程式人生 > >【轉】react-native-wechat元件使用介紹

【轉】react-native-wechat元件使用介紹

react-native-wechat 具有微信 登入,分享,收藏(v1.9.9+) 和支付的功能,適合iOS/Android 雙平臺使用

安裝 react-native-wechat
//npm 安裝
npm install react-native-wechat --save

//yarn 安裝
yarn add react-native-wechat
配置 react-native-wechat
  • iOS

自動配置執行以下命令:

react-native link react-native-wechat

link成功命令列會提示

Linking react-native-wechat ios dependency

或者你還可以手動配置

a.用xcode開啟你的專案, 右鍵點選左側專案目錄Libraries資料夾 ➜ Add Files to <...>

b.去node_modules ➜ react-native-wechat ➜ ios ➜ 選擇 RCTWeChat.xcodeproj

c.在工程Build Phases ➜ Link Binary With Libraries中新增libRCTWeChat.a(直接拖拽過去)

工程配置

在工程target的Build Phases->Link Binary with Libraries

中加入以下庫檔案:

SystemConfiguration.framework
CoreTelephony.framework
libsqlite3.0
libc++
libz

點選TARGETS 下的專案名 -> info ,新增你的 申請的 微信 AppID到 “URL type”的”URL Schema”處

新增URL Schema

iOS9 以上,新增 微信白名單

QQ20170329-170004.png

或開啟 info.plist原始碼新增:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>weixin</string>
    <string>wechat</string>
</array>

在你專案的AppDelegate.m新增以下程式碼,啟動[LinkingIOS]

#import <React/RCTLinkingManager.h>

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  return [RCTLinkingManager application:application openURL:url
                            sourceApplication:sourceApplication annotation:annotation];
}
  • Android

android/settings.gradle檔案下新增以下程式碼:

include ':RCTWeChat'
project(':RCTWeChat').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-wechat/android')

android/app/build.gradledependencies部分新增以下程式碼:

dependencies {
  compile project(':RCTWeChat')    // Add this line only.
}

MainActivity.java或者MainApplication.java檔案中新增以下程式碼:

import com.theweflex.react.WeChatPackage;       // Add this line before public class MainActivity
...

/**
 * A list of packages used by the app. If the app uses additional views
 * or modules besides the default ones, add more packages here.
 */
@Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
    new MainReactPackage(), 
    new WeChatPackage()        // Add this line
  );
}

在應用程式包中建立一個名為’wxapi’的包,並在其中建立一個名為’WXEntryActivity’的類。以便可以獲得微信的授權和分享許可權。

package your.package.wxapi;

import android.app.Activity;
import android.os.Bundle;
import com.theweflex.react.WeChatModule;

public class WXEntryActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WeChatModule.handleIntent(getIntent());
    finish();
  }
}

(可選)在應用程式包中建立一個名為“wxapi”的包,並在其中建立一個名為“WXPayEntryActivity”的類。 以便可以獲得微信支付許可權。

package your.package.wxapi;

import android.app.Activity;
import android.os.Bundle;
import com.theweflex.react.WeChatModule;

public class WXPayEntryActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WeChatModule.handleIntent(getIntent());
    finish();
  }
}

AndroidManifest.xml新增宣告

<manifest>
  <application>
    <activity
      android:name=".wxapi.WXEntryActivity"
      android:label="@string/app_name"
      android:exported="true"
    />
    <activity
      android:name=".wxapi.WXPayEntryActivity"
      android:label="@string/app_name"
      android:exported="true"
    />
  </application>
</manifest>

proguard-rules.pro中新增:

-keep class com.tencent.mm.sdk.** {
   *;
}

API

  • registerApp(appid) :註冊APP
  • registerAppWithDescription(appid, appdesc) : 註冊APP(僅支援iOS)
  • isWXAppInstalled() :檢查微信是否安裝
  • isWXAppSupportApi()
  • getApiVersion() :獲得微信SDK的版本
  • openWXApp() :開啟微信APP
  • sendAuthRequest([scope[, state]]) :傳送微信登入授權
  • shareToTimeline(data) : 分享到朋友圈
  • shareToSession(data) :分享到朋友
  • pay(data) :呼叫微信支付
  • addListener(eventType, listener[, context]) :監聽狀態
  • once(eventType, listener[, context]) :監聽狀態
  • removeAllListeners() :移除所有監聽
方法介面描述
  • registerApp(appid):註冊微信SDK

registerApp(appid)

@params

引數名 型別 預設值 描述
appid string 微信後臺的appid

示例程式碼

//建議在應用啟動時初始化,初始化之前無法使用此模組的其他方法。WeChat模組只需要初始化一次。
//const wechat = require('react-native-wechat')
import *as wechat from 'react-native-wechat'
// If you register here
componentDidMount (){
  wechat.registerApp('your appid')
}
  • registerAppWithDescription(appid, appdesc):註冊微信SDK(僅對iOS有效)

registerAppWithDescription(appid, appdesc)

params

引數名 型別 預設值 描述
appid string 微信後臺的appid
appdesc string 對你的APP的描述
  • isWXAppInstalled() : 檢查微信是否安裝

isWXAppInstalled()

return
{Promise}

示例程式碼

wechat.isWXAppInstalled()
   .then( ( isInstalled ) => {
        if ( isInstalled ) {
           ...
        } else {
          toastShort( '沒有安裝微信軟體,請您安裝微信之後再試' );
        }
    } );
  • isWXAppSupportApi() : 檢查是否支援微信開放介面

isWXAppSupportApi()

return
{Promise}
示例程式碼

同isWXAppInstalled
  • getApiVersion() : 獲取微信SDK版本

getApiVersion()

return
{Promise}
示例程式碼

同isWXAppInstalled
  • openWXApp() : 開啟微信

openWXApp()

return
{Promise}

  • sendAuthRequest([scope[, state]]) : 微信登入授權請求

sendAuthRequest([scope[, state]])

params

引數名 型別 預設值 描述
scope {Array/String} 應用授權作用域,如獲取使用者個人資訊則填寫snsapi_userinfo
state {String} 用於保持請求和回撥的狀態,授權請求後原樣帶回給第三方。該引數可用於防止csrf攻擊(跨站請求偽造攻擊),建議第三方帶上該引數,可設定為簡單的隨機數加session進行校驗

return
{Promise}

示例程式碼

//微信登入示例
WXLogin = () => {
  let scope = 'snsapi_userinfo';
  let state = 'wechat_sdk_demo';
  //判斷微信是否安裝
  wechat.isWXAppInstalled()
    .then((isInstalled) => {
      if (isInstalled) {
        //傳送授權請求
        wechat.sendAuthRequest(scope, state)
          .then(responseCode => {
            //返回code碼,通過code獲取access_token
            this.getAccessToken(responseCode.code);
          })
          .catch(err => {
            Alert.alert('登入授權發生錯誤:', err.message, [
              {text: '確定'}
            ]);
          })
      } else {
        Platform.OS == 'ios' ?
          Alert.alert('沒有安裝微信', '是否安裝微信?', [
            {text: '取消'},
            {text: '確定', onPress: () => this.installWechat()}
          ]) :
          Alert.alert('沒有安裝微信', '請先安裝微信客戶端在進行登入', [
            {text: '確定'}
          ])
      }
    })
};
引數名 型別 描述
errCode Number ERR_OK = 0(使用者同意) ERR_AUTH_DENIED = -4(使用者拒絕授權)ERR_USER_CANCEL = -2(使用者取消)
errStr String
openId String
code String 使用者換取access_token的code,僅在ErrCode為0時有效
  • shareToTimeline(data) : 分享到朋友圈

shareToTimeline(data)

params

引數名 型別 描述
thumbImage String 訊息的Thumb影象,可以是uri或資源id
type String {news/text/imageUrl/imageFile/imageResource/video/audio/file}
webpageUrl String 如果typenews,則使用此分享url
imageUrl String 如果typeimage,則使用此分享url
videoUrl String 如果typevideo,則使用此分享url
musicUrl String 如果typeaudio,則使用此分享url
filePath String 如果typefile,則使用此獲取本地檔案
fileExtension String 如果typefile,則使用此提供檔案型別

示例程式碼

WeChat.shareToTimeline({
    type: 'imageUrl',
    title: 'web image',
    description: 'share web image to time line',
    mediaTagName: 'email signature',
    messageAction: undefined,
    messageExt: undefined,
    imageUrl: 'http://www.ncloud.hk/email-signature-262x100.png'
  });

return

引數名 型別 描述
errCode Number 0 if authorization successed
errStr String Error message if any error occurred
  • shareToSession(data) :分享到好友

shareToSession(data)

示例程式碼

同 shareToTimeline(data) :
  • shareToFavorite(data) :收藏(v1.9.9+)

shareToFavorite(data)

示例程式碼

同 shareToTimeline(data) :
  • pay(data) : 微信支付

pay(data)

示例程式碼

const result = await WeChat.pay(
  {
    partnerId: '',  // 商家向財付通申請的商家id
    prepayId: '',   // 預支付訂單
    nonceStr: '',   // 隨機串,防重發
    timeStamp: '',  // 時間戳,防重發
    package: '',    // 商家根據財付通文件填寫的資料和簽名
    sign: ''        // 商家根據微信開放平臺文件對資料做的簽名
  }
);

return

引數名 型別 描述
errCode Number 0 if authorization successed
errStr String Error message if any error occurred
  • addListener(eventType, listener[, context]) : 監聽狀態

示例程式碼

        //監聽分享狀態
        // 'SendMessageToWX.Resp' 分享監聽欄位
        // 'PayReq.Resp'          支付監聽欄位
        // 'SendAuth.Resp'        登入監聽欄位
        wechat.addListener(
            'SendMessageToWX.Resp',
            (response) => {
                if (parseInt(response.errCode) === 0) {
                    toastShort('分享成功');
                } else {
                    toastShort('分享失敗');
                }
            }
        );
  • once(eventType, listener[, context])

addListener類似,但是被呼叫一次後會被移除

  • removeAllListeners()

移除所有監聽事件

問題蒐集:
1、在安卓機上測試的同學經常會遇到比如呼叫微信支付時閃一下就沒了的問題,這個問題100%跟簽名有關,請檢查你的簽名。
debug版本和release版本的簽名是不同的,請注意
2、如果遇到RN低於0.40版本無法使用的問題,請降級react-native-wechat試一下


原文連結