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}datacontain the message to send
{String}thumbImageThumb image of the message, which can be a uri or a resource id.
{String}typeType of this message. Can be {news|text|imageUrl|imageFile|imageResource|video|audio|file}
{String}webpageUrlRequired if type equalsnews. The webpage link to share.
{String}imageUrlProvide a remote image if type equalsimage.
{String}videoUrlProvide a remote video if type equalsvideo.
{String}musicUrlProvide a remote music if type equalsaudio.
{String}filePathProvide a local file if type equalsfile.
{String}fileExtensionProvide the file type if type equalsfile.
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.效果
暫無,如果有任何問題,可留言討論交流。
