微信小程序:登录自动弹出用户授权

JavaScript014

微信小程序:登录自动弹出用户授权,第1张

备注:已不能这样使用了,缅怀一下

小程序启动时,不是先运行app.js然后再调用index.js,而是异步执行的。

邀请好友答题,好友第一次进来要进行 微信登录 -->获取access-token -->获取用户信息 -->绑定个人信息 -->首页逻辑处理 -->跳转好友pk页 等,流程比价复杂并且还有数据交叉使用情况。

一开始我以index作为首页,因为app.js和index.js异步执行,使用Promise也发现启动过程很是繁琐复杂。所以参考了《知乎答题王》多加了一个home页。

流程清晰了不少。 如果有后台系统验证用户信息以及用户权限等业务,建议增加一个启动页。

获取用户信息拒绝后,默认不会再重新弹出授权框 ,需要调用 wx.openSetting 打开手机《设置》允许使用数据

从 2018/4/30 开始,使用 wx.getUserInfo 接口直接弹出授权框的开发方式将逐步不再支持,(因为Facebook用户隐私泄密事件引发的社会关注),想获取用户隐私信息必须要友好!

腾讯公告:小程序与小游戏获取用户信息接口调整

1.网站接入微信登录的好处

网站接入微信登录,微信登录使网站可以免除注册的流程,并充分利用庞大的微信用户群来实现快速传播;网站接入微信登录后,用户只需要使用手机扫码就可登录,简化用户注册流程,更有效率的提高转化用户流量。

2.站接入微信登录之前需要申请

接入微信登录前,网站需首先进行申请,获得对应的appid与appkey,以保证后续流程中可正确对网站与用户进行验证与授权;我们以瓴码官网http://www.zeropaas.com申请。

3.瓴码官网前端增加相关代码

let nowUrl = location.href

let result = /code=(w*)&state=([0-9]*)/.exec(nowUrl)

if(result){

window.parent.postMessage(nowUrl,'*')

}

4.网站前端将微信登录二维码图标内嵌至一个p中,并显示该p

!function (a, b, c) {

function d(a) {

var c = "default"

a.self_redirect === !0 ? c = "true" : a.self_redirect === !1 &&(c = "false")

var d = b.createElement("iframe"),

e = "https://open.weixin.qq.com/connect/qrconnect?appid=" + a.appid + "&scope=" + a.scope + "&redirect_uri=" + a.redirect_uri + "&state=" + a.state + "&login_type=jssdk&self_redirect=" + c + '&styletype=' + (a.styletype || '') + '&sizetype=' + (a.sizetype || '') + '&bgcolor=' + (a.bgcolor || '') + '&rst=' + (a.rst || '')

e += a.style ? "&style=" + a.style : "", e += a.href ? "&href=" + a.href : "", d.src = e, d.frameBorder = "0", d.allowTransparency = "true", d.scrolling = "no", d.width = "300px", d.height = "400px"

var f = b.querySelector('.weChatLogin_col_weChatBouncedDiv')//微信二维码内嵌p

f.innerHTML = "", f.appendChild(d)

}

a.WxLogin = d

}(window, document)

const state = Number(new Date()).toString()//获取状态值

window.sessionStorage.setItem('state', state )//暂存状态值

const obj = new WxLogin({//实例化一个二维码

self_redirect: true,

id: "weChatBouncedDiv",//微信二维码图标内嵌p的id

appid: "wxfb8bf3273365770a",//应用唯一标识

scope: "snsapi_login",

redirect_uri: "http%3a%2f%2fzeropaas.com",//回调地址

state: state ,//用于保持请求和回调的状态,授权请求后原样带回给第三方;该参数可应用于防止csrf攻击(跨站请求伪造攻击)

})

5.网站前端微信登录授权成功之后的处理

window.onmessage = function(e) {//微信登录授权成功后,官网触发该消息

let url = e.data//e.data="http://www.zeropaas.com/?code=xxx&state=xxx"

if(url.indexOf('?') != -1){

url = url.substr(url.indexOf('?'))//url="?code=xxx&state=xxx"

let arr = url.substr(1).split('&')//arr=["code=xxx","state=xxx"]

arr = arr.map(item =>{

item = item.split('=')

let map = new Map()

map.set(item[0],item[1])

item = Object.fromEntries(map)

return item

})//arr=[{code:"xxx"},{state:"xxx"}]

let oldState = window.sessionStorage.getItem('state')

let newState = arr[1].state

//

// loadingDiv.style.display = 'flex'

// loadingDiv.innerHTML = '正在登录中...'

$this.showVessel('loadingDiv',true,()=>{//显示正在登录中

$this.sm['loading'].startModule(function () {

$this.showSubModule('loading', true, function () {

if(oldState === newState){

$this.ep.thirdLogin(0,arr[0].code,1,1,0,null,function (result) {//向云端发送第三登录事件,code是微信登录码

if (result === null) {

$this.$router.push('/')//微信登录成功,并且不要绑定手机号

} else {//微信登录成功,并且需要绑定手机号

$this.openID = result//微信用户ID

$this.showSubModule('loading', false, function () {}, function () {})

$this.showVessel('loadingDiv',false,()=>{},()=>{})//隐藏正在登录中

$this.showBindingPhone()//绑定手机号

}

},function (err) {

console.log(err)

})

}

}, function () {})

}, function () {})

},()=>{})

window.onmessage = null

}

},

6.网站云端获取微信openid和access_token

function getOpenid_WX(appid,appSecret,code,successCB, errorCB){//获取微信openid和token

const request = require(global.nodePath + "/node_modules/request")

let url1= 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + appid + '&secret=' + appSecret + '&code=' + code + '&grant_type=authorization_code'

request.get(

{

url: url1,

method: "GET",

json: true,

headers: {

"Content-type": "application/json",

},

},function (error, response, body) {

if (response.statusCode == 200) {

let data = JSON.stringify(body, null, 4)//从一个对象解析出字符串,第三个参数是格式化缩进格式按照四个字符缩进

let data1 = (JSON.parse(data))

let access_token = data1.access_token

let openid = data1.openid

successCB(access_token,openid)

}else {

errorCB(['获取微信信息失败!状态码:'+ response.statusCode])

}

}

)

}

7.微信登录和QQ登录的区别

微信登录可以内嵌网站登录页面,也可以打开微信登录授权页面,QQ登录不可以内嵌网站登录授权页面,必须打开QQ登录授权页面,如果是打开微信或QQ登录授权页面,则登录授权成功后必须关闭该页面。

微信登录回调地址可以指定一级根目录或二级子目录,比如 "http%3a%2f%2fzeropaas.com "或"http%3a%2f%2fzeropaas.com/qqLogin", QQ登录回调地址必须指定二级子目录,比如 "http%3a%2f%2fzeropaas.com/qqLogin"