java微信公众号之带参二维码

公司因业务需求需要每个人都有自己的专属二维码,扫描此二维码可以直接关注公众号,并且要统计扫描每个人的二维码的次数。

先着手第一步吧,首先我们要获取appid和secret,接着就是通过这两个参数拿到access_token,因为token两个小时刷新一次,所以要定时的去获取获取将其存入数据库,用的时候取出来查询对比。闲话不说,上代码。

一、创建util工具类,此工具类包含了get/post请求

 //post请求
    public static String sendPost(String param, String url) {
         PrintWriter out = null;
         BufferedReader in = null;
         String result = "";
         try {
             URL realUrl = new URL(url);
             // 打开和URL之间的连接
             URLConnection conn = realUrl.openConnection();
             // 设置通用的请求属性
             conn.setRequestProperty("accept", "*/*");
             conn.setRequestProperty("connection", "Keep-Alive");
             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 = new PrintWriter(new OutputStreamWriter(
                       conn.getOutputStream(), "utf-8"));
             // 发送请求参数
             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) {
             System.out.println("发送 POST 请求出现异常!" + e);
             e.printStackTrace();
         }
         // 使用finally块来关闭输出流、输入流
         finally {
             try {
                  if (out != null) {
                       out.close();
                  }
                  if (in != null) {
                       in.close();
                  }
             } catch (IOException ex) {
                  ex.printStackTrace();
             }
         }
         return result;
    }
    
    /** 
     * 向指定URL发送GET方法的请求 
     *  
     */  
    public static String get(String url) {  
        BufferedReader in = null;  
        try {  
            URL realUrl = new URL(url);  
            // 打开和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.setConnectTimeout(5000);  
            connection.setReadTimeout(5000);  
            // 建立实际的连接  
            connection.connect();  
            // 定义 BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));  
            StringBuffer sb = new StringBuffer();  
            String line;  
            while ((line = in.readLine()) != null) {  
                sb.append(line);  
            }  
            return sb.toString();  
        } catch (Exception e) {  
        	
        }  
        // 使用finally块来关闭输入流  
        finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
            } catch (Exception e2) {  
                e2.printStackTrace();  
            }  
        }  
        return null;  
    }  
    
二、再写一个用于创建二维码的方法(此处的scene_id自定义,用于辨别)
 /*生成临时二维码*/
    public static String getTemporaryQR(String access_token,String scene_id){
    	//String access_token="7_JekEGh-c4Op13Z-mDkFs07C6dquttZu4maa6ntxz6kYS0mD5x6rNyv-brIVJ1a5xCjrnkPNs26H1I49inCcbeMwn-KvH1mouOJT_G_dURAgozHRLwOP9xSVCtKoM30lB1zbFlKFk9tKjnqilJWMaADAZMC";
         //获取数据的地址(微信提供)
         String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+access_token+"";

         //发送给微信服务器的数据
         String jsonStr = "{\"expire_seconds\": 2592000,\"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"						\": "+scene_id+"}}}";

         //将得到的字符串转化成json对象
         String response = sendPost(jsonStr, url);
         return response.toString();
    }

三、直接就是controller层,没有创建service层(此处代码还未优化,并且我是将access_token放在了数据库,所以我每次拿的时候需要去对比时间,大家可以写一个定时器)

	@RequestMapping("/getImg")
	@ResponseBody
	public void getImg(String account,HttpServletRequest request,HttpServletResponse resp) throws Exception{
		
		Wechattoken byId = imgService.getById(1);
		String access_token = null;
		if (byId==null) {
			String string = wechatImg.get(wechatImg.GET_TOKEN_URL+wechatImg.grant_type+"&"+wechatImg.APP_ID+"&"+wechatImg.SECRET);
			System.out.println(string);
			JSONObject fromObject = JSONObject.fromObject(string);
			access_token=fromObject.get("access_token").toString();
			Wechattoken tok = new Wechattoken();
			tok.setAccessToken(access_token);
			tok.setTime(DateTool.getTime());
			imgService.insert(tok);
		}else{
			String time1 = byId.getTime();
			String time2=DateTool.getTime();
			long minus = DateTool.getMinus(time1, time2);
			if (minus>115) {
				String string = wechatImg.get(wechatImg.GET_TOKEN_URL+wechatImg.grant_type+wechatImg.APP_ID+wechatImg.SECRET);
				JSONObject fromObject = JSONObject.fromObject(string);
				access_token=fromObject.get("access_token").toString();
				byId.setAccessToken(access_token);
				byId.setTime(DateTool.getTime());
				imgService.update(byId);
			}else{
				access_token=byId.getAccessToken();
			}
		}
		
		String scene_id=account;
		String temporaryQR = wechatImg.getTemporaryQR(access_token,scene_id);
		System.out.println(temporaryQR);
		JSONObject fromObject = JSONObject.fromObject(temporaryQR);
		String ticket = fromObject.get("ticket").toString();
		System.out.println(ticket);
		//wechatImg.downloadFile(wechatImg.DOWNLOADIMG+ticket, "F://image//"+account+"//"+account+".jpg");
		//DownLoadUtii.downloadAmachment(wechatImg.DOWNLOADIMG+ticket, account+".jpg", request, resp);
		json.put("account", account);
		json.put("ticket", ticket);
		json.put("errorMessage", errorMessage);
		json.put("resultCode", resultCode);
		ResponseTool.write(resp, json);
	}



你可能感兴趣的:(java)