版權(quán)聲明:本文為博主原創(chuàng)文章,未經(jīng)博主允許不得轉(zhuǎn)載。
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
自動配置執(zhí)行以下命令:
react-native link react-native-wechat
link成功命令行會提示
Linking react-native-wechat ios dependency
或者你還可以手動配置
a.用xcode打開你的項目, 右鍵點擊左側(cè)項目目錄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"處

iOS9 以上,添加 微信白名單

或打開 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.gradle的dependencies部分添加以下代碼:
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
);
}
在應(yīng)用程序包中創(chuàng)建一個名為'wxapi'的包,并在其中創(chuàng)建一個名為'WXEntryActivity'的類。以便可以獲得微信的授權(quán)和分享權(quán)限。
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();
}
}
(可選)在應(yīng)用程序包中創(chuàng)建一個名為“wxapi”的包,并在其中創(chuàng)建一個名為“WXPayEntryActivity”的類。 以便可以獲得微信支付權(quán)限。
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]]) :發(fā)送微信登錄授權(quán)
- shareToTimeline(data) : 分享到朋友圈
- shareToSession(data) :分享到朋友
- pay(data) :調(diào)用微信支付
- addListener(eventType, listener[, context]) :監(jiān)聽狀態(tài)
- once(eventType, listener[, context]) :監(jiān)聽狀態(tài)
- removeAllListeners() :移除所有監(jiān)聽
方法接口描述
-
registerApp(appid):注冊微信SDK
registerApp(appid)
@params
| 參數(shù)名 | 類型 | 默認(rèn)值 | 描述 |
|---|---|---|---|
| appid | string | 無 | 微信后臺的appid |
示例代碼
//建議在應(yīng)用啟動時初始化,初始化之前無法使用此模塊的其他方法。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
| 參數(shù)名 | 類型 | 默認(rèn)值 | 描述 |
|---|---|---|---|
| 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]]) : 微信登錄授權(quán)請求
sendAuthRequest([scope[, state]])
params
| 參數(shù)名 | 類型 | 默認(rèn)值 | 描述 |
|---|---|---|---|
| scope | {Array/String} |
無 | 應(yīng)用授權(quán)作用域,如獲取用戶個人信息則填寫snsapi_userinfo |
| state | {String} |
無 | 用于保持請求和回調(diào)的狀態(tài),授權(quán)請求后原樣帶回給第三方。該參數(shù)可用于防止csrf攻擊(跨站請求偽造攻擊),建議第三方帶上該參數(shù),可設(shè)置為簡單的隨機數(shù)加session進(jìn)行校驗 |
return
{Promise}
示例代碼
//微信登錄示例
WXLogin = () => {
let scope = 'snsapi_userinfo';
let state = 'wechat_sdk_demo';
//判斷微信是否安裝
wechat.isWXAppInstalled()
.then((isInstalled) => {
if (isInstalled) {
//發(fā)送授權(quán)請求
wechat.sendAuthRequest(scope, state)
.then(responseCode => {
//返回code碼,通過code獲取access_token
this.getAccessToken(responseCode.code);
})
.catch(err => {
Alert.alert('登錄授權(quán)發(fā)生錯誤:', err.message, [
{text: '確定'}
]);
})
} else {
Platform.OS == 'ios' ?
Alert.alert('沒有安裝微信', '是否安裝微信?', [
{text: '取消'},
{text: '確定', onPress: () => this.installWechat()}
]) :
Alert.alert('沒有安裝微信', '請先安裝微信客戶端在進(jìn)行登錄', [
{text: '確定'}
])
}
})
};
| 參數(shù)名 | 類型 | 描述 |
|---|---|---|
| errCode | Number | ERR_OK = 0(用戶同意) ERR_AUTH_DENIED = -4(用戶拒絕授權(quán))ERR_USER_CANCEL = -2(用戶取消) |
| errStr | String | 無 |
| openId | String | 無 |
| code | String | 用戶換取access_token的code,僅在ErrCode為0時有效 |
-
shareToTimeline(data) : 分享到朋友圈
shareToTimeline(data)
params
| 參數(shù)名 | 類型 | 描述 |
|---|---|---|
| thumbImage | String | 消息的Thumb圖像,可以是uri或資源id |
| type | String | {news/text/imageUrl/imageFile/imageResource/video/audio/file} |
| webpageUrl | String | 如果type為news,則使用此分享url |
| imageUrl | String | 如果type為image,則使用此分享url |
| videoUrl | String | 如果type為video,則使用此分享url |
| musicUrl | String | 如果type為audio,則使用此分享url |
| filePath | String | 如果type為file,則使用此獲取本地文件 |
| fileExtension | String | 如果type為file,則使用此提供文件類型 |
示例代碼
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
| 參數(shù)名 | 類型 | 描述 |
|---|---|---|
| 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: '', // 預(yù)支付訂單
nonceStr: '', // 隨機串,防重發(fā)
timeStamp: '', // 時間戳,防重發(fā)
package: '', // 商家根據(jù)財付通文檔填寫的數(shù)據(jù)和簽名
sign: '' // 商家根據(jù)微信開放平臺文檔對數(shù)據(jù)做的簽名
}
);
return
| 參數(shù)名 | 類型 | 描述 |
|---|---|---|
| errCode | Number | 0 if authorization successed |
| errStr | String | Error message if any error occurred |
-
addListener(eventType, listener[, context]) : 監(jiān)聽狀態(tài)
示例代碼
//監(jiān)聽分享狀態(tài)
// 'SendMessageToWX.Resp' 分享監(jiān)聽字段
// 'PayReq.Resp' 支付監(jiān)聽字段
// 'SendAuth.Resp' 登錄監(jiān)聽字段
wechat.addListener(
'SendMessageToWX.Resp',
(response) => {
if (parseInt(response.errCode) === 0) {
toastShort('分享成功');
} else {
toastShort('分享失敗');
}
}
);
-
once(eventType, listener[, context])
和addListener類似,但是被調(diào)用一次后會被移除
-
removeAllListeners()
移除所有監(jiān)聽事件
本文參考react-native-wechat組件GitHub的說明文檔翻譯:https://github.com/weflex/react-native-wechat
官方QQ交流群:
問題搜集:
1、在安卓機上測試的同學(xué)經(jīng)常會遇到比如調(diào)用微信支付時閃一下就沒了的問題,這個問題100%跟簽名有關(guān),請檢查你的簽名。
debug版本和release版本的簽名是不同的,請注意
2、如果遇到RN低于0.40版本無法使用的問題,請降級react-native-wechat試一下