React Native微信分享

捣鼓了有一段时间了,终于搞完这个微信分享的接口接入模块。直接看效果:

效果

第一步

首先你要有自己的打包签名完的项目,运行在你的手机设备上,因为后面需要用到应用签名。(具体怎么获得后面会讲解)
在自己的项目中,我们需要先把微信分享的布局写好,按照上面的效果图,在这里贴出代码,这个项目的源码在这里。我把它上传到了github上了,大家自行参考。

/**
 * Created by lam Date: 2018/8/31 Time: 下午14.25
 */
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(2);
        goBack();
        return true;
    };

   //leftPress回调方法returnData()告诉主页面继续播放视频
   leftPress() {
        this.props.navigation.state.params.returnData(2);
        this.props.navigation.goBack();
    }

    render() {
        return (
            <View style={{flex: 1}}>
                <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(80),
                    backgroundColor: '#fffbff99',
                    justifyContent: 'center',
                    alignItems: 'center',
                    bottom: 0,
                    position: 'absolute'
                }}>
                    <TouchableOpacity activeOpacity={0.5}
                                      onPress={this.wxShare}
                                      style={{
                                          width: width - zdp(40),
                                          height: zdp(45),
                                          justifyContent: 'center',
                                          backgroundColor: 'red',
                                          alignItems: 'center',
                                          borderRadius: zdp(20),
                                          shadowColor: 'grey',
                                          shadowOffset: {width: 0, height: 5},
                                          elevation: zdp(5)
                                      }}>
                        <Text style={{fontSize: zsp(20), 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(60),
                marginTop: zdp(150),
                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(7)
    },
    mb: {
        marginBottom: zdp(15)
    },
    sBar: {
        height: StatusBar.currentHeight,
        width: width
    },
});

第二步

2.1、申请微信开发平台的账户(https://open.weixin.qq.com/):
微信开发平台

2.2、 进入管理中心创建移动应用,填写基本信息:
(注意,应用名称要唯一,上传的应用图标要符合标准)

303191077566995359.jpg

2.2、 填写平台信息:

这里回答一下前面提到的应用签名的问题。
亲身实践过,RN调试版和发布版只有发布版(app-release.apk)有对应的签名,需要把App打包签名后运行到手机上,然后记住App的包名,下载微信官方提供的签名工具Gen_signatura_Android2.apk:下载链接
输入应用的包名:

复制获取到的应用签名
点击”Copy to clipboard”复制应用签名,至此我们就拿到了App的应用签名。

2.3、 提交
提交审核需要一段时间的周期,一般一天不到就可以审核完成,但是有时候说不准,周期几天的都有。。
审核成功后的界面,我们可以直接使用微信的分享到朋友圈和发送给朋友的接口。

第三步

在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])
效果如下所示:
发送给好友:

分享到朋友圈:

四、注意事项

出现点击微信分享后,返回错误码-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微信组件的使用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值