微信小程序推送模版消息

这是我一篇博客,望大家多多支持

发送模版消息之前会在小程序公众号里面去配置一个服务器配置


服务器地址填你要推送消息的接口,第一次需要认证,后面基本不需要了,博主用的解密模式xml解密模式

具体情况安自己项目需求来吧

直接贴代码

public void getWXChat(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
           response.getOutputStream().println(echostr);
		} else {// 进入POST聊天处理
			ServerChat s=new ServerChat();
			s.getmessage(request);
		}
	}//这个是一个接口类,加上requestMapping("xxx")
public class CheckUtil {  
    // 与接口配置信息中的Token要一致
    private static String token = "xxxx";  
    /** 
     * 验证签名 
     * 时间:2018年5月25日 09:55:42
     * @param signature 
     * @param timestamp 
     * @param nonce 
     * @return 
     */  
    public static boolean checkSignature(String signature, String timestamp, String nonce) {  
        String[] arr = new String[] { token, timestamp, nonce };  
        // 将token、timestamp、nonce三个参数进行字典序排序  
        // Arrays.sort(arr);  
        sort(arr);  
        StringBuilder content = new StringBuilder();  
        for (int i = 0; i < arr.length; i++) {  
            content.append(arr[i]);  
        }  
        MessageDigest md = null;  
        String tmpStr = null;  
  
        try {  
            md = MessageDigest.getInstance("SHA-1");  
            // 将三个参数字符串拼接成一个字符串进行sha1加密  
            byte[] digest = md.digest(content.toString().getBytes());  
            tmpStr = byteToStr(digest);  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        }  
        content = null;  
        // 将sha1加密后的字符串可与signature对比,标识该请求来源于微信  
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;  
    }  
  
    /** 
     * 将字节数组转换为十六进制字符串 
     *  
     * @param byteArray 
     * @return 
     */  
    private static String byteToStr(byte[] byteArray) {  
        String strDigest = "";  
        for (int i = 0; i < byteArray.length; i++) {  
            strDigest += byteToHexStr(byteArray[i]);  
        }  
        return strDigest;  
    }  
  
    /** 
     * 将字节转换为十六进制字符串 
     *  
     * @param mByte 
     * @return 
     */  
    private static String byteToHexStr(byte mByte) {  
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };  
        char[] tempArr = new char[2];  
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];  
        tempArr[1] = Digit[mByte & 0X0F];  
        String s = new String(tempArr);  
        return s;  
    }  
    public static void sort(String a[]) {  
        for (int i = 0; i < a.length - 1; i++) {  
            for (int j = i + 1; j < a.length; j++) {  
                if (a[j].compareTo(a[i]) < 0) {  
                    String temp = a[i];  
                    a[i] = a[j];  
                    a[j] = temp;  
                }  
            }  
        }  
    }  
}  
/**
 * 描述:获取微信消息并且处理
 * 
 * @author hedong 时间:2018年4月10日 21:35:35
 */
public class ServerChat {

	// 获取消息解密
	public void getmessage(HttpServletRequest request) throws Exception {
		InputStream is = request.getInputStream();
		BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
		StringBuffer bs = new StringBuffer();
		String u = null;
		while ((u = buffer.readLine()) != null) {
			bs.append(u);
		}
		// 解密的数据,xxx1是开发者设置的token,xxx2是开发者设置的EncodingAESKey,xxx3是公众平台appid,XMLParse.extract,WXBizMsgCrypt这是微信提供的解密的jar,自行去微信发送消息解密下载
		Object[] encrypt = XMLParse.extract(bs.toString());
		WXBizMsgCrypt wx = new WXBizMsgCrypt("xxx1", "xxx2", "xxx3");
		String str = wx.decrypt(encrypt[1].toString());
		processMessage(str);
	}
	// 解析消息中的文本

	@SuppressWarnings("static-access")
	public void processMessage(String message) throws Exception {
		Document doc = DocumentHelper.parseText(message);
		Element root = doc.getRootElement();
		String openid = root.elementText("FromUserName");// 用户的openid
		String msgtype = root.elementText("MsgType");// 消息属性
		WechatApiUrlConstants wechatApiUrlConstants = new WechatApiUrlConstants();
		wechatApiUrlConstants.postMessage(
				wechatApiUrlConstants.pushurl.replaceAll("ACCESS_TOKEN", wechatApiUrlConstants.getToken()),
				wechatApiUrlConstants.chat(openid, msgtype));
	}
}// post发送消息,后面的就很简单了}}


第一篇文章

2018年5月25日 

author: hedong

如果转载,请说明出处哦


猜你喜欢

转载自blog.csdn.net/MiaodXindng/article/details/80454701