微信公众号发送模板消息

业务需求需要给相应的用户发送满意度调查问券,与是我找了微信公众号的api地址如下:
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html模板消息接口
结果测试发现,自己的openid无效,梳理了下发现,有自己所拥有的是小程序的openid, 给公众号发消息需要的是小程序的公众号openid,然后查询得知,绑定的小程序和公众号他们会有一个统一的UnionID ,想用这个UnionID 来调用模板消息接口,结果发现还是无效的openid。
后来发现小程序的api里了也有发送模板消息接口,发现是正解,接口地址为:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/uniform-message/uniformMessage.send.html小程序模板消息接口
代码如下:

封装发送消息的数据结构
public void task(){
    String nowDate = DateUtil.getNowDate("yyyy-MM-dd");
    String startTime = nowDate + " 07:00:00";
    String endTime= nowDate + " 12:00:00";
//接收消息的用户查询
	List<Regist> regists = registService.getRegistJZTimeBetween(startTime,endTime);
	String accesstoken = SendMessageApplet.getToken(); //获取token
	 try {
            for (int i = 0; i < regists.size(); i++) {

                //模板消息格式
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("appid","wxbb**************"); //公众号appid,注意是公众后的appid,登录公众号后台查看
                jsonObject.put("template_id", "MpqYpSFxnhGoR8*****");//要发送的模板ID,在公众号后台设置
                jsonObject.put("url", "https://www.wjx.cn/vj/*****.aspx"); //消息点击是要跳转的地址
                JSONObject miniprogram = new JSONObject();
                miniprogram.put("appid","wx67d38a********"); //小程序appid
                miniprogram.put("pagepath","");  //小程序跳转地址,我这里不需要跳转小程序,所以此值致为空
                jsonObject.put("miniprogram","");

                JSONObject data = new JSONObject();
                JSONObject first = new JSONObject();
                first.put("value", "您曾在我院进行诊疗");
                //first.put("color", "#173177");
                JSONObject keyword1 = new JSONObject();
                keyword1.put("value", regists.get(i).getName());
                keyword1.put("color", "#173177");

                JSONObject keyword2 = new JSONObject();
                keyword2.put("value", "test医院");
                keyword2.put("color", "#173177");

                JSONObject keyword3 = new JSONObject();
                keyword3.put("value", regists.get(i).getDeptName());
                keyword3.put("color", "#173177");

                JSONObject keyword4 = new JSONObject();
                keyword4.put("value", regists.get(i).getDoctor());
                keyword4.put("color", "#173177");

                JSONObject keyword5 = new JSONObject();
                keyword5.put("value", regists.get(i).getJiuzhenTime());
                keyword5.put("color", "#173177");

                JSONObject remark = new JSONObject();
                remark.put("value", "特邀请您进行本次诊疗的满意度调查,我们很重视您提出的宝贵意见!");
                remark.put("color", "#173177");

                data.put("first", first);
                data.put("keyword1", keyword1);
                data.put("keyword2", keyword2);
                data.put("keyword3", keyword3);
                data.put("keyword4", keyword4);
                data.put("keyword5", keyword5);
                data.put("remark", remark);
                jsonObject.put("data", data);

                JSONObject requestObj = new JSONObject();
                requestObj.put("mp_template_msg",jsonObject);

                //开始推送模板消息
                requestObj.put("touser", regists.get(i).getWxId());
                String result = SendMessageApplet.sendTemplateMessage(requestObj,accesstoken);
                log.info("===========service===sendMessage===result:" + result);
                if(result != null && !"".equals(result)){
                    JSONObject objResult = JSONObject.parseObject(result);
                    if(0 == objResult.getInteger("errcode")){ //成功
                        log.info("满意度调查推送成功:" + regists.get(i).toString());
                    }else{
                        log.error("满意度调查推送失败:" + regists.get(i).toString()+ "======result:" + result);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("===========自动推送调研问卷异常======" + e.getMessage());
        }
    }

}
获取token, 调用模板


import com.alibaba.fastjson.JSONObject;
import com.zm.scheduleservice.util.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;


/**
 * 小程序发送消息
 */

@Slf4j
public class SendMessageApplet {


    //获取的 appid(微信公众号号)
    static  String  gzh_appid = "wxbb511f829****";
    //小程序 appid
    static String appid="wx67d38a6f1****";

    //小程序appsecrect
    static  String appsecrect="b4a585d91a9b*******";

    //小程序access_token接口地址
    static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?" +
            "grant_type=client_credential&appid="+ appid +"&secret="+appsecrect;

    //小程序发送模板消息的接口地址
    static String sendMessageUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=";


    public static String getToken(){
        //获取token值
        String accesstoken = HttpRequestUtil.sendGetToken(access_token_url);
        log.info("=======小程序调用accesstoken:"+ accesstoken);
        return  accesstoken;
    }


    public static String sendTemplateMessage(JSONObject jsonObject, String accesstoken){
        String result = HttpRequestUtil.sendTextMessage(jsonObject.toJSONString(),sendMessageUrl + accesstoken);
        log.info("======result小程序推送结果:======="+result);
        return result;
    }
}
http请求发送消息
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpRequestUtil {
    //消息推送
    public static String sendTextMessage(String jsonObiect,String sendPath){
        log.info("#####sendTextMessage#### url:" + sendPath );
        log.info("#####jsonObiect#### url:" + jsonObiect );
        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.info("========response:======="+response);
                //获取响应
                resp = EntityUtils.toString(response.getEntity(),"UTF-8");
                log.info("======resp:======="+resp);
            } catch (Exception e) {
                log.error("发送POST请求出现异常!" + e);
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }





    /**
     * 向指定的URL发送GET方法的请求
     * @param url    发送请求的URL
     * @param   ,请求参数应该是 name1=value1&name2=value2 的形式
     * @return       远程资源的响应结果
     */
    public static String sendGetToken(String url) {
            String result = HttpRequestUtil.sendGet(url);
            String accessToken = "";
            log.info("===========sendGetToken===>result:" + result);
            JSONObject obj = JSONObject.parseObject(result);
            if(obj != null){
                accessToken = obj.getString("access_token");
            }
        return accessToken;
    }



 /**
     * 向指定的URL发送GET方法的请求
     * @param url    发送请求的URL

     * @return       远程资源的响应结果
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader bufferedReader = null;
        try {
            //1、读取初始URL
            //String urlNameString = url + "?" + param;
            //2、将url转变为URL类对象
            URL realUrl = new URL(url);

            //3、打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            //4、设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //connection.setRequestProperty("ContentModel-Type", "application/json; charset=utf-8");

            //5、建立实际的连接
            connection.connect();
            //获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            //遍历所有的响应头字段
            for(String key : map.keySet()) {
                System.out.println(key + "---->" + map.get(key));
            }

            //6、定义BufferedReader输入流来读取URL的响应内容 ,UTF-8是后续自己加的设置编码格式,也可以去掉这个参数
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String line = "";
            while(null != (line = bufferedReader.readLine())) {
                result += line;
            }

            log.info("============sendGet=========" + result);
//			int tmp;
//            while((tmp = bufferedReader.read()) != -1){
//                result += (char)tmp;
//            }

        }catch (Exception e) {
            // TODO: handle exception
            System.out.println("发送GET请求出现异常!!!"  + e);
            e.printStackTrace();
        }finally {        //使用finally块来关闭输入流
            try {
                if(null != bufferedReader) {
                    bufferedReader.close();
                }
            }catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        return result;
    }



}

发送结果为:
在这里插入图片描述

注:token的有效期为两小时,重新获取后之前的将致为无效,可以将token值缓存起里,我这里没有没有需要便没有做缓存;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值