微信公众号-订阅号

原文地址:https://blog.youkuaiyun.com/ooiuy450/article/details/77623384

在进入微信开发前,首先我们要将我们的ip映射成url访问地址,这里我用的是natapp,感觉还是挺稳定的,只不过映射的地址搁一段时间会被替换掉

natapp的下载地址https://natapp.cn/

接下来进入到微信的公众号平台里面去,如果还没申请的话可以进行申请,微信的公众号分为三种:订阅号,服务号,企业号,由于这里是屌丝的聚集地,所以只能用订阅号来玩一玩。

公众号平台地址: 
https://mp.weixin.qq.com/cgi-bin/home 
接着我们点击开发-》基本配置-》服务器配置上点击启动,输入我们的后台网址,令牌,接着点击确定就可以了,如果提示错误,说明后台和微信平台没对接成功,需要检查一下传入的参数是否正确。如下是我的ip地址 
这里写图片描述

记得启动的natapp服务,以下是我用springmvc搭建的服务器代码,如下:

@Controller
@RequestMapping("wechat")
public class WeChatController {

    @RequestMapping(value = "/hello")
    public String index(){
        return "index";
    }

    @RequestMapping(value = "/detail")
    public String detail(){
        return "detailpage";
    }


    @RequestMapping(value = "/home",method= RequestMethod.GET)
    @ResponseBody
    public void valid(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        String code = request.getParameter("code");
        if (isGet) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");

            PrintWriter out = response.getWriter();
            // 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                out.print(echostr);
            }
            out.close();
            out = null;
        }else{
            userpost(request,response);
        }
    }

    @RequestMapping(value = "/home",method= RequestMethod.POST)
    public void userpost(HttpServletRequest request, HttpServletResponse response) throws IOException   {
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        String str = null;
        String code = request.getParameter("code");
        try {
            Map<String, String> message = MessageUtil.xmlToMap(request);
            String fromUser = message.get("FromUserName");
            String toUser = message.get("ToUserName");
            String content = message.get("Content");
            String msgType = message.get("MsgType");
            String msgId = message.get("MsgId");
            Message ms = new Message();
            ms.setContent(content);
            ms.setFromUserName(toUser);
            ms.setToUserName(fromUser);
            ms.setMsgType(msgType);
            str = MessageUtil.textMessageToXml(ms).replace("\n","").replace(" ","");
            out.print(str);
            out.close();
            out = null;
        }catch (Exception e){
            e.printStackTrace();
        }
    }

签名认证

/** 
 * 请求校验工具类 
 *  
 * @author liufeng 
 * @date 2013-05-18 
 */  
public class SignUtil {  
    // 与接口配置信息中的Token要一致  
    private static String token = "chenmianhai";

    /** 
     * 验证签名 
     *  
     * @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);  
        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;  
    }  
}  

pojo转换为xml

/**
 * 基于JAXB的XML生成器: 用于pojo与xml文件的相互转换
 * @author wuwz
 * @ClassName XmlBuilder
 * @DateTime 2016年3月29日 上午10:50:17
 */
public abstract class XmlBuilder {

    private final static Logger log= Logger.getLogger(XmlBuilder.class);
    /**
     * 将pojo转换为XML字符串
     * @param object
     * @return
     */
    public static String convertToXml(Object object) {
        Writer sw = new StringWriter();  
        try {  
            // 利用jdk中自带的转换类实现  
            JAXBContext context = JAXBContext.newInstance(object.getClass());

            Marshaller marshaller = context.createMarshaller();  
            // 格式化xml输出的格式  
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);  
            // 将对象转换成输出流形式的xml  
            marshaller.marshal(object, sw); 
            log.debug("XML字符串生成成功!");
        } catch (JAXBException e) {  
            e.printStackTrace();  
        } finally {
            if(sw != null) {
                try {
                    sw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sw.toString().replace("standalone=\"yes\"", "");  
    }

    /**
     * 将pojo转换为XML文件
     * @param obj
     * @param savePath
     */
    public static File convertToXmlFile(Object obj,String savePath) {
        File file = null;
        String xmlStr = convertToXml(obj);
        if(xmlStr != null && !"".equals(xmlStr)) {

            file = new File(savePath);
            if(!file.exists() && file.isFile()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(file.isDirectory()) {
                System.out.println(MessageFormat.format("{0}不是有效的文件路径.", savePath));
                return null;
            }

            Writer writer = null;

            try {
                writer = new FileWriter(file);
                writer.write(xmlStr);
                writer.flush();
                log.debug("XML文件生成成功!");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        return file;
    }


    /**
     * 将XML文件转换为指定类型的pojo
     * @param clazz
     * @param xmlPath
     * @return
     */
    public static Object xmlFileToObject(Class<?> clazz, String xmlPath) {
        Object xmlObject = null;
        Reader fr = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            fr = new FileReader(xmlPath);
            xmlObject = unmarshaller.unmarshal(fr);
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != fr) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return xmlObject;
    }

    /**
     * 将XML字符串转换为指定类型的pojo
     * 
     * @param clazz
     * @param xmlStr
     * @return
     */
    public static Object xmlStrToObject(Class<?> clazz, String xmlStr) {
        Object xmlObject = null;
        Reader reader = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            // 进行将Xml转成对象的核心接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            reader = new StringReader(xmlStr);
            xmlObject = unmarshaller.unmarshal(reader);
        } catch (JAXBException e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return xmlObject;
    }
}

以上的内容模拟的是消息接口的接收与回复,详情请查看微信的开发文档 
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140453

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值