react微信扫码登录

  1. 第一步
    方法一
    <script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js">
    import { Spin } from 'antd';
    import React, { useEffect, useState } from 'react';
    import axios from 'axios';
    export default function ceshi() {
      const [isLoading, setIsLoading] = useState(false);
      const onOpenLogin = () => {
        const timer = setTimeout(() => {
          initWX();
          clearTimeout(timer);
        }, 500);
      };
      const initWX = () => {
      const WxLoginLogin:any = window;
        new WxLoginLogin.WxLogin({
          self_redirect: true,
          id: 'login_container',
          appid: '',
          scope: 'snsapi_login', // 写死,网页应用暂时只支持这个值
          redirect_uri: '', // 扫码成功后重定向地址
          state: Math.random(), // 随机字符串
          style: 'black',
          href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30NCi5pbXBvd2VyQm94IC50aXRsZSB7ZGlzcGxheTogbm9uZTt9DQouaW1wb3dlckJveCAuaW5mbyB7d2lkdGg6IDI3MHB4O30='
        });
        setIsLoading(false);
      };
     const getUrlCode= (name:string)=> {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
      }
      useEffect(() => {
        getUrlCode("code")
        const code = getUrlCode('code')
        console.log('获取到的code值', code)
        onOpenLogin();
      },[]);
      return (
        <Spin spinning={isLoading}>
          <div  id="login_container" style={{ width:'1000px',textAlign: 'center' }} />
        </Spin>
      );
    }
    

      

     
  2. 第二步
    // 缓存已经加载的资源回调
    import loadScriptOnce from 'load-script-once'
    // 加载一次
    function loadScriptOnceSync(src:string, success:any) {
      loadScriptOnce(src).then(() => {
        if (typeof success === 'function') {
          success()
        }
      })
    }
    
    export default loadScriptOnceSync
    

     

  3. 第三步
    方法二
    import { Spin } from 'antd';
    import React, { useEffect, useState } from 'react';
    import loadScriptOnceSync from './loadScriptOnceSync';
    import axios from 'axios';
    export default function ceshi() {
      const [isLoading, setIsLoading] = useState(false);
      const onOpenLogin = () => {
        const timer = setTimeout(() => {
          initWX();
          clearTimeout(timer);
        }, 500);
      };
      const initWX = () => {
      const WxLoginLogin:any = window;
        new WxLoginLogin.WxLogin({
          self_redirect: true,// false 跳转到外部,true内嵌      
          id: 'login_container',
          appid: '',
          scope: 'snsapi_login', // 写死,网页应用暂时只支持这个值
          redirect_uri: '', // 扫码成功后重定向地址
          state: 'fm', // 随机字符串
          style: 'black',
          href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30NCi5pbXBvd2VyQm94IC50aXRsZSB7ZGlzcGxheTogbm9uZTt9DQouaW1wb3dlckJveCAuaW5mbyB7d2lkdGg6IDI3MHB4O30='
        });
        setIsLoading(false);
      };
      const initScript = () => {
        const WXLOGINJS_URL = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js';
        loadScriptOnceSync(WXLOGINJS_URL, () => setIsLoading(true));
      };
      const handleWxlogin = async () => {
        await initScript();
        onOpenLogin();
      };
      useEffect(() => {
        handleWxlogin();
        //  if (window.location.search.substring(6).split('&')[0]) {
        //     axios({
        //         'url': `https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx19909caac5d34d76&secret=4a115cefefe9bc9312e16dcb9b3b8a56&code=${window.location.search.substring(6).split('&')[0]}&grant_type=authorization_code`,
        //         'method': 'get'
        //     }).then(res=>{
        //         console.log('====================================');
        //         console.log('撒旦发射点发射点',res);
        //         console.log('====================================');
        //     })
        // }
      },[]);
      return (
        <Spin spinning={isLoading}>
          <div  id="login_container" style={{ width:'1000px',textAlign: 'center' }} />
        </Spin>
      );
    }
    

      

      

      

posted @ 2023-05-15 12:16  zjxgdq  阅读(756)  评论(0编辑  收藏  举报