微信授权之前准备工作,微信公众号后台,需要配置白名单,业务域名,以及网页授权域名,配置完成之后进行下面操作
一、获取code
const reUrl = location.href.split('#')[0] //获取code 之后返回的页面
const appid = 'xxxxxx' //公众号的appid
// 获取code 的url 地址 ,scope 的值有snsapi_userinfo和snsapi_base
//此处我用的是静默的方式
const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(reUrl)}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
location.href = url
注意:1) 接口域名需要在微信后台白名单以及微信后台绑定的域名和接口域名需要一致,我在使用扫码功能的时候就是这个原因不能使用
2)获取code时的那个返回的url , 如果是本地localhost:xxx会有问题,可以使用线上地址用微信编辑器调式
二、code 拿到之后,就可以通过获取url 参数的方法拿到code的值
我的具体案例如下,供参考:
getCode() { // 获取code
if (!this.getUrlCode('code')) {
const reUrl = location.href.split('#')[0]
const appid = 'xxxxx' //公众号的appid
const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(reUrl)}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
location.href = url
} else {
const code = this.getUrlCode('code')
this.code = code
// alert(this.code)
}
},
getUrlCode(name) { // 截取url中的code方法
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
var r = window.location.search.substr(1).match(reg)
if (r != null) return unescape(r[2])
return null
},