【React Native 实战】微信登录

1.前言
  在今天无论是游戏开发还是app开发,微信作为第三方登录必不可少,今天我们就用react-native-wechat实现微信登录,分享和支付同样的道理就不过多的介绍了。

2.属性

1)registerApp(appid):

  appid:String类型,从微信开放平台后台获取。

2)registerAppWithDescription(appid, appdesc):

  此方法只支持iOS; appid: String类型,从微信后台获取;  appdesc:String类型,描述信息。

3)openWXApp():

  打开微信app。

4)sendAuthRequest([scope[, state]]):

  微信登录请求,获取微信返回的token;  scope:应用授权作用域,如获取用户个人信息则填写snsapi_userinfo。

5) shareToTimeline(data):

  分享到朋友圈:

  {Object} data contain the message to send
  {String} thumbImage Thumb image of the message, which can be a uri or a resource id.
  
  {String} type Type of this message. Can be {news|text|imageUrl|imageFile|imageResource|video|audio|file}
 
  {String} webpageUrl Required if type equals news. The webpage link to share.
  
  {String} imageUrl Provide a remote image if type equals image.
  
  {String} videoUrl Provide a remote video if type equals video.
  
  {String} musicUrl Provide a remote music if type equals audio.
  
  {String} filePath Provide a local file if type equals file.
  
  {String} fileExtension Provide the file type if type equals file.

6) shareToSession(data)

  分享到好友或群,数据结构跟分享到朋友圈类似。

3.使用实例

1)安装react-native-wechat:

  npm install react-native-wechat --save

2) 自动关联:

  rnpm link react-native-wechat

  非到万不得已的时候,最好不要手动关联

3)在MainApplication中加入如下代码

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
  );
}

4)创建Package

  名称为你应用的包名+ wxapi,在新建的包中创建一个名字为WXEntryActivity的类。如包名为com.platformproject,目录结构和代码如下

5)在AndroidManifest.xml中加入微信Activity,如下

6)在componentDidMount中调用registerApp

componentDidMount() {
    try {
      WeChat.registerApp('xxxx');//从微信开放平台申请
    } catch (e) {
      console.error(e);
    }
    console.log(WeChat);
  }

7)调用微信登录认证

import * as WeChat from 'react-native-wechat';//首先导入react-native-wechat
WeChat.sendAuthRequest("snsapi_userinfo");//在需要触发登录的时候调用

  如果成功此时会弹出微信登录的认证界面,认证完就可以获取到token了。拿到token之后可以通过一下url进一步取到昵称,性别,头像等信息。

https://api.weixin.qq.com/sns/oauth2/access_token?appid="+Config.wechat_Appid+"&secret="+Config.wechat_AppSecret+"&code="+token+"&grant_type=authorization_code

  如果弹出Scope参数错误或没有Scope权限,则需要从微信开放平台,认证开发者,申请开通登录等权限。

8)注意

  微信开放平台,后台需要填写应用包名和应用签名,应用签名是使用微信开放平台提供的Android小工具生成的,手机安装小工具之后,输入应用的包名,即可生成对应的应用签名。

4.效果

  暂无,如果有任何问题,可留言讨论交流。

 

posted @ 2016-12-18 13:47  柳轩涤俗  阅读(16346)  评论(1编辑  收藏  举报