WechatController.java 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package com.ruoyi.web.controller.wechat;
  2. import com.ruoyi.common.core.controller.BaseController;
  3. import com.ruoyi.common.core.domain.AjaxResult;
  4. import com.ruoyi.common.core.domain.model.LoginBody;
  5. import com.ruoyi.common.utils.wechat.MessageUtil;
  6. import com.ruoyi.common.utils.wechat.xml.XMLUtil;
  7. import com.ruoyi.framework.web.service.WechatService;
  8. import com.ruoyi.system.wechatUtils.UserQueue;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.web.bind.annotation.*;
  11. import org.springframework.web.bind.annotation.RequestBody;
  12. import javax.servlet.http.HttpServletRequest;
  13. import java.io.IOException;
  14. import java.util.Map;
  15. /**
  16. * <p>
  17. * 与微信产生交换的控制器
  18. * </p>
  19. *
  20. * @author ruoyi
  21. * @date 2020-12-11
  22. */
  23. @RestController
  24. @RequestMapping("/wechat")
  25. public class WechatController extends BaseController {
  26. @Autowired
  27. private WechatService wechatService;
  28. /**
  29. * 公众号与微信服务器进行认证的API接口
  30. *
  31. * @param signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
  32. * @param timestamp 时间戳
  33. * @param nonce 随机数
  34. * @param echostr 随机字符串
  35. * @return 结果
  36. */
  37. @GetMapping(value = "/wechat")
  38. public Object check(String signature,
  39. String timestamp,
  40. String nonce,
  41. String echostr) {
  42. return echostr;
  43. }
  44. /**
  45. * 微信授权信息时返回token
  46. *
  47. * @param loginBody code
  48. * @return 结果
  49. */
  50. @PostMapping(value = "/programLogin")
  51. public AjaxResult weChatProgramLogin(@RequestBody LoginBody loginBody) {
  52. // 生成令牌
  53. AjaxResult result = wechatService.login(loginBody);
  54. System.out.println("生成的令牌:" + result.get("data"));
  55. return result;
  56. }
  57. /**
  58. * 公众号接收请求
  59. *
  60. * @param request 请求
  61. * @return 接口
  62. */
  63. @PostMapping(value = "/wechat", produces = {"application/xml;charset=utf-8"})
  64. public Object toRequest(HttpServletRequest request) throws IOException {
  65. Map<String, String> map = XMLUtil.getMap(request.getInputStream());
  66. String msgType = map.get("MsgType");
  67. String toUser = map.get("ToUserName");
  68. String fromUser = map.get("FromUserName");
  69. String createTime = map.get("CreateTime");
  70. String reply = "";
  71. if ("event".equals(msgType)) {
  72. String event = map.get("Event");
  73. if ("subscribe".equals(event)) {
  74. reply = "欢迎关注";
  75. UserQueue.ATTENTIONQUEUE.push(fromUser);
  76. } else if ("unsubscribe".equals(event)) {
  77. UserQueue.CHECKOFFQUEUE.push(fromUser);
  78. }
  79. }
  80. return MessageUtil.setMessage(fromUser, toUser, 45860, "text", reply);
  81. }
  82. }