微信小程序公众号模板消息发送,亲测可用

咳咳,今天一口气写了三个文章,大概讲解一下为什么要封装成接口,以往都是封装成一个方法在后台调用,因为前台调用通知较多,为了方便管理就封装成了一个接口,请不要纠结命名…因为这个命名是之前(不是我)规定好的,导致我加的时候也是这样子将就一下,不过建议不要这样,命名还是很重要
代码如下:

 /**
     * @param openId 用户openid
     * @param appcode 产品标识
     * @param tempId 模板id
     * @param data 数据
     * @param url 跳转链接
     * @param pagepath 小程序跳转页面
     */
    public void sendWeixinMessage(String openId, String appcode, String tempId, String data, String pagepath,
        String url, Document event,Document logDoc) throws Exception {
        String zkpath = WxPUserSyncUtil.getZkUrlByPlatform(appcode);
        JSONObject tokenObj = ZkUtils.getJsonData(server.getZooKeeper(),
            zkpath + "/access_token", false);
        String appId = WxPUserSyncUtil.getAppidByPlatform(appcode);
        String access_token = tokenObj.getString("access_token");
        JSONObject jsonObject = this.sendWxMsg(openId, appId, access_token, tempId, data, pagepath, url,logDoc);
        logDoc.put("appcode",appcode);
        logDoc.put("openId",openId);
        logDoc.put("messageId",jsonObject.getInt("msgid"));
        logDoc.put("tempId",tempId);
        logDoc.put("send_time",Tools.getFormatTime("yyyy-MM-dd HH:mm:ss", ts));
        logDoc.put("wx_timestamp",Tools.getFormatTime(ts));
        if (event != null) {
            event.put("wxid", jsonObject.getInt("msgid"));//记录发送id
            event.put("wx_time", Tools.getFormatTime("yyyy-MM-dd HH:mm:ss", ts));
            event.put("wx_timestamp", ts);
        }
    }

    //发送微信消息
    public JSONObject sendWxMsg(String openId, String appId, String access_token, String tempId,
        String data,
        String pagepath, String url,Document logDoc) throws Exception {
        JSONObject rsp = new JSONObject();
        JSONObject sendJsonObj = new JSONObject();

        sendJsonObj.put("wxAccessToken", access_token);
        sendJsonObj.put("redirectMiniProgramAppId", appId);
        sendJsonObj.put("type", "offical-account");

        //未读消息模版
        sendJsonObj.put("tempId", tempId);
        if (!"".equals(pagepath)) {
            sendJsonObj.put("pagepath", pagepath);
        }
        if (!"".equals(url)) {
            sendJsonObj.put("url", url);
        }
        sendJsonObj.put("dataJson", data);
        rsp = sendTemplate(sendJsonObj, openId,logDoc);
        /* }*/


        return rsp;
    }
    //发送模板消息
     public JSONObject sendTemplate(JSONObject sendJsonObj, String openId,Document logDoc) {
        String wxAccessToken = sendJsonObj.getString("wxAccessToken");
        String tempId = sendJsonObj.getString("tempId");
        String type = sendJsonObj.getString("type");
        String redirectMiniProgramAppId = "";
        JSONObject result = new JSONObject();
        if (sendJsonObj.has("redirectMiniProgramAppId")) {
            redirectMiniProgramAppId = sendJsonObj.getString("redirectMiniProgramAppId");
        }
        String pagepath = "";
        String url = "";
        if (sendJsonObj.has("pagepath")) {
            pagepath = sendJsonObj.getString("pagepath");
        } else if (sendJsonObj.has("url")) {
            url = sendJsonObj.getString("url");
        }
        String formId = "";
        if (sendJsonObj.has("formId")) {
            formId = sendJsonObj.getString("formId");
        }

        try {
            String token = wxAccessToken;
            String sendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
                + token;
            if (type.equals("miniprogram")) {
                sendUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="
                    + token;
            }
            JSONObject sendData = new JSONObject();
            sendData.put("touser", openId);
            sendData.put("template_id", tempId);
            if (type.equals("offical-account")) {
                JSONObject miniProgram = new JSONObject();
                miniProgram.put("appid", redirectMiniProgramAppId);
                if (!"".equals(pagepath)) {
                    miniProgram.put("pagepath", pagepath);
                }
                if (!"".equals(url)) {
                    miniProgram.put("url", url);
                }
                sendData.put("miniprogram", miniProgram);
            } else if (type.equals("miniprogram")) {
                sendData.put("form_id", formId);
                sendData.put("page", pagepath);
            }
            if (sendJsonObj.has("dataJson")) {
                String dataJson = sendJsonObj.getString("dataJson");
                JSONObject data = new JSONObject(dataJson);
                sendData.put("data", data);
            }
            /*      sendData.put("emphasis_keyword", "keyword1.DATA");*/
            System.out.println("sendWxMsg url is: " + sendUrl + "\nsend data is: " + sendData.toString());
            org.jsoup.nodes.Document doc2 = com.focus.util.HttpUtils.post(sendUrl, null,
                sendData.toString().getBytes());
            JSONObject sresult = new JSONObject(doc2.body().text());
            logDoc.put("sendData",Document.parse(sendData.toString()));
            logDoc.put("sresult",Document.parse(sresult.toString()));
            int r = sresult.getInt("errcode");
            if (r == 0) {
                result.put("errcode", r);
                result.put("errmsg", "OK");
                result.put("msgid", sresult.getInt("msgid"));
            } else {
                result.put("errcode", 500);
                result.put("errmsg", sresult.getString("errmsg"));
                result.put("msgid", "发送失败");
            }
        } catch (Exception e) {
            result.put("errcode", 500);
            result.put("errmsg", "接口系统异常");
        }
        //这里进行记录日志
        logDoc.put("status",result.getInt("errcode"));
        MongoCollection<Document> wxMessage = mongo().getCollection("zbj", logDoc.getString("appcode")+"_wxmessage");
        wxMessage.insertOne(logDoc);
        //记录发送情况
        //消息id  时间 openid  发送内容   参数内容 返回结果内容  是否成功

        return result;
    }

