欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java微信公众号消息模板推送功能实现

程序员文章站 2024-03-15 14:32:53
...

一 模板消息的优缺点

优点:显示形式有别于其他消息,信息通俗易懂且要美观一些是一种通知类消息,可以主动给用户发送,用户只需关注公众号不需要和公众号有交互;可根据行业的不同发送个性化消息

缺点:消息内容固定,不能进行过多的定制化

二 使用条件

已经通过微信认证的公众号并且已经申请开通过模板消息接口,而且还需要从模板库中选择过模板并已添加到自己的公众平台

首先点击这里的按钮:
java微信公众号消息模板推送功能实现
之后找到合适模板点“添加按钮”
java微信公众号消息模板推送功能实现
三 程序调用模板消息发送接口

1 模板消息由于模板选取不同需要传入参数的名称、值、参数个数也不同首先要封装2个实体

package com.ruoyi.wanshang.domain;

import com.ruoyi.common.core.domain.BaseEntity;

/**
 * 模板消息 TemplateParam
 *
 * @author ruoyi
 */
public class TemplateParam extends BaseEntity
{
	// 参数名称
	private String name;
	// 参数值
	private String value;
	// 颜色
	private String color;
	
    public TemplateParam(String name,String value,String color){
    	this.name=name;
    	this.value=value;
    	this.color=color;
    }
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public String getValue() {
		return value;
	}
 
	public void setValue(String value) {
		this.value = value;
	}
 
	public String getColor() {
		return color;
	}
 
	public void setColor(String color) {
		this.color = color;
	}

}

package com.ruoyi.wanshang.domain;

import java.util.List;

import com.ruoyi.common.core.domain.BaseEntity;

/**
 * 模板消息 Template
 *
 * @author ruoyi
 */
public class Template extends BaseEntity
{
	// 消息接收方
	private String toUser;
	// 模板id
	private String templateId;
	// 模板消息详情链接
	private String url;
	// 消息顶部的颜色
	private String topColor;
	// 参数列表
	private List<TemplateParam> templateParamList;
 
	public String getToUser() {
		return toUser;
	}
 
	public void setToUser(String toUser) {
		this.toUser = toUser;
	}
 
	public String getTemplateId() {
		return templateId;
	}
 
	public void setTemplateId(String templateId) {
		this.templateId = templateId;
	}
 
	public String getUrl() {
		return url;
	}
 
	public void setUrl(String url) {
		this.url = url;
	}
 
	public String getTopColor() {
		return topColor;
	}
 
	public void setTopColor(String topColor) {
		this.topColor = topColor;
	}
	
	public String toJSON() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("{");
		buffer.append(String.format("\"touser\":\"%s\"", this.toUser)).append(",");
		buffer.append(String.format("\"template_id\":\"%s\"", this.templateId)).append(",");
		buffer.append(String.format("\"url\":\"%s\"", this.url)).append(",");
		buffer.append(String.format("\"topcolor\":\"%s\"", this.topColor)).append(",");
		buffer.append("\"data\":{");
		TemplateParam param = null;
		for (int i = 0; i < this.templateParamList.size(); i++) {
		     param = templateParamList.get(i);
		    // 判断是否追加逗号
			if (i < this.templateParamList.size() - 1){
				
				buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"},", param.getName(), param.getValue(), param.getColor()));
			}else{
				buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"}", param.getName(), param.getValue(), param.getColor()));
			}
		
		}
		buffer.append("}");
		buffer.append("}");
		return buffer.toString();
		}
 
	public List<TemplateParam> getTemplateParamList() {
		return templateParamList;
	}
 
	public void setTemplateParamList(List<TemplateParam> templateParamList) {
		this.templateParamList = templateParamList;
	}

}

发送模板消息的主要方法

public static boolean sendTemplateMsg(String token,Template template){
		
		boolean flag=false;
		
		String requestUrl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
		requestUrl=requestUrl.replace("ACCESS_TOKEN", token);
	
		JSONObject jsonResult=CommonUtil.httpsRequest(requestUrl, "POST", template.toJSON());
		if(jsonResult!=null){
			int errorCode=jsonResult.getInt("errcode");
			String errorMessage=jsonResult.getString("errmsg");
			if(errorCode==0){
				flag=true;
			}else{
				System.out.println("模板消息发送失败:"+errorCode+","+errorMessage);
				flag=false;
			}
		}
		return flag;
		
		
		
}

调用模板消息的发送方法

Template tem=new Template();
tem.setTemplateId("0LYlQL2f4dyoU9fMHTqlQEXkFV5Pi5HBEqhwt3fkTLw");
tem.setTopColor("#00DD00");
tem.setToUser("oWOHzsm8htRGTadf14eDdcnLsAjM");
tem.setUrl("");
		
