React Native 全栈开发实战班 - 集成微信登录

微信登录 是许多移动应用常用的第三方登录方式,用户可以通过微信账号快速登录应用。实现微信登录需要使用微信开放平台提供的 SDK 和 API。React Native 社区提供了多个第三方库来简化微信登录的实现,本章节将介绍如何使用 react-native-wechat 库来实现微信登录,包括安装配置、登录流程、获取用户信息以及处理登录状态。


5.5.1 微信开放平台概述

在实现微信登录之前,需要在微信开放平台进行以下准备工作:

  1. 注册微信开放平台账号:

    • 前往 微信开放平台 注册账号,并创建一个应用。
    • 获取应用的 App IDApp Secret
  2. 配置应用信息:

    • 在微信开放平台的应用设置中,配置应用的包名(Android)和 Bundle Identifier(iOS)。
    • 配置 Universal Links(iOS)和 URL Scheme(Android),用于处理微信登录回调。
  3. 下载微信 SDK:

    • 下载微信 SDK 并按照文档进行配置。
5.5.2 使用 react-native-wechat 实现微信登录

react-native-wechat 是一个流行的第三方库,用于实现微信登录、分享等功能。

5.5.2.1 安装 react-native-wechat
npm install react-native-wechat

链接原生依赖(React Native 0.60 及以上版本自动链接):

cd ios
pod install
cd ..
5.5.2.2 配置微信 SDK
  1. 配置 iOS:

    • 在 Xcode 中,打开 Info.plist 文件,添加以下内容:

      <key>LSApplicationQueriesSchemes</key>
      <array>
        <string>weixin</string>
        <string>weixinULAPI</string>
      </array>
      <key>CFBundleURLTypes</key>
      <array>
        <dict>
          <key>CFBundleURLSchemes</key>
          <array>
            <string>wxYOUR_APP_ID</string>
          </array>
        </dict>
      </array>
      
    • AppDelegate.m 文件中,添加以下代码:

      #import <React/RCTBundleURLProvider.h>
      #import <React/RCTRootView.h>
      #import <ReactNativeWeChat/ReactNativeWeChat.h>
      
      @implementation AppDelegate
      
      - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
      {
        ...
        [WXApi registerApp:@"wxYOUR_APP_ID"];
        ...
        return YES;
      }
      
      - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
      {
        return [WXApi handleOpenURL:url delegate:self];
      }
      
      @end
      
  2. 配置 Android:

    • android/app/src/main/AndroidManifest.xml 文件中,添加以下内容:

      <activity android:name="com.theweflex.react.WeChatEntryActivity"
        android:exported="true"
        android:launchMode="singleTop"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <intent-filter>
          <action android:name="android.intent.action.VIEW" />
          <category android:name="android.intent.category.DEFAULT" />
          <category android:name="android.intent.category.BROWSABLE" />
          <data android:scheme="wxYOUR_APP_ID" />
        </intent-filter>
      </activity>
      
    • android/app/build.gradle 文件中,添加以下依赖:

      dependencies {
        implementation project(':react-native-wechat')
        ...
      }
      
    • android/settings.gradle 文件中,添加以下内容:

      include ':react-native-wechat'
      project(':react-native-wechat').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-wechat/android')
      
5.5.2.3 基本用法

示例:

import React from 'react';
import { View, Button, StyleSheet, Alert } from 'react-native';
import * as WeChat from 'react-native-wechat';

