微信公众号接触

使用SpringMVC搭建一个微信开发环境

直接从网络上下载一个demo修改开始学习,总结了下开发步骤
1、注册一个微信公众号
2、提供2个api接口,分别用户微信服务器验证公众号(get方法)和接收微信服务器转发消息用(post方法)

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public String wxInterface(HttpServletRequest request,HttpServletResponse response,WeChat wc) throws UnsupportedEncodingException{

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8"); 
    String signature = wc.getSignature();
    String timestamp = wc.getTimestamp();  
    String nonce = wc.getNonce(); 
    String echostr = wc.getEchostr();  

    if (SignUtil.checkSignature(signature, timestamp, nonce)) {  
        Log.info("是微信服务器发来的请求,请方心!");  
        return echostr;  
    } else {  
        Log.info("不是微信服务器发来的请求,请小心!");  
        return null;
    }  
}


@RequestMapping(method = RequestMethod.POST, produces = "application/xml;charset=UTF-8")    
//@ResponseBody
public void getWeiXinMessage(HttpServletRequest request, HttpServletResponse response) throws Exception
{
    Log.info("/api  post 请求");  
    response.setCharacterEncoding("UTF-8");

    //初始化配置文件
    String respMessage = CoreService.processRequest(request);
    // 响应消息  
    PrintWriter out = response.getWriter();         
    out.print(new String(respMessage.getBytes("GBK"), "GBK"));
    out.flush();      
    out.close();        
}

其中,get方法中checkSignature需要用到开发者自行给公众号设置的token值。
登录公众号平台,配置公账号服务器的地址、设置的token值、消息加密时用的加密密钥及消息加密方式等信息。设置后,如果启动成功,则最简单的微信开发框架就出来 了。
在公众号平台配置

post方法的CoreService.processRequest(request)是对不同消息类型进行处理,如文本消息,语音消息,图片消息,推送消息以及事件等。

public static String processRequest(HttpServletRequest request) {
    String respMessage = null;// 默认返回的文本消息内容
        String respContent = "ERROR:请求处理异常,请稍候尝试!";
        // xml请求解析
        // 调用消息工具类MessageUtil解析微信发来的xml格式的消息,遍历所有节点内容,解析的结果放在HashMap里;
        Map<String, String> requestMap = MessageUtil.parseXml(request);
        // 从HashMap中取出消息中的字段;
        // 发送方帐号(open_id)
        String fromUserName = requestMap.get("FromUserName");
        // 公众帐号
        String toUserName = requestMap.get("ToUserName");
        // 消息类型
        String msgType = requestMap.get("MsgType");
        // 消息内容
        String content = requestMap.get("Content");
        //根据不同的msgType做不同的响应处理
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值