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 相关文章推荐
图片在浏览器中底部对齐 解决方法之一
Nov 30 Javascript
jQuery获得内容和属性方法及示例
Dec 02 Javascript
JavaScript中双叹号!!作用示例介绍
Sep 21 Javascript
js脚本分页代码分享(7种样式)
Aug 19 Javascript
JS中的hasOwnProperty()、propertyIsEnumerable()和isPrototypeOf()
Aug 11 Javascript
利用JS实现页面删除并重新排序功能
Dec 09 Javascript
Angularjs验证用户输入的字符串是否为日期时间
Jun 01 Javascript
简单谈谈React中的路由系统
Jul 25 Javascript
js实现加载页面就自动触发超链接的示例
Aug 31 Javascript
详解50行代码,Node爬虫练手项目
Apr 22 Javascript
vue项目中引入Sass实例方法
Aug 27 Javascript
Vue3 实现双盒子定位Overlay的示例
Dec 22 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队列用法实例
2014/11/05 PHP
php curl中gzip的压缩性能测试实例分析
2016/11/08 PHP
CI框架表单验证实例详解
2016/11/21 PHP
PHP数组去重的更快实现方式分析
2018/05/09 PHP
javascript Array对象基础知识小结
2010/11/16 Javascript
深入理解JavaScript系列(28):设计模式之工厂模式详解
2015/03/03 Javascript
jQuery实现二级下拉菜单效果
2016/01/05 Javascript
巧用Vue.js+Vuex制作专门收藏微信公众号的app
2016/11/03 Javascript
Dropzone.js实现文件拖拽上传功能(附源码下载)
2016/11/22 Javascript
web 屏蔽BackSpace键实例代码
2016/12/24 Javascript
JQuery 进入页面默认给已赋值的复选框打钩
2017/03/23 jQuery
Bootstrap组件之下拉菜单,多级菜单及按钮布局方法实例
2017/05/25 Javascript
基于jQuery选择器之表单对象属性筛选选择器的实例
2017/09/19 jQuery
ES6下子组件调用父组件的方法(推荐)
2018/02/23 Javascript
一文搞懂ES6中的Map和Set
2019/05/20 Javascript
微信小程序判断页面是否从其他页面返回的实例代码
2019/07/03 Javascript
js实现时间日期校验
2020/05/26 Javascript
[00:48]DOTA2国际邀请赛公开赛报名开始 扫码开启逐梦之旅
2018/06/06 DOTA
详解Python中__str__和__repr__方法的区别
2015/04/17 Python
Django中使用Celery的教程详解
2018/08/24 Python
Python使用folium excel绘制point
2019/01/03 Python
Python发展简史 Python来历
2019/05/14 Python
PyQt5基本控件使用之消息弹出、用户输入、文件对话框的使用方法
2019/08/06 Python
Django获取应用下的所有models的例子
2019/08/30 Python
Python3.6 中的pyinstaller安装和使用教程
2020/03/16 Python
在pycharm中创建django项目的示例代码
2020/05/28 Python
Scrapy-Redis之RedisSpider与RedisCrawlSpider详解
2020/11/18 Python
python 利用matplotlib在3D空间中绘制平面的案例
2021/02/06 Python
3种方式实现瀑布流布局小结
2019/09/05 HTML / CSS
Net-A-Porter美国官网:全球时尚奢侈品名站
2017/02/11 全球购物
Raleigh兰令自行车美国官网:英国凤头牌自行车
2018/01/08 全球购物
高中毕业生生活的自我评价
2013/12/08 职场文书
2014年文学毕业生自我鉴定
2014/04/23 职场文书
党员自我剖析材料范文
2014/10/06 职场文书
经费申请报告
2015/05/15 职场文书
Django实现WebSocket在线聊天室功能(channels库)
2021/09/25 Python