微信公众号开发第一步 - 接入

本文写给没有公众号开发经验的程序员阅读,也是我第一篇博客。因为之前开发过程中遇到很多问题都是上百度查解决方案,大部分都来源于优快云,一直在索取却没有回报,感觉很不厚道!哈哈,废话不多说。

一、公众号开发准备。
1 申请微信公众号。具体是订阅号还是服务号,根据你的业务需求,官方平台有详细说明。开发阶段可以去申请微信测试号。
2 准备花生壳。项目开发阶段,可以去安装一个花生壳,配置好域名与ip的映射,这个ip是你本机的ip,然后把你tomcat的端口号也配置上去,就可以实现访问域名http://fuyang7412.vicp.cc/weixinDemo就定位到你的eclipse中的项目了。
这里写图片描述
3 准备云服务器。项目上线阶段,你需要去购买云服务器,然后去申请一个域名,这是因为你开发的web项目要接入微信公众平台,那么需要在公众平台配置域名,公众平台才能够访问到你的项目,才能互相通信。
4 准备公众平台开发者key、secret
这里写图片描述

二、接入代码
1 创建类PublicString.java。测试我就不暴露我自己的key和secret了,token随意填写

public class PublicString {
    /**公众号Key**/ 
    public static final String appKey = "XXXXXXXXXXXXXX";
    /**公众号Secret**/
    public static final String appSecret = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY";
    /**加密字符串**/
    public static final String Token = "helloweixin";
}

2 创建类VerifyMessageUtil.java。用于对微信服务器发来的接入参数进行验证,再将验证结果返回。

import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class VerifyMessageUtil {
    private String token;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public VerifyMessageUtil() {
        super();
    }

    public VerifyMessageUtil(String token) {
        super();
        this.token = token;
    }

    /**
     * 验证 消息请求 是否 合法
     * @param request
     * @param response
     * @throws IOException
     */
    public void rerifyRequest(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        if(token == null)
            throw new IllegalArgumentException("未指定要验证的token");
        /**
         * 第二步:验证URL有效性
         * 
         * 开发者提交信息后,微信服务器将发送GET请求到填写的URL上,GET请求携带四个参数:
         * 
         * 参数 描述 signature
         * 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。 timestamp
         * 时间戳 nonce 随机数 echostr 随机字符串
         * 开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器
         * ,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。
         * 
         * 加密/校验流程如下: 1. 将token、timestamp、nonce三个参数进行字典序排序 2.
         * 将三个参数字符串拼接成一个字符串进行sha1加密 3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
         * 检验signature的PHP示例代码:
         * 
         * 
         */
        Logger logger = Logger.getLogger("pdwy");
        logger.log(Level.INFO, "日志开始");

        String signature = request.getParameter("signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        String echostr = request.getParameter("echostr");

        logger.log(Level.INFO, String.format("收到:signature=%s,nonce=%s,timestamp=%s,echostr=%s", signature,nonce, timestamp, echostr));

        if(signature == null && nonce == null && timestamp== null && echostr== null){
            logger.log(Level.INFO, "参数不全");
            response.sendError(500,"参数不全");
            return;
        }

//      logger.log(Level.INFO, String.format(
//              "收到:signature=%s,nonce=%s,timestamp=%s,echostr=%s", signature,
//              nonce, timestamp, echostr));
        if (null == signature || "".equals(signature)) {
            response.sendError(500);
            return;
        }

        String[] arrs = new String[] { token, timestamp, nonce };
        Arrays.sort(arrs);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arrs.length; i++) {
            sb.append(arrs[i]);
        }
        String newSignature = sha1(sb.toString());
        if (signature.equals(newSignature)) {
            PrintWriter pw = response.getWriter();
            pw.write(echostr);
            pw.close();
        }
    }

    private static String sha1(String content) {
        // 首先用生成一个MessageDigest类,确定计算方法
        java.security.MessageDigest alga;
        try {
            alga = java.security.MessageDigest.getInstance("SHA");
            // 添加要进行计算摘要的信息
            alga.update(content.getBytes());
            // 计算出摘要
            byte[] digesta = alga.digest();
            return byteArrayToHexString(digesta);

            // String s1 = alga.digest().toString();
            // return s1;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String byteArrayToHexString(byte[] b) {
        String result = "";
        for (int i = 0; i < b.length; i++) {
            result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
        }
        return result;
    }
}

3 创建WeixinSvc.java。接收微信服务器的get请求,并将处理结果返回给微信服务器。

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class WeixinSvc extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /****************** 验证消息的合法性 ******************/
        VerifyMessageUtil util = new VerifyMessageUtil();
        util.setToken(PublicString.Token);
        util.rerifyRequest(request, response);

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

}

4 配置web.xml。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>WeixinSvc</servlet-name>
    <servlet-class>WeixinSvc</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>WeixinSvc</servlet-name>
    <url-pattern>/wxsvc</url-pattern>
  </servlet-mapping>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

5 运行项目,然后在微信公众平台配置上你的域名、key、secret、token,提交。如果弹出提交成功代表你和系统和微信公众号平台接入成功了!
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值