微信公众号扫码授权

开发之前可以先看下微信官方文档:

https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1453779503&token=&lang=zh_CN

我用的是第一种方式,具体实现之后的效果大家可以参考下:http://bj.96weixin.com/  如下图:

微信公众号扫码授权

微信公众号扫码授权

1  微信第三方平台注册第三方平台

 微信公众号扫码授权

注册之后2主要重点是以上截图不要乱写 尤其是"授权事件接受的url"

2  授权事件接受的url  接口

@RequestMapping(value = "/getComponentVerifyTicket", method = RequestMethod.POST)
    public String getComponentVerifyTicket(HttpServletRequest request, HttpServletResponse response,@RequestParam("timestamp")String timestamp, @RequestParam("nonce")String nonce,
            @RequestParam("msg_signature")String msgSignature, @RequestBody String postData) throws Exception{
        System.out.println("timestamp:"+timestamp+"nonce:"+nonce+"msgSignature:"+msgSignature+"postData:"+postData);
        logger.info("timestamp:"+timestamp+"---nonce:"+nonce+"-----msgSignature:"+msgSignature+"-----postData:"+postData);    
        WXBizMsgCrypt pc;
        try {
                                    //token, encodingAesKey, appId
            pc = new WXBizMsgCrypt("wxCustomerService", "U2FsdGVkX19krclKBf5AQVxKZLEj0TNRTvTGrBzuRHY", "wx4d7202c718e1ebf4");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader sr = new StringReader(postData);
            InputSource is = new InputSource(sr);
            Document document = db.parse(is);
            Element root = document.getDocumentElement();
            NodeList nodelist1 = root.getElementsByTagName("Encrypt");
            String encrypt = nodelist1.item(0).getTextContent();
            String format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";
            String fromXML = String.format(format, encrypt);

            //
            // 公众平台发送消息给第三方,第三方处理
            //

            // 第三方收到公众号平台发送的消息
            String result2 = pc.decryptMsg(msgSignature, timestamp, nonce, fromXML);
            System.out.println("解密后明文: " + result2);
            logger.info("解密后明文: " + result2);    
            Map<String, String> xmlToMap = xmlToMap(result2);
            logger.info("xmlToMap: " + xmlToMap);    
            String ComponentVerifyTicket = xmlToMap.get("ComponentVerifyTicket");
            TICKET=ComponentVerifyTicket;
            logger.info("ComponentVerifyTicket:"+ComponentVerifyTicket);    
            System.out.println(ComponentVerifyTicket);
        } catch (AesException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "success";
    }

其中有一些坑 大家可以参考下 一下博主的:

https://blog.csdn.net/lwx0313/article/details/77164506

public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                
            }
            return data;
        } catch (Exception ex) {
            throw ex;
        }

    }

3 获取取PreAuthCode

@RequestMapping(value = "/getPreAuthCode", method = RequestMethod.GET)
    public String getPreAuthCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
          if(!TICKET.equals("")) {
            try {
                String url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
                ComponentToken ct = new ComponentToken();
                ct.setComponent_appid("wx4d7202c718e1ebf4");
                ct.setComponent_appsecret("37a41c86d22a76240360fcf34943c728");
                ct.setComponent_verify_ticket(TICKET);
                net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(ct);
                String str = json.toString();
                byte[] result = HttpsUtil.post(url, str, "utf-8");
                String resultstrs = new String(result);
                net.sf.json.JSONObject obj = net.sf.json.JSONObject.fromObject(resultstrs);
                String component_access_token = (String) obj.get("component_access_token");
               
                String urls2="https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token="+component_access_token;
                  PreAuthCode pac = new PreAuthCode();
                  pac.setComponent_appid("wx4d7202c718e1ebf4");
                net.sf.json.JSONObject json2 = net.sf.json.JSONObject.fromObject(pac);
                String str2 = json2.toString();
                byte[] result2 = HttpsUtil.post(urls2, str2, "utf-8");
                String resultstrs2 = new String(result2);
                net.sf.json.JSONObject obj2 = net.sf.json.JSONObject.fromObject(resultstrs2);
                String pre_auth_code=(String) obj2.get("pre_auth_code");
                return pre_auth_code;
            } catch (Exception e) {
                // TODO: handle exception
                logger.error(e.toString());
                return "false";
            }
         }else {
            return "false";
         }
    }

4 前端调用后台接口获取参数

