react 微信授权 微信分享

1、微信授权

1-1、在BasicLayout做导航守卫,先判断浏览器环境,微信内的话,判断本地是否存在openId,有的话校验openId是否有效,有效的话缓存所需数据,无效的话跳转登录界面重新登陆,本地没有openId的话,判断路径中是否含code(第一次进入授权页面href中不带code,请求微信接口跳转页面路径中存在code,即第二次进入路径存在code),没有的话去授权页面


import './index.css';
import React, { PureComponent } from 'react';
import MenuBar from '@/components/MenuBar';
import { connect } from 'dva';
import withRouter from 'umi/withRouter';
import router from 'umi/router';
import { getToken, setAuthority,
  setToken,
  setCurrentUser} from '../utils/authority'
import { checkOpenId} from '@/services/login';
import '@/layouts/index.css';
// 底部有bar菜单
const BarRoutes = ['/', '/activity', '/ranking', '/user'];
class BasicLayout extends PureComponent {
  getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}
  componentWillMount() {
    const { children, location, loading, route } = this.props;
    //判断是否为微信环境
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      //console.log("微信")
      if (localStorage.getItem('openId')) {
        //已授权
        //console.log("已授权");
        let params = { 'openid': localStorage.getItem('openId') }
        //跟后台校验
        checkOpenId(params).then(res => {
          console.log(res);
          if(res.success){
            const { tokenType, accessToken, authority, account, userName, avatar, userid,companyid} = res.data
            const token = `${tokenType} ${accessToken}`;
            setToken(token);
            setAuthority(authority);
            setCurrentUser({ avatar, account, name: userName, authority, userid });
            localStorage.setItem('userid', userid);
            localStorage.setItem('companyid',companyid)
          }else{
              if(location.pathname=='/login'){
                return ;
              }else{
                router.replace('/login');
              } 
          }
        }).catch(err => {

        })

      } else {
        //console.log("未授权")
        if(this.getQueryString("code")){
          return;
        }else{
          localStorage.setItem('firstLink',window.location.href)
          router.replace('/author')
        }
      }

    } else {
      //浏览器
      console.log("浏览器")
      //next() 
      const token = getToken();
      if (token) {

      } else {
        router.replace('/login')
      }

    }
  }
  componentWillUnmount(){
    localStorage.setItem('lastLink',window.location.href)
  }
  render() {
    const { children, location, loading, route } = this.props;
    //去除tabbar的其他路由
    if (BarRoutes.indexOf(location.pathname) < 0) {
      // console.log(route.routes)
      // let title=CheckTitle(location,route.routes)
      return (
        
{children}
) } //Tabbar路由 return (
{children}
); } } export default withRouter(connect(({ app, loading }) => ({ app, loading }))(BasicLayout));

1-2、授权页面(以空白页进行静默授权)