//调用接口:

  public JSONObject handle(HttpServletRequest request, Document event) throws Exception {
        JSONObject rsp = new JSONObject();

        Document req = (Document) event.get("req");
        String openIds=req.getString("openIds");
        String appcode=req.getString("appcode");
        String tempId=req.getString("tempId");
        String pagepath=req.getString("pagepath");
        String url=req.getString("url");
        String database = req.getString("database");
        String tablename = req.getString("tablename");
        String _id = req.getString("_id");
        String title=req.getString("first");
        int keyWordCount=req.getInteger("keyWordCount",4);
        Document set = new Document();
        JSONObject data1 = new JSONObject();
        JSONObject keyvalue;
        keyvalue = new JSONObject();
        keyvalue.put("value", title);
        data1.put("first", keyvalue);

        if(keyWordCount>0){
            String keyword1=req.getString("keyword1");
            keyvalue = new JSONObject();
            keyvalue.put("value", keyword1);
            data1.put("keyword1", keyvalue);
        }
        if(keyWordCount>1){
            String keyword2=req.getString("keyword2");
            keyvalue = new JSONObject();
            keyvalue.put("value", keyword2);
            data1.put("keyword2", keyvalue);
        }
        if(keyWordCount>2){
            String keyword3=req.getString("keyword3");
            keyvalue = new JSONObject();
            keyvalue.put("value", keyword3);
            data1.put("keyword3", keyvalue);
        }
        if(keyWordCount>3){
            String keyword4=req.getString("keyword4");
            keyvalue = new JSONObject();
            keyvalue.put("value", keyword4);
            data1.put("keyword4", keyvalue);
        }
        String remark=req.getString("remark");
        Document logDoc=new Document();
        keyvalue = new JSONObject();
        keyvalue.put("value", remark);
        data1.put("remark", keyvalue);
        String[] openId=openIds.split(",");
        MongoCollection<Document> col = mongo().getCollection(database, tablename);
        if(openId.length>1){
            for (String openid:openId) {
                super.sendWeixinMessage(openid,appcode,tempId,data1.toString(),pagepath,url,set,logDoc);
            }
        }else {
            super.sendWeixinMessage(openId[0].toString(),appcode,tempId,data1.toString(),pagepath,url,set,logDoc);
        }
        col.updateOne(Filters.eq("_id", new ObjectId(_id)), new Document("$set", set));
        rsp.put("errcode", 0);
        rsp.put("errmsg", String.format("公众号通知成功"));
        return rsp;
    }

如有不足请大佬指出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值