同時在項目中編寫對應的Control層方法:html
public static final String TOKEN = "yfkj_xfcamp_token"; @RequestMapping("get") public void getToken(String signature,String timestamp,String nonce,String echostr,HttpServletResponse response) throws NoSuchAlgorithmException, IOException{ // 將token、timestamp、nonce三個參數進行字典序排序 System.out.println("signature:"+signature); System.out.println("timestamp:"+timestamp); System.out.println("nonce:"+nonce); System.out.println("echostr:"+echostr); System.out.println("TOKEN:"+TOKEN); String[] params = new String[] { TOKEN, timestamp, nonce }; Arrays.sort(params); // 將三個參數字符串拼接成一個字符串進行sha1加密 String clearText = params[0] + params[1] + params[2]; String algorithm = "SHA-1"; String sign = new String( org.apache.commons.codec.binary.Hex.encodeHex(MessageDigest.getInstance(algorithm).digest((clearText).getBytes()), true)); // 開發者得到加密後的字符串可與signature對比,標識該請求來源於微信 if (signature.equals(sign)) { response.getWriter().print(echostr); } }
@GetMapping("login") public void login(HttpServletResponse resp) throws IOException { // 公衆號: String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + "appid=" + appkey.getAppID() + "&" + "redirect_uri=" + appkey.getRedirectUri() + "&" + "response_type=code&" + "scope=snsapi_userinfo&" // snsapi_base + "state=STATE#wechat_redirect"; /* * String url = "https://open.weixin.qq.com/connect/qrconnect?" + * "appid="+appkey.getAppID()+"&" + "redirect_uri="+appkey.getRedirectUri()+"&" * + "response_type=code&" + "scope=snsapi_base&" + * "state=STATE#wechat_redirect"; */ resp.sendRedirect(url); } @GetMapping("get/callback") public void callback(HttpServletRequest req, HttpServletResponse resp) throws IOException { String code = req.getParameter("code"); ObjectMapper objectMapper = new ObjectMapper(); String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=" + appkey.getAppID() + "&" + "secret=" + appkey.getAppSecret() + "&" + "code=" + code + "&" + "grant_type=authorization_code"; ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class); String str = null; if (forEntity.getStatusCodeValue() == 200) { str = forEntity.getBody(); } AccessTokenBO accessTokenBO = null; try { accessTokenBO = objectMapper.readValue(str, AccessTokenBO.class); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } System.out.println(accessTokenBO.toString()); url = "https://api.weixin.qq.com/sns/userinfo?" + "access_token=" + accessTokenBO.getAccess_token() + "&" + "openid=" + accessTokenBO.getOpenid() + "&" + "lang=zh_CN"; forEntity = restTemplate.getForEntity(url, String.class); if (forEntity.getStatusCodeValue() == 200) { str = forEntity.getBody(); } UserInfoBO userInfoBO = null; try { userInfoBO = objectMapper.readValue(str, UserInfoBO.class); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } System.out.println(userInfoBO.toString()); resp.sendRedirect("/index.html"); }