vue项目中微信登录的实现操作


Posted in Javascript onSeptember 08, 2020

1、下载组件 wxlogin

npm install vue-wxlogin --save

2、引入组件,给组件传参

3、重定向的url应该是微信登录官网中的微信授权作用域

4、如果url里面有端口号,微信授权作用里面也要有

5、重定向的url:需要在http://tool.chinaz.com/tools/urlencode.aspx中转码

6、微信登录成功后,会自动重定向到新地址,此时的地址栏中就有code参数

7、如果报错说不能从组件跳到页面,那就找到wxlogin组件里面的iframe标签,加上这个属性:sandbox=“allow-scripts allow-top-navigation allow-same-origin”

报错内容:

qrconnect?scope=snsapi_login&redirect_uri=http%3a%2f%2f%2f&state=&login_type=jssdk&self_redirect=false&style=black&href=:84 Unsafe JavaScript attempt to initiate navigation for frame with origin 'http://localhost:9020' from frame with URL 'https://open.weixin.qq.com/connect/qrconnect?app&scope=snsapi_login&redirect_uri=http%3a%2f%2f&state=&login_type=jssdk&self_redirect=false&style=black&href='. The frame attempting navigation is targeting its top-level window, but is neither same-origin with its target nor has it received a user gesture. See https://www.chromestatus.com/features/5851021045661696.```

补充知识:vue移动端微信授权登录插件封装

1.新建wechatAuth.js文件

const qs = require('qs')
//应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
const SCOPES = ['snsapi_base', 'snsapi_userinfo']

class VueWechatAuthPlugin {

 constructor () {
 this.appid = null
 this.redirect_uri = null
 this.scope = SCOPES[1]
 this._code = null
 this._redirect_uri = null
 }

 install (Vue, options) {
 let wechatAuth = this
 this.setAppId(options.appid)
 Vue.mixin({
 created: function () {
 this.$wechatAuth = wechatAuth
 },
 })

 }

 static makeState () {
 return Math.random().toString(36).substring(2, 15) +
 Math.random().toString(36).substring(2, 15)
 }

 setAppId (appid) {
 this.appid = appid
 }

 set redirect_uri (redirect_uri) {
 this._redirect_uri = encodeURIComponent(redirect_uri)
 }

 get redirect_uri () {
 return this._redirect_uri
 }

 get state () {
 return localStorage.getItem('wechat_auth:state')
 }

 set state (state) {
 localStorage.setItem('wechat_auth:state', state)
 }

 get authUrl () {
 if (this.appid === null) {
 throw 'appid must not be null'
 }
 if (this.redirect_uri === null) {
 throw 'redirect uri must not be null'
 }
 this.state = VueWechatAuthPlugin.makeState()
 return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${this.redirect_uri}&response_type=code&scope=${this.scope}&state=${this.state}#wechat_redirect`
 }

 returnFromWechat (redirect_uri) {
 let parsedUrl = qs.parse(redirect_uri.split('?')[1])
 if (process.env.NODE_ENV === 'development') {
 // console.log('parsedUrl: ', parsedUrl)
 this.state = null
 this._code = parsedUrl.code
 } else {
 if (this.state === null) {
 throw 'You did\'t set state'
 }
 if (parsedUrl.state === this.state) {
 this.state = null
 this._code = parsedUrl.code
 } else {
 this.state = null
 throw `Wrong state: ${parsedUrl.state}`
 }
 }
 }

 get code () {
 if (this._code === null) {
 throw 'Not get the code from wechat server!'
 }
 // console.log(this)
 // console.log('this._code: ' + this._code)
 let code = this._code
 this._code = null
 // console.log('code: ' + code)
 return code
 }
}

const vueWechatAuthPlugin = new VueWechatAuthPlugin()

if (typeof window !== 'undefined' && window.Vue) {
 window.Vue.use(VueWechatAuthPlugin)
}

export default vueWechatAuthPlugin

2.main.js中导入

import wechatAuth from './plugins/wechatAuth'//微信登录插件
const qs= require('qs');
Vue.use(wechatAuth, {appid: XXXXXXXXX});

3.路由钩子中可以进行相关操作

router.beforeEach((to, from, next) => {
 if (store.state.loginStatus == 0) {
 //微信未授权登录跳转到授权登录页面
 let url = window.location.href;
 //解决重复登录url添加重复的code与state问题
 let parseUrl = qs.parse(url.split('?')[1]);
 let loginUrl;
 if (parseUrl.code && parseUrl.state) {
 delete parseUrl.code;
 delete parseUrl.state;
 loginUrl = `${url.split('?')[0]}?${qs.stringify(parseUrl)}`;
 } else {
 loginUrl = url;
 }
 wechatAuth.redirect_uri = loginUrl;
 store.dispatch('setLoginStatus', 1);
 window.location.href = wechatAuth.authUrl
 } else if (store.state.loginStatus == 1) {
 try {
 wechatAuth.returnFromWechat(to.fullPath);
 } catch (err) {
 store.dispatch('setLoginStatus', 0)
 next()
 }
 store.dispatch('loginWechatAuth', wechatAuth.code).then((res) => {
 if (res.status == 1) {
 store.dispatch('setLoginStatus', 2)
 } else {
 store.dispatch('setLoginStatus', 0)
 }
 next()
 }).catch((err) => {
 next()
 })
 }else {
 next()
 }
});

