二维码门禁(基于微信小程序)

门禁系统是一个经典系统,很多人都在做,比如说指纹门禁、人脸门禁等。二维码门禁相比于传统的门禁有什么特点:1:权限分明,2:日志跟踪,3:管理方便。

硬件:二维码扫描器、继电器、电池锁、网线

软件:微信小程序(前端)、web(后台)

技术:二维码生成、二维码解码、http协议数据传输和接受、局域网使用、公网使用

微信小程序生成二维码代码

// pages/main/index.js
var QR = require("../../utils/qrcode.js");
Page({
  data: {
    canvasHidden: false,
    maskHidden: true,
    imagePath: '',
    placeholder: '如:A401'//默认二维码生成文本
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    var size = this.setCanvasSize();//动态设置画布大小
    var initUrl = this.data.placeholder;
    this.createQrCode(initUrl, "mycanvas", size.w, size.h);
    //获取access_token
    wx.request({
      url: 'https://www.babybackhome.com/lg/wxsendmesController/at',
      success: function (res) {
        var at = wx.setStorageSync("at", res.data.mes)
        console.log("后台获取的access——token"+res.data.mes)
      }
    })
    //获取openid
    wx.login({
      success: function (res) {
        var code1 = res.code
        var appid1 = "wx9d0142f81a1707c4"
        var secret1 = "ececd3066a8334df7905c35502242498"
        var ul = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid1 + '&secret=' + secret1 + '&js_code=' + code1 + '&grant_type=authorization_code'
        //获取openid
        wx.request({
          url: ul,
          method: 'GET',
          success: function (e) {
            var openid = e.data.openid
            console.log('获取登录身份的唯一openid', openid)
            wx.setStorageSync('openid', openid)
          }
        })
      }
    })

  },
  onReady: function () {

  },
  onShow: function () {

    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onPullDownRefresh: function () {
    //获取access_token
    wx.request({
      url: 'https://www.babybackhome.com/lg/wxsendmesController/at',
      success: function (res) {
        var at = wx.setStorageSync("at", res.data.mes)
        console.log(res.data.mes)
      }
    })
    //获取openid
    wx.login({
      success: function (res) {
        var code1 = res.code
        var appid1 = "wx9d0142f81a1707c4"
        var secret1 = "ececd3066a8334df7905c35502242498"
        var ul = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid1 + '&secret=' + secret1 + '&js_code=' + code1 + '&grant_type=authorization_code'
        //获取openid
        wx.request({
          url: ul,
          method: 'GET',
          success: function (e) {
            var openid = e.data.openid
            console.log('获取登录身份的唯一openid', openid)
            wx.setStorageSync('openid', openid)
          }
        })
      }
    })

  },
  onUnload: function () {
    // 页面关闭

  },
  //适配不同屏幕大小的canvas
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 750 / 686;//不同屏幕下canvas的适配比例;设计稿是750宽
      var width = res.windowWidth / scale;
      var height = width;//canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
    }
    return size;
  },
  createQrCode: function (url, canvasId, cavW, cavH) {
    //调用插件中的draw方法,绘制二维码图片
    QR.api.draw(url, canvasId, cavW, cavH);
    setTimeout(() => { this.canvasToTempImage(); }, 1000);

  },
  //获取临时缓存照片路径,存入data中
  canvasToTempImage: function () {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        console.log(tempFilePath);
        that.setData({
          imagePath: tempFilePath,
          // canvasHidden:true
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //点击图片进行预览,长按保存分享图片
  previewImg: function (e) {
    var img = this.data.imagePath;
    console.log(img);
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: [img] // 需要预览的图片http链接列表
    })
  },
  formSubmit: function (e) {
    var that = this;
    var url = e.detail.value.url;
    //获取fromid
    that.setData({
      maskHidden: false,
    });
    wx.showToast({
      title: '生成中...',
      icon: 'loading',
      duration: 2000
    });
    var st = setTimeout(function () {
      wx.hideToast()
      var size = that.setCanvasSize();
      //绘制二维码
      that.createQrCode(url, "mycanvas", size.w, size.h);
      that.setData({
        maskHidden: true
      });
      clearTimeout(st);
    }, 2000)


    //消息服务通知
    //获取fromid
    var fromid = e.detail.formId
    wx.setStorageSync("fromid", fromid)
   

    //往后台传输数据存到数据库
      var today = new Date();
      var year = today.getFullYear();
      var m1 = today.getMonth();
      var month = m1 + 1
      var day = today.getDate();
      var h = today.getHours();
      var m = today.getMinutes();
      var etime = year + "-" + month + "-" + day
      var time = h + ":" + m
      let _jsonData =
      {
        "touser": wx.getStorageSync("openid"),
        "weapp_template_msg": {
          "template_id": "rziENQKqDXfCWPF7sN1C1JNyI0RHBavc8JF2ZbF3JdQ",
          //服务通知中进入小程序的入口
          "page": "pages/index/index",
          "form_id": e.detail.formId,
          "data": {
            "keyword1": {
              "value": wx.getStorageSync("name")
            },
            "keyword2": {
              "value": etime
            },
            "keyword3": {
              "value": time
            },
            "keyword4": {
              "value": "内蒙古师范大学大数据楼316"
            }
          },
          "emphasis_keyword": "keyword1.DATA"
        }
      }
    wx.request({
      url: 'https://www.babybackhome.com/lg/wxsendmesController/addsenddata',
      data: _jsonData,
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log("res")
        console.log(res)
      }
    })
     
      // wx.request({
      //   url: 'https://www.lined5530.top/lg/wxsendmesController/sendMsg',
      //   data: _jsonData,
      //   method: 'POST',
      //   header: {
      //     'content-type': 'application/json' // 默认值
      //   },
      //   success: function (res) {
      //     console.log("res")
      //     console.log(res)
      //   }
      // })
      // console.log("faxiaox")
    

  }

})

