com.jfinal.weixin.sdk.api.ApiResult Java Examples

The following examples show how to use com.jfinal.weixin.sdk.api.ApiResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JbootWechatController.java    From jboot with Apache License 2.0 6 votes vote down vote up
private void doRedirect(String gotoUrl, String wechatOpenId, String accessToken) {

        /**
         * 由于 wechatOpenId 或者 accessToken 是可能从session读取的,
         * 从而导致失效等问题
         */
        ApiResult apiResult = WechatApis.getUserInfo(accessToken, wechatOpenId);

        if (!apiResult.isSucceed()) {
            redirect(gotoUrl);
            return;
        }

        setSessionAttr(SESSION_WECHAT_USER_JSON, apiResult.getJson());
        redirect(gotoUrl);
    }
 
Example #2
Source File: WechatAuthorizationController.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static ApiResult getOpenId(String appId, String appSecret, String code) {

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" + "?appid={appid}"
                + "&secret={secret}" + "&code={code}" + "&grant_type=authorization_code";

        String getOpenIdUrl = url.replace("{appid}", appId)
                .replace("{secret}", appSecret)
                .replace("{code}", code);

        String jsonResult = null;
        try {
            jsonResult = HttpUtils.get(getOpenIdUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (jsonResult == null) {
            return null;
        }

        return new ApiResult(jsonResult);
    }
 
Example #3
Source File: _WechatArticleImport.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void doImport() {

        ApiResult apiResult = MediaApi.getMaterialCount();
        if (!apiResult.isSucceed()) {
            renderJson(Ret.fail().set("message", "无法获取公众号文章信息,请查看公众号配置是否正确。"));
            return;
        }

        int articleCount = apiResult.getInt("news_count");
        doSyncArticles(articleCount);

        renderJson(Ret.ok().set("message", "后台正在为您同步 " + articleCount + " 篇文章及其附件,请稍后查看。"));
    }
 
Example #4
Source File: _WechatController.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 微信菜单同步
 */
public void doMenuSync() {
    List<WechatMenu> wechatMenus = wechatMenuService.findAll();
    SortKit.toTree(wechatMenus);

    if (wechatMenus == null || wechatMenus.isEmpty()) {
        renderJson(Ret.fail().set("message", "微信菜单为空"));
        return;
    }

    JSONArray button = new JSONArray();
    for (WechatMenu wechatMenu : wechatMenus) {
        if (wechatMenu.hasChild()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", wechatMenu.getText());
            List<WechatMenu> childMenus = wechatMenu.getChilds();
            JSONArray sub_buttons = new JSONArray();
            for (WechatMenu child : childMenus) {
                createJsonObjectButton(sub_buttons, child);
            }
            jsonObject.put("sub_button", sub_buttons);
            button.add(jsonObject);
        } else {
            createJsonObjectButton(button, wechatMenu);
        }
    }

    JSONObject wechatMenuJson = new JSONObject();
    wechatMenuJson.put("button", button);
    String jsonString = wechatMenuJson.toJSONString();

    ApiResult result = WechatApis.createMenu(jsonString);
    if (result.isSucceed()) {
        renderJson(Ret.ok().set("message", "微信菜单同步成功"));
    } else {
        renderJson(Ret.fail().set("message", "错误码:" + result.getErrorCode() + "," + result.getErrorMsg()));
    }

}
 
Example #5
Source File: WechatMiniProgramApiController.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 1、小程序端调用 wx.login() 之后,会得到code ,
 * 详情:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
 * <p>
 * 2、小程序端得到code之后,需调用此接口那code来换session_key,同时服务器存储session_key
 * 3、为什么要存储session_key呢?目的是为了获取用户信息
 * 4、小程序调用 wx.login() 之后,接下来会调用 wx.getUserInfo() ,
 * 此时要注意:wx.getUserInfo()得到的信息是加密的,需要解密才能获取文本信息
 * <p>
 * 5、解密就用到刚才的 session_key 了,session_key 其实就是解密的钥匙 (密钥)
 */
public void code2session() {

    String code = getPara("code");
    if (StrUtil.isBlank(code)) {
        renderFailJson(105, "code is blank");
        return;
    }


    // 获取SessionKey 和 openId
    // 返回{"session_key":"nzoqhc3OnwHzeTxJs+inbQ==","expires_in":2592000,"openid":"oVBkZ0aYgDMDIywRdgPW8-joxXc4"}
    ApiResult apiResult = wxaUserApi.getSessionKey(code);
    if (!apiResult.isSucceed()) {
        renderFailJson(apiResult.getErrorCode(), apiResult.getErrorMsg());
        return;
    }


    String sessionKey = apiResult.getStr("session_key");
    String sessionId = StrUtil.uuid();

    //把sessionKey存储起来,接下来用户解密要用到这个sessionKey
    IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();
    accessTokenCache.set("wxa:session:" + sessionId, sessionKey);


    //把sessionId传给客户端,客户端解密数据的时候,必须把这个sessionId传入进来,才能获取sessionKey
    renderJson(Ret.ok().set("sessionId", sessionId));

}
 
Example #6
Source File: WechatMsgUtil.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean sendImage(String openId, File imageFile) {

        if (!imageFile.exists() || !imageFile.isFile() || !imageFile.canRead()) {
            return false;
        }

        /**
         * 上传临时素材
         * {"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
         */
        ApiResult apiResult = MediaApi.uploadMedia(MediaApi.MediaType.IMAGE, imageFile);
        if (!apiResult.isSucceed()) {
            LOG.error("MediaApi.uploadMedia..." + imageFile + " \n" + apiResult.toString());
            return false;
        }

        String mediaId = apiResult.get("media_id");
        /**
         * 发送海报
         */
        ApiResult sendImageApiResult = CustomServiceApi.sendImage(openId, mediaId);
        if (!sendImageApiResult.isSucceed()) {
            LOG.error("CustomServiceApi.sendImage() is error : " + imageFile + " \n" + sendImageApiResult.getErrorMsg() + sendImageApiResult.toString());
            return false;
        }

        return true;
    }
 
Example #7
Source File: WechatMsgUtil.java    From jpress with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static boolean sendText(String openId, String text) {
    ApiResult result = CustomServiceApi.sendText(openId, text);
    return result.isSucceed();
}
 
Example #8
Source File: _WechatArticleImport.java    From jpress with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void doSyncArticles(final int articleCount) {
    new Thread(() -> {
        int times = articleCount <= 20 ? 1 : articleCount / 20;

        List<Article> articles = new ArrayList<>();
        List<String> images = new ArrayList<>();
        for (int i = 0; i < times; i++) {
            ApiResult newsResult = MediaApi.batchGetMaterialNews(i * 20, 20);
            if (newsResult.isSucceed()) {
                JSONArray jsonArray = newsResult.get("item");
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONArray array = jsonArray.getJSONObject(j).getJSONObject("content").getJSONArray("news_item");
                    for (int a = 0; a < array.size(); a++) {
                        JSONObject articleObject = array.getJSONObject(a);
                        String title = articleObject.getString("title");
                        String content = articleObject.getString("content");
                        String summary = articleObject.getString("digest");

                        if (StrUtil.isNotBlank(content)) {
                            content = processContentImages(content, images);
                        }

                        Article article = new Article();
                        article.setTitle(title);
                        article.setContent(content);
                        article.setSummary(summary);
                        article.setCreated(new Date());
                        article.setModified(new Date());
                        article.setStatus(Article.STATUS_NORMAL);

                        articles.add(article);
                    }
                }
            }
        }

        doSaveArticles(articles);
        doDownloadImages(images);

    }).start();
}
 
Example #9
Source File: WechatAuthorizationController.java    From jpress with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Long doGetOrCreateUser(ApiResult apiResult) {

        /**
         * {
         "subscribe": 1,
         "openid": "xxx",
         "nickname": "Band",
         "sex": 1,
         "language": "zh_CN",
         "city": "广州",
         "province": "广东",
         "country": "中国",
         "headimgurl":  "xxx",
         "subscribe_time": xxxx,
         "unionid": " xxxx"
         "remark": "",
         "groupid": 0,
         "tagid_list":[128,2]
         }
         */

        String openId = apiResult.get("openid");
        String unionId = apiResult.get("unionid");


        User user = null;

        //优先根据 unioinId 进行查询
        if (StrUtil.isNotBlank(unionId)) {
            user = userService.findFistByWxUnionid(unionId);
            if (user != null) {
                return user.getId();
            }
        }

        //之后根据 openId 进行查询
        if (StrUtil.isNotBlank(openId)) {
            user = userService.findFistByWxOpenid(openId);
            if (user != null) {
                return user.getId();
            }
        }

        UserOpenidService userOpenidService = Aop.get(UserOpenidService.class);

        String uid = CookieUtil.get(this, JPressConsts.COOKIE_UID);
        if (StrUtil.isNotBlank(uid)) {
            user = userService.findById(uid);
            if (user != null) {
                userOpenidService.saveOrUpdate(user.getId(), UserOpenid.TYPE_WECHAT, openId);
                if (StrUtil.isNotBlank(unionId)) {
                    userOpenidService.saveOrUpdate(user.getId(), UserOpenid.TYPE_WECHAT_UNIONID, unionId);
                }

                return user.getId();
            }
        }


        // 都查询不到,说明该用户是一个新的用户,创建一个新的用户
        String nickName = apiResult.get("nickname");
        int sex = apiResult.get("sex");
        String city = apiResult.get("city");
        String province = apiResult.get("province");
        String country = apiResult.get("country");
        String avatarUrl = apiResult.get("headimgurl");

        user = new User();
        user.setNickname(nickName);
        user.setAddress(country + province + city);
//        user.setWxUnionid(unionId);
//        user.setWxOpenid(openId);
        user.setAvatar(avatarUrl);
        user.setCreated(new Date());
        user.setLogged(new Date());
        user.setCreateSource(User.SOURCE_WECHAT_WEB);
        user.setAnonym(CookieUtil.get(this, JPressConsts.COOKIE_ANONYM));

        boolean isNotActivate = JPressOptions.getAsBool("reg_users_is_not_activate");
        if (isNotActivate) {
            user.setStatus(User.STATUS_REG);
        }else {
            user.setStatus(User.STATUS_OK);
        }


        Long userId = (Long) userService.save(user);


        userOpenidService.saveOrUpdate(userId, UserOpenid.TYPE_WECHAT, openId);
        if (StrUtil.isNotBlank(unionId)) {
            userOpenidService.saveOrUpdate(userId, UserOpenid.TYPE_WECHAT_UNIONID, unionId);
        }


        return userId;
    }
 
Example #10
Source File: WechatAuthorizationController.java    From jpress with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static ApiResult getUserInfo(String openId, String accessToken) {
    ParaMap pm = ParaMap.create("access_token", accessToken).put("openid", openId).put("lang", "zh_CN");
    return new ApiResult(HttpKit.get("https://api.weixin.qq.com/sns/userinfo", pm.getData()));
}
 
Example #11
Source File: WechatAuthorizationController.java    From jpress with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void back() {
    String gotoUrl = getPara("goto");
    String code = getPara("code");

    String appId = JPressOptions.get(JPressConsts.OPTION_WECHAT_APPID);
    String appSecret = JPressOptions.get(JPressConsts.OPTION_WECHAT_APPSECRET);

    if (StrUtil.isBlank(appId) || StrUtil.isBlank(appSecret)) {
        renderText("管理员的微信AppId或AppSecret配置错误,请联系管理在后台 -> 微信 -> 基础设置 配置正确。");
        return;
    }

    ApiResult result = getOpenId(appId, appSecret, code);
    if (result == null) {
        renderText("网络错误,获取不到微信信息,请联系管理员");
        return;
    }

    //在某些时候获取不到微信信息
    //一般情况下是code有问题
    //重复发起刚才的过程
    if (result.isSucceed() == false) {
        redirect(StrUtil.urlDecode(gotoUrl));
        return;
    }

    String openId = result.getStr("openid");
    String accessToken = result.getStr("access_token");

    ApiResult userInfoResult = getUserInfo(openId, accessToken);

    Long userId = doGetOrCreateUser(userInfoResult);
    if (userId == null) {
        //这种情况非常严重,一般情况下只有链接不上数据库了
        //或者是在 RPC 下,无法调用到 provider 了
        renderText("can not query user or save user to database");
        return;
    }

    CookieUtil.put(this, JPressConsts.COOKIE_UID, userId);
    redirect(StrUtil.urlDecode(gotoUrl));
}
 
Example #12
Source File: WechatMsgUtil.java    From jpress with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static ApiResult sendMiniprogram(String openId,
                                        String title,
                                        String appid,
                                        String pagepath,
                                        File imageCover) {

    if (!imageCover.exists() || !imageCover.isFile() || !imageCover.canRead()) {
        return null;
    }

    /**
     * 上传临时素材
     * {"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
     */
    ApiResult apiResult = MediaApi.uploadMedia(MediaApi.MediaType.IMAGE, imageCover);
    if (!apiResult.isSucceed()) {
        LOG.error("MediaApi.uploadMedia..." + imageCover + " \n" + apiResult.toString());
        return apiResult;
    }

    String mediaId = apiResult.get("media_id");


    Map<String, Object> jsonMap = new HashMap<String, Object>();
    jsonMap.put("touser", openId);
    jsonMap.put("msgtype", "miniprogrampage");


    Map<String, Object> miniprogrampageMap = new HashMap<String, Object>();
    miniprogrampageMap.put("title", title);
    miniprogrampageMap.put("appid", appid);
    miniprogrampageMap.put("pagepath", pagepath);
    miniprogrampageMap.put("thumb_media_id", mediaId);

    jsonMap.put("miniprogrampage", miniprogrampageMap);

    String accessToken = AccessTokenApi.getAccessTokenStr();
    String jsonResult = HttpUtils.post(customMessageUrl + accessToken, JsonUtils.toJson(jsonMap));

    return new ApiResult(jsonResult);
}
 
Example #13
Source File: UserController.java    From jboot-admin with Apache License 2.0 4 votes vote down vote up
@Override
public Object doSaveOrUpdateUserByApiResult(ApiResult apiResult) {
    // 根据自己需求扩展,比如保存微信用户信息,与内部用户做关联
    System.out.println(JsonKit.toJson(apiResult));
    return apiResult;
}
 
Example #14
Source File: WechatMiniProgramApiController.java    From jpress with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Long doGetOrCreateUser(ApiResult apiResult) {

        /**
         * 文档:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html
         * apiResult的数据格式如下
         * {
         "openId": "OPENID",
         "nickName": "NICKNAME",
         "gender": GENDER,
         "city": "CITY",
         "province": "PROVINCE",
         "country": "COUNTRY",
         "avatarUrl": "AVATARURL",
         "unionId": "UNIONID",
         "watermark": {
         "appid": "APPID",
         "timestamp": TIMESTAMP
         }
         }
         */

        String openId = apiResult.get("openId");
        String unionId = apiResult.get("unionId");


        User user = null;

        //优先根据 unioinId 进行查询
        if (StrUtil.isNotBlank(unionId)) {
            user = userService.findFistByWxUnionid(unionId);
            if (user != null) {
                return user.getId();
            }
        }

        //之后根据 openId 进行查询
        if (StrUtil.isNotBlank(openId)) {
            user = userService.findFistByWxOpenid(openId);
            if (user != null) {
                return user.getId();
            }
        }

        // 都查询不到,说明该用户是一个新的用户,创建一个新的用户
        String nickName = apiResult.get("nickName");
        int gender = apiResult.getInt("gender");
        String city = apiResult.get("city");
        String province = apiResult.get("province");
        String country = apiResult.get("country");
        String avatarUrl = apiResult.get("avatarUrl");

        user = new User();
        user.setNickname(nickName);
        user.setAddress(country + province + city);
//        user.setWxUnionid(unionId);
//        user.setWxOpenid(openId);
        user.setAvatar(avatarUrl);
        user.setCreated(new Date());
        user.setLogged(new Date());
        user.setCreateSource(User.SOURCE_WECHAT_MINIPROGRAM);

        boolean isNotActivate = JPressOptions.getAsBool("reg_users_is_not_activate");
        if (isNotActivate) {
            user.setStatus(User.STATUS_REG);
        }else {
            user.setStatus(User.STATUS_OK);
        }


        Long userId = (Long) userService.save(user);

        UserOpenidService openidService = Aop.get(UserOpenidService.class);
        openidService.saveOrUpdate(userId, UserOpenid.TYPE_WECHAT,openId);
        openidService.saveOrUpdate(userId, UserOpenid.TYPE_WECHAT_UNIONID,unionId);


        return userId;
    }
 
Example #15
Source File: WechatMiniProgramApiController.java    From jpress with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 小程序端调用 wx.getUserInfo() 后,得到的是加密的用户数据
 * 需要调用此接口,才能获取到具体的数据
 * 解密用户数据,小程序的相关接口 https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html
 */
public void decryptUserInfo() {


    String postData = getRawData();
    if (StrUtil.isBlank(postData)) {
        renderFailJson(107, "can not get data");
        return;
    }

    JSONObject json = JSON.parseObject(postData);

    //小程序端调用 /api/wechat/mp/code2session之后得到的sessionId
    String sessionId = json.getString("sessionId");

    IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();
    String sessionKey = accessTokenCache.get("wxa:session:" + sessionId);
    if (StrUtil.isBlank(sessionKey)) {
        renderFailJson(107, "session id is error.");
        return;
    }


    //不包括敏感信息的原始数据字符串,用于计算签名
    String rawData = json.getString("rawData");

    //签名:使用 sha1( rawData + sessionkey ) 得到字符串,用于校验用户信息
    String signature = json.getString("signature");

    //包括敏感数据在内的完整用户信息的加密数据
    //具体加密方法在:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html#%E5%8A%A0%E5%AF%86%E6%95%B0%E6%8D%AE%E8%A7%A3%E5%AF%86%E7%AE%97%E6%B3%95
    String encryptedData = json.getString("encryptedData");

    //加密算法的初始向量
    String iv = json.getString("iv");


    // 用户信息校验
    boolean check = wxaUserApi.checkUserInfo(sessionKey, rawData, signature);
    if (check == false) {
        renderFailJson(500, "userInfo check fail");
        return;
    }

    // 服务端解密用户信息,得到原始的用户信息
    ApiResult apiResult = wxaUserApi.getUserInfo(sessionKey, encryptedData, iv);
    if (!apiResult.isSucceed()) {
        renderFailJson(apiResult.getErrorCode(), apiResult.getErrorMsg());
        return;
    }

    Long userId = doGetOrCreateUser(apiResult);
    if (userId == null) {
        //这种情况非常严重,一般情况下只有链接不上数据库了
        //或者是在 RPC 下,无法调用到 provider 了
        renderFailJson(501, "can not query user or save user to database");
        return;
    }


    setJwtAttr(JPressConsts.JWT_USERID, userId);

    //设置 jwt Token 给客户端
    //以后客户端通过此token定位用户信息
    renderJson(Ret.ok().set("token", createJwtToken()));
}
 
Example #16
Source File: JbootWechatController.java    From jboot with Apache License 2.0 4 votes vote down vote up
@Clear(WechatUserInterceptor.class)
public void wechatCallback() {

    String gotoUrl = getPara("goto");
    String code = getPara("code");

    //获得不到code?
    if (StrUtil.isBlank(code)) {
        renderText("获取不到正确的code信息");
        return;
    }


    /**
     * 在某些情况下,相同的callback会执行两次,code相同。
     */
    String wechatOpenId = getSessionAttr(SESSION_WECHAT_OPEN_ID);
    String accessToken = getSessionAttr(SESSION_WECHAT_ACCESS_TOKEN);

    if (StrUtil.isNotBlank(wechatOpenId)
            && StrUtil.isNotBlank(accessToken)) {
        doRedirect(gotoUrl, wechatOpenId, accessToken);
        return;
    }


    ApiResult result = WechatApis.getAccessTokenAndOpenId(code);
    if (result == null) {
        renderText("网络错误,获取不到微信信息,请联系管理员");
        return;
    }

    /**
     * 成功获取到 accesstoken 和 openid
     */
    if (result.isSucceed()) {
        wechatOpenId = result.getStr("openid");
        accessToken = result.getStr("access_token");
        setSessionAttr(SESSION_WECHAT_OPEN_ID, wechatOpenId);
        setSessionAttr(SESSION_WECHAT_ACCESS_TOKEN, accessToken);
        setSessionAttr(SESSION_WECHAT_SCOPE, result.getStr("scope"));
    } else {
        wechatOpenId = getSessionAttr(SESSION_WECHAT_OPEN_ID);
        accessToken = getSessionAttr(SESSION_WECHAT_ACCESS_TOKEN);

        if (StrUtil.isBlank(wechatOpenId) || StrUtil.isBlank(accessToken)) {
            renderText("错误:" + result.getErrorMsg());
            return;
        }
    }

    if ("snsapi_base".equalsIgnoreCase(result.getStr("scope"))) {
        redirect(gotoUrl);
        return;
    }

    doRedirect(gotoUrl, wechatOpenId, accessToken);
}
 
Example #17
Source File: JbootWechatController.java    From jboot with Apache License 2.0 votes vote down vote up
/**
 * 根据 apiResult 数据来保存或更新用户信息
 * <p>
 * 用户第一次访问的时候
 * <p>
 * <p>
 * <p>
 * apiResult内如如下:
 * {
 * "subscribe": 1,
 * "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
 * "nickname": "Band",
 * "sex": 1,
 * "language": "zh_CN",
 * "city": "广州",
 * "province": "广东",
 * "country": "中国",
 * "headimgurl":  "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4
 * eMsv84eavHiaiceqxibJxCfHe/0",
 * "subscribe_time": 1382694957,
 * "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
 * "remark": "",
 * "groupid": 0,
 * "tagid_list":[128,2]
 * }
 *
 * @param apiResult
 * @return
 */

public abstract Object doSaveOrUpdateUserByApiResult(ApiResult apiResult);