Open the service of intranet penetration (backend 8333, front end 8080):
Start the intranet penetration service:
Create CourseApiController to implement keyword query course information:
package com.lxl.ggkt.vod.api; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.lxl.ggkt.model.vod.Course; import com.lxl.ggkt.result.Result; import com.lxl.ggkt.vo.vod.CourseQueryVo; import com.lxl.ggkt.vo.vod.CourseVo; import com.lxl.ggkt.vod.service.CourseService; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax. management. Query; import java.util.List; import java.util.Map; @RestController @RequestMapping(value = "/api/vod/course") public class CourseApiController {<!-- --> @Autowired private CourseService courseService; //Query course information according to course id @ApiOperation("Query courses by ID") @GetMapping("inner/getById/{courseId}") public Course getById( @ApiParam(value = "Course ID", required = true) @PathVariable Long courseId){<!-- --> Course course = courseService.getById(courseId); return course; } //Query the course list according to the course classification (pagination) @ApiOperation("Query course list according to course classification") @GetMapping("{subjectParentId}/{page}/{limit}") public Result findPageCourse(@ApiParam(value = "Course Classification ID", required = true) @PathVariable Long subjectParentId, @ApiParam(name = "page", value = "current page number", required = true) @PathVariable Long page, @ApiParam(name = "limit", value = "Number of records per page", required = true) @PathVariable Long limit){<!-- --> //Encapsulation conditions CourseQueryVo courseQueryVo = new CourseQueryVo(); courseQueryVo.setSubjectParentId(subjectParentId); //Create page object Page<Course> pageParam = new Page<>(page, limit); Map<String,Object> map = courseService. findPage(pageParam,courseQueryVo); return Result.ok(map); } //Query course details according to course id @ApiOperation("Query course details according to course id") @GetMapping("getInfo/{courseId}") public Result getInfo(@PathVariable Long courseId){<!-- --> Map<String,Object> map = courseService.getInfoById(courseId); return Result.ok(map); } @ApiOperation("Query courses based on keywords") @GetMapping("inner/findByKeyword/{keyword}") public List<Course> findByKeyword( @ApiParam(value = "keyword",required = true) @PathVariable String keyword){<!-- --> QueryWrapper<Course> wrapper = new QueryWrapper<>(); wrapper.like("title",keyword); List<Course> list = courseService. list(wrapper); return list; } }
Official account message reception and related business module design:
MessageController:
package com.lxl.ggkt.wechat.controller; import com.alibaba.fastjson.JSONObject; import com.lxl.ggkt.result.Result; import com.lxl.ggkt.wechat.service.MessageService; import com.lxl.ggkt.wechat.utils.SHA1; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping("/api/wechat/message") public class MessageController {<!-- --> private static final String token = "ggkt"; @Autowired private MessageService messageService; @GetMapping("/pushPayMessage") public Result pushPayMessage() throws WxErrorException {<!-- --> messageService.pushPayMessage(1L); return Result.ok(null); } /** * Server validity verification * @param request * @return */ @GetMapping public String verifyToken(HttpServletRequest request) {<!-- --> String signature = request. getParameter("signature"); String timestamp = request. getParameter("timestamp"); String nonce = request. getParameter("nonce"); String echostr = request. getParameter("echostr"); //log.info("signature: {} nonce: {} echostr: {} timestamp: {}", signature, nonce, echostr, timestamp); if (this. checkSignature(signature, timestamp, nonce)) {<!-- --> // log. info("token ok"); return echostr; } return echostr; } private boolean checkSignature(String signature, String timestamp, String nonce) {<!-- --> String[] str = new String[]{<!-- -->token, timestamp, nonce}; //sort Arrays. sort(str); // splicing string StringBuffer buffer = new StringBuffer(); for (int i = 0; i < str. length; i ++ ) {<!-- --> buffer.append(str[i]); } //Perform sha1 encryption String temp = SHA1.encode(buffer.toString()); //Match with the signature provided by WeChat return signature. equals(temp); } /** * Receive messages sent by WeChat server * @param request * @return * @throws Exception */ @PostMapping public String receiveMessage(HttpServletRequest request) throws Exception {<!-- --> // WxMpXmlMessage wxMpXmlMessage = WxMpXmlMessage.fromXml(request.getInputStream()); // System.out.println(JSONObject.toJSONString(wxMpXmlMessage)); Map<String, String> param = this. parseXml(request); String message = messageService. receiveMessage(param); return message; } private Map<String, String> parseXml(HttpServletRequest request) throws Exception {<!-- --> Map<String, String> map = new HashMap<String, String>(); InputStream inputStream = request. getInputStream(); SAXReader reader = new SAXReader(); Document document = reader. read(inputStream); Element root = document. getRootElement(); List<Element> elementList = root. elements(); for (Element e : elementList) {<!-- --> map. put(e. getName(), e. getText()); } inputStream. close(); inputStream = null; return map; } }
MessageServiceImpl:
package com.lxl.ggkt.wechat.service.impl; import com.lxl.ggkt.client.course.CourseFeignClient; import com.lxl.ggkt.model.vod.Course; import com.lxl.ggkt.wechat.service.MessageService; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.template.WxMpTemplateData; import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import javax.servlet.http.HttpServletRequest; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Random; @Service public class MessageServiceImpl implements MessageService {<!-- --> @Autowired private CourseFeignClient courseFeignClient; @Autowired private WxMpService wxMpService; //receive message @Override public String receiveMessage(Map<String, String> param) {<!-- --> String content = ""; try {<!-- --> String msgType = param. get("MsgType"); switch(msgType){<!-- --> case "text" : content = this. search(param); break; case "event" : String event = param. get("Event"); String eventKey = param. get("EventKey"); if("subscribe".equals(event)) {<!-- -->//Follow the official account content = this. subscribe(param); } else if("unsubscribe".equals(event)) {<!-- -->//Unsubscribe the official account content = this. unsubscribe(param); } else if("CLICK".equals(event) & amp; & amp; "aboutUs".equals(eventKey)){<!-- --> content = this.aboutUs(param); } else {<!-- --> content = "success"; } break; default: content = "success"; } } catch (Exception e) {<!-- --> e.printStackTrace(); content = this.text(param, "Please re-enter the keyword, no relevant video courses are matched").toString(); } return content; } @Override public void pushPayMessage(long id) {<!-- --> String openid = "oYtdy6gjiie2TF8o74YJbeJItpCA"; WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder() .toUser(openid)//user openid to push .templateId("ivOxy9PfqDONOWOqOqjvppO-YYebxVbPLBog1e-4nEU")//template id .url("http://ggkt2.vipgz1.91tunnel.com/#/pay/" + id)//Click the URL to visit in the template message .build(); //3, if the official version sends a message, you need to configure your information here templateMessage.addData(new WxMpTemplateData("first", "Dear user: You have successfully paid for an order.", "#272727")); templateMessage.addData(new WxMpTemplateData("keyword1", "1314520", "#272727")); templateMessage.addData(new WxMpTemplateData("keyword2", "java basic course", "#272727")); templateMessage.addData(new WxMpTemplateData("keyword3", "2022-01-11", "#272727")); templateMessage.addData(new WxMpTemplateData("keyword4", "100", "#272727")); templateMessage.addData(new WxMpTemplateData("remark", "Thank you for purchasing the course, if you have any questions, please feel free to consult!", "#272727")); try {<!-- --> String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage); } catch (WxErrorException e) {<!-- --> throw new RuntimeException(e); } } /** * about Us * @param param * @return */ private String aboutUs(Map<String, String> param) {<!-- --> return this.text(param, "Silicon Valley Classroom now offers Java, HTML5 front-end + full-stack, big data, full-link UI/UE design, artificial intelligence, big data operation and maintenance + Python automation, Android + HTML5 hybrid development, etc. At the same time, through video sharing, Guli Academy online classroom, Dachang Academy live broadcast classroom and other methods, it has met the needs of programming enthusiasts across the country for diverse learning scenarios, and has sent a large number of IT technical talents to the industry.") .toString(); } /** * Handle concern events * @param param * @return */ private String subscribe(Map<String, String> param) {<!-- --> //Process business return this.text(param, "Thank you for your attention to "Silicon Valley Classroom", you can search for the video tutorials you want to watch according to keywords, such as: JAVA basics, Spring boot, big data, etc.").toString(); } /** * Handle the unfollow event * @param param * @return */ private String unsubscribe(Map<String, String> param) {<!-- --> //Process business return "success"; } /** * Handle keyword search event * Number of graphic messages; when a user sends six types of messages: text, picture, voice, video, graphic, and geographic location, the developer can only reply to 1 graphic message; in other scenarios, a maximum of 8 graphic messages can be replied * @param param * @return */ private String search(Map<String, String> param) {<!-- --> String fromusername = param. get("FromUserName"); String tousername = param. get("ToUserName"); String content = param. get("Content"); //The unit is seconds, not milliseconds Long createTime = new Date(). getTime() / 1000; StringBuffer text = new StringBuffer(); List<Course> courseList = courseFeignClient.findByKeyword(content); if(CollectionUtils. isEmpty(courseList)) {<!-- --> text = this.text(param, "Please re-enter the keyword, no relevant video courses are matched"); } else {<!-- --> //Only return one at a time Random random = new Random(); int num = random.nextInt(courseList.size()); Course course = courseList. get(num); StringBuffer articles = new StringBuffer(); articles.append("<item>"); articles.append("<Title><![CDATA[" + course.getTitle() + "]]></Title>"); articles.append("<Description><![CDATA[" + course.getTitle() + "]]></Description>"); articles.append("<PicUrl><![CDATA[" + course.getCover() + "]]></PicUrl>"); articles.append("<Url><![CDATA[http://glkt.atguigu.cn/#/liveInfo/" + course.getId() + "]]></Url>"); articles.append("</item>"); text.append("<xml>"); text.append("<ToUserName><![CDATA[" + fromusername + "]]></ToUserName>"); text.append("<FromUserName><![CDATA[" + tousername + "]]></FromUserName>"); text.append("<CreateTime><![CDATA[" + createTime + "]]></CreateTime>"); text.append("<MsgType><![CDATA[news]]></MsgType>"); text.append("<ArticleCount><![CDATA[1]]></ArticleCount>"); text.append("<Articles>"); text.append(articles); text.append("</Articles>"); text.append("</xml>"); } return text.toString(); } /** * reply text * @param param * @param content * @return */ private StringBuffer text(Map<String, String> param, String content) {<!-- --> String fromusername = param. get("FromUserName"); String tousername = param. get("ToUserName"); //The unit is seconds, not milliseconds Long createTime = new Date(). getTime() / 1000; StringBuffer text = new StringBuffer(); text.append("<xml>"); text.append("<ToUserName><![CDATA[" + fromusername + "]]></ToUserName>"); text.append("<FromUserName><![CDATA[" + tousername + "]]></FromUserName>"); text.append("<CreateTime><![CDATA[" + createTime + "]]></CreateTime>"); text.append("<MsgType><![CDATA[text]]></MsgType>"); text.append("<Content><![CDATA[" + content + "]]></Content>"); text.append("</xml>"); return text; } }
Test account application template message display:
WeChat authorized login:
Test account configuration web page authorization to obtain basic user information:
After completing the front end, introduce the WeChat toolkit:
<dependencies> <dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-mp</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> </dependency> </dependencies>
Configure the id and key of the WeChat public account at the same time
wechat.mpAppId: wxd4e0bcc0aa6b50d0 wechat.mpAppSecret: ad5712c888df46205b11fb77cddd0f0a wechat.userInfoUrl: http://ggktlxl.free.idcfengye.com/api/user/wechat/userInfo
See the previous chapter for the configuration of the tool class ConstantPropertiesUtil and WeChatMpConfig.
Use token to realize user information transfer:
Import jwt dependencies:
<dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> </dependency> </dependencies>
Add JWT tool class:
package com.lxl.ggkt.utils; import io.jsonwebtoken.*; import org.springframework.util.StringUtils; import java.util.Date; public class JwtHelper {<!-- --> //token string valid time private static long token Expiration = 24*60*60*1000; //encrypted encoding key private static String tokenSignKey = "123456"; //Generate token string based on userid and username public static String createToken(Long userId, String userName) {<!-- --> String token = Jwts. builder() //Set token classification .setSubject("GGKT-USER") //token string valid duration .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) //private part (user information) .claim("userId", userId) .claim("userName", userName) //According to the secret key, use the encryption encoding method to encrypt and compress the string .signWith(SignatureAlgorithm.HS512, tokenSignKey) .compressWith(CompressionCodecs.GZIP) .compact(); return token; } //Get userid from token string public static Long getUserId(String token) {<!-- --> if(StringUtils. isEmpty(token)) return null; Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token); Claims claims = claimsJws. getBody(); Integer userId = (Integer)claims. get("userId"); return userId. longValue(); } //Get getUserName from the token string public static String getUserName(String token) {<!-- --> if(StringUtils.isEmpty(token)) return ""; Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token); Claims claims = claimsJws. getBody(); return (String) claims. get("userName"); } public static void main(String[] args) {<!-- --> String token = JwtHelper.createToken(1L, "lucy"); System.out.println(token); System.out.println(JwtHelper.getUserId(token)); System.out.println(JwtHelper.getUserName(token)); } }