前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >微信开发教程(一):服务器环境搭建

微信开发教程(一):服务器环境搭建

作者头像
肖哥哥
发布2019-02-22 11:10:07
1.1K0
发布2019-02-22 11:10:07
举报

微信配置第一步,进行服务器接口的绑定,这样才能让手机可以关注访问

如果只是个人开发测试使用,为了有完整权限,建议使用测试账号:  申请地址http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index

最简单的办法就是将下面的源码拷贝到一个jsp页面里面,导入相关的基础包进行认证

jsp源码如下:

代码语言:javascript
复制
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@page import="java.util.Date"%>
<%@page import="org.dom4j.Element"%>
<%@page import="org.dom4j.DocumentHelper"%>
<%@page import="org.dom4j.Document"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.io.Reader"%>
<%@page import="java.security.MessageDigest"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="java.util.Arrays"%>
<%@page import="java.util.*"%>
<%  String path = request.getContextPath();   %>
<%  
    final String TOKEN="weixin";
    final HttpServletRequest final_request=request;
    final HttpServletResponse final_response=response;
    final HttpSession final_session =session;
    final ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
%>
<% class WeiXinHandler{  
        public void valid(){
            String echostr=final_request.getParameter("echostr");   
            if(null==echostr||echostr.isEmpty()){    
                try{     
                    responseMsg();    
                }catch(Exception ex){     
                    ex.printStackTrace();
                }
            }else{
                if(this.checkSignature()){
                    this.print(echostr);
                }else{
                    this.print("error"); 
                }
            }
        }
        //自动回复内容  
        public void responseMsg()throws Exception{
            String postStr=null;
            postStr=this.readStreamParameter(final_request.getInputStream());
            System.out.println("22:"+postStr);
            if (null!=postStr&&!postStr.isEmpty()){
                Document document=null;
                try{
                    document = DocumentHelper.parseText(postStr);
                }catch(Exception e){
                    e.printStackTrace();
                }
                if(null==document){
                    this.print("");
                    return;
                }
                Element root=document.getRootElement();
                String fromUsername = root.elementText("FromUserName");
                String toUsername = root.elementText("ToUserName");
                String keyword = root.elementTextTrim("Content"); //消息内容
                String msgtype =root.elementTextTrim("MsgType"); //消息类型
                String event =root.elementTextTrim("Event"); //事件推送  click 表示自定义菜单点击事件
                String eventKey =root.elementTextTrim("EventKey"); //自定义菜单接口中KEY值对应
                String location_x =root.elementTextTrim("Location_X"); //地理位置纬度 
                String location_y =root.elementTextTrim("Location_Y"); //地理位置经度
                String scale = root.elementTextTrim("Scale");//地图缩放大小
                String label = root.elementTextTrim("Label");//地理位置信息
                String time = new Date().getTime()+"";
                System.out.println("keyword: "+keyword);
                System.out.println("msgtype: "+msgtype); 
                //文本消息
                String textTpl ="<xml>"+       "<ToUserName><![CDATA[%1$s]]></ToUserName>"+       "<FromUserName><![CDATA[%2$s]]></FromUserName>"+       "<CreateTime>%3$s</CreateTime>"+       "<MsgType><![CDATA[%4$s]]></MsgType>"+       "<Content><![CDATA[%5$s]]></Content>"+       "<FuncFlag>0</FuncFlag>"+       "</xml>";
                //图文消息     
                String textTpl2 ="<xml>"+      "<ToUserName><![CDATA["+fromUsername+"]]></ToUserName>"+      "<FromUserName><![CDATA["+toUsername+"]]></FromUserName>"+      "<CreateTime>"+new Date().getTime()+"</CreateTime>"+      "<MsgType><![CDATA[news]]></MsgType>"+      "<Content><![CDATA[]]></Content>"+      "<ArticleCount>2</ArticleCount>"+      "<Articles>"+      "<item>"+      "<Title><![CDATA[%1$s]]></Title>"+      "<Description><![CDATA[]]></Description>"+      "<PicUrl><![CDATA[%2$s]]></PicUrl>"+      "<Url><![CDATA[%3$s]]></Url>"+      "</item>"+      "<item>"+      "<Title><![CDATA[%4$s]]></Title>"+      "<Description><![CDATA[]]></Description>"+      "<PicUrl><![CDATA[]]></PicUrl>"+      "<Url><![CDATA[%5$s]]></Url>"+      "</item>"+      "</Articles>"+      "<FuncFlag>0</FuncFlag>"+      "</xml>";
            }
        }
        
        //微信接口验证
        public boolean checkSignature(){
            String signature = final_request.getParameter("signature");
            String timestamp = final_request.getParameter("timestamp");
            String nonce = final_request.getParameter("nonce");
            String token=TOKEN;
            String[] tmpArr={token,timestamp,nonce};
            Arrays.sort(tmpArr);
            String tmpStr=this.ArrayToString(tmpArr);
            tmpStr=this.SHA1Encode(tmpStr);
            if(tmpStr.equalsIgnoreCase(signature)){
                return true;
            }else{
                return false;
            }
        }
        
        //向请求端发送返回数据
        public void print(String content){
            try{
                final_response.getWriter().print(content);
                final_response.getWriter().flush();
                final_response.getWriter().close();
            }catch(Exception e){
                
            }
        }
        
        //数组转字符串  
        public String ArrayToString(String [] arr){
            StringBuffer bf = new StringBuffer();
            for(int i = 0; i < arr.length; i++){
                bf.append(arr[i]);
            }
            return bf.toString();
        }
        
        //sha1加密  
        public String SHA1Encode(String sourceString) {
            String resultString = null;
            try {
                resultString = new String(sourceString);
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                resultString = byte2hexString(md.digest(resultString.getBytes()));
            } catch (Exception ex) {
                
            }
            return resultString;
        }
        
        public final String byte2hexString(byte[] bytes) {
            StringBuffer buf = new StringBuffer(bytes.length * 2);
            for (int i = 0; i < bytes.length; i++) {
                if (((int) bytes[i] & 0xff) < 0x10) {
                    buf.append("0");
                }
                buf.append(Long.toString((int) bytes[i] & 0xff, 16));
            }
            return buf.toString().toUpperCase();
        }
        
        //从输入流读取post参数
        public String readStreamParameter(ServletInputStream in){
            StringBuilder buffer = new StringBuilder();
            BufferedReader reader=null;
            try{
                reader = new BufferedReader(new InputStreamReader(in));
                String line=null;
                while((line = reader.readLine())!=null){
                    buffer.append(line);
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                if(null!=reader){
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return buffer.toString();
        }
    } %>

<%  WeiXinHandler handler=new WeiXinHandler();
    handler.valid();
%>

直接拷贝到一个全新的jsp页面,完全覆盖,不需要再有头,尾啥的

然后接口配置信息里面配置好一个可供外网访问的项目具体路径

如:

  URL :  http://www.xiaochangwei.cn/weixin/demo/configure.jsp

  Token: weixin (和代码中  final String TOKEN="weixin"; 一致即可)

不知道怎么将自己本地项目可让外网访问的可以参考如下链接和工具:

1. 工具 pagekite  免费, 速度一般,偶尔不稳定

2. 工具 花生壳

3.  路由器端口映射  详情点击blog.chinaunix.net/uid-29632145-id-4228889.html

新手建议采用第一种

有不懂得地方请大家交流  后续将有更多内容呈现  大家共同交流进步

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-09-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档