React微信扫码

准备的配置

iframe通信react

静态资源页面,微信扫描成功后重定向,由于微信登录是iframe嵌入,所以使用iframereact通信方式传递数据
public\success.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    </head>
    <body>
        <div id="container">
            <p class="title">成功!</p>
        </div>

        <script>
            //获取url参数信息
            var params = location.search;
            params = params.substring(1);
            params = params.split('&');
            var obj = {};
            params.forEach(function(item){
                var arr = item.split('=');
                obj[arr[0]] = decodeURI(arr[1]);
            });
            // 传输obj给 src\common\WXLogin\index.jsx 的 message监听事件
            parent.postMessage(obj ,'*');
        </script>
    </body>
</html>

appid配置文件

放在public下,方便打包上线后微信appid的修改
public\config.json

{
  "weixinAppId": "wx123456katsuki", // 写入对应的授权id
}

项目根目录页引入

src\index.js

import axios from 'axios' // 直接npm安装引用
// 获取项目配置
axios.get(window.location.origin + '/config.json').then((res) => {
  window.APP_CONFIG = res.data
})

加载一次Script

// 缓存已经加载的资源回调
import loadScriptOnce from 'load-script-once'

// 加载一次
function loadScriptOnceSync(src, success) {
  loadScriptOnce(src).then(() => {
    if (typeof success === 'function') {
      success()
    }
  })
}

export default loadScriptOnceSync

扫码页

二维码的样式更改:百度搜索base64转码,将写好的样式代码放入转换,复制到href
WXLogin.jsx

import React, { Component } from 'react'
import { Spin } from 'antd'
import { randomStr } from '@/utils' // 随机字符串封装
import loadScriptOnceSync from '@/utils/loadScriptOnce'

let globalsid
class WXLogin extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isLoading: true,
      scriptLoaded: false,
    }
  }

  async componentDidMount() {
    await this.initScript()
    this.onOpenLogin()
    let that = this
    window.receiveMessageFromIndex = function (event) {
      if (event != undefined) {
        // 发送请求 event.data为微信信息对象 为对象类型再请求接口
        if (typeof event.data === 'object') {
          let WXCode = event.data.code
          // 没有code或已发请求 不重复请求,isLogining为是否在登录中判断值
          if (!WXCode || that.props.isLogining) return
          let body = {
            code: WXCode,
          }
          // 执行项目的登录流程
          that.props.loginWX(body)
        }
      }
    }
    //监听来自iframe的message事件
    window.addEventListener('message', window.receiveMessageFromIndex, false)
  }

  componentWillUnmount() {
    window.removeEventListener('message', window.receiveMessageFromIndex)
  }

  initScript = () => {
    const WXLOGINJS_URL = 'http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
    loadScriptOnceSync(
      WXLOGINJS_URL,
      () => this.setState({ scriptLoaded: true }),
      () => console.log('加载完成')
    )
  }

  onOpenLogin = () => {
    const timer = setTimeout(() => {
      this.initWX()
      clearTimeout(timer)
    }, 2000)
  }

  initWX() {
    const sid = randomStr(5)
    globalsid = sid
    new window.WxLogin({
      self_redirect: true,
      id: 'login_container', 
      appid: window.APP_CONFIG.weixinAppId,
      scope: 'snsapi_login', // 写死,网页应用暂时只支持这个值
      redirect_uri: encodeURIComponent(window.location.origin + `/success.html`), // 扫码成功后重定向地址
      state: globalsid, // 随机字符串
      style: 'black',
      // base64加密的样式代码
	  href:'data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30NCi5pbXBvd2VyQm94IC50aXRsZSB7ZGlzcGxheTogbm9uZTt9DQouaW1wb3dlckJveCAuaW5mbyB7d2lkdGg6IDI3MHB4O30=',
    })
    this.setState({ isLoading: false })
  }

  render() {
    const { isLoading } = this.state
    return (
	    <Spin spinning={isLoading}>
	      <div className={styles.wx_container} onClick={this.onOpenLogin}>
	        <div id="login_container" style={{ textAlign: 'center' }} />
	      </div>
	    </Spin>
    )
  }
}

export default WXLogin
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值