1. 程式人生 > >java微信公眾號之帶參二維碼

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);
	}