微信公眾號開發總結(一) --程序入口


  最近准備利用業務時間寫一個公眾號練練手,查看了微信官方文檔后,發現文檔內容寫的非常詳細,前期粗略的看了下開發指南,比以前接入的第三方接口簡單多了,於是磨刀霍霍按照開發指南一步步配置服務器、申請測試賬號並在線調試,輕輕松松的就接入成功。

  下面就是我接入微信、接收微信通知的代碼,寫的比較粗糙,望不吝賜教.

  引入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("\n接收到來自微信服務器的認證消息:[{}, {}, {}, {}]", 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("\n接收微信請求:[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
            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("\n消息解密后內容為:\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage());
        }

        log.info("\n組裝回復信息:{}", 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。

 

   以上就是接入公眾號的前期准備,服務器配置這些官方文檔已經說的很清楚了,所以本文就沒有介紹。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM