1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 微信小程序授权登录实现Demo

微信小程序授权登录实现Demo

时间:2024-07-19 22:08:39

相关推荐

微信小程序授权登录实现Demo

微信小程序实现授权登录实战。

本篇只讲述后端实现代码,前端代码自行观看官方文档。

不多说,直接上代码。

1.util类。

public static JSONObject getSessionKeyOropenid(String code){//微信端登录code值Map userInfo = new HashMap();Map<String,String> requestUrlParam = new HashMap<String,String>();requestUrlParam.put("appid", WxParameter.MP_APP_ID);//开发者设置中的appIdrequestUrlParam.put("secret", WxParameter.MP_APP_SECRET);//开发者设置中的appSecretrequestUrlParam.put("js_code", code);//小程序调用wx.login返回的coderequestUrlParam.put("connect_redirect", "1");//固定值requestUrlParam.put("grant_type", "authorization_code");//默认参数//发送post请求读取调用微信 https://api./sns/oauth2/access_token 接口获取openid用户唯一标识JSONObject jsonObject = JSON.parseObject(sendPost(WxParameter.OPENID_URL, requestUrlParam));return jsonObject;}//发送请求配置public static String sendPost(String url, Map<String, ?> paramMap) {PrintWriter out = null;BufferedReader in = null;String result = "";String param = "";Iterator<String> it = paramMap.keySet().iterator();while(it.hasNext()) {String key = it.next();param += key + "=" + paramMap.get(key) + "&";}try {URL realUrl = new URL(url);// 打开和URL之间的连接URLConnection conn = realUrl.openConnection();// 设置通用的请求属性conn.setRequestProperty("accept", "*/*");conn.setRequestProperty("connection", "Keep-Alive");conn.setRequestProperty("Accept-Charset", "utf-8");conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// 发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);// 获取URLConnection对象对应的输出流out = new PrintWriter(conn.getOutputStream());// 发送请求参数out.print(param);// flush输出流的缓冲out.flush();// 定义BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {}//使用finally块来关闭输出流、输入流finally{try{if(out!=null){out.close();}if(in!=null){in.close();}}catch(Exception ex){ex.printStackTrace();}}return result;}

2.Controller

//获取前端传的code,并调用util类的方法@ResponseBody@PostMapping("/login")public ResultObject login(HttpServletRequest request, @RequestBody Code code) {String c = code.getCode();JSONObject jsonObject = WxAppletUserInfo.getSessionKeyOropenid(c);String open_id = (String) jsonObject.get("openid");HttpSession session = request.getSession();session.setAttribute("open_id", open_id);String sessionId = session.getId();//微信小程序需要将sessionId传给前端,前端进行保存。if (open_id == null) {return new ResultObject(201, "失败", "");} else {return new ResultObject(200, "成功", sessionId);}}//获取用户信息@ResponseBody@PostMapping("/message")public ResultObject message(HttpServletRequest request, String avatar, String nickname, Integer sex) {HttpSession session = request.getSession();String open_id = (String) session.getAttribute("open_id");session.setAttribute("open_id", open_id);List<User> user1 = userService.selectByOpen_id1(open_id);SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间sdf.applyPattern("yyyy-MM-dd HH:mm:ss");// a为am/pm的标记Date date = new Date();String u_createTime = sdf.format(date);if (user1.isEmpty() || user1 == null) {userService.add(avatar, nickname, sex, open_id, u_createTime, u_createTime);//插入操作return new ResultObject(200, "授权成功", "");} else {userService.updateByOpen_id(open_id, avatar, sex, nickname, u_createTime);//更新操作return new ResultObject(200, "用户已授权过了,修改用户信息", "");}}

3.Pojo

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import lombok.Data;import java.io.Serializable;@Data@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler" })public class Code implements Serializable{private String code;public String getCode() {return code;}public void setCode(String code) {this.code = code;}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。