实现微信公众账号推送功能

    1.首先你要有个手机号 申请个测试信息

    2.然后就可以开始写了

    a.获取用户accessToken

  

public String getToken(String appid, String secrect) {
		String urlStr = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid
				+ "&secret=" + secrect;
		String res = requestInterface(urlStr);
		JSONObject jsonObj = JSONObject.fromObject(res);
		return (String) jsonObj.get("access_token");
	}
   b.通过token获取用户列表

	public List<String> getUserId(String token) {
		String requst_url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + token + "&next_openid=";
		List<String> userList = new ArrayList<String>();
		String res = requestInterface(requst_url);
		JSONObject dataObj = JSONObject.fromObject(res);
		JSONObject openidObj = JSONObject.fromObject(dataObj.get("data"));
		String[] openidStr = openidObj.get("openid").toString().replace("[", "").replace("]", "").split(",");
		for (String openid : openidStr) {
			userList.add(openid.replaceAll("\"", ""));
		}
		return userList;
	}

  c.发送模板消息接口

public boolean do_push_Template(String token, String userId, String template_id, String url, String data) {
		String requst_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("touser", userId);
		map.put("template_id", template_id);
		map.put("url", url);
		map.put("data", data);
		String response = HttpRequest.sendPost2(requst_url, map,null);
		JSONObject responseObj = JSONObject.fromObject(response);
		String responseFlag = responseObj.get("errmsg").toString();
		System.out.println("response:" + responseFlag);
		if (responseFlag.equals("ok")) {
			return true;
		} else {
			return false;
		}


3.把三个接口串起来就可以实现微信推送功能了

String token = new WechatPush().getToken("xx", "xx");
		List<String> list = new WechatPush().getUserId(token);
		Map<String,Object> dataMap=new HashMap<String,Object>();
		dataMap.put("All_testcases", 52);
		dataMap.put("Pass_testcases", 52);
		dataMap.put("Fail_testcases", 52);
		dataMap.put("Error_testcases", 52);
		dataMap.put("Pass_rate", 52);
		dataMap.put("Report_name", 52);
		String data=JSONObject.fromObject(dataMap).toString();
		System.out.println(data);
		boolean flag=new WechatPush().do_push_Template(token, list.get(0), "xx",
				"https://api.weixin.qq.com/cgi-bin/message",data );
		System.out.println(flag);

4.文章中的HttpRequest.sendPost2可以访问文章 关于要访问http和https地址,post访问的参数map对象


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值