小程序的登录关键在于使用wx.login()方法后,要到取到code值传到后台,
再用小程序平台本帐号生成的appid+addsecret+code去微信接口服务取得用户唯一标识后即可登录【注意:此步骤必须要在本项目后台服务中才能成功,在小程序端是无效的】
appid+addsecret
下图是官方的登录流程图:
放上代码
showTopTips:function(e){ //登录/注册提交事件 if (userName==\'\'){ app.toastShow(this, "请输入手机号", "error"); } else if (userPassword==\'\'){ app.toastShow(this, "请输入验证码", "error"); }else{ var that = this wx.login({//调用获取用户openId success: function (res) { var loginDevice = \'W\'; //唯一标识 = W + 临时code值 loginDevice = loginDevice + res.code //临时code值 var appid = \'1100310183560349\'; //appid wxf79825c96701f981 var timestamp = Date.parse(new Date());//获取当前时间戳 timestamp = timestamp / 1000; var version = \'1.0\'; //版本号 var sign = \'erwlkrjlkwjelrjwlke\'; //签名 var timestamp = Date.parse(new Date());//获取当前时间戳 timestamp = timestamp / 1000; var loginChannel = \'1003\'; //登录渠道:1001 ios手机 1002 android手机 1003 微信小程序 1004 手机H5 wx.request({ method: "post", url: \'http://uat.*****.com/xiao***/user/baseInfo/userLogin\', //仅为示例,并非真实的接口地址 data: \'{"appId": "\' + appid + \'", "timestamp": \' + timestamp + \', "version": "\' + version + \'", "sign": "\' + sign + \'", "mobile": "\' + userName + \'","validateCode":"\' + userPassword + \'","loginChannel":"\' + loginChannel + \'","loginDevice":"\' + loginDevice + \'",}@#@1100310183560349\' //"validateWay": 1, "validateType": 2 , dataType: "json", header: { \'content-type\': \'application/json\' // 默认值 }, success: function (res) { var userIdEnc = res.data.data.userIdEnc; //用户唯一标识 var loginDevice = res.data.data.loginDevice; wx.setStorageSync(\'userIdEnc\', userIdEnc); //将userIdEnc存入本地缓存 wx.setStorageSync(\'loginDevice\', loginDevice);//将loginDevice存入本地缓存 that.redirectToIndex(); // that.setData({ // id_token: res.data.id_token, // response: res // }) // try { // wx.setStorageSync(\'id_token\', res.data.id_token) // } catch (e) { // } if (res.code == \'0000\') { console.log("注册成功"); // wx.redirectTo({ // url: \'../../pages/index/index\', // }) } else if (res.code == \'1002\') { //超时 that.errorShow(\'超时\'); } else if (res.code == \'1002\') { //帐号冻结 that.errorShow(\'帐号冻结\'); } else { //失败 that.errorShow(\'注册/登录失败\'); } }, fail: function (res) { //console.log(res.data); console.log(\'is failed\') } }) }, fail: function (res) { console.log(\'获取临时code失败!\' + res.errMsg) } }) } },
请发表评论