vue移动端,点击微信授权登录

封装微信登录接口:

const wxLogin = (appid, url) => {
  let redirect_uri = encodeURIComponent(url)
  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATUS#wechat_redirect`
}
参数说明:

1、let redirect_uri = encodeURIComponent(url)  ——  授权后重定向的回调链接地址,并把字符串编码为 URI 组件。

2、windows.location.href="/url"  ——  当前页面打开URL页面
3、appid  -  公众号的唯一标识(必填)
4、redirect_uri  -  授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理(必填)
5、response_type  -  返回类型,请填写code(必填)
6、scope  -  应用授权作用域,snsapi_base(静默登录,不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )(必填)
7、state  -  重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节(非必填)
8、#wechat_redirect  -  无论直接打开还是做页面302重定向时候,必须带此参数(必填)

1、第一个参数用?号隔开,之后的参数用&隔开,最后的#wechat_redirect不用加&
2、open.weixin.qq.com/connect/oauth2/authorize  微信默认地址
3、文档地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842


页面中使用:
template:
 <div @click="wxlogin">
     <p>使用微信登录</p>
 </div>

 

script
import {wxLogin} from "@/api/apis";

// methods
wxlogin(){
        wxLogin('wx546563fe38304393', 'http://whc.mouhua.cn/mobile/v-accredit')
}
 第一个参数是公众号的appid,第二个是跳转的默认空白页。

accredit空白页:
<template>
<div>
</div>
</template>

<script>
import { login } from '@/api'
import { getUrlParam } from '@/utils/utils'
export default {
name: 'accredit',
data(){
return{
}
},
mounted() {
let code = this.$route.query.code || getUrlParam('code');
let state = this.$route.query.state || getUrlParam('state');
login({
code
})
.then( res => {
let role = res.data.role;
localStorage.setItem('accessToken', res.data.accessToken)
localStorage.setItem('role', role)
this.$router.replace(state);
this.$message({
message:'登录成功',
type:'success',
onClose(){
_this.$router.push('/')
localStorage.setItem('ifLoading', '1')
}
})
      })
},
methods: {
}
}
</script>

1.import { getUrlParam } from '@/utils/utils'    ——  引用

封装获取url的参数的方法:

// 获取url上的参数
export const getUrlParam = (name) => {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");      //构造一个含有目标参数的正则表达式对象
  let r = window.location.search.substr(1).match(reg);        //匹配目标参数
  if (r != null) return decodeURIComponent(r[2]); return null;   //返回参数值 
}

 

2.import { wechatLogin } from '@/api/apis'  ——  引用微信登录接口

const wechatLogin = get('/api/v1/user/wechatLogin');

 

3.

let code = this.$route.query.code || getUrlParam('code');

login({
code
})
.then( res => {
localStorage.setItem('accessToken', res.data.accessToken)
})

  ——  获取url上的code,调用微信登录传入code,localStorage.setItem('accessToken',存储登录时的token


特殊项目,非必需

this.$route.query(获取参数)

state(重定向后会带上state参数,非必填,用于记录多页面)

role (获取用户的角色)

this.$router.replace(同样是跳转到指定的url,但是这个方法不会向history里面添加新的记录,点击返回,会跳转到上上一个页面。上一个记录是不存在的。)

 

this.$message(element框架登录成功后的提示)

 

posted @ 2019-08-05 18:01  峻宇  阅读(12346)  评论(3编辑  收藏  举报