您的位置:首页 > 移动开发 > 微信开发

微信小程序----------保持登录状态访问后台数据

2018-08-14 18:00 716 查看
首先需求是这样的,用户打开小程序,只有在登录的情况下根据用户查询信息返回后台数据,只有登陆后的用户才能访问后台。

我这里后台是Java采用的是MVC的模式,不多说,直接上代码。

第一种方式:调用自己的后台的登录方式进行登录

  1. 小程序的js页面的登录方法
primary: function () {
var that = this
wx.request({
url: 'http://127.0.0.1:8080/hxkj/wxlogin', //自己的后台登录方法(即cortroller层的登录方法地址)
method: 'GET',
data: {
username: this.data.username,  //微信前端页面的输入用户名
password: this.data.password   //微信前端页面的输入密码
},
header: {
'content-type': 'application/json'
},
success: function (res) {
console.log('登录状态:'+res.data.message)
//console.log('sessionId:' + res.data.sessionId)
if (res.data.message == "登录成功"){
getApp().globalData.header.Cookie = 'JSESSIONID=' + res.data.sessionId;  //这一句很重要。
wx.navigateTo({
url: '../index/index'     //登录成功之后需要跳转到的页面
})
}
},
fail: function(){
console.log('登录时网络错误')
}
})
}
  1. 后台登录方法
    //微信小程序登录
@RequestMapping(method = RequestMethod.GET,value = "/wxlogin")
public @ResponseBody Object wxLogin(String username,String password) {
JSONObject jsonObject = new JSONObject();
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
try {
CsUser user = serviceContext.csUserService.check_login(username, password);
if(user != null){
UserSession userSession = new UserSession();
//设置你需要放进session中的信息
userSession.setLogin(true);
request.getSession().setAttribute("userSession", userSession);
String sessionId = request.getSession().getId();
jsonObject.element("sessionId",sessionId);
jsonObject.element("message", "登录成功");
}else{
jsonObject.element("message", "用户名不存在");
}
} catch (NoRowException e) {
System.out.println(e.getLocalizedMessage());
jsonObject.element("message", "密码错误");
}
catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
  1. 登录成功之后,访问其他页面的时候代码如下
primary: function () {
var header = getApp().globalData.header; //必须带上这一句
var that = this;
wx.request({
url: 'http://127.0.0.1:8080/hxkj/selfBillInfo',
method: 'GET',
data: {
},
header: header,
success: function (res) {
}
})
},
  1. 访问页面的后台代码
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "/selfBillInfo")
public Object selfBill(@RequestParam String jobdate,@RequestParam String currency,@RequestParam String type){
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
UserSession userSession = (UserSession) request.getSession().getAttribute("userSession");
//这样就可以获取从微信端传过来的session
}
  1. 在app.js中加入下面方法

2 当用户与微信小程序绑定之后,用户打开小程序自动登录

1.微信小程序端
在app.js文件中加如下方法

//1、调用微信登录接口,获取code
wx.login({
success: function (r) {
var code = r.code;//登录凭证
if (code) {
//2、调用获取用户信息接口
wx.getUserInfo({
success: function (res) {
//3.请求自己的服务器,解密用户信息 获取openId和unionId等加密信息
wx.request({
url: 'http://127.0.0.1:8080/hxkj/decodeUserInfo',//自己的服务接口地址
method: 'post',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: {
encryptedData: res.encryptedData,
iv: res.iv,
code: code
},
success: function (data) {
//4.解密成功后 获取自己服务器返回的结果
if (data.data.status == 1) {
getApp().globalData.header.Cookie = 'JSESSIONID=' + data.data.sessionId
} else {
console.log('自动登录失败')
}
},
fail: function () {
console.log('系统错误')
}
})
},
fail: function () {
console.log('获取用户信息失败')
}
})
} else {
console.log('获取用户登录态失败!' + r.errMsg)
}
},
fail: function () {
console.log('登陆失败')
}
})
  1. 后台代码
@ResponseBody
@RequestMapping(value = "/decodeUserInfo", method = RequestMethod.POST)
public  Map decodeUserInfo(@RequestParam String encryptedData, @RequestParam String iv, @RequestParam String code) {
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
Map map = new HashMap();
// 登录凭证不能为空
if (code == null || code.length() == 0) {
map.put("status", 0);
map.put("msg", "code 不能为空");
return map;
}
// 小程序唯一标识 (在微信小程序管理后台获取)
String wxspAppid = "123";
// 小程序的 app secret (在微信小程序管理后台获取)
String wxspSecret = "123";
// 授权(必填)
String grant_type = "authorization_code";
// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
// 请求参数
String params = "appid=" + wxspAppid + "&secret=" + wxspSecret
+ "&js_code=" + code + "&grant_type=" + grant_type;
// 发送请求
String sr = HttpRequestUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session", params); //HttpRequestUtil为工具类
// 解析相应内容(转换成json对象)
JSONObject json = JSONObject.fromObject(sr);
// 获取会话密钥(session_key)
String session_key = json.get("session_key").toString();
// 用户的唯一标识(openid)
String openid = (String) json.get("openid");
try {
if (null != openid && openid.length() > 0) {
CsUser user = serviceContext.csUserService.check_login2(openid); //判断openid是否存在从而定义登录状态
if(user != null){
UserSession userSession = new UserSession();
userSession.setLogin(true);
request.getSession().setAttribute("userSession", userSession);
String sessionId = request.getSession().getId();
map.put("sessionId", sessionId);
map.put("status", 1);
map.put("msg", "自动登录成功");
return map;
}
}
} catch (Exception e) {
e.printStackTrace();
}
map.put("status", 0);
map.put("msg", "自动登录失败");
return map;
}

附上sendGet方法

public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}

以上就是微信小程序登录的整套代码,本人也是刚刚才接触微信小程序,正在研究这方面。

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: