Java微信公众号开发之标签管理、分组管理(全)

用户标签(分组)管理

开发者可以使用用户标签管理的相关接口,实现对公众号的标签进行创建、查询、修改、删除等操作,也可以对用户进行打标签、取消标签等操作。

注意:标签管理即分组管理,把url里面的tags换成groups的效果一样。

 

1. 创建标签

一个公众号,最多可以创建100个标签。

接口调用请求说明

http请求方式:POST(请使用https协议)
https://api.weixin.qq.com/cgi-bin/tags/create?access_token=ACCESS_TOKEN

POST数据格式:JSON 
POST数据示例:

{   "tag" : {     "name" : "广东"//标签名   } }

参数说明

参数说明
access_token调用接口凭据
name标签名(30个字符以内)

返回说明(正常时返回的json数据包示例)

{   "tag":{ "id":134,//标签id "name":"广东"   } }

返回参数说明

参数说明
id标签id,由微信分配
name标签名,UTF8编码

错误码说明

错误码说明
-1系统繁忙
45157标签名非法,请注意不能和其他标签重名
45158标签名长度超过30个字节
45056创建的标签数过多,请注意不能超过100个

 创建分组程序Java实现代码:

	/**
     * 创建群组
     * @param appId
     * @param appSecret
     * @param groupName 群组名称
     * @return 如{"group": { "id": 107, "name": "test" } }
     */
	public static JSONObject createGroup(String appId, String appSecret, String groupName){
		String url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=" + AccessTokenInfo.accessToken.getAccessToken();
		JSONObject j = new JSONObject();
		JSONObject group = new JSONObject();
		try {
			j.put("name",groupName);
            group.put("group",j);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		String rtn = weixinRequest(url, group.toString(), "POST");
		System.out.println("创建群组:"+rtn);
		JSONObject json;
		try {
			json = new JSONObject(JSON.parseObject(rtn));
		} catch (JSONException e) {
			throw new RuntimeException(e.getMessage(),e);
		}
		return json;
	}

2. 获取公众号已创建的标签

接口调用请求说明

http请求方式:GET(请使用https协议) 
https://api.weixin.qq.com/cgi-bin/tags/get?access_token=ACCESS_TOKEN

返回说明

{   "tags":[{       "id":1,       "name":"每天一罐可乐星人",       "count":0 //此标签下粉丝数 },{   "id":2,   "name":"星标组",   "count":0 },{   "id":127,   "name":"广东",   "count":5 }   ] }

 查询所有分组程序Java实现代码:

    /**
     * 查询所有分组
     * @param appId
     * @param appSecret
     * @return
     */
    public static JSONObject getAllGroups(String appId, String appSecret){
        String url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=" + AccessTokenInfo.accessToken.getAccessToken();
        //https://api.weixin.qq.com/cgi-bin/tags/get?access_token=ACCESS_TOKEN
        String rtn = weixinRequest(url, null, "GET");
        System.out.println("分组信息:"+rtn);
        JSONObject json;
        try {
            json = new JSONObject(JSON.parseObject(rtn));
        } catch (JSONException e) {
            throw new RuntimeException(e.getMessage(),e);
        }
        return json;
    }

3. 编辑标签

接口调用请求说明

http请求方式:POST(请使用https协议)
https://api.weixin.qq.com/cgi-bin/tags/update?access_token=ACCESS_TOKEN

POST数据格式:JSON 
POST数据例子:

{   "tag" : {     "id" : 134,     "name" : "广东人"   } }

返回说明

{   "errcode":0,   "errmsg":"ok" }

错误码说明

错误码说明
-1系统繁忙
45157标签名非法,请注意不能和其他标签重名
45158标签名长度超过30个字节
45058不能修改0/1/2这三个系统默认保留的标签

编辑标签程序Java实现代码: 

    /**
     * 修改分组名
     * @param appId
     * @param appSecret
     * @param groupId
     * @param newGroupName
     * @return 如 {"errcode": 0, "errmsg": "ok"}
     */
    public static JSONObject updateGroup(String appId, String appSecret, String groupId, String newGroupName){
        String url = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=" + AccessTokenInfo.accessToken.getAccessToken();
        JSONObject j = new JSONObject();
        JSONObject group = new JSONObject();
        try {
            j.put("id", groupId);
            j.put("name",newGroupName);
            group.put("group",j);
        } catch (JSONException e) {
            e.printStackTrace();
        }
       
        String rtn = weixinRequest(url, group.toString(), "POST");
        System.out.println("修改分组名:"+rtn);
        JSONObject json;
        try {
            json = new JSONObject(JSON.parseObject(rtn));
        } catch (JSONException e) {
            throw new RuntimeException(e.getMessage(),e);
        }
        return json;
    }

4. 删除标签

请注意,当某个标签下的粉丝超过10w时,后台不可直接删除标签。此时,开发者可以对该标签下的openid列表,先进行取消标签的操作,直到粉丝数不超过10w后,才可直接删除该标签。

接口调用请求说明

http请求方式:POST(请使用https协议) 
https://api.weixin.qq.com/cgi-bin/tags/delete?access_token=ACCESS_TOKEN

POST数据格式:JSON 
POST数据例子:

{   "tag":{        "id" : 134   } }

返回说明

{   "errcode":0,   "errmsg":"ok" }

错误码说明

错误码说明
-1系统繁忙
45058不能修改0/1/2这三个系统默认保留的标签
45057该标签下粉丝数超过10w,不允许直接删除

删除标签程序Java实现代码:  

	/**
     * 删除群组
     * @param appId
     * @param appSecret
     * @param groupName 群组名称
     * @return 如{"group": { "id": 107, "name": "test" } }
     */
	public static JSONObject deleteGroup(String appId, String appSecret, String groupName){
		String url = "https://api.weixin.qq.com/cgi-bin/groups/delete?access_token=" + AccessTokenInfo.accessToken.getAccessToken();
		JSONObject j = new JSONObject();
        JSONObject group = new JSONObject();
		try {
            j.put("id",groupName);
            group.put("group",j);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		String rtn = weixinRequest(url, group.toString(), "POST");
		System.out.println("deleteGroup()"+rtn);
		JSONObject json;
		try {
			json = new JSONObject(JSON.parseObject(rtn));
		} catch (JSONException e) {
			throw new RuntimeException(e.getMessage(),e);
		}
		return json;
	}

5. 获取标签下粉丝列表

接口调用请求说明

http请求方式:GET(请使用https协议) 
https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=ACCESS_TOKEN

POST数据格式:JSON 
POST数据例子:

{   "tagid" : 134,   "next_openid":""//第一个拉取的OPENID,不填默认从头开始拉取 }

返回说明(正常时返回的json包示例)

{   "count":2,//这次获取的粉丝数量   
"data":{//粉丝列表
"openid":[  
"ocYxcuAEy30bX0NXmGn4ypqx3tI0",    
"ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"  ]  
},  
"next_openid":"ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"//拉取列表最后一个用户的openid 
}

错误码说明

错误码说明
-1系统繁忙
40003传入非法的openid
45159非法的tag_id

获取标签下粉丝列表程序Java实现代码:  

    /**
     * 获取分组下粉丝列表
     * @param appId
     * @param appSecret
     * @param id 分组id
     * @return 如 {"errcode": 0, "errmsg": "ok"}
     */
    public static JSONObject ListGroup(String appId, String appSecret, String id){
        String url = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=" + AccessTokenInfo.accessToken.getAccessToken();
        JSONObject j = new JSONObject();
        try {
        	j.put("tagid",id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
       
        String rtn = weixinRequest(url, j.toString(), "GET");
        System.out.println("分组粉丝列表:"+rtn);
        JSONObject json;
        try {
            json = new JSONObject(JSON.parseObject(rtn));
        } catch (JSONException e) {
            throw new RuntimeException(e.getMessage(),e);
        }
        return json;
    }

6.移动用户分组

接口调用请求说明

http请求方式: POST(请使用https协议)
https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=ACCESS_TOKEN
POST数据格式:json
POST数据例子:{"openid":"oDF3iYx0ro3_7jD4HFRDfrjdCM58","to_groupid":108}

参数说明

参数说明
access_token调用接口凭证
openid用户唯一标识符
to_groupid分组id

返回说明 正常时的返回JSON数据包示例:

{"errcode": 0, "errmsg": "ok"}

错误时的JSON数据包示例(该示例为AppID无效错误):

{"errcode":40013,"errmsg":"invalid appid"}

移动用户分组程序Java实现代码:

    /**
     * 移动用户分组
     * @param appId
     * @param appSecret
     * @param toGroupId 新分组的id
     * @param openId 用户id
     * @return 如 {"errcode": 0, "errmsg": "ok"}
     */
    public static JSONObject updateUserGroup(String appId, String appSecret, String toGroupId, String openId){
        String url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=" + AccessTokenInfo.accessToken.getAccessToken();
        JSONObject j = new JSONObject();
        try {
            j.put("openid", openId);
            j.put("to_groupid", toGroupId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
       
        String rtn = weixinRequest(url, j.toString(), "POST");
        System.out.println("更新用户组:"+rtn);
        JSONObject json;
        try {
            json = new JSONObject(JSON.parseObject(rtn));
        } catch (JSONException e) {
            throw new RuntimeException(e.getMessage(),e);
        }
        return json;
    }

 7. 通过ID获取用户身上的标签

接口调用请求说明

http请求方式:POST(请使用https协议)
https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=ACCESS_TOKEN

POST数据格式:JSON 
POST数据例子:

{   "openid" : "ocYxcuBt0mRugKZ7tGAHPnUaOW7Y" }

错误码说明

错误码说明
-1系统繁忙
40003传入非法的openid
49003传入的openid不属于此AppID

 获取用户身上的标签程序Java实现代码:  

    /**
     * 通过用户的OpenID查询其所在的GroupID
     * @param appId
     * @param appSecret
     * @param openId 用户的OpenID
     * @return 如:{ "groupid": 102 }
     */
    public static JSONObject getUserGroup(String appId, String appSecret, String openId){
        String url = "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=" + AccessTokenInfo.accessToken.getAccessToken();
        JSONObject j = new JSONObject();
        try {
        	j.put("openid", openId);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
       
        String rtn = weixinRequest(url, j.toString(), "POST");
        System.out.println("用户分组:"+rtn);
        JSONObject json;
        try {
            json = new JSONObject(JSON.parseObject(rtn));
        } catch (JSONException e) {
            throw new RuntimeException(e.getMessage(),e);
        }
        return json;
    }

8.用户管理

标签功能目前支持公众号为用户打上最多20个标签。

1. 批量为用户打标签

接口调用请求说明

http请求方式:POST(请使用https协议)
https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=ACCESS_TOKEN

POST数据例子:

{   "openid_list" : [//粉丝列表    
"ocYxcuAEy30bX0NXmGn4ypqx3tI0",    
"ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"   ],   
"tagid" : 134 }

返回说明(正常时返回的json包示例)

{   
"errcode":0,   
"errmsg":"ok"
}

错误码说明

错误码说明
-1系统繁忙
40032每次传入的openid列表个数不能超过50个
45159非法的标签
45059有粉丝身上的标签数已经超过限制,即超过20个
40003传入非法的openid
49003传入的openid不属于此AppID

2. 批量为用户取消标签

接口调用请求说明

http请求方式:POST(请使用https协议) 
https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token=ACCESS_TOKEN

POST数据格式:JSON 
POST数据例子:

{   "openid_list" : [//粉丝列表     
"ocYxcuAEy30bX0NXmGn4ypqx3tI0",     
"ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"   ],   
"tagid" : 134 }

返回说明(正常时返回的json包示例)

{  
"errcode":0,   
"errmsg":"ok"
}

错误码说明

错误码说明
-1系统繁忙
40032每次传入的openid列表个数不能超过50个
45159非法的标签
40003传入非法的openid
49003传入的openid不属于此AppID

9.工具类

    private static String weixinRequest(String urlStr, String data, String method){
		try {
			System.setProperty("jsse.enableSNIExtension", "false");
			
//			SSLContext ctx = SSLContext.getInstance("TLS");
//			SSLSocketFactory factory = ctx.getSocketFactory();
			
			URL url = new URL(urlStr);
			HttpsURLConnection http = (HttpsURLConnection) url.openConnection();
			http.setHostnameVerifier(new HostnameVerifier(){
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });
//			http.setSSLSocketFactory(factory);
			if(method == null || "".equals(method))method = "GET";
			http.setRequestMethod(method);
			http.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			if(data != null && !"".equals(data)){
				OutputStream os = http.getOutputStream();
				os.write(data.getBytes("UTF-8"));// 传入参数
				os.flush();
				os.close();
			}

			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			return message;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(),e);
		}
	}

全部代码https://download.csdn.net/download/u011752195/10721016

如果缺少工具包请参考https://download.csdn.net/download/u011752195/10721024  包括commons-codec-1.9 commons-httpclient-3.0 commons-logging-1.2 dom4j-2.0.2 fastjson-1.2.49 httpcore-4.4.3

整个下来通过网络资源整理学习,并且完善了一些代码,程序员挺累的

如果觉得不错可以点歌关注吧~

后续将分享更多程序代码~

合作请联系chat 1012638162

有问题可以在下面提出来~

如果本文对您有一丢丢帮助,可以通过下方二维码支持作者哦 后续将分享更多高质量代码~

        Alipay                    WeChat

      

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值