天天看點

生成微信二維碼注意事項

1.   scene_id必須為整數

生成微信二維碼注意事項
生成微信二維碼注意事項

1.   scene_id必須為整數

2.   微信推送事件

使用者未關注時,進行關注後的事件推送

<xml><ToUserName><![CDATA[toUser]]></ToUserName>        //開發者微信号

<FromUserName><![CDATA[FromUser]]></FromUserName>       //發送者賬号(openid)

<CreateTime>123456789</CreateTime>                //消息建立時間(整型)

<MsgType><![CDATA[event]]></MsgType>              //消息類型 event

<Event><![CDATA[subscribe]]></Event>              //事件類型(subscribe)

<EventKey><![CDATA[qrscene_123 ]]></EventKey>        //事件KEY值,qrscene_為字首,後面為二維碼參數值

<Ticket><![CDATA[TICKET]]></Ticket>               //二維碼ticke值,可以用來換取二維碼圖檔

</xml>

 紅色背景的值和上面紅線中scene_id的值一樣

3接收微信推送事件并解析xml字元串

@RequestMapping(value = "/",method = RequestMethod.POST)
    public String getMessage(HttpServletRequest request,HttpServletResponse response,Model m){
        FileOutputStream fileOutputStream=null;

        BufferedReader buffer=null;
         System.out.println("log................");
        try {


              ///var/ww/tmp/1.txt
            fileOutputStream=new FileOutputStream(new File("d:/2.txt"));
            buffer=request.getReader();

            String line;
            String result=null;
            while ((line = buffer.readLine())!= null) {
                result += line;
            }
            System.out.println(result);


            Document doc=DocumentHelper.parseText(result.substring(4));
            Element rescode = doc.getRootElement();
            String ToUserName = rescode.elementText("ToUserName");
            String FromUserName = rescode.elementText("FromUserName");
            String MsgType = rescode.elementText("MsgType");
            String Event = rescode.elementText("Event");
            String EventKey = rescode.elementText("EventKey");
            String Ticket = rescode.elementText("Ticket");

             System.out.println("Event"+Event);
            String str="log......";
            str=str+result+ToUserName+FromUserName+MsgType+Event+"//evnetkey>>"+EventKey;
//            if(("SCAN").equals(Event)) {
              fileOutputStream.write(str.getBytes());
//            }
//            System.out.println("result="+result.length());
            System.out.println("log................1"+ToUserName+FromUserName);

            if (null != EventKey&&!EventKey.equals("")) {
                //System.out.println(EventKey.substring(0, 4));
                if (EventKey.substring(0,8).equals("qrscene_")) {
                    Integer uid = Integer.parseInt(EventKey.substring(8));
                    Users user = usersService.selectByPrimaryKey(uid);
                    Association association = new Association();
                    association.setHostid(user.getOpenid());
                    association.setSubid(FromUserName);
                    if (null==associationService.selectsubId(FromUserName)) {
                         associationService.insert(association);

                            //m.addAttribute("hostId",user.getOpenid());

                        }
                    //return "redirect:showAssociation/"+user.getOpenid();

                }
            }
        }catch(Exception e){
            e.printStackTrace();
        logger.error(e);
        }finally {
            try {
                if (buffer != null) {
                    buffer.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            }catch (Exception e){
                logger.error(e);
            }
        }

     return null;
    }      

4.在jsp頁面顯示二維碼

<img src="data:image/jpg;base64,${img}" class="erma" alt="二維碼">      

5工具類代碼

public class WeixinUtil {
    public static String httpPostRequest( String token,String scene_id)
    { String result="";
        try {

        String Post_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+token;
        URL url =new URL(Post_URL);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        Map map1=new HashMap();
        map1.put("scene_id",scene_id);
        Map map=new HashMap();
        map.put("scene",map1);

        JSONObject jo=new JSONObject();
        jo.put("expire_seconds", 3600);
        jo.put("action_name", "QR_SCENE");

        jo.put("action_info", map);

//POST請求
        DataOutputStream out = new DataOutputStream(
                connection.getOutputStream());
        out.writeBytes(jo.toJSONString());
        BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));

        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
         System.out.println(result);

        out.flush();
        out.close();
        } catch (Exception e) {

            e.printStackTrace();
        }
        return result;
    }
    public static String  getImageQRCode(String ticket){
        String requestUrl="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();

        try{
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();


            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 設定請求方式(GET/POST)
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();

            // 将傳回的輸入流轉換成字元串
            InputStream inputStream = httpUrlConn.getInputStream();
            BufferedInputStream bis=new BufferedInputStream(inputStream);


            byte[] buffer = new byte[1024*4];
            int len = 0;
            while( (len=bis.read(buffer)) != -1 ){
                outStream.write(buffer, 0, len);
            }
            bis.close();
            // 釋放資源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
        }catch(Exception e){
            e.printStackTrace();
        }
        return encode(outStream.toByteArray());
    }      
public static byte[] readInputStream(InputStream inStream) throws Exception{
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    //建立一個Buffer字元串
    byte[] buffer = new byte[1024];
    //每次讀取的字元串長度,如果為-1,代表全部讀取完畢
    int len = 0;
    //使用一個輸入流從buffer裡把資料讀取出來
    while( (len=inStream.read(buffer)) != -1 ){
        //用輸出流往buffer裡寫入資料,中間參數代表從哪個位置開始讀,len代表讀取的長度
        outStream.write(buffer, 0, len);
    }
    //關閉輸入流
    inStream.close();
    //把outStream裡的資料寫入記憶體
    return outStream.toByteArray();
}
public static String encode(final byte[] bytes) {
    return new String(Base64.encodeBase64(bytes));
}      

.在jsp頁面顯示二維碼

<img src="data:image/jpg;base64,${img}" class="erma" alt="二維碼">      

 [X1]和上面紅線中scene_id的值一樣

繼續閱讀