微信公众号发送消息给指定的用户
近期做的需求是一个流程提交后,在微信公众号上推送消息给流程的审核人员,通知审核人员。
分析:
首先推送给用户的话,需要用户关注微信公众号,将公众号对应的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://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(Listyhlist,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 openidList = new ArrayList();
JwglxtIndexModel model= newJwglxtIndexModel();
String[] yharr= (String[])yhlist.toArray(newString[yhlist.size()]);
model.setPks(yharr);
openidList=indeDao.getOpenidByuser(model);//模板消息格式
JSONObject jsonObject = newJSONObject();
jsonObject.put("template_id", template_id);
jsonObject.put("url", "");
JSONObject data= newJSONObject();
JSONObject first= newJSONObject();
first.put("value", "调课详细信息");
first.put("color", "#173177");
JSONObject keyword1= newJSONObject();
keyword1.put("value", context);
keyword1.put("color", "#173177");
JSONObject remark= newJSONObject();
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 = newJSONObject();
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 staticString 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();
}returnresp;
}//获取access_token值,有待优化过期时间问题。
public staticString getAccessToken(String app_accesstoken_path){
String access_token= "";
HttpResponse response= null;try{//构造httprequest设置
HttpClient client = newDefaultHttpClient();
HttpGet request= newHttpGet(app_accesstoken_path);//添加请求头
request.addHeader("User-Agent", "Mozilla/5.0");
response=client.execute(request);
BufferedReader rd= newBufferedReader(newInputStreamReader(response.getEntity().getContent()));
StringBuffer result= newStringBuffer();
String line= "";while ((line = rd.readLine()) != null) {
result.append(line);
}
LOG.error("resultxx:"+result);
Map access_tokenMap = (Map)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();
}
}returnaccess_token;
}
结语:以上是实现微信公众号发送消息的步骤,不足之处请见谅!