vue nuxt.js springmvc 前后端分离 微信扫码登录

3 篇文章 0 订阅

在微信开放平台 配置回调域名

在 nuxt 配置中引入 wxLogin.js

head: {
    script: [
      { src: 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js' }
    ]
  }

nuxt.js 使用wxLogin.js 加载二维码 

<div class="loginBox">
      <div class="inBox">
        <div class="line1">
          <h3>欢迎登录</h3>
          <ins v-if="$route.path !== '/login'" @click="close(true)" class="close iconfont iconquxiao"/>
        </div>
        <div class="lines"/>
        <p class="cenLine">
          请使用微信扫描二维码登录
        </p>
        <div class="codeBar">
          <p id="wxCode"/>
        </div>
      </div>
    </div>
<script>
import loginApi from '@/api/loginApi'

export default {
  data (){
    uuid: null,
    pollingCount: 300
  },
  methods: {
    getWxcode: function(){
        this.setUuid()
        // eslint-disable-next-line
        new WxLogin({
          self_redirect: true,
          id: 'wxCode', // 二维码地址
          appid: '',
          scope: 'snsapi_login',
          redirect_uri: '开放平台配置回调域/项目接口?u=' + this.uuid,
          state: '',
          style: 'black',
          href: ''
        })
        this.polling()
    },
    setUuid () {
      var s = []
      var hexDigits = "0123456789abcdef"
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
      }
      s[14] = "4"  // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)  // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-"
      this.uuid = s.join("")
    },
    polling: function () {
      let _this = this
      const i = setInterval(function () {
        if (_this.uuid) {
          loginApi.polling(_this.uuid).then(res => {
            _this.pollingCount --
            if (res.data) {
              if (res.data.wxKey) {
                // _this.toBind(res.data) // 绑定手机号
              } else {
                // _this.setLoginToken(res.data) //调取微信扫码登录后处理
                // 跳转地址
              }
            }
            if (res.data || _this.pollingCount <= 0) {
              clearInterval(i)
            }
          })
        }
      }, 1000)
    }
  }
}
</script>

loginApi.js

import instance from '.'

const api = {}

export default api

api.polling = (data) => {
  return instance.get('/v4/auth/polling?uuid=' + data)
}

 index.js

import axios from 'axios'

const instance = axios.create({
  baseURL: '/appServer/',
  method: 'post'
})

// POST传参序列化
instance.interceptors.request.use((config) => {
  return config
}, (error) => {
  return Promise.reject(error)
})
// 返回状态判断
instance.interceptors.response.use((res) => {
  if (res.status === 200) {
    return res.data
  } else {
    return Promise.reject(res)
  }
}, (error) => {
  if (error.response.status === 401) {
    window.$nuxt.$store.dispatch('auth/logout')
    console.log(window.$nuxt)
    window.location.href = '/login?from=' + window.$nuxt._route.fullPath
  } else {
    return Promise.reject(error)
  }
})

export default instance

java 代码

   /**
     * 接收微信扫码后回调 存储微信获取用户信息
     *
     * @param code
     * @param u    uuid
     * @return
     */
    @RequestMapping("/auth")
    public void v2_oauth(String code, String u) {
        if (code != null) {
                //通过code换取网页授权access_token
                SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(WebPropertiesUtil.wxLoginAppId, WebPropertiesUtil.wxLoginAppSecret, code);
                SnsUserInfo snsUserInfo = SnsAccessTokenApi.getUserInfo(snsAccessToken.getOpenid(), snsAccessToken.getAccessToken());
                // 存入缓存 this.cache.set(CacheKeyConstant.LOGIN_WX_KEY + u, 300, snsUserInfo.getUnionId(), SerializationType.JSON);
            } else {
                throw new CustomErrorException(ErrorCodes.WX_AUTH_LOGIN_ERROR);
            }
    }


    // 轮询查询是否有对应数据在 cache中
    @RequestMapping(value = "/polling")
    public RestResult polling(String uuid, HttpServletRequest request, HttpServletResponse response) {
        RestResult restResult = new RestResult();
        try {
            // 通过uuid在缓存中获取对应的值
            // String unionId = this.cache.get(CacheKeyConstant.LOGIN_WX_KEY + uuid, SerializationType.JSON);
            if (StringUtils.isNotEmpty(unionId)) {
                // 查询uuid对应的缓存中值
                // this.cache.delete(CacheKeyConstant.LOGIN_WX_KEY + uuid);
                BrdAccount account = authService.getAccountByWeiXin(unionId);
                // 登录
                if (account != null) {
                    // 登录
                    new Thread(new UpdateLoginTime(this.authService, new BrdAccount(account.getAccountId(), HttpTookit.getRealIpAddr(request)))).start();
                    if (!"".equals(account.getAccountMobile())) {
                        this.loginResult(restResult, account, response);
                    }
                } else {
                    account = new BrdAccount();
                    account.setWxKey(unionId);
                    restResult.setData(account);
                }
            }
        } catch (CustomErrorException e) {
            e.printErrorCode(restResult);
        } catch (Exception e) {
            CustomErrorException.printErrorCode(restResult, ErrorCodes.AUTH_LOGIN_ERROR, e);
        }
        return restResult;
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值