微信公众平台发送模板消息

1.申请测试用的公众号

申请地址

扫描后获得appid和secret

2.获取access_token

https请求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

3.获取用户openid(关注公众号的用户对应该公众号唯一id)

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

4.发送模板消息

http请求方式: POST
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN

 参数格式

{
           "touser":"OPENID",
           "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
           "url":"http://weixin.qq.com/download",            
           "data":{
                   "first": {
                       "value":"恭喜你购买成功!",
                       "color":"#173177"
                   }
           }
       }

5完整代码

流程:获取token -> 获取所有用户openid ->遍历openid 发送模板消息

package wxtemp;

import java.io.IOException;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class test {

	static String secret = "xxxxxxxxx";
	static String appid = "xxxxxxxx";
	static String tokenurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}";
	static String userlisturl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=${token}";
	static String sendtempurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${token}";
	static String userinfourl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=${token}&openid=${openid}&lang=zh_CN";
	static String tempid = "xxxxxxx";

	public static void main(String args[]) {

		// String entityJson=JSONObject.fromObject(a).toString();
		testwxtemp();
	}

	public static String createJson(String openid, String tempid, String namestr) {

		JSONObject jo = new JSONObject();
		jo.put("touser", openid);
		jo.put("template_id", tempid);
		jo.put("url", "http://baidu.com");
		JSONObject data = new JSONObject();

		JSONObject name = new JSONObject();
		name.put("value", namestr);
		name.put("color", "#173177");

		JSONObject time = new JSONObject();
		time.put("value", new Date().toString());
		time.put("color", "#173177");

		data.put("name", name);
		data.put("time", time);

		jo.put("data", data);

		return jo.toString();
	}

	public static void testwxtemp() {

		String token = getToken();

		JSONArray openids = getOpenids(token);

		for (int i = 0; i < openids.size(); i++) {
			System.out.println(openids.get(i));

			String openid = openids.getString(i);

			String tempjsonstr = test.createJson(openid, tempid, test.getName(token, openid));

			System.out.println("==========>" + post(sendtempurl.replace("${token}", token), tempjsonstr));
		}
	}

	public static String getName(String token, String openid) {

		String jsonstr = get(userinfourl.replace("${token}", token).replace("${openid}", openid));
		JSONObject obj = JSONObject.fromObject(jsonstr);
		return obj.getString("nickname");
	}

	public static String getToken() {
		String jsonstr = get(tokenurl.replace("${appid}", appid).replace("${secret}", secret));
		JSONObject obj = JSONObject.fromObject(jsonstr);
		return obj.getString("access_token");
	}

	public static JSONArray getOpenids(String token) {
		String usrlistjson = get(userlisturl.replace("${token}", token));
		System.out.println(usrlistjson);
		JSONObject usrjo = JSONObject.fromObject(usrlistjson);
		JSONObject data = usrjo.getJSONObject("data");
		JSONArray openids = data.getJSONArray("openid");
		return openids;
	}

	public static String get(String url) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet getMethod = new HttpGet(url);
		HttpResponse response;
		try {
			response = httpclient.execute(getMethod);
			return EntityUtils.toString(response.getEntity());
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static String post(String url, String entityJson) {
		HttpPost httpost = new HttpPost(url); // 设置响应头信息
		httpost.addHeader("Content-Type", "application/json; charset=UTF-8");
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();// 设置请求和传输超时时间
		httpost.setConfig(requestConfig);
		httpost.setEntity(new StringEntity(entityJson, "UTF-8"));
		String returnStr = null;
		try {
			HttpResponse response = HttpClientBuilder.create().build().execute(httpost);
			returnStr = EntityUtils.toString(response.getEntity(), "utf-8");

		} catch (Exception e) {
		} finally {
			httpost.releaseConnection();
		}
		return returnStr;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值