List<TemplateParam> paras=new ArrayList<TemplateParam>();
paras.add(new TemplateParam("first","亲爱的商户,您有新的已支付订单,请尽快发货哦~~","#FF3333"));
    	paras.add(new TemplateParam("keyword1","ZD2007041586267116","#FF0000"));//订单号
    	paras.add(new TemplateParam("keyword2","洁比世 长柄杯刷","#000000"));//商品名称
    	paras.add(new TemplateParam("keyword3","justbest-SN42","#000000"));//规格
    	paras.add(new TemplateParam("keyword4","1","#000000"));//商品数量
    	paras.add(new TemplateParam("keyword5","2020-07-05 10:29:28","#000000"));//时间
    	paras.add(new TemplateParam("remark","广东省深圳市南山区创新大厦...","#000000"));//收货人信息
		
tem.setTemplateParamList(paras);
    	//获取token
    	Object access_token = iWsUserService.getToken();
        String token = access_token.toString();	
boolean result=sendTemplateMsg(token,tem);

获取token

    public Object getToken() {
    	String param = "grant_type=client_credential"+"&appid="+PayState.APPID+"&secret="+PayState.APPSECRET;
        String access_tokens = "https://api.weixin.qq.com/cgi-bin/token";
        String sendGet1 = HttpRequestUtils.sendGet(access_tokens, param);
        JSONObject jsonObject = JSONObject.parseObject(sendGet1);
        Object accessToken = jsonObject.get("access_token");
        return accessToken;
    }

HttpRequestUtils工具类

package com.ruoyi.wanshang.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * http请求工具类
 */
public class HttpRequestUtils {
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            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.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 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;
    }
}

CommonUtil工具类

package com.ruoyi.wanshang.utils;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
 
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
 
import net.sf.json.JSONObject;
 
public class CommonUtil {
	
	public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) { 
		
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();  
        try {  
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化  
            TrustManager[] tm = { new MyX509TrustManager() };  
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
            sslContext.init(null, tm, new java.security.SecureRandom());  
            // 从上述SSLContext对象中得到SSLSocketFactory对象  
            SSLSocketFactory ssf = sslContext.getSocketFactory();  
  
            URL url = new URL(requestUrl);  
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
            httpUrlConn.setSSLSocketFactory(ssf);  
  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式(GET/POST)  
            httpUrlConn.setRequestMethod(requestMethod);  
  
            if ("GET".equalsIgnoreCase(requestMethod)) {
            	 httpUrlConn.connect();  
            } 
               
  
            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式,防止中文乱码  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  
  
            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            jsonObject = JSONObject.fromObject(buffer.toString());  
        } catch (ConnectException ce) {  
            ce.printStackTrace();
        } catch (Exception e) {  
            e.printStackTrace();
        }  
        return jsonObject;  
    }
	
    public static String httpRequest(String requestUrl, String requestMethod, String outputStr) { 
		
        
        StringBuffer buffer = new StringBuffer();  
        try {  
          
  
            URL url = new URL(requestUrl);  
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  
           
  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式(GET/POST)  
            httpUrlConn.setRequestMethod(requestMethod);  
  
            if ("GET".equalsIgnoreCase(requestMethod)) {
            	 httpUrlConn.connect();  
            } 
               
  
            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式,防止中文乱码  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  
  
            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            //jsonObject = JSONObject.fromObject(buffer.toString());  
        } catch (ConnectException ce) {  
            ce.printStackTrace();
        } catch (Exception e) {  
            e.printStackTrace();
        }  
        return buffer.toString();  
    }
	public static String urlEncodeUTF8(String source){
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
	
    public static String httpsRequestForStr(String requestUrl, String requestMethod, String outputStr) { 
		
        String result="";
        StringBuffer buffer = new StringBuffer();  
        try {  
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化  
            TrustManager[] tm = { new MyX509TrustManager() };  
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
            sslContext.init(null, tm, new java.security.SecureRandom());  
            // 从上述SSLContext对象中得到SSLSocketFactory对象  
            SSLSocketFactory ssf = sslContext.getSocketFactory();  
  
            URL url = new URL(requestUrl);  
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
            httpUrlConn.setSSLSocketFactory(ssf);  
  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式(GET/POST)  
            httpUrlConn.setRequestMethod(requestMethod);  
  
            if ("GET".equalsIgnoreCase(requestMethod)) {
            	 httpUrlConn.connect();  
            } 
               
  
            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式,防止中文乱码  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  
  
            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            result=buffer.toString();  
        } catch (ConnectException ce) {  
            ce.printStackTrace();
        } catch (Exception e) {  
            e.printStackTrace();
        }  
        return result;  
    }
}

最后,效果图如下:
java微信公众号消息模板推送功能实现

相关标签: java