me.ixfan.wechatkit.user.UserManager.java Source code

Java tutorial

Introduction

Here is the source code for me.ixfan.wechatkit.user.UserManager.java

Source

/*
 * MIT License
 *
 * Copyright (c) 2016 Warren Fan
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package me.ixfan.wechatkit.user;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import me.ixfan.wechatkit.WeChatKitComponent;
import me.ixfan.wechatkit.common.WeChatConstants;
import me.ixfan.wechatkit.exceptions.WeChatApiErrorException;
import me.ixfan.wechatkit.token.TokenManager;
import me.ixfan.wechatkit.user.model.UserTag;
import me.ixfan.wechatkit.user.model.WeChatFollower;
import me.ixfan.wechatkit.util.HttpClientUtil;
import org.apache.http.util.Args;
import org.apache.http.util.TextUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * ?
 *
 * Created by xfan on 16/3/26.
 */
public class UserManager extends WeChatKitComponent {

    public UserManager(TokenManager tokenManager) {
        super(tokenManager);
    }

    /**
     * ? OpenID?????OpenID???10000 OpenID????
     *
     * @param nextOpenId ?OPENID??
     * @return  OpenId ? <code>next_openid</code>
     * @throws WeChatApiErrorException API??
     */
    public String[] getFollowerList(String nextOpenId) throws WeChatApiErrorException {
        JsonObject jsonResp;
        try {
            final String url = WeChatConstants.WECHAT_GET_USER_LIST.replace("${ACCESS_TOKEN}",
                    super.tokenManager.getAccessToken());
            jsonResp = HttpClientUtil.sendGetRequestAndGetJsonResponse(
                    url.replace("${NEXT_OPENID}", null != nextOpenId ? nextOpenId : ""));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (jsonResp.has("count") && jsonResp.get("count").getAsInt() > 0) {
            final ArrayList<String> openids = new ArrayList<>();
            jsonResp.get("data").getAsJsonObject().get("openid").getAsJsonArray()
                    .forEach(e -> openids.add(e.getAsString()));
            if (jsonResp.has("next_openid")) {
                openids.add(jsonResp.get("next_openid").getAsString());
            }
            return openids.toArray(new String[0]);
        } else {
            throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(),
                    jsonResp.get("errmsg").getAsString());
        }
    }

    /**
     * ?? UnionId ?????UnionId ?
     *
     * @param openId  OpenId
     * @param lang zh_CN zh_TW ?en  zh_CN
     * @return {@link WeChatFollower}
     * @throws WeChatApiErrorException API??
     */
    public WeChatFollower getUserInfo(final String openId, String lang) throws WeChatApiErrorException {
        Args.notBlank(openId, "OpenId");
        if (TextUtils.isBlank(lang)) {
            lang = "zh_CN";
        }
        Args.check(lang.equals("zh_CN") || lang.equals("zh_TW") || lang.equals("en"),
                "'lang' ? zh_CN, zh_TW  en.");

        final String url = WeChatConstants.WECHAT_GET_USER_INFO
                .replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken()).replace("${OPENID}", openId)
                .replace("${LANG}", lang);
        JsonObject jsonResponse;
        try {
            jsonResponse = HttpClientUtil.sendGetRequestAndGetJsonResponse(url);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (jsonResponse.has("subscribe")) {
            return WeChatFollower.fromJson(jsonResponse);
        } else {
            throw new WeChatApiErrorException(jsonResponse.get("errcode").getAsInt(),
                    jsonResponse.get("errmsg").getAsString());
        }
    }

    /**
     * ?????100?
     * @param openIds  OpenId 
     * @param lang zh_CN zh_TW ?en  zh-CN
     * @return {@link WeChatFollower}s
     * @throws WeChatApiErrorException API??
     */
    public List<WeChatFollower> batchGetUserInfo(final List<String> openIds, String lang)
            throws WeChatApiErrorException {
        Args.notEmpty(openIds, "OpenIds");
        if (TextUtils.isBlank(lang)) {
            lang = "zh_CN";
        }
        Args.check(lang.equals("zh_CN") || lang.equals("zh_TW") || lang.equals("en"),
                "'lang' ? zh_CN, zh_TW  en.");

        final String finalLang = lang;
        JsonObject jsonResponse;
        try {
            final List<Map<String, String>> data = new ArrayList<>();
            openIds.forEach(openid -> {
                Map<String, String> map = new HashMap<>();
                map.put("openid", openid);
                map.put("lang", finalLang);
                data.add(map);
            });
            final Map<String, List<Map<String, String>>> jsonMap = new HashMap<>();
            jsonMap.put("user_list", data);
            Gson gson = new Gson();
            jsonResponse = HttpClientUtil
                    .sendPostRequestWithJsonBody(WeChatConstants.WECHAT_POST_BATCH_GET_USER_INFO
                            .replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken()), gson.toJson(jsonMap));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (jsonResponse.has("user_info_list")) {
            return WeChatFollower.batchFromJson(jsonResponse.get("user_info_list").getAsJsonArray());
        } else {
            throw new WeChatApiErrorException(jsonResponse.get("errcode").getAsInt(),
                    jsonResponse.get("errmsg").getAsString());
        }
    }

