2018-03-08,模板消息推送,全代码,多多指教

微信推送模板消息:

一.预备工作

 公众号appid,密钥APPSECRET

请求地址:

//获取access_token的url

url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET;

//发送模板消息的url

    String applyUrl="https://api.weixin.qq.com/cgi-bin/message/template/send";

消息模板实体类

package com.qcmc.entity;

import java.io.Serializable;

/** 
 * 微信API返回状态 
 *  
 * @author wori 
 * @date 2018年3月6日 
 * 
 */ 

public class ResultState implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1692432930341768342L;
	
	private int errcode; // 状态  
    
    private String errmsg; //信息  
  
    public int getErrcode() {  
        return errcode;  
    }  
  
    public void setErrcode(int errcode) {  
        this.errcode = errcode;  
    }  
  
    public String getErrmsg() {  
        return errmsg;  
    }  
  
    public void setErrmsg(String errmsg) {  
        this.errmsg = errmsg;  
    }  

}

package com.qcmc.entity;

/** 
 * 模板消息 返回的结果 
 * @author wori 
 * @date 2018年3月6日 
 * 
 */  
public class TemplateMsgResult extends ResultState {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3198012785950215862L;
	
	 private String msgid; // 消息id(发送模板消息)  
	  
	    public String getMsgid() {  
	        return msgid;  
	    }  
	  
	    public void setMsgid(String msgid) {  
	        this.msgid = msgid;  
	    }  

}

public class WechatTemplateMsg {
	
	
	private String touser;//车主openid
	
	private String template_id; //模板ID
	
	private String url; //模板跳转链接  
	
	private TreeMap<String, TreeMap<String, String>> data; //data数据  

	public TreeMap<String, TreeMap<String, String>> getData() {
		return data;
	}

	public void setData(TreeMap<String, TreeMap<String, String>> data) {
		this.data = data;
	}

	public String getTouser() {
		return touser;
	}

	public void setTouser(String touser) {
		this.touser = touser;
	}

	public String getTemplate_id() {
		return template_id;
	}

	public void setTemplate_id(String template_id) {
		this.template_id = template_id;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
	
    /** 
     * 参数 
     * @param value 
     * @param color 可不填 
     * @return 
     */ 
    public static TreeMap<String, String> item(String value, String color) {  
        TreeMap<String, String> params = new TreeMap<String, String>();  
        params.put("value", value);  
        params.put("color", color);  
        return params;  
    }
}
/**
 * 
 * @author wori
 *	发送请求的工具类
 */
public class WXSendHttpsUtil {
	
	//发送https请求
	public static String getAccessToken(String requestUrl,String requesMethod){
		StringBuffer buffer=null;
		//请求地址
		try{
		//创建SSLContext
		SSLContext sslContext=SSLContext.getInstance("SSL");
		TrustManager[] tm={new MyX509TrustManager()};
		//初始化
		sslContext.init(null, tm, new java.security.SecureRandom());;
		//获取SSLSocketFactory对象
		SSLSocketFactory ssf=sslContext.getSocketFactory();
		URL url=new URL(requestUrl);
		HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		//请求方法
		conn.setRequestMethod(requesMethod);
		//设置当前实例使用的SSLSoctetFactory
		conn.setSSLSocketFactory(ssf);
		conn.connect();
		//往服务器端写内容
		//发起请求需要带的参数
//		if(null!=outputStr){
//			OutputStream os=conn.getOutputStream();
//			os.write(outputStr.getBytes("utf-8"));
//			os.close();
//		}
		
		//读取服务器端返回的内容
		InputStream is=conn.getInputStream();
		InputStreamReader isr=new InputStreamReader(is,"utf-8");
		BufferedReader br=new BufferedReader(isr);
		buffer=new StringBuffer();
		String line=null;
		while((line=br.readLine())!=null){
			buffer.append(line);
		}
		}catch(Exception e){
			e.printStackTrace();
		}
		return buffer.toString();
	}
	