后台(ssm)接受解码数据的代码

package org.lg.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lg.entity.classroom;
import org.lg.entity.comroomhis;
import org.lg.entity.senddata;
import org.lg.service.classroomService;
import org.lg.service.comroomhisService;
import org.lg.service.senddataService;
import org.lg.utils.WeChatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import net.sf.json.JSONObject;

@RequestMapping("ewmController")
@Controller
public class ewmController {
	@Autowired
	public comroomhisService comroomhisservice;
	@Autowired
	public classroomService classroomservice;
	@Autowired
	public senddataService senddataservice;
	
	@RequestMapping("test")
	public void test(HttpServletRequest request,HttpServletResponse response) throws IOException {
		//System.out.println("测试");
		BufferedReader reader = request.getReader();
		String content = reader.readLine();//一行一行的读数据
		System.out.println(content.length());
	    int length = content.length();
	    String comnum = content.substring(15);//拿到想要的数据
	    System.out.println("房间号"+comnum);
        comroomhis querycodetag = comroomhisservice.querycomroomhiscodetag(comnum);//机房的权限
        System.out.println("35678"+querycodetag);
        
        //比赛代码
        if(querycodetag==null) {
        	System.out.println("门无法打开");
        }else {
        	String tag = querycodetag.getCodetag();
        	if(tag.equals("1")) {
        		//给扫描器返回高电平
			    PrintWriter out = response.getWriter();
			    out.write("code=0000");
//			 // 微信小程序ID
//		        String appid = "wxf087609e0fb66298";
//		        // 微信小程序秘钥
//		        String secret = "9d230ef9975532e7192e5993100ee7e9";
//
//		        senddata querynewdata = senddataservice.querynewdata();
//		        String jsondata2 = querynewdata.getJsondata();
//		        String ACCESS_TOKEN=querynewdata.getAt();
//		        // 根据小程序穿过来的code想这个url发送请求
//		        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token="+ACCESS_TOKEN;
//		        // 发送请求,返回Json字符串
//		        String str = WeChatUtil.httpRequest(url, "POST", jsondata2);
//		        // 转成Json对象 获取openid
//		        JSONObject fromObject = JSONObject.fromObject(str);
//		        //JSONObject jsonObject = JSONObject.parseObject(str);
//		        System.out.println("jsonObject____"+fromObject.toString());
//		        // 我们需要的openid,在一个小程序中,openid是唯一的
        	}else {
        		System.out.println("门打不开");
        	}
        }
        
        //毕业设计代码
//	    if(querycodetag==null) {
//	    	   System.out.println("输入有误或者不在打卡时间内");
//	    	   List opentag1 = classroomservice.opentag1(comnum);//申请教室的权限
//	    	   System.out.println("234567890-09876534267"+opentag1);
//	   	    if(opentag1.size()==0) {
//		    	System.out.println("申请的教室没有通过");
//		    }else {
//		    	//给扫描器返回高电平
//			    PrintWriter out = response.getWriter();
//			    out.write("code=0000");
//		    }
//	    }else {
//	    	String codetag = querycodetag.getCodetag();
//	    	   System.out.println(codetag);
//	    	   if(codetag.equals("1")) {
//	    		 //给扫描器返回高电平
//	    		    PrintWriter out = response.getWriter();
//	    		    out.write("code=0000");
//	    	   }else {
//	    		
//	    	   }
//	    	
//	    } 
	}

}

实现主要思路,微信小程序生成二维码,二维码扫描器解码,通过http协议将数据传输到后台,后台对应的接口接受数据,进行逻辑处理。只要给扫描器返回高低电平就可以,实现门禁控制。

实现的效果
二维码门禁(基于微信小程序)_第1张图片
了解实现的效果和源码可以扫描关注下方公众号获取和了解。(也可以搜索:《小白XBIT》进行关注)
二维码门禁(基于微信小程序)_第2张图片

你可能感兴趣的:(物联网,ssm,微信小程序)