【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.效果

  暫無,如果有任何問題,可留言討論交流。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM