Java微信公众号开发(一:接入平台,验证token)

Java微信公众号开发(一:接入平台,验证token)

开发环境:

  • 环境:JDK1.8
  • 框架:springBoot

首先,在我们接入微信公众平台之前,我们需要注册微信公众号的开发者账号,获取开发者ID(AppID),并设置你自己的开发者密码(AppSecret),服务器地址(URL),令牌(Token),消息加解密密钥(EncodingAESKey)等信息,地址在下面。

前题条件

https://mp.weixin.qq.com/

当我们注册完开发者账号后,登陆,在页面最下方找到’基本配置’,按需求配置就可以了。这里注意一点的是,自己的开发者密码(AppSecret)一定要保存好,后面很多接口的调用都需要用到。其中里面的一些信息我们后期需要在代码中用到。

代码开发

在代码开发之前,我们应该看一看他腾讯官方给我们的开发文档

https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html

在开发文档中的接入指南里,我们能明确的看到:微信公众号接口必须以http://或https://开头,分别支持80端口和443端口。所以,别犯傻,8080可不支持,但如果你做转发,那就另说了。

接下来就是紧张刺激的Coding了。

<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>
<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.4.9</version>
</dependency>

上边的jar包看个人需求。引不引的无所谓,看心情吧,开心才是最重要的了。

首先,我们要知道,在我们接入微信公众号时,微信服务器会发送一条GET请求到我们填写的服务器地址URL上,同时在URL上会携带如下参数

参数描述
signature微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
timestamp时间戳
nonce随机数
echostr随机字符串

我们需要通过检验signature对请求进行校验。若确认此次GET请求来自微信服务器,正确返回echostr参数内容,则接入生效,成为开发者,否则接入失败。

  • 将token、timestamp、nonce三个参数进行字典排序
  • 将三个参数字符串拼接成一个字符串进行sha1加密
  • 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
package com.liu.surprise.until;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @author HB_LIU
 */
public class WeixinCheckoutUtil {
    /**
     * token可以自己进行定义,必须为英文或者是数字,长度为3-32字符,这个token要跟服务器配置中的token一致
     */
    private static String token = "你的微信公众号token";

    /**
     * 校验签名
     * @param signature 签名
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @return 布尔值
     */
    public static boolean checkSignature(String signature,String timestamp,String nonce){
        String checktext = null;
        if (null != signature) {
            //对ToKen,timestamp,nonce 按字典排序
            String[] paramArr = new String[]{token,timestamp,nonce};
            Arrays.sort(paramArr);
            //将排序后的结果拼成一个字符串
            String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);

            try {
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                //对接后的字符串进行sha1加密
                byte[] digest = md.digest(content.toString().getBytes());
                checktext = byteToStr(digest);
            } catch (NoSuchAlgorithmException e){
                e.printStackTrace();
            }
        }
        //将加密后的字符串与signature进行对比
        return checktext !=null ? checktext.equals(signature.toUpperCase()) : false;
    }

    /**
     * 将字节数组转化我16进制字符串
     * @param byteArrays 字符数组
     * @return 字符串
     */
    private static String byteToStr(byte[] byteArrays){
        String str = "";
        for (int i = 0; i < byteArrays.length; i++) {
            str += byteToHexStr(byteArrays[i]);
        }
        return str;
    }

    /**
     *  将字节转化为十六进制字符串
     * @param myByte 字节
     * @return 字符串
     */
    private static String byteToHexStr(byte myByte) {
        char[] Digit = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        char[] tampArr = new char[2];
        tampArr[0] = Digit[(myByte >>> 4) & 0X0F];
        tampArr[1] = Digit[myByte & 0X0F];
        String str = new String(tampArr);
        return str;
    }
}

接下来我们需要传递参数调用上面的方法进行接入,官方文档中已经说明了接入是的请求为GET请求,所以,我们需要创建一个controller用来调用接入。具体代码如下

package com.liu.surprise.controller;

import com.liu.surprise.service.MessageService;
import com.liu.surprise.until.WeixinCheckoutUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * @author HB_LIU
 */
@RestController
@RequestMapping("/wxPublic")
public class WeixinCheckController {
    @Resource
    MessageService messageService;

    private static final Logger LOGGER = LoggerFactory.getLogger(WeixinCheckController.class);

    @RequestMapping(method = RequestMethod.GET)
    public String checkToken(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 (WeixinCheckoutUtil.checkSignature(signature, timestamp, nonce)) {
                LOGGER.info("微信加密签名:" + signature + ";时间戳:" + timestamp + ";随机数:" + nonce);
                out.print(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
            out = null;
        }
        return null;
    }
}

测试

微信公众号接入、验证token的代码部分到这就结束了,接下来我们需要启动项目,通过微信公众平台接口测试工具测试代码。但是因为我们的代码现在是跑在我们本地,微信无法发送请求到我们本地,这就需要用到一个叫内网穿透的工具了,网上有很多,这个大家就可以自由发挥了。我用的是ngrok.下载好后,我们通过命令行cd到ngrok的存放目录,输入下面的命令。

./ngrok http 80

ngrok by @inconshreveable                                                                                                                                         (Ctrl+C to quit)

Session Status                online
Session Expires               7 hours, 59 minutes
Version                       2.3.35
Region                        United States (us)
Web Interface                 http://127.0.0.1:4040
Forwarding                    http://1234567890.ngrok.io -> http://localhost:80
Forwarding                    https://71234567890.ngrok.io -> http://localhost:80

Connections                   ttl     opn     rt1     rt5     p50     p90
                              0       0       0.00    0.00    0.00    0.00

当有上边的显示后,就说明其他人就可以通过http://1234567890.ngrok.io访问我们本机的80端口了。接下来打开微信公众平台接口测试工具。找到基本配置->服务器配置->修改配置,将所需的信息填入。点击提交

在这里插入图片描述

如果token验证通过,当前页面会主动关闭。这样,我们就成功接入微信公众号了

需要注意的是,因为我用的是安全模式,这样会涉及到后面的接口需要做签名验证,解密等操作才会得到我们想要的信息,大家如果只是自己试水,明文模式也是可以的,会省去很多安全验证的操作。

下面的文章我们将介绍如何实现微信公众号的消息自动回复与关注推送

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值