微信公众号登陆开发流程
1.首先需要获取到openId 用于返回给公众号前台,之后前台传回openId到后台做业务处理
@Autowired private WXAuthorizationBiz wxAuthorizationBiz; //获取微信openId @RequestMapping(value = "/getWechatOpenId", method = RequestMethod.POST) @ResponseBody public TResponse<?> getWechatOpenId(@Validated @RequestBody ReqGetWechatOpenIdDTO reqDto, BindingResult errors){ TResponse<?> response = null; try { if(errors.hasErrors()){ return TResponse.error(errorMsg(errors)); } response = wxAuthorizationBiz.getWechatOpenId(reqDto); } catch (Exception e) { LOG.error(e); response = TResponse.error("访问异常"); } return response; }
1 //微信appid 2 private String appid = "wx33777933fae68e32"; 3 //微信secret 4 private String secret = "dcecb6ad81d86600106b3e4436f00321"; 5 //获取微信code 6 private String getCodeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ appid + "&redirect_uri={0}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"; 7 //获取openid接口 8 private String getOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ appid +"&secret=" + secret + "&code={0}&grant_type=authorization_code"; 9 //获取token接口 10 private String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appid + "&secret=" + secret; 11 //客服消息接口 12 private String sendMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}"; 13 14 15 public String getCodeUrl(String redirectUri) { 16 if (CommomUtil.isNullOrEmpty(redirectUri)) { 17 return null; 18 } 19 return MessageFormat.format(getOpenIdUrl, redirectUri); 20 } 21 22 23 public ResGetWXOpenIdDTO getOpenId(String wxCode) throws Exception { 24 try { 25 String resJson = httpClientUtil.GET(MessageFormat.format(getOpenIdUrl, wxCode)); 26 if (CommomUtil.isNullOrEmpty(resJson)) { 27 throw new Exception("获取微信OpenId失败,resJson为空"); 28 } 29 LOG.info("getOpenId.resJson = " + resJson); 30 ResGetWXOpenIdDTO resDto = gson.fromJson(resJson, ResGetWXOpenIdDTO.class); 31 if (resDto == null || CommomUtil.isNullOrEmpty(resDto.getOpenid())) { 32 throw new Exception("获取微信OpenId失败,OpenId为空"); 33 } 34 return resDto; 35 } catch (Exception e) { 36 LOG.error(e); 37 throw e; 38 } 39 }
2.获取短信验证码
public TResponse<?> getWXVerifyCode(ReqGetWXVerifyCodeDTO reqDto) { try { String telphone = reqDto.getTelphone().trim(); if (!CheckTelPhone.isTelphoneNum(telphone)) { return TResponse.error("手机号码格式不正确"); } //发送验证码 Random random = new Random(); String code = random.nextInt(9999) + ""; boolean flag = JuheSMS.sendVerifyCode(telphone, code); if (!flag){ return TResponse.error("获取验证码失败"); } String openId = reqDto.getOpenId().trim(); VerifyCode verifyCode = new VerifyCode(code, System.currentTimeMillis()); //保存 verifyCodeMap.put(openId, verifyCode); return TResponse.success("获取验证码成功"); } catch (Exception e) { throw new RuntimeException(e); } public class JuheSMS { private static Gson gson = GsonUtil.getInstance().getGson(); private static final String DEF_CHATSET = "UTF-8"; private static final int DEF_CONN_TIMEOUT = 30000; private static final int DEF_READ_TIMEOUT = 30000; private static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36"; // 配置您申请的KEY private static final String APPKEY = "8790cc59919810935fa25c544a29471a"; private static final String tpl_id = "13577"; public static boolean sendVerifyCode(String telphone, String verifyCode) throws Exception { Map<String, Object> params = new HashMap<String, Object>();// 请求参数 params.put("mobile", telphone); params.put("tpl_id", tpl_id); params.put("tpl_value", "#code#=" + verifyCode); params.put("key", APPKEY); params.put("dtype", "json"); String result = net("http://v.juhe.cn/sms/send", params, "GET"); if (CommomUtil.isNullOrEmpty(result)) { throw new Exception("发送短信验证码失败,result为空"); } ResJuHeSMSDTO resJuHeSMSDTO = gson.fromJson(result, ResJuHeSMSDTO.class); if (resJuHeSMSDTO == null) { throw new Exception("发送短信验证码失败,反序列化失败"); } if (resJuHeSMSDTO.getResult() != null && CommomUtil.isNotNullOrEmpty(resJuHeSMSDTO.getResult().getSid())) { return true;//发送成功 } return false; } /** * @param strUrl 请求地址 * @param params 请求参数 * @param method 请求方法 * @return 网络请求字符串 * @throws Exception */ private static String net(String strUrl, Map<String, Object> params, String method) throws Exception { HttpURLConnection conn = null; BufferedReader reader = null; String rs = null; try { if (method == null || method.equals("GET")) { strUrl = strUrl + "?" + urlencode(params); } URL url = new URL(strUrl); conn = (HttpURLConnection) url.openConnection(); if (method == null || method.equals("GET")) { conn.setRequestMethod("GET"); } else { conn.setRequestMethod("POST"); conn.setDoOutput(true); } conn.setRequestProperty("User-agent", userAgent); conn.setUseCaches(false); conn.setConnectTimeout(DEF_CONN_TIMEOUT); conn.setReadTimeout(DEF_READ_TIMEOUT); conn.setInstanceFollowRedirects(false); conn.connect(); if (params != null && method.equals("POST")) { try { DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(urlencode(params)); } catch (Exception e) { throw new RuntimeException(e); } } InputStream is = conn.getInputStream(); reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET)); StringBuilder strber = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) strber.append(line + "\n"); // 得到请求结果数据 String ret = strber.toString(); ret = ret.replaceAll("&", "&"); return ret; } catch (IOException e) { throw new RuntimeException(e); } finally { if (reader != null) { reader.close(); } if (conn != null) { conn.disconnect(); } } } // 将map型转为请求参数型 private static String urlencode(Map<String, Object> data) { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, Object> i : data.entrySet()) { try { sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } return sb.toString(); } } }