当前位置:   article > 正文

SpringBoot对接微信公众号,持续更新

SpringBoot对接微信公众号,持续更新

作者不是大牛,有问题请指出

一、创建SpringBoot项目,配置内网穿透

1. 创建一个SpringBoot项目,此步骤省略

2. 在pom中引用班纳睿工具包

        班纳睿

  1. <!-- 公众号 -->
  2. <dependency>
  3. <groupId>com.github.binarywang</groupId>
  4. <artifactId>wx-java-mp-spring-boot-starter</artifactId>
  5. <version>4.1.0</version>
  6. </dependency>

3. 内网穿透配置

我这边用到的是 ngrok

在ngrok中选择免费的项目,然后配置相对应的域名映射到本地的相应端口

配置完后,在隧道管理菜单可以看到隧道 id

下载ngrok的客户端,我这里下载的是 windows版本,下载解压后,打开 windows_amd64文件夹,点击Sunny-Ngrok启动工具,然后输入隧道id敲回车。界面出现oline表示穿透成功。

 

二、 在微信公众平台申请测试公众号,对接SpringBoot项目

1. 在微信公众平台申请开发测试公众号

        申请测试号后,可以得到appID,appsecret

2. 配置SpringBoot中对应的公众号信息

      在SpringBoot项目的application.yml中配置公众号相应的信息,将appId和secret 配置成公众号界面分配的信息,token自己在公众号界面填写一个,然后对应的配置在yml文件中。

   

 在SpringBoot项目中创建config文件夹

 在 config文件夹下创建 WechatMpProperties类,获取yml文件中的配置信息

  1. @Configuration
  2. @ConfigurationProperties(prefix = "wechat.mp")
  3. @Data
  4. public class WechatMpProperties {
  5. /**
  6. * 设置微信公众号的appid
  7. */
  8. private String appId;
  9. /**
  10. * 设置微信公众号的app secret
  11. */
  12. private String secret;
  13. /**
  14. * 设置微信公众号的token
  15. */
  16. private String token;
  17. /**
  18. * 设置微信公众号的EncodingAESKey
  19. */
  20. private String aesKey;
  21. }

 在 config文件下创建 WxMpConfiguration类,将 WechatMpProperties的配置信息配置进去

  1. @AllArgsConstructor
  2. @Configuration
  3. public class WxMpConfiguration {
  4. @Autowired
  5. private WechatMpProperties properties;
  6. @Bean
  7. public WxMpService wxMpService() {
  8. WxMpService service = new WxMpServiceImpl();
  9. WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
  10. configStorage.setAppId(properties.getAppId());
  11. configStorage.setSecret(properties.getSecret());
  12. configStorage.setToken(properties.getToken());
  13. configStorage.setAesKey(properties.getAesKey());
  14. Map<String, WxMpConfigStorage> storageMap = new HashMap<>();
  15. storageMap.put(properties.getAppId(), configStorage);
  16. service.setMultiConfigStorages(storageMap);
  17. return service;
  18. }
  19. }

 在 SpringBoot项目中创建 controller文件夹,在 controller文件夹下创建 WxPortalController类

  1. @Slf4j
  2. @AllArgsConstructor
  3. @RestController
  4. @RequestMapping("/wx/portal/{appid}")
  5. public class WxPortalController {
  6. private final WxMpService wxService;
  7. private final WxMpMessageRouter messageRouter;
  8. @GetMapping(produces = "text/plain;charset=utf-8")
  9. public String authGet(@PathVariable String appid,
  10. @RequestParam(name = "signature", required = false) String signature,
  11. @RequestParam(name = "timestamp", required = false) String timestamp,
  12. @RequestParam(name = "nonce", required = false) String nonce,
  13. @RequestParam(name = "echostr", required = false) String echostr) {
  14. log.info("\n接收到来自微信服务器的认证消息:[{}, {}, {}, {}]", signature,
  15. timestamp, nonce, echostr);
  16. if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
  17. throw new IllegalArgumentException("请求参数非法,请核实!");
  18. }
  19. if (!this.wxService.switchover(appid)) {
  20. throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
  21. }
  22. if (wxService.checkSignature(timestamp, nonce, signature)) {
  23. return echostr;
  24. }
  25. return "非法请求";
  26. }
  27. @PostMapping(produces = "application/xml; charset=UTF-8")
  28. public String post(@PathVariable String appid,
  29. @RequestBody String requestBody,
  30. @RequestParam("signature") String signature,
  31. @RequestParam("timestamp") String timestamp,
  32. @RequestParam("nonce") String nonce,
  33. @RequestParam("openid") String openid,
  34. @RequestParam(name = "encrypt_type", required = false) String encType,
  35. @RequestParam(name = "msg_signature", required = false) String msgSignature) {
  36. log.info("\n接收微信请求:[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
  37. + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
  38. openid, signature, encType, msgSignature, timestamp, nonce, requestBody);
  39. if (!this.wxService.switchover(appid)) {
  40. throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
  41. }
  42. if (!wxService.checkSignature(timestamp, nonce, signature)) {
  43. throw new IllegalArgumentException("非法请求,可能属于伪造的请求!");
  44. }
  45. String out = null;
  46. if (encType == null) {
  47. // 明文传输的消息
  48. WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
  49. WxMpXmlOutMessage outMessage = this.route(inMessage);
  50. if (outMessage == null) {
  51. return "";
  52. }
  53. out = outMessage.toXml();
  54. } else if ("aes".equalsIgnoreCase(encType)) {
  55. // aes加密的消息
  56. WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(),
  57. timestamp, nonce, msgSignature);
  58. log.debug("\n消息解密后内容为:\n{} ", inMessage.toString());
  59. WxMpXmlOutMessage outMessage = this.route(inMessage);
  60. if (outMessage == null) {
  61. return "";
  62. }
  63. out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage());
  64. }
  65. log.debug("\n组装回复信息:{}", out);
  66. return out;
  67. }
  68. private WxMpXmlOutMessage route(WxMpXmlMessage message) {
  69. try {
  70. return this.messageRouter.route(message);
  71. } catch (Exception e) {
  72. log.error("路由消息时出现异常!", e);
  73. }
  74. return null;
  75. }
  76. }

3. 在微信公众平台调试

        在接口配置信息,url 填写 域名+ /wx/portal/{appid}

        配置完后,在下发点击发送按钮。配置成功,会弹出配置成功窗口。

三、 开发关注公众号和取关公众号时相应的业务

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/274146
推荐阅读
相关标签
  

闽ICP备14008679号