Java Code Examples for com.jfinal.weixin.sdk.api.ApiResult#isSucceed()

The following examples show how to use com.jfinal.weixin.sdk.api.ApiResult#isSucceed() . 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: _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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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));
}