react 위챗 권한 위챗 공유

11548 단어
1. 위챗 인증
1. Basic Layout에서 내비게이션 수위를 하고 브라우저 환경을 판단한다. 위챗 안에 있으면 로컬에 오픈Id가 존재하는지 판단한다. 어떤 것은 오픈Id가 유효한지 검사하고 유효하면 캐시에 필요한 데이터를 저장한다. 무효면 로그인 인터페이스를 돌려 다시 로그인한다. 로컬에 오픈Id가 없으면경로에 코드가 포함되어 있는지 판단(첫 번째 권한 수여 페이지에 들어가는 href에 코드가 없고 위챗 인터페이스가 페이지 경로로 이동하도록 요청하는 경로에 코드가 존재한다. 즉, 두 번째 접근 경로에 코드가 존재한다) 없으면 권한 수여 페이지에 간다

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()
        })
      }
    });
}

좋은 웹페이지 즐겨찾기