微信公眾號登陸開發流程
阿新 • • 發佈:2019-03-13
line 返回 ucc useragent for webkit builder request cgi
1.首先需要獲取到openId 用於返回給公眾號前臺,之後前臺傳回openId到後臺做業務處理
@Autowired private WXAuthorizationBiz wxAuthorizationBiz; //獲取微信openId @RequestMapping(value = "/getWechatOpenId", method = RequestMethod.POST) @ResponseBody public TResponse<?> getWechatOpenId(@Validated @RequestBody ReqGetWechatOpenIdDTO reqDto, BindingResult errors){ TResponseView Code<?> 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";View Code7 //獲取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(); } } }View Code
微信公眾號登陸開發流程