React Native 接入微信登录

1.微信开放平台进行准备 微信开放平台

        1.创建开发者账户,进行开发者认证- 认证需要付费(300元)

        2.创建应用,填写相关信息,需要准备一个关于应用的官网

        3.审核通过后,可以在详情中获取APPID 和 AppSecret

2.react native 配置

        1.安卓

                1.在包名目录下创建 wxapi 目录 新建 WXEntryActivity.java 文件

                

package com.xxxx.xxxx.wxapi;

//com.xxxx.xxxx为包名

// react-native-wechat-lib support (
import android.app.Activity;
import android.os.Bundle;
import com.wechatlib.WeChatLibModule;

public class WXEntryActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WeChatLibModule.handleIntent(getIntent());
        finish();
    }
}
// )

        2.在包名下的MainApplication.java中 加入代码

// react-native-wechat-lib support (
import com.wechatlib.WeChatLibPackage;
// )


packages.add(new WeChatLibPackage());

        3.在AndroidManifest.xml 中加入配置

<queries>
        <package android:name="com.tencent.mm" />
</queries>


<!-- 在此处添加微信的 activity 配置 -->
        <activity
            android:name=".wxapi.WXEntryActivity"
            android:label="@string/app_name"
            android:exported="true"
            android:taskAffinity="com.xxxxx.xxxx" 包名
            android:launchMode="singleTask"
        />

2.ios 配置

        1.在AppDelegate.h 中加入

#import "WXApi.h"


@interface AppDelegate : RCTAppDelegate<WXApiDelegate>

       2.在 Info.plist  加入

<dict>
        	<key>CFBundleTypeRole</key>
        	<string>Editor</string>
        	<key>CFBundleURLName</key>
        	<string>weixin</string>
        	<key>CFBundleURLSchemes</key>
        	<array>
        		<string>放在微信开放平台获取的APPID</string>
        	</array>
        </dict>

<key>LSApplicationQueriesSchemes</key>
	<array>
		<string>weixin</string>
		<string>wechat</string>
		<string>weixinULAPI</string>
		<string>weixinURLParamsAPI</string>
	</array>

       3.在AppDelegate.m 中进行修改 或添加 代码

        提示:下方代码谨慎使用,每个项目写法不一样,,如果代码文件中有类似的代码可以不修改此文件,此段代码作用是

  • 通过 WXApi 处理打开 URL 的请求,用于处理微信的回调。
  • 处理 Universal Link 的请求,也是用于处理微信的回调。
#import "RCTLinkingManager.h"

// 添加到文件顶部
#import <React/RCTLinkingManager.h>

// 确保以下代码已经存在于你的 AppDelegate.m 文件中
- (BOOL)application:(UIApplication *)application
   openURL:(NSURL *)url
   options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
  return [RCTLinkingManager application:application openURL:url options:options];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
  return [RCTLinkingManager application:application openURL:url
                      sourceApplication:sourceApplication annotation:annotation];
}

        4.在Podfile 中加入配置 安卓微信SDK

  pod 'WechatOpenSDK-XCFramework'

        5.ios 需要配置深度链接 ,微信开发平台审核ios应该时是需要用到,代码中也需要

                1.创建 apple-app-site-association.json 文件  将文件放在 服务器根目录下或放在.well-known目录下,确保在 `https://xxx.xxx.com/.well-known/apple-app-site-association` 或 `https://xxx.xxx.com/apple-app-site-association` 下能访问到,切记不能带.json 访问

{
  "applinks": {
    "apps": [],
    "details": [
      {
        "appID": "YOUR_TEAM_ID.com.your.bundle.id", 团队id(在苹果开发者中可以找到)+包名   
        "paths": [ "open/app/*" ] 路径配置,需要以“/*”结尾
      }
    ]
  }
}

        2.在Xcode中进行配置

        打开你的 Xcode 项目,选择目标项目,转到 Signing & Capabilities 标签页,点击 + Capability 按钮,选择 Associated Domains

        在 Associated Domains 下添加你的域名:applinks:xxx.xxx.com

3. react native 代码

        1.安装  react-native-wechat-lib 库  我使用的版本时"3.0.4"

        2.js 代码

import * as WeChat from 'react-native-wechat-lib';


WeChat.registerApp('APID', 'ios深度链接');
// 例如:WeChat.registerApp('wx432342342344243', 'https://xxx.xxx.com/open/app/');



  handleWeChatLogin = async () => {
        try {
            const isWeChatInstalled = await WeChat.isWXAppInstalled();
            if (!isWeChatInstalled) {
                alertToast.show('请先安装微信')
                return;
            }
            const number=Math.floor(100000 + Math.random() * 900000);
            const state=number.toString()
            const response = await WeChat.sendAuthRequest('snsapi_userinfo', state);
            // 用户换取 access_token 的 code,仅在 ErrCode 为 0 时有效
            if (response && response.code) {
                // 使用code直接调用微信API获取access_token
                const appId = 'APPID';
                const appSecret = 'AppSecret'; //在微信开发平台可以获取
                const tokenResponse = await         
                     fetch(`https://api.weixin.qq.com/sns/oauth2/access_token? 
appid=${appId}&secret=${appSecret}&code=${response.code}&grant_type=authorization_code`);
                const tokenData = await tokenResponse.json();
                if (tokenData.access_token) {
                    const userInfoResponse = await fetch(`https://api.weixin.qq.com/sns/userinfo?access_token=${tokenData.access_token}&openid=${tokenData.openid}`);
                    const userInfo = await userInfoResponse.json();
                        //userInfo 有微信名、头像、openID,
                         //通过这些参数可以进行登录注册操作
                    let params = {
                        openId: userInfo.openid,
                        bindType: 1,
                        name: userInfo.nickname
                    }
                    this.goToLogin(params);
                } else {
                    alertToast.show('登录失败,获取 access_token 失败')
                }
            } else {
                alertToast.show('登录失败,错误码:', response.errCode)
            }
        } catch (error) {
            this.setState({loading: false})
            console.error('微信登录失败:', error);
        }
    };


4.错误提示

        1.如果安装了微信 ,却提示未安装微信  应该是 没有添加这段代码

        2.如果安卓执行`WeChat.sendAuthRequest('snsapi_userinfo', state)` 没有响应数据,也不报错,有可能安卓配置没有配好,或者是有缓存。缓存问题可以退出微信重新登录,或者在另一台手机上登录

参考:

1.https://github.com/EatherToo/react-native-wechat-lib

2.https://github.com/little-snow-fox/react-native-wechat-lib/

3.https://juejin.cn/post/6844903651425648653

4.https://www.cnblogs.com/jinzhengping/p/10602666.html

5.关于react native项目中使用react-native-wechat-lib@3.0.4-CSDN博客

  • 25
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值