NutzCN Logo
问答 wxHandler中如何管理access_token的
发布于 11天前 作者 qq_d6d46f6d 49 次浏览 复制 上一个帖子 下一个帖子
标签:

我在里面没看到刷新access_token的操作。

package com.timemans.services.wx;


import com.timemans.domains.cms.Cms_article;
import com.timemans.domains.wx.*;
import com.timemans.services.cms.CmsArticleService;
import com.vdurmont.emoji.EmojiParser;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.weixin.bean.WxArticle;
import org.nutz.weixin.bean.WxInMsg;
import org.nutz.weixin.bean.WxOutMsg;
import org.nutz.weixin.impl.AbstractWxHandler;
import org.nutz.weixin.repo.com.qq.weixin.mp.aes.AesException;
import org.nutz.weixin.repo.com.qq.weixin.mp.aes.WXBizMsgCrypt;
import org.nutz.weixin.spi.WxApi2;
import org.nutz.weixin.spi.WxResp;
import org.nutz.weixin.util.Wxs;

import java.util.ArrayList;
import java.util.List;

/**
 *  on 2016/7/3.
 */
@IocBean(name = "handler")
public class WxHandler extends AbstractWxHandler {
    private final static Log log = Logs.get();
    protected String token;
    protected String aeskey;
    protected WXBizMsgCrypt msgCrypt;
    protected String appid;
    protected WxApi2 api;

    @Inject
    private WxConfigService wxConfigService1;
    @Inject
    private WxUserService wxUserService;
    @Inject
    private WxReplyService wxReplyService;
    @Inject
    private WxReplyNewsService wxReplyNewsService;
    @Inject
    private WxReplyTxtService wxReplyTxtService;
    @Inject
    private WxMsgService wxMsgService;
    @Inject
    private CmsArticleService articleService;




    public boolean check(String signature, String timestamp, String nonce, String key) {
        if(!Strings.isEmpty(key)) {
            Wx_config appInfo = wxConfigService1.fetch(Cnd.where("id", "=", key));
            System.out.println(Json.toJson(appInfo));
            if (appInfo != null) {
                this.token = appInfo.getToken();
                this.aeskey = appInfo.getEncodingAESKey();
                this.appid = appInfo.getAppid();
                return Wxs.check(appInfo.getToken(), signature, timestamp, nonce);
            }
        }
        return false;
    }

    public WXBizMsgCrypt getMsgCrypt() {
        if (this.msgCrypt == null) {
            try {
                // 若抛异常Illegal key size ,需更新JDK的加密库为不限制长度
                this.msgCrypt = new WXBizMsgCrypt(this.token, this.aeskey, this.appid);
            } catch (AesException var2) {
                throw new RuntimeException(var2);
            }
        }

        return this.msgCrypt;
    }

