UNPKG

react-app-shell

Version:

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

126 lines (106 loc) 3.82 kB
import React, {PureComponent} from 'react'; import queryString from 'query-string'; import {wechatService} from '../../service'; import {AccountsType} from '../../constants'; import {appConfig} from '../../config'; import {message, localStore} from '../../utils'; /** * 用户授权code已经被使用 * @type {number} */ const CODE_ALREADY_USED = 40163; /** * 用户授权code无效 * @type {number} */ const CODE_INVALID = 40029; /** * 微信用户主动授权 */ export default class WechatAuth extends PureComponent { constructor(props) { super(props); // url参数 this.urlParams = queryString.parse(window.location.search); // 执行用户主动授权 this.execUserAuth(); } /** * 执行用户主动授权 * @returns {Promise<void>} */ execUserAuth = async () => { try { // returnUrl 前台应用地址 const {code, state, ...params} = this.urlParams; let {account, returnUrl} = params; let userAuthUrl; let openIdKey; const {nicknameKey} = appConfig.cookie; switch (account) { case AccountsType.MAIN: userAuthUrl = appConfig.resources.mainUserAuthUrl; openIdKey = appConfig.cookie.mainOpenIdKey; break; case AccountsType.ACTIVITY: userAuthUrl = appConfig.resources.activityUserAuthUrl; openIdKey = appConfig.cookie.activityOpenIdKey; break; case AccountsType.BONNY: userAuthUrl = appConfig.resources.bonnyUserAuthUrl; openIdKey = appConfig.cookie.bonnyOpenIdKey; break; } // 微信 用户主动授权的URL const {protocol, host, pathname} = window.location; const redirectUri = `${protocol}//${host}${pathname}?${queryString.stringify(params)}`; const fullUserAuthUrl = `${userAuthUrl}&redirect_uri=${encodeURIComponent( redirectUri )}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`; // 没有授权码, 跳转主动授权 if (!code) { window.location.replace(fullUserAuthUrl); return; } // account 为BONNY, 该接口的wxToken需在接口手动写入,其他情况下不需要 let res = await wechatService.getOpenIdByCodeAndAccount(code, account); if (!res) { message.error('授权失败, 请您刷新尝试!'); return; } if (typeof res === 'string') { console.log('JSON.parse(res)'); res = JSON.parse(res); } console.log('getOpenIdByCodeAndAccount >> res', res); // 授权code无效或者已经使用过, 跳转重新主动授权 if ( res.code === CODE_ALREADY_USED || res.code === CODE_INVALID || res.code === 'CODE_ALREADY_USED' || res.code === 'CODE_INVALID' ) { window.location.replace(fullUserAuthUrl); return; } const {openId, nickname} = res; if (!openId) { message.error('授权失败, 请您刷新尝试!'); return; } localStore.set(openIdKey, openId); localStore.set(nicknameKey, nickname); if (returnUrl) { returnUrl = decodeURIComponent(returnUrl); // 跳转回前端应用页面 window.location.replace(returnUrl); } } catch (error) { console.error('WechatAuth', error); message.error('授权失败, 请您刷新尝试!'); } }; render() { return <div></div>; } }