GitHub地址:https://github.com/erlieStar/wechat
效果图
如果不需要定制化的服务,只是推送一些文章的时候,没必要开发自己的服务器,步骤1和步骤4就足够了
LZ用的是Sunny-Ngrok
下载地址:https://www.ngrok.cc/
LZ下载的是Win 64Bit版本,看了作者写的使用博客搭建好了
http://www.sunnyos.com/article-show-71.html
这样我就把本地的地址映射为http://erlie.free.ngrok.cc
不过国人的真心卡啊,果断用了另一个https://ngrok.com/
教程地址:https://jingyan.baidu.com/article/f006222826c2bcfbd3f0c885.html
ngrok http 80
进入软件所在路径,在命令行中运行上面的命令,这样就能把一个外网地址映射为内网,只不过每次重新启动域名会变
地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
appID和appsecret以后都会用到
url填写的内容是http://erlie.free.ngrok.cc/server/system,其中/server/system是接口名字,因为是Spring Boot项目,所以不用写项目名字,token随便写,主要用于验证作用。此时点提交会显示配置失败,因为你得把本地的服务启动起来,并且让微信完成校验
这个是官方写的验证说明:
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319
@Controller
@RequestMapping("server")
public class WeChatController {
/*
* 微信公众号服务器
*/
private final String token = "erlie";
@GetMapping(value = "system")
public void doGet(HttpServletRequest request, HttpServletResponse response) {
//获取参数值
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对比,标识该请求来源于微信
if (CheckUtil.checkSignature(token, timeStamp, nonce).equals(signature)) {
//作出响应,即原样返回随机字符串
out.println(echostr);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
out.close();
}
}
}
public class CheckUtil {
/*
* 微信校验的帮助类
*/
public static String checkSignature(String token, String timeStamp, String nonce) {
String[] arr = new String[]{token, timeStamp, nonce};
//将token、timestamp、nonce三个参数进行字典序排序
Arrays.sort(arr);
//生成字符串
StringBuffer sb = new StringBuffer();
for (int i=0;i<arr.length;i++){
sb.append(arr[i]);
}
//将三个参数字符串拼接成一个字符串进行sha1加密
String temp = getSha1(sb.toString());
return temp;
}
public static String getSha1(String str) {
if (str == null || str.length() == 0) {
return null;
}
char hexDigite[] = {'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++] = hexDigite[byte0 >>> 4 & 0xf];
buf[k++] = hexDigite[byte0 & 0xf];
}
return new String(buf);
}catch (Exception e){
return null;
}
}
}
把本地的服务开启,点击提交就成功了
@Override
public String toString() {
String template = "\n" +
" \n" +
" \n" +
"createTime \n" +
" \n" +
" \n" +
"";
String xmlStr = template.replace("toUser", toUserName)
.replace("fromUser", fromUserName)
.replace("createTime", createTime)
.replace("msgType", msgType)
.replace("content", content);
return xmlStr;
}
地址如下:https://mp.weixin.qq.com/debug/,可以查看返回的各种数据是否正确
微信公众平台开发书籍推荐
[1]http://www.cnblogs.com/txw1958/p/weixin-book-dev.html