    // 用户发送的是文本的时候调用这个方法
    public WxOutMsg text(WxInMsg msg) {
        Wx_reply reply = wxReplyService.fetch(Cnd.where("wxid", "=", msg.getExtkey()).and("type", "=", "keyword").and("keyword", "=", msg.getContent()));
        if (reply != null) {
            if ("txt".equals(reply.getMsgType())) {
                String txtId = reply.getContent();
                Wx_reply_txt txt = wxReplyTxtService.fetch(txtId);
                return Wxs.respText(null, txt == null ? "" : txt.getContent());
            } else if ("news".equals(reply.getMsgType())) {
                String[] newsIds = Strings.sBlank(reply.getContent()).split(",");
                List<WxArticle> list = new ArrayList<>();
                List<Wx_reply_news> newsList = wxReplyNewsService.query(Cnd.where("id", "in", newsIds).asc("location"));
                for (Wx_reply_news news : newsList) {
                    WxArticle wxArticle = new WxArticle();
                    wxArticle.setDescription(news.getDescription());
                    wxArticle.setPicUrl(news.getPicUrl());
                    wxArticle.setTitle(news.getTitle());
                    wxArticle.setUrl(news.getUrl());
                    list.add(wxArticle);
                }
                return Wxs.respNews(null, list);
            } else if ("article".equals(reply.getMsgType())) {
                String[] newsIds = Strings.sBlank(reply.getContent()).split(",");
                List<WxArticle> list = new ArrayList<>();
                List<Cms_article> newsList = articleService.query(Cnd.where("id", "in", newsIds).asc("location"));
                for (Cms_article article : newsList) {
                    WxArticle wxArticle = new WxArticle();
                    wxArticle.setDescription(article.getInfo());
                    wxArticle.setPicUrl(article.getPicurl());
                    wxArticle.setTitle(article.getTitle());
                    wxArticle.setUrl(article.getUrl());
                    list.add(wxArticle);
                }
                return Wxs.respNews(null, list);
            }
        }
        Wx_user usr = wxUserService.fetch(Cnd.where("openid", "=", msg.getFromUserName()));
        Wx_msg wxMsg = new Wx_msg();
        wxMsg.setOpenid(msg.getFromUserName());
        wxMsg.setContent(EmojiParser.parseToAliases(msg.getContent(), EmojiParser.FitzpatrickAction.REMOVE));
        wxMsg.setWxid(msg.getExtkey());
        wxMsg.setType("txt");
        wxMsg.setNickname(usr == null ? "匿名" : usr.getNickname());
//        wxMsg.setDelFlag(false);
        wxMsgService.insert(wxMsg);
        return Wxs.respText(null, "您的留言已收到!");
    }

    public WxOutMsg eventClick(WxInMsg msg) {
        String eventKey = msg.getEventKey();
        log.debug("eventKey: " + eventKey);
        Wx_reply reply=wxReplyService.fetch(Cnd.where("type","=","keyword").and("wxid","=",msg.getExtkey()).and("keyword","=",eventKey));
        if (reply != null) {
            if ("txt".equals(reply.getMsgType())) {
                String txtId = reply.getContent();
                Wx_reply_txt txt = wxReplyTxtService.fetch(txtId);
                return Wxs.respText(null, txt == null ? "" : txt.getContent());
            } else if ("news".equals(reply.getMsgType())) {
                String[] newsIds = Strings.sBlank(reply.getContent()).split(",");
                List<WxArticle> list = new ArrayList<>();
                List<Wx_reply_news> newsList = wxReplyNewsService.query(Cnd.where("id", "in", newsIds).asc("location"));
                for (Wx_reply_news news : newsList) {
                    WxArticle wxArticle = new WxArticle();
                    wxArticle.setDescription(news.getDescription());
                    wxArticle.setPicUrl(news.getPicUrl());
                    wxArticle.setTitle(news.getTitle());
                    wxArticle.setUrl(news.getUrl());
                    list.add(wxArticle);
                }
                return Wxs.respNews(null, list);
            } else if ("article".equals(reply.getMsgType())) {
                String[] newsIds = Strings.sBlank(reply.getContent()).split(",");
                List<WxArticle> list = new ArrayList<>();
                List<Cms_article> newsList = articleService.query(Cnd.where("id", "in", newsIds).asc("location"));
                for (Cms_article article : newsList) {
                    WxArticle wxArticle = new WxArticle();
                    wxArticle.setDescription(article.getInfo());
                    wxArticle.setPicUrl(article.getPicurl());
                    wxArticle.setTitle(article.getTitle());
                    wxArticle.setUrl(article.getUrl());
                    list.add(wxArticle);
                }
                return Wxs.respNews(null, list);
            }
        }
        return defaultMsg(msg);
    }

