springboot开发微信环境搭建
需要用到IntelliJ IDEA、微信公号测试平台、springboot、内网穿透(本地开发比较方便,这里我用的是小米球内网穿透)
请自行建立springboot项目
首先我们需要登录到微信测试开发平台,接口配置信息如下图:
我们在配置的时候需要建立springboot项目,将项目运行起来才可以配置成功,我们先去建立controller类,类里面的请求方法:
@Controller
public class WechatController {
@GetMapping("/wx")
@ResponseBody
public String login(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
String signature = httpServletRequest.getParameter("signature");
String timestamp = httpServletRequest.getParameter("timestamp");
String nonce = httpServletRequest.getParameter("nonce");
String echostr = httpServletRequest.getParameter("echostr");
if (CheckUntil.checkSignatures(signature, timestamp, nonce)) {
return echostr;
}
return null;
}
}
建立微信工具类和SHA1加密类:
public class CheckUntil {
private static final String token = "这里写的你的token";
public static boolean checkSignatures(String signature, String timestamp, String nonce) {
String[] strings = new String[]{nonce, token, timestamp};
Arrays.sort(strings);
StringBuffer stringBuffer = new StringBuffer();
for (String string : strings) {
stringBuffer.append(string);
}
if (SHA1.encode(stringBuffer.toString()).equals(signature)) {
return true;
}
return false;
}
}
public final class SHA1 {
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* Takes the raw bytes from the digest and formats them correct.
*
* @param bytes the raw bytes from the digest.
* @return the formatted bytes.
*/
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
// 把密文转换成十六进制的字符串形式
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
public static String encode(String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
这时候运行项目之后,我们就可以继续配置微信接口,。
下一节
希望能交流更多技术,关注小白的微信公众号吧。