Vue实现微信授权登录
时间:2022-07-24
本文章向大家介绍Vue实现微信授权登录,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
新建个文件wechatAuth.js 这个文件可以不用更改
const queryString = require('qs')
// 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),
// snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
const SCOPES = ['snsapi_base', 'snsapi_userinfo']
class VueWechatAuthPlugin {
install(Vue, options) {
let wechatAuth = this
this.setAppId(options.appid)
this.scope = SCOPES[options.scope ? 1 : 0]
Vue.mixin({
created() {
this.$wechatAuth = wechatAuth
},
})
}
constructor() {
this.appid = null
this.redirectUri = null
this.scope = null
this._code = null
this._redirectUri = null
}
static makeState() {
return (
Math.random()
.toString(36)
.substring(2, 15) +
Math.random()
.toString(36)
.substring(2, 15)
)
}
setAppId(appid) {
this.appid = appid
}
set redirectUri(redirectUri) {
this._redirectUri = encodeURIComponent(redirectUri)
}
get redirectUri() {
return this._redirectUri
}
get state() {
return localStorage.getItem('wechat_auth:state')
}
set state(state) {
localStorage.setItem('wechat_auth:state', state)
}
get authUrl() {
if (this.appid === null) {
throw new Error('appid must not be null')
}
if (this.redirectUri === null) {
throw new Error('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.redirectUri
}&response_type=code&scope=${this.scope}&state=${this.state}#wechat_redirect`
}
returnFromWechat(redirectUri) {
let parsedUrl = queryString.parse(redirectUri.split('?')[1])
if (process.env.NODE_ENV === 'development') {
this.state = null
this._code = parsedUrl.code
} else {
if (this.state === null) {
throw new Error("You did't set state")
}
if (parsedUrl.state.replace('#/', '') === this.state) {
this.state = null
this._code = parsedUrl.code
} else {
this.state = null
throw new Error(`Wrong state: ${parsedUrl.state}`)
}
}
}
get code() {
console.log('code', this._code)
if (this._code === null) {
throw new Error('Not get the code from wechat server!')
}
const code = this._code
this._code = null
return code
}
}
const vueWechatAuthPlugin = new VueWechatAuthPlugin()
export default vueWechatAuthPlugin
在main.js里
import wechatAuth from './axios/wechatAuth'
//这里是配置微信公众号的appid
Vue.use(wechatAuth, {
appid: "123",
scope: 'snsapi_userinfo',
})
在router里的js里
import Vue from 'vue'
import Router from 'vue-router'
import wechatAuth from '../axios/wechatAuth'
import axios from 'axios'
Vue.use(Router)
Vue.prototype.$axios = axios;
import {
Dialog
} from "vant";
在路由里配置路由守卫
//截取code
function getCode() {
var url = location.search;
var code = "";
if (url.indexOf("?") != -1) {
var split = url.split("?code=")
code = split[1].split("&")[0]
}
return code;
}
// 获取sign
function getSign(next) {
let theCode = getCode();
if (theCode) {
var formData = new FormData();
formData.append("code", theCode);
axios({
method: "post",
url: "http:api",
data: formData
}).then(res => {
if (res.data.status == 1) {
localStorage.setItem("wx_sign", res.data.data.sign);
let realUrl = window.location.href.split("?")[0];
window.location.href = realUrl;
next()
} else {
Dialog.alert({
title: '提示',
message: res.data.msg,
}).then(() => {
WeixinJSBridge.call('closeWindow')
})
}
});
} else if (localStorage.getItem("wx_sign") == null) {
wechatAuth.redirectUri = window.location.href
window.location.href = wechatAuth.authUrl
} else {
next()
}
}
router.beforeEach((to, from, next) => {
window.document.title = to.meta.title;
if (process.env.NODE_ENV == "production") {
getSign(next)
} else {
next();
}
});
github拉取完整项目
https://github.com/skywalk94/vueWechatH5
- 批量导出csv文件的基本尝试(r8笔记第44天)
- Golang 中的并发限制与超时控制
- 一条简单的报警信息发现的oracle bug(r8笔记第42天)
- 一条insert语句导致的性能问题分析(一)(r8笔记第40天)
- 一条insert语句导致的性能问题分析(二)(r8笔记第43天)
- dataguard中的密码文件管理(r8笔记第39天)
- Mybatis_day02
- Golang构建HTTP服务(一)--- net/http库源码笔记
- Golang构建HTTP服务(二)--- Handler,ServeMux与中间件
- 使用Let's Encrypt的SSL证书配置HTTPS手记
- Mybatis_day01
- golang 如何验证struct字段的数据格式
- ggolot2 画ROC曲线
- 47. 访问MySql数据库实现增删改查 | 厚土Go学习笔记
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法