后台代码

控制器

  1. package com.example.demo.controller;
  2. import com.example.demo.util.Sha1Util;
  3. import org.springframework.http.ResponseEntity;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RequestParam;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import java.util.Arrays;
  8. @RestController
  9. public class WechatController {
  10. /**
  11. * @return 微信请求接收
  12. */
  13. @GetMapping(value = "/weixin", produces = "text/plain;charset=UTF-8")
  14. public ResponseEntity weixin(@RequestParam(name = "signature") String signature,
  15. @RequestParam(name = "timestamp") String timestamp,
  16. @RequestParam(name = "nonce") String nonce,
  17. @RequestParam(name = "echostr") String echostr) {
  18. String auths[] = {token(自己填的 token), timestamp, nonce};
  19. Arrays.sort(auths);
  20. if (signature.equals(Sha1Util.getSha1(auths[0] + auths[1] + auths[2]))) {
  21. if (null != echostr) {
  22. return ResponseEntity.ok(this.auth(echostr));
  23. }
  24. }
  25. return ResponseEntity.ok().build();
  26. }
  27. /**
  28. * @param echostr
  29. * @return 认证
  30. */
  31. private String auth(String echostr) {
  32. return echostr;
  33. }
  34. @GetMapping(value = "/test")
  35. public ResponseEntity test() {
  36. return ResponseEntity.ok("测试成功!");
  37. }
  38. }

Sha1 加密

  1. package com.example.demo.util;
  2. import java.security.MessageDigest;
  3. public class Sha1Util {
  4. public static String getSha1(String str){
  5. if (null == str || 0 == str.length()){
  6. return null;
  7. }
  8. char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  9. 'a', 'b', 'c', 'd', 'e', 'f'};
  10. try {
  11. MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
  12. mdTemp.update(str.getBytes("UTF-8"));
  13. byte[] md = mdTemp.digest();
  14. int j = md.length;
  15. char[] buf = new char[j * 2];
  16. int k = 0;
  17. for (int i = 0; i < j; i++) {
  18. byte byte0 = md[i];
  19. buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
  20. buf[k++] = hexDigits[byte0 & 0xf];
  21. }
  22. return new String(buf);
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. return null;
  26. }
  27. }
  28. }

微信后台配置

{EM]BC]ZXS5(7UG]UG%ZRHM.png

后台的 token 就是控制器中自己配置的 token
url 就填 http://你的链接/weixin

提交就验证成功了