先说坑,我觉得真坑
要想做公众号开发,但是个人账号是没有公众平台的全部接口权限的,所以需要申请测试账号。URL填写需要一个域名,所以选择用内网穿透,我这里使用的就是ngrok,直接去官网下就可以了。我这里主要遇到的问题就是,配置ngrok的时候,设置了校验的密码。
http验证用户名: http验证密码:千万千万不要配,你配了微信服务器发你本地请求就发送不到,我今天被这个问题困扰了一下午,最后我把自己的地址发给我朋友去帮我测试的时候,才意识到的!
搭建工程
一、创建个springboot工程
写个控制器
import com.example.wx.utils.SHA1;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
@RestController
@RequestMapping("/wx")
public class WxController
{
private static final Log log= LogFactory.getLog(WxController.class);
public static final String TOKEN = "zhbcm";
@GetMapping("/init")
public void init(HttpServletRequest req, HttpServletResponse resp) throws NoSuchAlgorithmException, IOException
{
String signature = req.getParameter("signature");
String timestamp = req.getParameter("timestamp");
String nonce = req.getParameter("nonce");
String echostr = req.getParameter("echostr");
String[] arr = {
WxController.TOKEN, timestamp, nonce};
Arrays.sort(arr);//排序
StringBuilder builder = new StringBuilder();
for (String s : arr)
{
builder.append(s);//合并
}
String sha1 = SHA1.sha1(builder.toString());//加密
if (sha1.equals(signature))
{
PrintWriter pw = resp.getWriter();
pw.println(echostr);
pw.flush();
pw.close();
log.info("接入成功!");
} else
{
log.error("接入失败!");
}
}
}
加密包
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA1
{
/**
* sha1加密
*
* @param data
* @return
* @throws NoSuchAlgorithmException
*/
public static String sha1(String str) throws NoSuchAlgorithmException
{
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)
{
return null;
}
}
}
接口测试
url里输入内网穿透的域名加上你的路径
输入你自定义的token
点击确定,然后看控制台打印!
做个宣传
技术交流群,免费提供jerbrant系列 idea webstorm等工具自动化开启包
技术交流分享②群:272712006
技术交流分享③群:1093476453
bilibili学习教程地址:https://space.bilibili.com/439411741/video
简书地址:https://www.jianshu.com/p/133af2e4fe3f