天天看點

React Native微信分享

搗鼓了有一段時間了,終于搞完這個微信分享的接口接入子產品。直接看效果:

React Native微信分享

第一步

首先你要有自己的打包簽名完的項目,運作在你的手機裝置上,因為後面需要用到應用簽名。(具體怎麼獲得後面會講解)

在自己的項目中,我們需要先把微信分享的布局寫好,按照上面的效果圖,在這裡貼出代碼,這個項目的源碼在這裡。我把它上傳到了github上了,大家自行參考。

/**
 * Created by lam Date: // Time: 下午
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    TouchableOpacity,
    Image,
    Dimensions,
    BackHandler
} from 'react-native';

const {width, height} = Dimensions.get('window');
import BackgroundPage from '../../common/BackgroundPage';

import {
    Content,
    Icon,
    Card,
    CardItem,
    Text,
    Left,
} from "native-base";
import {StatusBar} from "react-native";
import {zdp, zsp} from "../../utils/ScreenUtil";
import NavBar from "../../common/NavBar";
import ToastUtil from "../../utils/ToastUtil";

var WeChat = require('react-native-wechat');
export default class ShareScreen extends Component {

    static navigationOptions = {
        header: null
    };

    constructor(props) {
        super(props);
        WeChat.registerApp('wx86715bab7c585603');
        this.state = {
            isShowCard: false
        };
    }

    componentWillMount() {
        BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
    }

    //監聽實體Back鍵回調方法returnData()告訴首頁面繼續播放視訊
    onBackAndroid = () => {
        const {navigate, goBack, state} = this.props.navigation;
        state.params.returnData();
        goBack();
        return true;
    };

   //leftPress回調方法returnData()告訴首頁面繼續播放視訊
   leftPress() {
        this.props.navigation.state.params.returnData();
        this.props.navigation.goBack();
    }

    render() {
        return (
            <View style={{flex: }}>
                <StatusBar
                    translucent={true}
                    animated={true}
                    backgroundColor={"#73808080"}
                    barStyle={"light-content"}
                />
                <View style={styles.sBar} backgroundColor={'#1D82E2'}/>
                <NavBar title={'邀請好友'}
                        leftIcon={"ios-arrow-back"}
                        leftPress={
                            this.leftPress
                        }/>
                <Image source={require('../../assets/images/share.png')}
                       style={{width, height, position: 'absolute'}}/>

                <View style={{
                    width: width,
                    height: zdp(),
                    backgroundColor: '#fffbff99',
                    justifyContent: 'center',
                    alignItems: 'center',
                    bottom: ,
                    position: 'absolute'
                }}>
                    <TouchableOpacity activeOpacity={}
                                      onPress={this.wxShare}
                                      style={{
                                          width: width - zdp(),
                                          height: zdp(),
                                          justifyContent: 'center',
                                          backgroundColor: 'red',
                                          alignItems: 'center',
                                          borderRadius: zdp(),
                                          shadowColor: 'grey',
                                          shadowOffset: {width: , height: },
                                          elevation: zdp()
                                      }}>
                        <Text style={{fontSize: zsp(), color: 'white'}}>
                            立即邀請好友加入
                        </Text>
                    </TouchableOpacity>
                </View>

                {this.state.isShowCard ? <BackgroundPage
                    backgroundColor={this.state.isShowCard ? '#e4e1e177' : 'transparent'}
                    onPress={() => {
                        this.setState({
                            isShowCard: false
                        });
                    }}/> : null}

                {this.state.isShowCard ? this.getCardView() : null}
            </View>);
    }

    wxShare = () => {
        this.setState({
            isShowCard: true
        });
    };

    getCardView = () => {
        // const card =
        return (
            <Content style={{
                width: width - zdp(),
                marginTop: zdp(),
                alignSelf: 'center',
                position: 'absolute'
            }} padder>
                <Card style={styles.mb}>
                    <CardItem header bordered>
                        <Text>邀請好友</Text>
                    </CardItem>
                    {this.getButtonCardItem('微信好友', 'logo-googleplus', '#DD5044', () => {
                        WeChat.isWXAppInstalled()
                            .then((isInstalled) => {
                                if (isInstalled) {
                                    WeChat.shareToSession({type: 'text', description: '測試微信好友分享文本'})
                                        .catch((error) => {
                                            ToastUtil.showShort(error.message);
                                        });
                                } else {
                                    ToastUtil.showShort('沒有安裝微信軟體,請您安裝微信之後再試');
                                }
                            });
                        console.log('微信分享');
                    })}

                    {this.getButtonCardItem('朋友圈', 'logo-facebook', '#3B579D', () => {
                        WeChat.isWXAppInstalled()
                            .then((isInstalled) => {
                                if (isInstalled) {
                                    WeChat.shareToTimeline({
                                        title: '微信朋友圈測試連結',
                                        description: '分享自:江清清的技術專欄(www.lcode.org)',
                                        thumbImage: 'http://mta.zttit.com:8080/images/ZTT_1404756641470_image.jpg',
                                        type: 'news',
                                        webpageUrl: 'http://www.lcode.org'
                                    })
                                        .catch((error) => {
                                            ToastUtil.showShort(error.message);
                                        });
                                } else {
                                    ToastUtil.showShort('沒有安裝微信軟體,請您安裝微信之後再試');
                                }
                            });
                        console.log('dianji');
                    })}
                </Card>
            </Content>);
    };

    getButtonCardItem = (title, iconName, iconColor, onPress) => {
        return (
            <CardItem button onPress={
                onPress
            }>
                <Left>
                    <Icon
                        active
                        name={iconName}
                        style={{color: iconColor}}
                    />
                    <Text>{title}</Text>
                </Left>
            </CardItem>
        )
    }

}
const styles = StyleSheet.create({
    container: {
        backgroundColor: "#FFF"
    },
    text: {
        alignSelf: "center",
        marginBottom: zdp()
    },
    mb: {
        marginBottom: zdp()
    },
    sBar: {
        height: StatusBar.currentHeight,
        width: width
    },
});
           
React Native微信分享

第二步

2.1、申請微信開發平台的賬戶(https://open.weixin.qq.com/):

React Native微信分享

2.2、 進入管理中心建立移動應用,填寫基本資訊:

(注意,應用名稱要唯一,上傳的應用圖示要符合标準)

React Native微信分享
React Native微信分享
React Native微信分享

2.2、 填寫平台資訊:

React Native微信分享

這裡回答一下前面提到的應用簽名的問題。

親身實踐過,RN調試版和釋出版隻有釋出版(app-release.apk)有對應的簽名,需要把App打包簽名後運作到手機上,然後記住App的包名,下載下傳微信官方提供的簽名工具Gen_signatura_Android2.apk:下載下傳連結

輸入應用的包名:

React Native微信分享

複制擷取到的應用簽名

點選”Copy to clipboard”複制應用簽名,至此我們就拿到了App的應用簽名。

2.3、 送出

送出稽核需要一段時間的周期,一般一天不到就可以稽核完成,但是有時候說不準,周期幾天的都有。。

稽核成功後的界面,我們可以直接使用微信的分享到朋友圈和發送給朋友的接口。

React Native微信分享

第三步

在RN上接入微信依賴庫react-native-wechat,內建微信SDK(由于我是用Windows的,這裡隻提供Android端的內建步驟)

3.1、 安裝react-native-wechat

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

//yarn 安裝
yarn add react-native-wechat
           

3.2、 配置(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
  );
}
           

在應用程式包中建立一個名為’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();
  }
}
           

在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.** {
   *;
}
           

OK,至此需要做的準備也做好了,現在隻需要在代碼中調用react-native-wechat庫中提供的方法就可以了!

3.3、 使用

首先我們需要注冊App:

//建議在應用啟動時初始化,初始化之前無法使用此子產品的其他方法。WeChat子產品隻需要初始化一次。
//const wechat = require('react-native-wechat')
import *as wechat from 'react-native-wechat'
// If you register here
componentDidMount (){
  wechat.registerApp('your appid')
}
           

在你寫的方法代碼中這樣使用 :

{this.getButtonCardItem('微信好友', 'logo-googleplus', '#DD5044', () => {
    WeChat.isWXAppInstalled()
        .then((isInstalled) => {
            if (isInstalled) {
                WeChat.shareToSession({type: 'text', description: '測試微信好友分享文本'})
                    .catch((error) => {
                        ToastUtil.showShort(error.message);
                    });
            } else {
                ToastUtil.showShort('沒有安裝微信軟體,請您安裝微信之後再試');
            }
        });
    console.log('微信分享');
})}

{this.getButtonCardItem('朋友圈', 'logo-facebook', '#3B579D', () => {
    WeChat.isWXAppInstalled()
        .then((isInstalled) => {
            if (isInstalled) {
                WeChat.shareToTimeline({
                    title: '微信朋友圈測試連結',
                    description: '分享自:江清清的技術專欄(www.lcode.org)',
                    thumbImage: 'http://mta.zttit.com:8080/images/ZTT_1404756641470_image.jpg',
                    type: 'news',
                    webpageUrl: 'http://www.lcode.org'
                })
                    .catch((error) => {
                        ToastUtil.showShort(error.message);
                    });
            } else {
                ToastUtil.showShort('沒有安裝微信軟體,請您安裝微信之後再試');
            }
        });
    console.log('dianji');
})}
           

其中

* title是分享時顯示的标題,

* description是描述的内容體,

* webpageurl點選後打開的連結,

* thumbImage,這個是分享時左側現實的圖檔,

* imageUrl,這個和webpageurl類似,是分享的圖檔位址,

* videoUrl這是分享的視訊位址

* musicUrl這是分享的音樂位址

* filePath這是分享檔案位址,可以分享檔案

* fileExtension,這個是分享的檔案的字尾,如果分享的是doc文檔,如:fileExtension:‘.doc’;

此外還有監聽的方法:addListener(eventType, listener[, context])

效果如下所示:

發送給好友:

React Native微信分享

分享到朋友圈:

React Native微信分享

四、注意事項

出現點選微信分享後,傳回錯誤碼-6:

1. 申請key不正确。

如簽名是79:1E:0B:61:1B:2F:E0:24,要填寫成791E0B611B2FE024.

2. 運作打包時用的簽名和申請微信key用的簽名不是同一個簽名

點選微信分享沒反應:

列印日志觀察是否有錯誤資訊;試着關機重新開機。

改包名的話集中在三個地方更改:

(1)java的類包 rename

(2)微信接口包 包名.wxapi

(3)AndroidManifest.xml 中 包名屬性

改完需要等一會,十分鐘左右,如果還是不行,點選分享之後沒反應,可以跟我一樣手機關機重新開機一下,微信可能有緩存了~

OK,結束!

參考文章:

React-Native之微信好友、朋友圈分享、支付

React Native綁定微信分享/登入/支付(示範+實作步驟+注意事項)

打安卓包,更換包名 的 三個 關鍵點 微信登入接入流程

react-native-wechat微信元件的使用

繼續閱讀