$.ajax({
        url: "/wxbot/userManagement/getPreAuthCode",  //对应3
        type: "get",
        data: {},
        success: function (data) {
            if(data!="false"){
                window.location.href="http://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=wx4d7202c718e1ebf4&pre_auth_code="+data+"&redirect_uri=http://pr.weixin.qq.com/wxbot/userManagement/getAuthorizationCode";
            }
        }
    });

redirect_uri是回调的url  根据回调返回来的参数 可以去查一些公众号的相关信息  之后保存自己需要的数据

5 回调接口(还未测试)

@RequestMapping(value = "/getAuthorizationCode", method = RequestMethod.GET)
    public String getAuthorizationCode(HttpServletRequest request, HttpServletResponse response,@RequestParam("auth_code")String authCode, @RequestParam("expires_in")String expiresin) throws Exception {
        logger.info("authCode: " + authCode);    
        if(!TICKET.equals("")) {
            try {
                String url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
                ComponentToken ct = new ComponentToken();
                ct.setComponent_appid("wx4d7202c718e1ebf4");
                ct.setComponent_appsecret("37a41c86d22a76240360fcf34943c728");
                ct.setComponent_verify_ticket(TICKET);
                net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(ct);
                String str = json.toString();
                byte[] result = HttpsUtil.post(url, str, "utf-8");
                String resultstrs = new String(result);
                net.sf.json.JSONObject obj = net.sf.json.JSONObject.fromObject(resultstrs);
                String component_access_token = (String) obj.get("component_access_token");
                logger.info("component_access_token: " + component_access_token);    
                
                String urls2="https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token="+component_access_token;
                ApiQueryAuth aqa = new ApiQueryAuth();
                aqa.setComponent_appid("wx4d7202c718e1ebf4");
                aqa.setAuthorization_code(authCode);
                net.sf.json.JSONObject json2 = net.sf.json.JSONObject.fromObject(aqa);
                String str2 = json2.toString();
                byte[] result2 = HttpsUtil.post(urls2, str2, "utf-8");
                String resultstrs2 = new String(result2);
                net.sf.json.JSONObject obj2 = net.sf.json.JSONObject.fromObject(resultstrs2);
                String authorizer_appid=(String) obj2.get("authorizer_appid");
                logger.info("authorizer_appid: " + authorizer_appid);    
                
                String urls3="https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token="+component_access_token;
                ApiAuthorizer aa = new ApiAuthorizer();
                aa.setComponent_appid("wx4d7202c718e1ebf4");
                aa.setAuthorizer_appid(authorizer_appid);
                net.sf.json.JSONObject json3 = net.sf.json.JSONObject.fromObject(aa);
                String str3 = json3.toString();
                byte[] result3 = HttpsUtil.post(urls3, str3, "utf-8");
                String resultstrs3 = new String(result3);
                net.sf.json.JSONObject obj3 = net.sf.json.JSONObject.fromObject(resultstrs3);
                JSONObject authorizer_info = (JSONObject) obj3.get("authorizer_info");
                String authorization_appid=(String) obj3.get("authorization_appid");
                String user_name = (String) authorizer_info.get("user_name");
                String principal_name = (String) authorizer_info.get("principal_name");
                logger.info("authorizer_info: " + authorizer_info);    
                logger.info("user_name: " + user_name);    
                logger.info("principal_name: " + principal_name);    
                try{
                    
                    String openid = UserAuthentication.getOpenidFromCookie(request);
                    if (openid.isEmpty())
                        return "false";
                    
                    WechatUser user = userManagementService.getWechatUserByOpenid(openid);
                    Integer adminUser = user.getId();
                    
                    SystemBusinessList sbltmp = userManagementService.getSystemBusinessListByAppname(adminUser+"");
                    sbltmp.setAppName(user_name);
                    sbltmp.setAppSecret("");
                    sbltmp.setCName(principal_name);
                    sbltmp.setAppId(authorization_appid);
                    boolean ret = userManagementService.saveSystemBusinessList(sbltmp);
                    if(!ret){
                        return "false";
                    }
                }catch(Exception e){
                    logger.error(e.toString());
                    return "false";
                }
                return "wxAutomaticService/page/home";
            } catch (Exception e) {
                // TODO: handle exception
                logger.error(e.toString());
                return "false";
            }
            
        }else {
            return "false";
        }
        
    }

 

希望可以帮助的你们  当初自己做的时候是两眼一抹黑