大家好,我是小悟

在做微信小程序或公众号开发的有时候,难免会遇到须要在用户关注或取关公众号后处理业务逻辑的需要,只须要几步就能够搞定。

1、配置

首先咱们须要在微信公众号后盾进行服务器配置,登录公众号后盾->开发->根本配置->服务器配置,如下:

服务器地址就是咱们写的一个controller(代码在上面),用来给微信校验,和接管微信发过来的音讯,如果地址谬误或者token谬误,提交信息的时候会报错

2、代码实现

SignUtil

/** * @description */public class SignUtil {        /**         * 验证签名         * @param token         * @param signature 签名用来核实最初的后果是否统一         * @param timestamp 工夫标记         * @param nonce 随机数字标记         * @return 一个布尔值确定最初加密失去的是否与signature统一         */        public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {            //将传入参数变成一个String数组而后进行字典排序            String[] arr = new String[] { token, timestamp, nonce };            // 将token、timestamp、nonce三个参数进行字典排序            Arrays.sort(arr);            //创立一个对象贮存排序后三个String的结合体            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");                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;        }}

MsgUtil

/** * @description */public class MsgUtil {    public static final String MSGTYPE_EVENT = "event";//音讯类型--事件    public static final String MESSAGE_SUBSCIBE = "subscribe";//音讯事件类型--订阅事件    public static final String MESSAGE_UNSUBSCIBE = "unsubscribe";//音讯事件类型--勾销订阅事件    public static final String MESSAGE_TEXT = "text";//音讯类型--文本音讯    /**     * 组装文本音讯     */    public static String textMsg(String toUserName,String fromUserName,String content){        TextMsg text = new TextMsg();        text.setFromUserName(toUserName);        text.setToUserName(fromUserName);        text.setMsgType(MESSAGE_TEXT);        text.setCreateTime(new Date().getTime());        text.setContent(content);        return XmlUtil.textMsgToxml(text);    }    /**     * 响应订阅事件--回复文本音讯     */    public static String subscribeForText(String toUserName,String fromUserName,String content){        return textMsg(toUserName, fromUserName, content);    }    /**     * 响应勾销订阅事件     */    public static String unsubscribeForText(String toUserName,String fromUserName,String content){        System.out.println("用户:"+ fromUserName +"勾销关注~");        return "";    }}

application.yml

parameter:  #微信公众号  publicAppId: 微信公众号AppId  publicAppSecret: 微信公众号AppSecret

WxPublicController

/** * @description */@Controller@RequestMapping(value = "/message/weixin")public class WxPublicController {    protected static Logger logger = LoggerFactory.getLogger(WxPublicController.class);   //填写和公众号后盾配置的一样的token    private static final String TOKENN = "";    /**     * 微信公众号appId     */    @Value("${parameter.publicAppId}")    private String publicAppId;    /**     * 微信公众号appSecret     */    @Value("${parameter.publicAppSecret}")    private String publicAppSecret;    @RequestMapping(method = RequestMethod.GET)    public void get(HttpServletRequest request, HttpServletResponse response) {        // 微信加密签名,signature联合了开发者填写的token参数和申请中的timestamp参数、nonce参数。        String signature = request.getParameter("signature");        // 工夫戳        String timestamp = request.getParameter("timestamp");        // 随机数        String nonce = request.getParameter("nonce");        // 随机字符串        String echostr = request.getParameter("echostr");        PrintWriter out = null;        try {            out = response.getWriter();            // 通过测验signature对申请进行校验,若校验胜利则原样返回echostr,否则接入失败            if (SignUtil.checkSignature(TOKENN, signature, timestamp, nonce)) {                out.print(echostr);            }        } catch (IOException e) {            e.printStackTrace();        } finally {            if (out != null ) {                out.close();            }        }    }    @RequestMapping(method = RequestMethod.POST)    public void post(HttpServletRequest request, HttpServletResponse response) {        // 响应音讯        PrintWriter out = null;        String resMessage = "";        try {            request.setCharacterEncoding("UTF-8");            response.setCharacterEncoding("UTF-8");            //把微信返回的xml信息本义成map            Map<String, String> map = XmlUtil.parseXml(request);            //消息来源用户标识            String fromUserName = map.get("FromUserName");            //音讯目标用户标识            String toUserName = map.get("ToUserName");            //音讯创立工夫(整型)            String createTime = map.get("CreateTime");            //音讯类型            String msgType = map.get("MsgType");            //事件类型:subscribe/unsubscribe            String eventType = map.get("Event");            //如果为事件类型            if(MsgUtil.MSGTYPE_EVENT.equals(msgType)){                //解决订阅事件                if(MsgUtil.MESSAGE_SUBSCIBE.equals(eventType)){                    resMessage = MsgUtil.subscribeForText(toUserName, fromUserName, "您好,谢谢您的关注!!!");                    //TODO 业务逻辑                    //解决勾销订阅音讯                } else if(MsgUtil.MESSAGE_UNSUBSCIBE.equals(eventType)) {                    //TODO 业务逻辑                }                logger.info("eventType:"+eventType+",fromUserName:"+fromUserName+",toUserName:"+toUserName+",msgType:"+msgType+",createTime:"+createTime);            }            out = response.getWriter();            out.println(resMessage);        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } catch (Exception e) {            e.printStackTrace();        } finally {            if (out != null ) {                out.close();            }        }    }}

您的一键三连,是我更新的最大能源,谢谢

山水有相逢,来日皆可期,谢谢浏览,咱们再会

我手中的金箍棒,上能通天,下能探海