Springboot开发微信公众号
1:准备工作
(1) Natapp的安装 参照https://natapp.cn/article/natapp_newbie
(2) 微信后端接入服务器编写
新建Springboot工程 步骤参考
https://jingyan.baidu.com/article/48206aea8b3570216bd6b310.html
在application.properties中修改端口号为80
server.port=80
在新建的Springboot工程中新建controller类
@Controller
public class TestController
{
@RequestMapping("/test")
@ResponseBody
public String test(HttpServletRequest request,HttpServletResponse response)
{
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
if(CheckUtil.checkSignature(signature, timestamp, nonce)){
//如果校验成功,将得到的随机字符串原路返回
System.out.println(echostr);
}
return echostr;
}
其中请求参数signature是微信加密签名,timestamp是时间戳,nonce是随机数,echostr是随机字符串
将token、timestamp、nonce三个参数进行字典序排序 2)将三个参数字符串拼接成一个字符串进行sha1加密 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
加密算法工具类
public class CheckUtil {
public static final String tooken = "e09acc65959b24d9"; // 开发者自行定义Tooken
public static boolean checkSignature(String signature, String timestamp, String nonce) {
//1.定义数组存放tooken,timestamp,nonce
String[] arr = { tooken, timestamp, nonce };
//2.对数组进行排序
Arrays.sort(arr);
//3.生成字符串
StringBuffer sb = new StringBuffer();
for (String s : arr) {
sb.append(s);
}
//4.sha1加密,网上均有现成代码
String temp = getSha1(sb.toString());
//5.将加密后的字符串,与微信传来的加密签名比较,返回结果
return temp.equals(signature);
}
public static String getSha1(String str) {
if (str == null || str.length() == 0) {
return null;
}
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
}
开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败
(3) 微信测试公众号申请
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421137522
其中URL为申请natapp获得的隐射url再加上controller的requestmap
比如:natapp的url为http://pp7q34.natappfree.cc 则该url为
http://pp7q34.natappfree.cc/test
Token 为natapp中的token
提交后如果现实配置成功表示服务端搭建完成