    @Override
    public WxOutMsg eventSubscribe(WxInMsg msg) {
        if (api == null)
            api = wxConfigService1.getWxApi2(msg.getExtkey());
        Wx_user usr = wxUserService.fetch(Cnd.where("openid", "=", msg.getFromUserName()));
        WxResp resp = api.user_info(msg.getFromUserName(), "zh_CN");
        System.out.println("------subscribeMsg:" + msg);
        System.out.println("------usr:" + Json.toJson(usr));
        System.out.println("------resp:" + resp);
        if (usr == null) {
            usr = Json.fromJson(Wx_user.class, Json.toJson(resp.user()));
            usr.setNickname(EmojiParser.parseToAliases(usr.getNickname(), EmojiParser.FitzpatrickAction.REMOVE));
            usr.setSubscribeAt((int) (resp.user().getSubscribe_time()));
            usr.setWxid(msg.getExtkey());
            String wxUserId = wxUserService.insert(usr).getId();
            System.out.println("------resp:" + wxUserId);
        } else {
            String id = usr.getId();
            usr = Json.fromJson(Wx_user.class, Json.toJson(resp.user()));
            usr.setNickname(EmojiParser.parseToAliases(usr.getNickname(), EmojiParser.FitzpatrickAction.REMOVE));
//            usr.setOpAt((int) (System.currentTimeMillis() / 1000));
            usr.setWxid(msg.getExtkey());
            usr.setId(id);
            System.out.println("------resp:" + id);
            wxUserService.updateIgnoreNull(usr);
        }
        Wx_reply reply = wxReplyService.fetch(Cnd.where("wxid", "=", msg.getExtkey()).and("type", "=", "follow"));
        if (reply != null) {
            if ("txt".equals(reply.getMsgType())) {
                String txtId = reply.getContent();
                Wx_reply_txt txt = wxReplyTxtService.fetch(txtId);
                return Wxs.respText(null, txt == null ? "" : txt.getContent());
            } else if ("news".equals(reply.getMsgType())) {
                String[] newsIds = Strings.sBlank(reply.getContent()).split(",");
                List<WxArticle> list = new ArrayList<>();
                List<Wx_reply_news> newsList = wxReplyNewsService.query(Cnd.where("id", "in", newsIds).asc("location"));
                for (Wx_reply_news news : newsList) {
                    WxArticle wxArticle = new WxArticle();
                    wxArticle.setDescription(news.getDescription());
                    wxArticle.setPicUrl(news.getPicUrl());
                    wxArticle.setTitle(news.getTitle());
                    wxArticle.setUrl(news.getUrl());
                    list.add(wxArticle);
                }
                return Wxs.respNews(null, list);
            } else if ("article".equals(reply.getMsgType())) {
                String[] newsIds = Strings.sBlank(reply.getContent()).split(",");
                List<WxArticle> list = new ArrayList<>();
                List<Cms_article> newsList = articleService.query(Cnd.where("id", "in", newsIds).asc("location"));
                for (Cms_article article : newsList) {
                    WxArticle wxArticle = new WxArticle();
                    wxArticle.setDescription(article.getInfo());
                    wxArticle.setPicUrl(article.getPicurl());
                    wxArticle.setTitle(article.getTitle());
                    wxArticle.setUrl(article.getUrl());
                    list.add(wxArticle);
                }
                return Wxs.respNews(null, list);
            }
        }
        return Wxs.respText(null, "谢谢您的关注!");
    }

    @Override
    public WxOutMsg eventUnsubscribe(WxInMsg msg) {
        Wx_user usr = wxUserService.fetch(Cnd.where("openid", "=", msg.getFromUserName()));
        if (usr != null) {
            wxUserService.update(Chain.make("subscribe", false).add("opAt", (int) (System.currentTimeMillis() / 1000)), Cnd.where("openid", "=", msg.getFromUserName()));
        }
        return super.eventUnsubscribe(msg);
    }

    public WxOutMsg eventView(WxInMsg msg) {
        return super.eventView(msg);
    }



    @Override
    public WxOutMsg defaultMsg(WxInMsg msg) {
        return Wxs.respText("这是缺省回复哦.你发送的类型是:" + msg.getMsgType());
    }
}

module方法

 @At("/wx") // 拼起来的全路径就是 /weixin/msgin
    public View msgin(HttpServletRequest req) throws IOException {
        try {

            View view = Wxs.handle(handler, req, "1");
            return view;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
4 回复

WxApi2已经带了access token管理

那就是说, protected WxApi2 api;

    api = wxConfigService1.getWxApi2(msg.getExtkey());

生成实例之后,这里面会自动触发access_token的刷新吗?

自行看看WxApi2Impl的代码

通过日志已经确认、是能够刷新的。谢谢

添加回复
请先登陆
回到顶部