const WeChatLoginExample = () => {
  const [isWeChatInstalled, setIsWeChatInstalled] = React.useState(false);

  React.useEffect(() => {
    // 检查微信是否安装
    WeChat.isWXAppInstalled()
      .then((isInstalled) => {
        setIsWeChatInstalled(isInstalled);
      })
      .catch((error) => {
        console.error('检查微信安装失败:', error);
      });
  }, []);

  const handleWeChatLogin = async () => {
    try {
      const scope = 'snsapi_userinfo';
      const state = 'wechat_sdk_demo';
      const result = await WeChat.sendAuthRequest(scope, state);
      console.log('微信登录结果:', result);
      // 发送 code 到服务器,服务器使用 code 换取 access token 和 openid
      // 然后使用 openid 和 access token 获取用户信息
    } catch (error) {
      console.error('微信登录失败:', error);
      Alert.alert('微信登录失败', error.message);
    }
  };

  return (
    <View style={styles.container}>
      {isWeChatInstalled ? (
        <Button title="微信登录" onPress={handleWeChatLogin} />
      ) : (
        <Text>微信未安装</Text>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
});

export default WeChatLoginExample;

解释:

  • isWXAppInstalled 方法: 检查微信是否安装。
  • sendAuthRequest 方法: 发起微信登录请求。
    • scope: 授权范围,snsapi_userinfo 表示获取用户信息。
    • state: 用于保持请求和回调的状态,防止 CSRF 攻击。
  • 登录结果: sendAuthRequest 方法返回一个 SendAuthResponse 对象,包含 code 字段。
  • 服务器端处理:
    • 应用将 code 发送到服务器。
    • 服务器使用 code 换取 access_tokenopenid
    • 服务器使用 access_tokenopenid 获取用户信息。
5.5.2.4 获取用户信息

微信登录获取用户信息需要服务器端进行以下步骤:

  1. 使用 code 换取 access_tokenopenid:

    请求 URL:

    https://api.weixin.qq.com/sns/oauth2/access_token?appid=YOUR_APP_ID&secret=YOUR_APP_SECRET&code=CODE&grant_type=authorization_code
    

    返回结果:

    {
      "access_token": "ACCESS_TOKEN",
      "expires_in": 7200,
      "refresh_token": "REFRESH_TOKEN",
      "openid": "OPENID",
      "scope": "snsapi_userinfo"
    }
    
  2. 使用 access_tokenopenid 获取用户信息:

    请求 URL:

    https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
    

    返回结果:

    {
      "openid": "OPENID",
      "nickname": "NICKNAME",
      "sex": 1,
      "province": "PROVINCE",
      "city": "CITY",
      "country": "COUNTRY",
      "headimgurl": "http://wx.qlogo.cn/mmopen/.../0",
      "privilege": [],
      "unionid": "UNIONID"
    }
    
  3. 服务器端返回用户信息给客户端:

    服务器端可以将获取到的用户信息返回给客户端,客户端可以将其存储在本地或进行其他处理。

示例:

const handleWeChatLogin = async () => {
  try {
    const scope = 'snsapi_userinfo';
    const state = 'wechat_sdk_demo';
    const result = await WeChat.sendAuthRequest(scope, state);
    console.log('微信登录结果:', result);
    const { code } = result;
    // 发送 code 到服务器
    const response = await fetch('https://yourserver.com/wechat-login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ code }),
    });
    const data = await response.json();
    console.log('服务器返回的用户信息:', data);
    // 处理用户信息
  } catch (error) {
    console.error('微信登录失败:', error);
    Alert.alert('微信登录失败', error.message);
  }
};

服务器端示例(Node.js):

const express = require('express');
const axios = require('axios');
const app = express();

app.use(express.json());

app.post('/wechat-login', async (req, res) => {
  const { code } = req.body;
  const appId = 'YOUR_APP_ID';
  const appSecret = 'YOUR_APP_SECRET';
  try {
    const response = await axios.get(`https://api.weixin.qq.com/sns/oauth2/access_token`, {
      params: {
        appid: appId,
        secret: appSecret,
        code,
        grant_type: 'authorization_code',
      },
    });
    const { access_token, openid } = response.data;
    const userInfoResponse = await axios.get(`https://api.weixin.qq.com/sns/userinfo`, {
      params: {
        access_token,
        openid,
      },
    });
    const userInfo = userInfoResponse.data;
    // 将用户信息存储到数据库,并生成 JWT 或其他认证 token
    // 返回用户信息给客户端
    res.json(userInfo);
  } catch (error) {
    console.error('微信登录服务器端错误:', error);
    res.status(500).json({ message: '微信登录服务器端错误' });
  }
});

app.listen(3000, () => {
  console.log('服务器已启动');
});

5.5.3 注意事项
  • 微信开放平台配置: 确保在微信开放平台正确配置应用的包名和 Bundle Identifier,并配置 URL Scheme 和 Universal Links。
  • URL Scheme: 微信登录需要使用 URL Scheme 进行回调,确保在 Info.plistAndroidManifest.xml 中正确配置。
  • 用户授权: 微信登录需要用户授权,应用应明确告知用户需要获取哪些信息。
  • 错误处理: 处理可能的错误,如用户取消登录、微信未安装、网络错误等。

5.6 总结

本章节介绍了 React Native 中的微信登录功能,包括如何使用 react-native-wechat 库来实现微信登录,以及服务器端如何处理微信登录流程。通过合理使用微信登录,可以简化用户注册和登录流程,提高用户体验。


课后作业

  1. 实现一个包含微信登录功能的应用。
  2. 获取并显示用户信息,如用户昵称和头像。
  3. 实现服务器端处理微信登录流程,并返回用户信息给客户端。
  4. 阅读 react-native-wechat 官方文档,深入了解其他高级功能和最佳实践。

作者简介

前腾讯电子签的前端负责人,现 whentimes tech CTO,专注于前端技术的大咖一枚!一路走来,从小屏到大屏,从 Web 到移动,什么前端难题都见过。热衷于用技术打磨产品,带领团队把复杂的事情做到极简,体验做到极致。喜欢探索新技术,也爱分享一些实战经验,帮助大家少走弯路!

温馨提示:可搜老码小张公号联系导师

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老码小张

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值