    /**
     * 
     *
     * @param tagName ??30
     * @return {@link UserTag} 
     * @throws WeChatApiErrorException API??
     */
    public UserTag createTag(String tagName) throws WeChatApiErrorException {
        Args.notEmpty(tagName, "Tag name");
        final String url = WeChatConstants.WECHAT_POST_CREATE_TAG.replace("${ACCESS_TOKEN}",
                super.tokenManager.getAccessToken());
        final String jsonData = "{\"tag\":{\"name\":\"" + tagName + "\"}}";
        JsonObject jsonResponse;
        try {
            jsonResponse = HttpClientUtil.sendPostRequestWithJsonBody(url, jsonData);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (jsonResponse.has("tag")) {
            return new UserTag(jsonResponse.getAsJsonObject("tag").get("id").getAsInt(),
                    jsonResponse.getAsJsonObject("tag").get("name").getAsString());
        } else {
            throw new WeChatApiErrorException(jsonResponse.get("errcode").getAsInt(),
                    jsonResponse.get("errmsg").getAsString());
        }
    }

    /**
     * ?
     *
     * @return 
     * @throws WeChatApiErrorException API??
     */
    public List<UserTag> getExistingTags() throws WeChatApiErrorException {
        final String url = WeChatConstants.WECHAT_GET_GET_TAGS.replace("${ACCESS_TOKEN}",
                super.tokenManager.getAccessToken());
        JsonObject jsonResp;
        try {
            jsonResp = HttpClientUtil.sendGetRequestAndGetJsonResponse(url);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (jsonResp.has("tags")) {
            Gson gson = new Gson();
            return Arrays.asList(gson.fromJson(jsonResp.getAsJsonArray("tags"), UserTag[].class));
        } else {
            throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(),
                    jsonResp.get("errmsg").getAsString());
        }
    }

    /**
     * 
     *
     * @param tagId ID
     * @param tagName ??
     * @throws WeChatApiErrorException API??
     */
    public void updateTag(int tagId, String tagName) throws WeChatApiErrorException {
        Args.notNegative(tagId, "Tag ID");
        Args.notEmpty(tagName, "Tag name");

        final String url = WeChatConstants.WECHAT_POST_UPDATE_TAG.replace("${ACCESS_TOKEN}",
                super.tokenManager.getAccessToken());
        final String jsonData = "{\"tag\":{\"id\":" + String.valueOf(tagId) + ",\"name\":\"" + tagName + "\"}}";
        JsonObject jsonResp;
        try {
            jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(url, jsonData);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (0 != jsonResp.get("errcode").getAsInt()) {
            throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(),
                    jsonResp.get("errmsg").getAsString());
        }
    }

    /**
     * 
     *
     * @param tagId ID
     * @throws WeChatApiErrorException API??
     */
    public void deleteTag(int tagId) throws WeChatApiErrorException {
        Args.notNegative(tagId, "Tag ID");

        final String url = WeChatConstants.WECHAT_POST_DELETE_TAG.replace("${ACCESS_TOKEN}",
                super.tokenManager.getAccessToken());
        final String jsonData = "{\"tag\":{\"id\":" + String.valueOf(tagId) + "}}";
        JsonObject jsonResp;
        try {
            jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(url, jsonData);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (0 != jsonResp.get("errcode").getAsInt()) {
            throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(),
                    jsonResp.get("errmsg").getAsString());
        }
    }

    /**
     * ??
     *
     * @param tagId ID
     * @param nextOpenId ?OPENID??
     * @return  OpenId ? <code>next_openid</code>
     * @throws WeChatApiErrorException API??
     */
    public String[] getUsersWithTag(int tagId, String nextOpenId) throws WeChatApiErrorException {
        Args.notNegative(tagId, "Tag ID");

        final String url = WeChatConstants.WECHAT_GET_USER_WITH_TAG.replace("${ACCESS_TOKEN}",
                super.tokenManager.getAccessToken());
        final String jsonData = "{\"tagid\":${TAG_ID},\"next_openid\":\"${NEXT_OPENID}\"}";
        JsonObject jsonResp;
        try {
            jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(url,
                    jsonData.replace("${TAG_ID}", String.valueOf(tagId)).replace("${NEXT_OPENID}",
                            null != nextOpenId ? nextOpenId : ""));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (jsonResp.has("count")) {
            final ArrayList<String> openids = new ArrayList<>();
            if (jsonResp.get("count").getAsInt() > 0) {
                jsonResp.get("data").getAsJsonObject().get("openid").getAsJsonArray()
                        .forEach(e -> openids.add(e.getAsString()));
                if (jsonResp.has("next_openid")) {
                    openids.add(jsonResp.get("next_openid").getAsString());
                }
            }
            return openids.toArray(new String[0]);
        } else {
            throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(),
                    jsonResp.get("errmsg").getAsString());
        }
    }

    /**
     * ????
     *
     * @param tagId ID
     * @param openIds ?OpenID?openid?50
     * @throws WeChatApiErrorException API??
     */
    public void batchTaggingUsersWithTag(int tagId, List<String> openIds) throws WeChatApiErrorException {
        Args.notNegative(tagId, "Tag ID");
        Args.notEmpty(openIds, "OpenIds");

        final String url = WeChatConstants.WECHAT_POST_BATCH_TAGGING.replace("${ACCESS_TOKEN}",
                super.tokenManager.getAccessToken());
        final String jsonData = "{\"openid_list\":[${OPENIDS}],\"tagid\":${TAG_ID}}";
        JsonObject jsonResp;
        try {
            jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(url,
                    jsonData.replace("${OPENIDS}", openIds.stream().collect(Collectors.joining(",")))
                            .replace("${TAG_ID}", String.valueOf(tagId)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (jsonResp.get("errcode").getAsInt() != 0) {
            throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(),
                    jsonResp.get("errmsg").getAsString());
        }
    }

    /**
     * ??
     *
     * @param tagId ID
     * @param openIds ?OpenID?openid?50
     * @throws WeChatApiErrorException API??
     */
    public void batchUntaggingUsers(int tagId, List<String> openIds) throws WeChatApiErrorException {
        Args.notNegative(tagId, "Tag ID");
        Args.notEmpty(openIds, "OpenIds");

        final String url = WeChatConstants.WECHAT_POST_BATCH_UNTAGGING.replace("${ACCESS_TOKEN}",
                super.tokenManager.getAccessToken());
        final String jsonData = "{\"openid_list\":[${OPENIDS}],\"tagid\":${TAG_ID}}";
        JsonObject jsonResp;
        try {
            jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(url,
                    jsonData.replace("${OPENIDS}", openIds.stream().collect(Collectors.joining(",")))
                            .replace("${TAG_ID}", String.valueOf(tagId)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (jsonResp.get("errcode").getAsInt() != 0) {
            throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(),
                    jsonResp.get("errmsg").getAsString());
        }
    }

    /**
     * ?
     *
     * @param openId ?OpenID
     * @return ID
     * @throws WeChatApiErrorException API??
     */
    public int[] getTagsOfUser(String openId) throws WeChatApiErrorException {
        Args.notEmpty(openId, "OpenID");

        final String url = WeChatConstants.WECHAT_POST_GET_TAGS_OF_USER.replace("${ACCESS_TOKEN}",
                super.tokenManager.getAccessToken());
        final String jsonData = "{\"openid\":\"${OPENID}\"}";
        JsonObject jsonResp;
        try {
            jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(url, jsonData.replace("${OPENID}", openId));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (jsonResp.has("tagid_list")) {
            JsonArray jsonArray = jsonResp.getAsJsonArray("tagid_list");
            int[] tagIds = new int[jsonArray.size()];
            if (jsonArray.size() > 0) {
                IntStream.range(0, jsonArray.size()).forEach(i -> tagIds[i] = jsonArray.get(i).getAsInt());
            }
            return tagIds;
        } else {
            throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(),
                    jsonResp.get("errmsg").getAsString());
        }
    }

}