import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { getOpenId} from '@/services/login';
import router from 'umi/router';
import styles from './index.less';
@connect(({ login, loading }) => ({
    login,
    loading,
}))
class Author extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
        }
    }
    getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    }
    // 截取code
    GetUrlParame(parameName) {
        /// 获取地址栏指定参数的值
        /// 参数名
        // 获取url中跟在问号后面的部分
        var parames = window.location.search
        // 检测参数是否存在
        if (parames.indexOf(parameName) > -1) {
            var parameValue = ''
            parameValue = parames.substring(parames.indexOf(parameName), parames.length)
            // 检测后面是否还有参数
            if (parameValue.indexOf('&') > -1) {
                // 去除后面多余的参数, 得到最终 parameName=parameValue 形式的值
                parameValue = parameValue.substring(0, parameValue.indexOf('&'))
                // 去掉参数名, 得到最终纯值字符串
                parameValue = parameValue.replace(parameName + '=', '')
                return parameValue
            }
            return ''
        }
    }
    componentWillMount() {
        //localStorage.setItem('firstLink',window.location.href)
        if (!this.getQueryString("code") && !localStorage.getItem('code')) {
            let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx49072aeabf0d54bd&redirect_uri=${encodeURIComponent(window.location.href)}&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect`
            window.location.href = url;
            //console.log("第一次进入")
        } else if (!localStorage.getItem('code')) {
            //console.log('第二次进入且路径中存在code')
            localStorage.setItem('code', this.GetUrlParame("code"));
            //后台请求微信返回openiD成功跳转登录界面
            let params = { 'wxcode': localStorage.getItem('code') }
            getOpenId(params).then(res=>{
                //console.log(res)
                localStorage.setItem('openId',res.data.openid);
                router.replace('/login')
            }).catch(err=>{
                console.log(err)
            })
        } else {
            //console.log("2次以上进入")
        }
    }
    render() {
        return (
            
); } } export default Author;

2、微信分享

2-1、安装weixin-js-sdk

yarn add weixin-js-sdk

2-2、 新建wxshare.js

import {wxShare} from '../services/wxshare'
import wx from 'weixin-js-sdk';
//
		//要用到微信API								
function getJSSDK(shareUrl,dataForWeixin) {
  let params={'shareUrl':shareUrl}
  wxShare(params).then(res => {
    //console.log('22222',res,dataForWeixin);
    //console.log(typeof(res));
    // let response=JSON.parse(res.data);
    // console.log(response)
    wx.config({
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
      appId: res.data.appId, // 必填,公众号的唯一标识
      timestamp: res.data.timestamp, // 必填,生成签名的时间戳
      nonceStr: res.data.noncestr, // 必填,生成签名的随机串
      signature: res.data.signature, // 必填,签名
      jsApiList:[
        'onMenuShareTimeline', 
        'onMenuShareAppMessage'
      ] 
    })
    wx.ready(function () {
        //分享给微信朋友
      wx.onMenuShareAppMessage({
        title: dataForWeixin.title,
        desc: dataForWeixin.des,
        link: dataForWeixin.linkurl,
        imgUrl: dataForWeixin.img,
        success: function success(res) {
          console.log(res,'已分享');
        },
        cancel: function cancel(res) {
          console.log('已取消');
        },
        fail: function fail(res) {
          //alert(JSON.stringify(res));
        }
      });
      // 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
      wx.onMenuShareTimeline({
        title: dataForWeixin.title,
        link: dataForWeixin.linkurl,
        imgUrl: dataForWeixin.img,
        success: function success(res) {
          //alert('已分享');
        },
        cancel: function cancel(res) {
          //alert('已取消');
        },
        fail: function fail(res) {
          //alert(JSON.stringify(res));
        }
      });
	// 2.3 监听“分享到QQ”按钮点击、自定义分享内容及分享结果接口
    //   wx.onMenuShareQQ({
    //     title: dataForWeixin.title,
    //     desc: dataForWeixin.desc,
    //     link: dataForWeixin.linkurl,
    //     imgUrl: dataForWeixin.img,
    //     trigger: function trigger(res) {
    //       //alert('用户点击分享到QQ');
    //     },
    //     complete: function complete(res) {
    //       alert(JSON.stringify(res));
    //     },
    //     success: function success(res) {
    //       //alert('已分享');
    //     },
    //     cancel: function cancel(res) {
    //       //alert('已取消');
    //     },
    //     fail: function fail(res) {
    //       //alert(JSON.stringify(res));
    //     }
    //   });
      // 2.4 监听“分享到微博”按钮点击、自定义分享内容及分享结果接口
    //   wx.onMenuShareWeibo({
    //     title: dataForWeixin.title,
    //     desc: dataForWeixin.desc,
    //     link: dataForWeixin.linkurl,
    //     imgUrl: dataForWeixin.img,
    //     trigger: function trigger(res) {
    //       //alert('用户点击分享到微博');
    //     },
    //     complete: function complete(res) {
    //       // alert(JSON.stringify(res));
    //     },
    //     success: function success(res) {
    //       //alert('已分享');
    //     },
    //     cancel: function cancel(res) {
    //       // alert('已取消');
    //     },
    //     fail: function fail(res) {
    //     // alert(JSON.stringify(res));
    //     }
    //   });
    })
    wx.error(function (res) {
      //alert("微信验证失败");
    });
  })
}
export default {
  // 获取JSSDK
  getJSSDK
}

2-3、在组件生命周期上挂在,IOS验签失败,重新加载验签成功

import sdk from "../../../utils/wxshare"

 componentDidMount() {
    this.setState({ animating: true })
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      var u = navigator.userAgent, app = navigator.appVersion;
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      if (isIOS) {
        if (window.location.href.indexOf("#reloaded") == -1) {
          window.location.href = window.location.href + "#reloaded";
          window.location.reload();
        }
      }
    }
    const { dispatch, location } = this.props;
    //请求详情数据
    dispatch({
      type: 'activity/fetchDetail',
      payload: {
        id: this.props.match.params.id,
        userid: localStorage.getItem('userid')
      },
      callback: res => {
        //console.log(res);
        let obj = {
          title: res.data.pgname,
          des: res.data.pgdesc,
          linkurl: window.location.href,
          img: `${res.data.pgpic}`,
        }
        let url = encodeURIComponent(window.location.href.split('#')[0]);
        sdk.getJSSDK(url, obj);
        this.setState({
          pgStartTime: res.data.pgstarttime,
          pgEndTime: res.data.pgendtime,
          animating: false
        },()=>{
          this._initScroll()
        })
      }
    });
}

 

你可能感兴趣的:(react 微信授权 微信分享)