UNPKG

react-app-shell

Version:

react打包脚本和example, 这里的版本请忽略

64 lines (51 loc) 1.82 kB
import {PureComponent} from 'react'; import PropTypes from 'prop-types'; import queryString from 'query-string'; import {wechatUtils, message} from '../../utils'; /** * 微信环境, 检查用户主动授权的组件 */ export default class UserWechatAuth extends PureComponent { static propTypes = { redirectUrl: PropTypes.string.isRequired, // 当 微信环境内的用户授权码 无效或者被使用时 的跳转路径, 以 'http' 开头的Url onSuccess: PropTypes.func, // 用户主动授权成功 并且获取到openId 的回调 }; static defaultProps = { onSuccess: (openId) => { console.log('用户主动授权成功, openId = ', openId); }, }; constructor(props) { super(props); this.urlParams = queryString.parse(window.location.search); // 同步检查用户授权, 如果未授权, 则让用户选择同意授权 wechatUtils.checkUserAuth(); } componentDidMount() { this.initData(); } initData = async () => { const {redirectUrl, onSuccess} = this.props; // 用户主动授权的code const {code} = this.urlParams; // code值不存在时 console.log('UserWechatAuth >>> 判断code值 >> code', code); if (!code) { return; } try { const openId = await wechatUtils.getOpenIdByCode(code, redirectUrl); console.log('UserWechatAuth >>> 获取 openId >> ', openId); // 未获取到openId if (!openId) { return; } onSuccess && onSuccess(openId); } catch (error) { message.error(error && error.msg || '获取授权的用户信息失败'); } }; render() { return null; } }