赞
踩
最近需要开发一个客服的功能,由于对socket知识比较匮乏,为了不影响开发进度,准备接入第三方进行二次开发。
第一步:在IM控制台中创建应用,获取SDKAppID和密钥。
第二步:引入相关依赖
- <!-- 腾讯云IM-sdk -->
- <dependency>
- <groupId>com.github.tencentyun</groupId>
- <artifactId>tls-sig-api-v2</artifactId>
- <version>2.0</version>
- </dependency>
第三步:yml配置
- #腾讯云IM配置
- IMConfig:
- sdkAppId: 这里填你自己的sdkAppId
- secretKey: 这里填入你的密钥
第四步:腾讯云IM API路径封装
- public enum TencentCloudImApiEnum {
-
- /**
- * 账号管理
- */
- ACCOUNT_IMPORT("导入单个账号", "v4/im_open_login_svc/account_import"),
- MULTI_ACCOUNT_IMPORT("导入多个账号", "v4/im_open_login_svc/multiaccount_import"),
- ACCOUNT_DELETE("删除账号", "v4/im_open_login_svc/account_delete"),
- ACCOUNT_CHECK("查询账号", "v4/im_open_login_svc/account_check"),
- KICK("失效账号登录状态", "v4/im_open_login_svc/kick"),
- QUERY_ONLINE_STATE("查询账号在线状态", " v4/openim/query_online_status"),
-
- /**
- * 单聊消息
- */
- SEND_MSG("单发单聊消息", "v4/openim/sendmsg"),
- BATCH_SEND_MSG("批量发单聊消息", "v4/openim/batchsendmsg"),
- IMPORT_MSG("导入单聊消息", "v4/openim/importmsg"),
- ADMIN_GET_ROAM_MSG("查询单聊消息", "v4/openim/admin_getroammsg"),
- ADMIN_MSG_WITH_DRAW("撤回单聊消息", "v4/openim/admin_msgwithdraw"),
- ADMIN_SET_MSG_READ("设置单聊消息已读", "v4/openim/admin_set_msg_read"),
- GET_C2C_UNREAD_MSG_NUM("查询单聊未读消息计数", "v4/openim/get_c2c_unread_msg_num"),
- MODIFY_C2C_MSG("修改单聊历史消息", "v4/openim/modify_c2c_msg"),
-
- /**
- * 全员推送
- */
- IM_PUSH("全员推送", "v4/all_member_push/im_push"),
- IM_SET_ATTR_NAME("设置应用属性名称", "v4/all_member_push/im_set_attr_name"),
- IM_GET_ATTR_NAME("获取应用属性名称", "v4/all_member_push/im_get_attr_name"),
- IM_GET_ATTR("获取用户属性", "v4/all_member_push/im_get_attr"),
- IM_SET_ATTR("设置用户属性", "v4/all_member_push/im_set_attr"),
- IM_REMOVE_ATTR("删除用户属性", "v4/all_member_push/im_remove_attr"),
- IM_GET_TAG("获取用户标签", "v4/all_member_push/im_get_tag"),
- IM_ADD_TAG("添加用户标签", "v4/all_member_push/im_add_tag"),
- IM_REMOVE_TAG("删除用户标签", "v4/all_member_push/im_remove_tag"),
- IM_REMOVE_ADD_TAGS("删除用户所有标签", "v4/all_member_push/im_remove_all_tags"),
-
- /**
- * 资料管理
- */
- PORTRAIT_SET("设置资料", "v4/profile/portrait_set"),
- PORTRAIT_GET("拉取资料", "v4/profile/portrait_get"),
-
- /**
- * 关系链管理
- */
- FRIEND_ADD("添加好友", "v4/sns/friend_add"),
- FRIEND_IMPORT("导入好友", "v4/sns/friend_import"),
- FRIEND_UPDATE("更新好友", "v4/sns/friend_update"),
- FRIEND_DELETE("删除好友", "v4/sns/friend_delete"),
- FRIEND_DELETE_ALL("删除所有好友", "v4/sns/friend_delete_all"),
- FRIEND_CHECK("校验好友", "v4/sns/friend_check"),
- FRIEND_GET("拉取好友", "v4/sns/friend_get"),
- FRIEND_GET_LIST("拉取指定好友", "v4/sns/friend_get_list"),
- BLACK_LIST_ADD("添加黑名单", "v4/sns/black_list_add"),
- BLACK_LIST_DELETE("删除黑名单", "v4/sns/black_list_delete"),
- BLACK_LIST_GET("拉取黑名单", "v4/sns/black_list_get"),
- BLACK_LIST_CHECK("校验黑名单", "v4/sns/black_list_check"),
- GROUP_ADD("添加分组", "v4/sns/group_add"),
- GROUP_DELETE("删除分组", "v4/sns/group_delete"),
- GROUP_GET("拉取分组", "v4/sns/group_get"),
-
- /**
- * 最近联系人
- */
- CONTACT_GET_LIST("拉取会话列表", "v4/recentcontact/get_list"),
- CONTACT_DELETE("删除单个会话", "v4/recentcontact/delete"),
- CREATE_CONTACT_GROUP("创建会话分组数据", "v4/recentcontact/create_contact_group"),
- DEL_CONTACT_GROUP("删除会话分组数据", "v4/recentcontact/del_contact_group"),
- UPDATE_CONTACT_GROUP("更新会话分组数据", "v4/recentcontact/update_contact_group"),
- SEARCH_CONTACT_GROUP("搜索会话分组标记数据", "v4/recentcontact/search_contact_group"),
- MARK_CONTACT("创建或更新会话标记数据", "v4/recentcontact/mark_contact"),
- GET_CONTACT_GROUP("拉取会话分组标记数据", "v4/recentcontact/get_contact_group"),
-
- /**
- * 群组管理
- */
- GET_APPID_GROUP_LIST("获取APP中的所有群组", "v4/group_open_http_svc/get_appid_group_list"),
- CREATE_GROUP("创建群组", "v4/group_open_http_svc/create_group"),
- GET_GROUP_INFO("获取群详细资料", "v4/group_open_http_svc/get_group_info"),
- GET_GROUP_MEMBER_INFO("获取群成员详细资料", "v4/group_open_http_svc/get_group_member_info"),
- MODIFY_GROUP_BASE_INFO("修改群基础资料", "v4/group_open_http_svc/modify_group_base_info"),
- ADD_GROUP_MEMBER("增加群成员", "v4/group_open_http_svc/add_group_member"),
- DELETE_GROUP_MEMBER("删除群成员", "v4/group_open_http_svc/delete_group_member"),
- MODIFY_GROUP_MEMBER_INFO("修改群成员资料", "v4/group_open_http_svc/modify_group_member_info"),
- DESTROY_GROUP("解散群组", "v4/group_open_http_svc/destroy_group "),
- GET_JOINED_GROUP_LIST("获取用户所加入的群组", "v4/group_open_http_svc/get_joined_group_list"),
- GET_ROLE_IN_GROUP("查询用户在群组中的身份", "v4/group_open_http_svc/get_role_in_group"),
- FORBID_SEND_MSG("批量禁言和取消禁言", "v4/group_open_http_svc/forbid_send_msg"),
- GET_GROUP_MUTED_ACCOUNT("获取被禁言群成员列表", "v4/group_open_http_svc/get_group_muted_account"),
- SEND_GROUP_MSG("在群组中发送普通消息", "v4/group_open_http_svc/send_group_msg"),
- SEND_GROUP_SYSTEM_NOTIFICATION("在群组中发送系统通知", "v4/group_open_http_svc/send_group_system_notification"),
- GROUP_MSG_RECALL("撤回群消息", "v4/group_open_http_svc/group_msg_recall"),
- CHANGE_GROUP_OWNER("转让群主", "v4/group_open_http_svc/change_group_owner"),
- IMPORT_GROUP("导入群基础资料", "v4/group_open_http_svc/import_group"),
- IMPORT_GROUP_MSG("导入群消息", "v4/group_open_http_svc/import_group_msg "),
- IMPORT_GROUP_MEMBER("导入群成员", "v4/group_open_http_svc/import_group_member"),
- SET_UNREAD_MSG_NUM("设置成员未读消息计数", "v4/group_open_http_svc/set_unread_msg_num"),
- DELETE_GROUP_MSG_BY_SENDER("删除指定用户发送的消息", "v4/group_open_http_svc/delete_group_msg_by_sender"),
- GROUP_MSG_GET_SIMPLE("拉取群历史消息", "v4/group_open_http_svc/group_msg_get_simple"),
- GET_ONLINE_MEMBER_NUM("获取直播群在线人数", "v4/group_open_http_svc/get_online_member_num"),
- GET_MEMBERS("获取直播群在线成员列表", "v4/group_open_avchatroom_http_svc/get_members"),
- MODIFY_USER_INFO("设置直播群成员标记", "v4/group_open_avchatroom_http_svc/modify_user_info"),
- GET_GROUP_ATTR("获取群自定义属性", "v4/group_open_attr_http_svc/get_group_attr"),
- GET_GROUP_BAN_MEMBER("获取封禁群成员列表", "v4/group_open_http_svc/get_group_ban_member"),
- BAN_GROUP_MEMBER("群成员封禁", "v4/group_open_http_svc/ban_group_member"),
- UNBAN_GROUP_MEMBER("群成员解封", "v4/group_open_http_svc/unban_group_member"),
- MODIFY_GROUP_ATTR("修改群自定义属性", "v4/group_open_http_svc/modify_group_attr"),
- CLEAR_GROUP_ATTR("清空群自定义属性", "v4/group_open_http_svc/clear_group_attr"),
- SET_GROUP_ATTR("重置群自定义属性", "v4/group_open_http_svc/set_group_attr"),
- MODIFY_GROUP_MSG("修改群聊历史消息", "v4/openim/modify_group_msg"),
- SEND_BROADCAST_MSG("直播群广播消息", "v4/group_open_http_svc/send_broadcast_msg"),
- GET_GROUP_COUNTER("获取群计数器", "v4/group_open_http_svc/get_group_counter"),
- UPDATE_GROUP_COUNTER("更新群计数器", "v4/group_open_http_svc/update_group_counter"),
- DELETE_GROUP_COUNTER("删除群计数器", "v4/group_open_http_svc/delete_group_counter"),
-
- /**
- * 全局禁言管理
- */
- SET_NO_SPEAKING("设置全局禁言", " v4/openconfigsvr/setnospeaking"),
- GET_NO_SPEAKING("查询全局禁言", " v4/openconfigsvr/getnospeaking"),
-
- /**
- * 运营管理
- */
- GET_APP_INFO("拉取运营数据", "v4/openconfigsvr/getappinfo"),
- GET_HISTORY("下载消息记录", "v4/open_msg_svc/get_history"),
- GET_IP_LIST("获取服务器IP地址", "v4/ConfigSvc/GetIPList"),
- FORBID_ILLEGAL_OBJECT("聊天文件封禁", "v4/im_cos_msg/forbid_illegal_object"),
- ALLOW_BANNED_OBJECT("聊天文件解封", "v4/im_cos_msg/allow_banned_object"),
- GET_COS_SIG("聊天文件签名", "v4/im_cos_msg/get_cos_sig");
-
- private final String description;
-
- private final String url;
-
- TencentCloudImApiEnum(String description, String url) {
- this.description = description;
- this.url = url;
- }
-
- public String description() {
- return description;
- }
-
- public String getUrl() {
- return url;
- }
- }
第五步:基础API封装
- @Slf4j
- @Component
- public class TencentCloudImUtil {
- private static final String HTTPS_URL_PREFIX = "https://console.tim.qq.com/";
- private static final String APP_MANAGER = "administrator";
- private static final String REDIS_IM_USER_SIG = "silence:im_user_sig:";
-
- @Value("${king.IMConfig.sdkAppId}")
- private long sdkAppId;
- @Value("${king.IMConfig.secretKey}")
- private String secretKey;
-
- @Autowired
- private Cache cache;
-
- /**
- * 获取腾讯云用户签名
- */
- public String getTxCloudUserSig() {
- String userSig = (String) cache.get(REDIS_IM_USER_SIG + APP_MANAGER);
- if (StringUtils.isEmpty(userSig)) {
- TLSSigAPIv2 tlsSigApi = new TLSSigAPIv2(sdkAppId, secretKey);
- userSig = tlsSigApi.genUserSig(APP_MANAGER, 86400);
- cache.put(REDIS_IM_USER_SIG + APP_MANAGER, userSig, 86400L);
- }
- return userSig;
- }
-
- /**
- * 获取腾讯im请求路径
- */
- private String getHttpsUrl(String imServiceApi, Integer random) {
- return String.format("%s%s?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=json",
- HTTPS_URL_PREFIX, imServiceApi, sdkAppId, APP_MANAGER, this.getTxCloudUserSig(), random);
- }
-
- /**
- * 导入单个账号
- * @param userId 用户id
- */
- public void accountImport(String userId) {
- accountImport(userId, null);
- }
-
- public void accountImport(String userId, String userName) {
- accountImport(userId, userName, null);
- }
-
- public void accountImport(String userId, String userName, String faceUrl) {
- Integer random = RandomUtils.nextInt(0, 999999999);
- String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.ACCOUNT_IMPORT.getUrl(), random);
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("Identifier", userId);
- if (StringUtils.isNotEmpty(userName)) {
- jsonObject.put("Nick", userName);
- }
- if (StringUtils.isNotEmpty(faceUrl)) {
- jsonObject.put("FaceUrl", faceUrl);
- }
- log.info("腾讯云im导入单个账号,请求参数:{}", jsonObject.toString());
- String result = HttpClientUtils.doPost(httpsUrl, jsonObject);
- log.info("腾讯云im导入单个账号,返回结果:{}", result);
- }
-
- /**
- * 导入多个账号
- * @param userIds 用户id集合
- */
- public void multiAccountImport(List<String> userIds) {
- Integer random = RandomUtils.nextInt(0, 999999999);
- String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.MULTI_ACCOUNT_IMPORT.getUrl(), random);
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("Accounts", userIds);
- log.info("腾讯云im导入多个账号,请求参数:{}", jsonObject.toString());
- String result = HttpClientUtils.doPost(httpsUrl, jsonObject);
- log.info("腾讯云im导入单个账户,返回结果:{}", result);
- }
-
- /**
- * 批量删除账号
- * @param userIds 用户id集合
- */
- public void accountDeleteBatch(List<String> userIds) {
- Integer random = RandomUtils.nextInt(0, 999999999);
- String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.ACCOUNT_DELETE.getUrl(), random);
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("DeleteItem", getUserIdJsonList(userIds));
- log.info("腾讯云im删除账号,请求参数:{}", jsonObject.toString());
- String result = HttpClientUtils.doPost(httpsUrl, jsonObject);
- log.info("腾讯云im删除账户,返回结果:{}", result);
- }
-
- /**
- * 查询账号是否已经导入im
- * @param userIds 用户id集合
- */
- public String accountCheck(List<String> userIds) {
- Integer random = RandomUtils.nextInt(0, 999999999);
- String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.ACCOUNT_CHECK.getUrl(), random);
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("CheckItem", getUserIdJsonList(userIds));
- log.info("腾讯云im查询账号,请求参数:{}", jsonObject.toString());
- String result = HttpClientUtils.doPost(httpsUrl, jsonObject);
- log.info("腾讯云im查询账号,返回结果:{}", result);
- return result;
- }
-
- private List<JSONObject> getUserIdJsonList(List<String> userIds) {
- return userIds.stream().map(v -> {
- JSONObject userIdJson = new JSONObject();
- userIdJson.put("UserID", v);
- return userIdJson;
- }).collect(Collectors.toList());
- }
-
- /**
- * 单发单聊消息
- * @param syncOtherMachine 是否同步消息到发送方(1-同步,2-不同步)
- * @param fromUserId 发送方用户id
- * @param toUserId 接收方用户id
- * @param msgType 消息对象类型
- * @param msgContent 消息内容
- */
- public String sendMsg(Integer syncOtherMachine, String fromUserId, String toUserId, String msgType, String msgContent) {
- Integer random = RandomUtils.nextInt(0, 999999999);
- String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.SEND_MSG.getUrl(), random);
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("SyncOtherMachine", syncOtherMachine);
- if (StringUtils.isNotEmpty(fromUserId)) {
- // 发送方不为空表示指定发送用户,为空表示为管理员发送消息
- jsonObject.put("From_Account", fromUserId);
- }
- jsonObject.put("To_Account", toUserId);
- jsonObject.put("MsgRandom", random);
- List<JSONObject> msgBody = getMsgBody(msgType, msgContent);
- jsonObject.put("MsgBody", msgBody);
- log.info("腾讯云im单发单聊消息,请求参数:{}", jsonObject.toString());
- String result = HttpClientUtils.doPost(httpsUrl, jsonObject);
- log.info("腾讯云im单发单聊消息,返回结果:{}", result);
- return result;
- }
-
- /**
- * 批量发单聊消息
- * @param syncOtherMachine 是否同步消息到发送方(1-同步,2-不同步)
- * @param fromUserId 发送方用户id
- * @param toUserIds 接收方用户id集合
- * @param msgType 消息对象类型
- * @param msgContent 消息内容
- */
- public String batchSendMsg(Integer syncOtherMachine, String fromUserId, List<String> toUserIds, String msgType, String msgContent) {
- Integer random = RandomUtils.nextInt(0, 999999999);
- String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.BATCH_SEND_MSG.getUrl(), random);
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("SyncOtherMachine", syncOtherMachine);
- if (StringUtils.isNotEmpty(fromUserId)) {
- // 发送方不为空表示指定发送用户,为空表示为管理员发送消息
- jsonObject.put("From_Account", fromUserId);
- }
- jsonObject.put("To_Account", toUserIds);
- jsonObject.put("MsgRandom", random);
- List<JSONObject> msgBody = getMsgBody(msgType, msgContent);
- jsonObject.put("MsgBody", msgBody);
- log.info("腾讯云im批量发单聊消息,请求参数:{}", jsonObject.toString());
- String result = HttpClientUtils.doPost(httpsUrl, jsonObject);
- log.info("腾讯云im批量发单聊消息,返回结果:{}", result);
- return result;
- }
-
-
- /**
- * 拼接发送消息内容
- * @param msgType 消息类型
- * @param msgContent 发送消息内容
- * @return 消息内容
- */
- private List<JSONObject> getMsgBody(String msgType, String msgContent) {
- List<JSONObject> msgBody = new ArrayList<>();
- if (msgType.equals(TencentCloudImConstant.TIM_TEXT_ELEM)) {
- // 文本类型
- JSONObject msgBodyJson = new JSONObject();
- msgBodyJson.put("MsgType", msgType);
- JSONObject msgContentObj = new JSONObject();
- msgContentObj.put("Text", msgContent);
- msgBodyJson.put("MsgContent", msgContentObj);
- msgBody.add(msgBodyJson);
- }
- return msgBody;
- }
-
- /**
- * 查询单聊消息
- * @param fromUserId 发送方用户id
- * @param toUserId 接收方用户id
- * @param maxCnt 查询条数
- * @param startTime 起始时间(单位:秒)
- * @param endTime 结束时间(单位:秒)
- * @param lastMsgKey 最后一条消息的 MsgKey
- * @return 单聊消息列表
- */
- public String adminGetRoamMsg(String fromUserId, String toUserId, Integer maxCnt, Long startTime, Long endTime, String lastMsgKey) {
- Integer random = RandomUtils.nextInt(0, 999999999);
- String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.ADMIN_GET_ROAM_MSG.getUrl(), random);
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("From_Account", fromUserId);
- jsonObject.put("To_Account", toUserId);
- jsonObject.put("MaxCnt", maxCnt);
- jsonObject.put("MinTime", startTime);
- jsonObject.put("MaxTime", endTime);
- if (StringUtils.isNotEmpty(lastMsgKey)){
- jsonObject.put("LastMsgKey", lastMsgKey);
- }
- log.info("腾讯云im查询单聊消息,请求参数:{}", jsonObject.toString());
- String result = HttpClientUtils.doPost(httpsUrl, jsonObject);
- log.info("腾讯云im查询单聊消息,返回结果:{}", result);
- return result;
- }
-
- /**
- * 撤回单聊消息
- * @param fromUserId 发送方用户id
- * @param toUserId 接收方用户id
- * @param msgKey MsgKey
- */
- public void adminMsgWithDraw(String fromUserId, String toUserId, String msgKey) {
- Integer random = RandomUtils.nextInt(0, 999999999);
- String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.ADMIN_MSG_WITH_DRAW.getUrl(), random);
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("From_Account", fromUserId);
- jsonObject.put("To_Account", toUserId);
- jsonObject.put("MsgKey", msgKey);
- log.info("腾讯云im撤回单聊消息,请求参数:{}", jsonObject.toString());
- String result = HttpClientUtils.doPost(httpsUrl, jsonObject);
- log.info("腾讯云im撤回单聊消息,返回结果:{}", result);
- }
-
- /**
- * 设置单聊消息已读
- * @param reportUserId 读取消息的用户
- * @param peerUserId 发送消息的用户
- */
- public void adminSetMsgRead(String reportUserId, String peerUserId) {
- Integer random = RandomUtils.nextInt(0, 999999999);
- String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.ADMIN_SET_MSG_READ.getUrl(), random);
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("Report_Account", reportUserId);
- jsonObject.put("Peer_Account", peerUserId);
- log.info("腾讯云im设置单聊消息已读,请求参数:{}", jsonObject.toString());
- String result = HttpClientUtils.doPost(httpsUrl, jsonObject);
- log.info("腾讯云im设置单聊消息已读,返回结果:{}", result);
- }
- }
到这一步已经差不多了,可以愉快的开始开发了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。