	 /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    
    
    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static JSONObject doPost(String url,JSONObject json){
        
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        //请求头添加编码格式
        post.addHeader("Content-Type", "application/json;charset=utf-8"); 
        JSONObject response = null;
        try {
        	StringEntity s = new StringEntity(json.toString(),"utf-8");
        	System.out.println("js=================="+json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                String result = EntityUtils.toString(res.getEntity());// 返回json格式:
                response = JSONObject.fromObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }
}
因为项目为了方便调用,所以只写了service层,没到controller,以下是实现类,接口就不贴了
public class IMessageServiceImpl implements IMessageService{
	
	@Resource(name = "daoSupport")
	private DAO dao;
	
	@Resource(name = "IUserService")
	private com.qcmc.userservices.IUserService IUserService;
	
	static String APPID=Constants.appId;
	static String APPSECRET=Constants.secret;
	//获取access_token的url
	static String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET;
	//发送模板消息的url
	String applyUrl="https://api.weixin.qq.com/cgi-bin/message/template/send";
	
	@Override
	public DataModel pushMessage(DataModel pd) throws Exception {
		String accessToken="";
		//用openid查询车主车牌号
		String OPPEN_ID=pd.get("OPPEN_ID").toString();
		pd.put("openid",OPPEN_ID);
		System.out.println("=========查询车主信息");
		DataModel dm= IUserService.getUserInfo(pd);
		//整理模板消息参数
		TemplateMsgResult templateMsgResult = null;  
	    TreeMap<String,TreeMap<String,String>> params = new TreeMap<String,TreeMap<String,String>>();  
	    params.put("first",WechatTemplateMsg.item("您好,您收到一条挪车提醒", "#ff0000"));  
        params.put("keyword1",WechatTemplateMsg.item("系统", "#000000"));  
        params.put("keyword2",WechatTemplateMsg.item("您的爱车挡住路啦,麻烦您尽快前往挪车", "#996633"));  
        params.put("remark",WechatTemplateMsg.item("如有疑问,请联系客服", "#000000"));  
		WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();  
        wechatTemplateMsg.setTemplate_id("fzFRfTjBahKqVcPi9Zb8p2s1J05BS9__U8O-4nWIEJ0");    
        wechatTemplateMsg.setTouser(OPPEN_ID);  
        wechatTemplateMsg.setUrl(pd.getString("URL"));  
        wechatTemplateMsg.setData(params);  
        JSONObject json = JSONObject.fromObject(wechatTemplateMsg);
        System.out.println("====json数据"+json.toString());
        //请求获取access_token
        System.out.println("获取access_token");
      	String result=WXSendHttpsUtil.getAccessToken(url,"GET");
      	System.out.println(result);
      	//解析返回的json获取access_token
      	JSONObject sf = JSONObject.fromObject(result);
      	accessToken=(String) sf.get("access_token");
      	System.out.println("acc==================="+accessToken);
      	String wxapplyUrl=applyUrl+"?access_token="+accessToken;
      	System.out.println("applyurl++++++++++++++++"+wxapplyUrl);
      	//推送消息
      	System.out.println("=============推送消息");
        templateMsgResult = sendTemplate(wxapplyUrl, json);
        System.out.println("code=================="+templateMsgResult.getErrcode());
        System.out.println("msgid=================="+templateMsgResult.getMsgid());
        dm.put("templateMsgResult", templateMsgResult);  
		//保存推送日志记录
		System.out.println("=============保存推送记录");
		long time=DateUtils.DateToLong();
		pd.put("time", time);
		Integer row= (Integer) dao.save("UserMapper.savePushMessage", pd);
		dm.put("row", row);
		return dm;
	}
	
	/** 
     * 发送模板消息 
     * @param accessToken 
     * @param json 
     * @return 状态 
     */  
    @Override  
    public TemplateMsgResult sendTemplate(String applyUrl, JSONObject json) {  
        TemplateMsgResult templateMsgResult = null;  
        //发起post请求,发送json数据,返回json对象
        JSONObject result = WXSendHttpsUtil.doPost(applyUrl, json); 
        //将返回的json对象转为json字符串
        String restr=result.toString();
        //解析返回结果
        templateMsgResult = JsonUtils.jsonToPojo(restr, TemplateMsgResult.class);  
        return templateMsgResult;  
    }  
}
注意:在post请求发送json数据时,因为使用的是httpcilent,在newStringEntity对象时,务必指明编码格式,防止乱码-------深受其害的我
StringEntity s = new StringEntity(json.toString(),"utf-8");



                                                                                                //2018.03.08
                                                                                                //第一次微信公众号接口开发
                                                                                                //模板消息推送


 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值