微信公眾號發送消息給指定的用戶
近期做的需求是一個流程提交后,在微信公眾號上推送消息給流程的審核人員,通知審核人員。
分析:
首先推送給用戶的話,需要用戶關注微信公眾號,將公眾號對應的openid與業務系統的用戶表進行綁定從而建立對照關系;
然后便是在流程提交的時候獲取到對應的審核人員,去數據庫中取得對應的openid,根據 openid 進行消息推送,消息推送建議寫成異步的,避免發送消息報錯影響到正常的業務系統。
說明:做這個需求之前已經做過另外一個需求,就是微信公眾號增加業務系統的訪問菜單,用戶第一次訪問的時候,需要對業務系統進行綁定(用戶表的yhm 和openid做綁定),
綁定成功后進入業務系統,第二次在訪問的時候直接進入業務系統,不需要二次登錄和二次綁定。當然還有解綁。
第一步、獲取access_token
這里獲取的access_token是普通的access_token值,通過 https請求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET 來獲取。

詳情可參考此鏈接:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
第二步、調用推送接口發送消息
發送文本消息的接口地址:https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=
發送模板消息的接口地址:https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=
發送模板消息需要創建一個模板,可以在微信公眾號后台模板消息一欄中去添加模板。

目前針對多個用戶的消息推送,只能是for循環逐一推送,如果朋友們有更好的方法也推薦下。
代碼實現:代碼中appid,appsecret,template_id 需要用實際的值,
目前代碼沒有針對發送失敗的情況做處理,朋友們可以自行做處理。
public static void sendWechatMessage(List<String> yhlist,String context){
//獲取的 appid(微信公眾號號)
String appid = "343546ghdfdfg";
//獲取的 appid(微信公眾號)
String appsecret = "fdsdfgsdfsdfg4334lgdfg";
//發送文本消息接口https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=
String textMessagePath = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";
//發送模板消息的接口地址:https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=
String templateMeaagePath = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
//獲取微信服務號的access_token接口地址:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
String app_accesstoken_path = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=";
//模板ID
String template_id = "sdfgdgdfhgfgjdfgserye";
//獲取token值 String accesstoken = HttpRequestUtil.getAccessToken(app_accesstoken_path+appid+"&secret="+appsecrect);
//yhlist是業務系統獲取的人員,需要根據這個獲取用戶表中對應的openid。 List<String> openidList = new ArrayList<String>(); JwglxtIndexModel model = new JwglxtIndexModel(); String[] yharr = (String[])yhlist.toArray(new String[yhlist.size()]); model.setPks(yharr); openidList = indeDao.getOpenidByuser(model); //模板消息格式 JSONObject jsonObject = new JSONObject(); jsonObject.put("template_id", template_id); jsonObject.put("url", ""); JSONObject data = new JSONObject(); JSONObject first = new JSONObject(); first.put("value", "調課詳細信息"); first.put("color", "#173177"); JSONObject keyword1 = new JSONObject(); keyword1.put("value", context); keyword1.put("color", "#173177"); JSONObject remark = new JSONObject(); remark.put("value", "請同學之間相互告知"); remark.put("color", "#173177"); data.put("first",first); data.put("keyword1",keyword1); data.put("remark",remark); jsonObject.put("data", data); //開始推送模板消息 for(String openID:openidList){ jsonObject.put("touser", openID); String result = HttpRequestUtil.sendTextMessage(jsonObject.toJSONString(),templateMeaagePath +accesstoken); LOG.error("result 推送結果:"+result); }
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("msgtype", "text");
JSONObject data = new JSONObject();
data.put("content", context);
jsonObject1.put("text", data);
//開始推送文本消息
for(String openID:openidList){
jsonObject1.put("touser", openID);
result = HttpRequestUtil.sendTextMessage(jsonObject1.toJSONString(),textMessagePath+accesstoken);
LOG.error("result 推送結果:"+result);
}
}
HttpRequestUtil工具類
//消息推送 public static String sendTextMessage(String jsonObiect,String sendPath){ String resp = "";//響應 try { try { // 構造httprequest設置 CloseableHttpClient httpClient = null; HttpPost postMethod = null; HttpResponse response = null; httpClient = HttpClients.createDefault(); postMethod = new HttpPost(sendPath);//傳入URL地址 //設置請求頭 postMethod.addHeader("Content-type", "application/json; charset=utf-8"); postMethod.addHeader("X-Authorization", "AAAA"); postMethod.setEntity(new StringEntity(jsonObiect, Charset.forName("UTF-8"))); response = httpClient.execute(postMethod); LOG.error("response:"+response); //獲取響應 resp = EntityUtils.toString(response.getEntity(),"UTF-8"); LOG.error("resp:"+resp); } catch (Exception e) { LOG.error("發送POST請求出現異常!" + e); e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } return resp; } //獲取access_token值,有待優化過期時間問題。 public static String getAccessToken(String app_accesstoken_path){ String access_token = ""; HttpResponse response = null; try { // 構造httprequest設置 HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(app_accesstoken_path); //添加請求頭 request.addHeader("User-Agent", "Mozilla/5.0"); response = client.execute(request); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } LOG.error("resultxx:"+result); Map<String, String> access_tokenMap = (Map<String,String>)JSON.parse(result.toString()); LOG.error("access_tokenMapxx:"+access_tokenMap.toString()); access_token = access_tokenMap.get("access_token"); LOG.error("access_tokenxx:"+access_token); } catch (Exception e) { LOG.error("發送GET請求出現異常!" + e); e.printStackTrace(); }finally { try { ((BufferedReader) response).close(); } catch (IOException e) { e.printStackTrace(); } } return access_token; }
結語:以上是實現微信公眾號發送消息的步驟,不足之處請見諒!
