ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

微信公众号发送消息给指定的用户

2019-12-19 15:52:58  阅读:714  来源: 互联网

标签:access String 微信 指定 发送 token JSONObject put new


微信公众号发送消息给指定的用户

近期做的需求是一个流程提交后,在微信公众号上推送消息给流程的审核人员,通知审核人员。

分析:

  首先推送给用户的话,需要用户关注微信公众号,将公众号对应的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;
        
    }

 

结语:以上是实现微信公众号发送消息的步骤,不足之处请见谅!

标签:access,String,微信,指定,发送,token,JSONObject,put,new
来源: https://www.cnblogs.com/misscole/p/12068239.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有