zoukankan      html  css  js  c++  java
  • 微信公众号开发总结(一) --程序入口

      最近准备利用业务时间写一个公众号练练手,查看了微信官方文档后,发现文档内容写的非常详细,前期粗略的看了下开发指南,比以前接入的第三方接口简单多了,于是磨刀霍霍按照开发指南一步步配置服务器、申请测试账号并在线调试,轻轻松松的就接入成功。

      下面就是我接入微信、接收微信通知的代码,写的比较粗糙,望不吝赐教.

      引入pom依赖

    <!-- https://mvnrepository.com/artifact/com.github.binarywang/weixin-java-mp -->
            <dependency>
                <groupId>com.github.binarywang</groupId>
                <artifactId>weixin-java-mp</artifactId>
                <version>3.6.0</version>
            </dependency>

      定义 wxMpService Bean

       @Bean
        public WxMpService wxMpService() {
    
            WxMpService service = new WxMpServiceImpl();
    
            WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
            //下面的四个参数替换成你自己的就可以了
            configStorage.setAppId(appid);
            configStorage.setSecret(secret);
            configStorage.setToken(token);
            configStorage.setAesKey(aesKey);
    
            Map<String, WxMpConfigStorage> config = new HashMap<> ();
    config.put(appid,configStorage); service.setMultiConfigges(config);
    return service; }

      

    @Slf4j
    @AllArgsConstructor
    @RestController
    @RequestMapping("/wx/portal/{appid}")
    public class WxPortalController {
        @Autowired
        private WxMpService wxService;
        @Autowired
        private WxMpMessageRouter messageRouter;
    
        /**  验证消息 https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html **/
        @GetMapping(produces = "text/plain;charset=utf-8")
        public String authGet(@PathVariable String appid,
                              @RequestParam(name = "signature", required = false) String signature,
                              @RequestParam(name = "timestamp", required = false) String timestamp,
                              @RequestParam(name = "nonce", required = false) String nonce,
                              @RequestParam(name = "echostr", required = false) String echostr) {
            log.info("
    接收到来自微信服务器的认证消息:[{}, {}, {}, {}]", signature,
                timestamp, nonce, echostr);
            if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
                throw new IllegalArgumentException("请求参数非法,请核实!");
            }
    
            if (!this.wxService.switchover(appid)) {
                throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
            }
    
            if (wxService.checkSignature(timestamp, nonce, signature)) {
                return echostr;
            }
            return "非法请求";
        }
    
        /** 事件推送 https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_event_pushes.html **/ 
        @PostMapping(produces = "application/xml; charset=UTF-8")
        public String post(@PathVariable String appid,
                           @RequestBody String requestBody,
                           @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("openid") String openid,
                           @RequestParam(name = "encrypt_type", required = false) String encType,
                           @RequestParam(name = "msg_signature", required = false) String msgSignature) {
            log.info("
    接收微信请求:[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                    + " timestamp=[{}], nonce=[{}], requestBody=[
    {}
    ] ",
                openid, signature, encType, msgSignature, timestamp, nonce, requestBody);
    
            if (!this.wxService.switchover(appid)) {
                throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
            }
    
            if (!wxService.checkSignature(timestamp, nonce, signature)) {
                throw new IllegalArgumentException("非法请求,可能属于伪造的请求!");
            }
    
            String out = null;
            if (encType == null) {
                // 明文传输的消息
                WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
                WxMpXmlOutMessage outMessage = this.route(inMessage);
                if (outMessage == null) {
                    return "";
                }
    
                out = outMessage.toXml();
            } else if ("aes".equalsIgnoreCase(encType)) {
                // aes加密的消息
                WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
                log.info("
    消息解密后内容为:
    {} ", inMessage.toString());
                WxMpXmlOutMessage outMessage = this.route(inMessage);
                if (outMessage == null) {
                    return "";
                }
    
                out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage());
            }
    
            log.info("
    组装回复信息:{}", out);
            return out;
        }
    
        private WxMpXmlOutMessage route(WxMpXmlMessage message) {
            try {
                return this.messageRouter.route(message);
            } catch (Exception e) {
                log.error("路由消息时出现异常!", e);
            }
            return null;
        }
    
    }

       消息验证成功后,我们就可以获取AccessToken,公众号中接口几乎都会用到这个token,但是这个token并非保持不变的,有效期2H。

       以上就是接入公众号的前期准备,服务器配置这些官方文档已经说的很清楚了,所以本文就没有介绍。

  • 相关阅读:
    dubbo注册服务IP解析异常及IP解析源码分析
    Linux下安装并破解StarUML
    Mysql中int(1)的误解及说明
    grep参数说明及常用用法
    ubuntu中使用nginx把本地80端口转到其他端口
    IDEA下安装/配置Jrebel
    Eclipse下安装/配置Jrebel6.X
    shell脚本问题read: Illegal option -t
    docker pull 提示错误的username or password
    linux 安装 rpm 的jdk
  • 原文地址:https://www.cnblogs.com/JackpotHan/p/12156628.html
Copyright © 2011-2022 走看看