2018.8.31更新

更新微信授权登录vue-cli 3.x与2.x的demo vue-wechat-login,查看对应分支即可。

2019.7.23更新

代码进行了相关重构 vue-wechat-login

以上这篇vue项目中微信登录的实现操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
jQuery + Flex 通过拖拽方式动态改变图片的代码
Aug 03 Javascript
IE6已终止操作问题的2种情况及解决
Apr 23 Javascript
jQuery 和 CSS 的文本特效插件集锦
Dec 12 Javascript
JavaScript制作windows经典扫雷小游戏
Mar 31 Javascript
JS实现设置ff与ie元素绝对位置的方法
Mar 08 Javascript
jQuery animate和CSS3相结合实现缓动追逐效果附源码下载
Apr 18 Javascript
前端JS面试中常见的算法问题总结
Dec 23 Javascript
基于jQuery实现火焰灯效果导航菜单
Jan 04 Javascript
servlet+jquery实现文件上传进度条示例代码
Jan 25 Javascript
分析JavaScript数组操作难点
Dec 18 Javascript
详解element-ui表格中勾选checkbox,高亮当前行
Sep 02 Javascript
Vite和Vue CLI的优劣
Jan 30 Vue.js
关于element-ui表单中限制输入纯数字的解决方式
Sep 08 #Javascript
快速解决element的autofocus失效问题
Sep 08 #Javascript
vue axios请求成功却进入catch的原因分析
Sep 08 #Javascript
JavaScript数组类型Array相关的属性与方法详解
Sep 08 #Javascript
vue中后端做Excel导出功能返回数据流前端的处理操作
Sep 08 #Javascript
vue等两个接口都返回结果再执行下一步的实例
Sep 08 #Javascript
基于postman获取动态数据过程详解
Sep 08 #Javascript
You might like
PHP个人网站架设连环讲(四)
2006/10/09 PHP
一周让你学会PHP 不错的学习资料
2009/02/06 PHP
Prototype使用指南之base.js
2007/01/10 Javascript
js原生态函数中使用jQuery中的 $(this)无效的解决方法
2011/05/25 Javascript
jquery插件制作 自增长输入框实现代码
2012/08/17 jQuery
JSON传递bool类型数据的处理方式介绍
2013/09/18 Javascript
js弹出div并显示遮罩层
2014/02/12 Javascript
js 通过html()及text()方法获取并设置p标签的显示值
2014/05/14 Javascript
jQuery的deferred对象详解
2014/11/12 Javascript
微信JSSDK调用微信扫一扫功能的方法
2017/07/25 Javascript
Node.js简单入门前传
2017/08/21 Javascript
vue展示dicom文件医疗系统的实现代码
2018/08/27 Javascript
ES6知识点整理之模块化的应用详解
2019/04/15 Javascript
基于Bootstrap和JQuery实现动态打开和关闭tab页的实例代码
2019/06/10 jQuery
小程序中canvas的drawImage方法参数使用详解
2019/07/04 Javascript
vue 子组件和父组件传值的示例
2020/09/11 Javascript
JavaScript事件概念详解(区分静态注册和动态注册)
2021/02/05 Javascript
编写Python脚本使得web页面上的代码高亮显示
2015/04/24 Python
Python第三方库xlrd/xlwt的安装与读写Excel表格
2017/01/21 Python
Python3.6笔记之将程序运行结果输出到文件的方法
2018/04/22 Python
python的pygal模块绘制反正切函数图像方法
2019/07/16 Python
python中的global关键字的使用方法
2019/08/20 Python
python实现文件的分割与合并
2019/08/29 Python
关于numpy.where()函数 返回值的解释
2019/12/06 Python
详解python对象之间的交互
2020/09/29 Python
Python字符串对齐、删除字符串不需要的内容以及格式化打印字符
2021/01/23 Python
CSS3 please 跨浏览器的CSS3产生器
2010/03/14 HTML / CSS
Spanx塑身衣官网:美国知名内衣品牌
2017/01/11 全球购物
Perfumetrader荷兰:香水、化妆品和护肤品在线商店
2017/09/15 全球购物
如何启动时不需输入用户名与密码
2014/05/09 面试题
群众路线个人剖析材料
2014/10/07 职场文书
个人总结怎么写
2015/02/26 职场文书
网络研修随笔感言
2015/11/18 职场文书
《浅水洼里的小鱼》教学反思
2016/02/16 职场文书
flex弹性布局详解
2022/03/20 HTML / CSS
配置nginx负载均衡
2022/05/06 Servers