首先,获取微信公众号配置
1. 登录微信公众平台,查看APPID,appsecret
2. 获取到这俩关键值后,还是平台页面,往下滑找到开发配置 -》基本配置 -》IP白名单,点击查看,添加上你服务器的IP地址,可以通过换行来添加多个,确定修改,需要管理员扫码确认,OK,配置完成。
开始开发:
客服消息—发消息 点击查看微信官方文档
微信公众平台在线调试 点击前往
1. 获取微信的access_token,传入APPID,appsecret(注意:请求ip必须在APPID对应的公众号的ip白名单)
/**
* @Description: 获取access_token
* @author: Hanweihu
* @date: 2019/7/12 11:14
* @param: [appid, appsecret]
* @return: java.lang.String
*/
public String getAccess_token(String appid, String appsecret) {
// 先判断redis中是否存在
String token = redisTemplate.opsForValue().get(自定义key);
if (StringUtils.isBlank(token) == false) {
// token还未过期,获取后直接返回,无需重新获取
return token;
}
// token已过期或不存在,需重新获取
redisTemplate.delete(自定义key);
String access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + appid + "&secret=" + appsecret;
String message = "";
try {
URL url = new URL(access_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
//获取返回的字符
InputStream inputStream = connection.getInputStream();
int size = inputStream.available();
byte[] bs = new byte[size];
inputStream.read(bs);
message = new String(bs, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
//获取access_token
JSONObject jsonObject = JSONObject.fromObject(message);
log.info("======获取公众号平台的access_token:" + jsonObject.toString());
String accessToken = jsonObject.getString("access_token");
String expires_in = jsonObject.getString("expires_in");
// 防止代码运行超时,提前1分钟让微信token失效
redisTemplate.opsForValue().set(自定义key, accessToken, Integer.valueOf(expires_in) - 60, TimeUnit.SECONDS);
return accessToken;
}
2. 成功获取到access_token后,就可以根据文档来发客服消息了
/**
* @Description: 微信--推送客服消息
* @author: Hanweihu
* @date: 2019/7/15 14:28
* @param: [unionid]
* @return: void
*/
@RequestMapping(value = "/pushWxAdmin", method = RequestMethod.POST)
@ApiOperation("微信--推送客服消息")
public void pushWxAdmin(String unionid) {
// unionid是用来查询用户下单信息的,查到信息后推送给管理员。
if (StringUtils.isBlank(unionid)) {
return;
}
// 调用上面的方法,获取AccessToken,传入APPID,appsecret
String wxAccessToken = getAccess_token(APPID, appsecret);
if (StringUtils.isBlank(wxAccessToken)) {
return;
}
// 查询用户下单信息
// ==省略查数据库代码,CustomerSignUp为数据实体类,你们自定义
CustomerSignUp customerSignUp = customerSignUpList.get(0);
StringBuffer stringBuffer = new StringBuffer("");
stringBuffer.append("姓名:" + customerSignUp.getCustomerName() + "\n");
stringBuffer.append("电话:" + customerSignUp.getCustomerPhone() + "\n");
stringBuffer.append("身份证号:" + customerSignUp.getCustomerIdCard() + "\n");
stringBuffer.append("公司名称:" + customerSignUp.getCustomerCompanyName() + "\n");
stringBuffer.append("助教姓名:" + customerSignUp.getHelpTeachName() + "\n");
stringBuffer.append("助教公司:" + customerSignUp.getHelpTeachCompanyName() + "\n");
stringBuffer.append("支付时间:" + sdf.format(customerSignUp.getCreateDate()) + "\n");
stringBuffer.append("支付状态:" + (customerSignUp.getPayStatus() == 2 ? "已支付" : "未支付"));
// 获取admin的openID
String admin_openid = "";
if (StringUtils.isBlank(admin_openid) == false) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("content", stringBuffer.toString());
wxProPushMessage(admin_openid, wxAccessToken, jsonObject);
}
}
/**
* @Description: 只给管理员发送客户报名成功消息
* @author: Hanweihu
* @date: 2019/7/12 11:25
* @param:
* @return: void
*/
public void wxProPushMessage(String touser, String accesstoken, String data) {
StringBuilder requestUrl = new StringBuilder("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=");
requestUrl.append(accesstoken);
JSONObject json = new JSONObject();
json.put("touser", touser);// 设置openid
json.put("msgtype", "text");// 设置消息类型
json.put("text", data);// 设置模板消息内容
log.info("推送消息:" + json.toString());
Map<String, Object> map = null;
try {
HttpClient client = HttpClientBuilder.create().build();//构建一个Client
HttpPost post = new HttpPost(requestUrl.toString());//构建一个POST请求
StringEntity s = new StringEntity(json.toString(), "UTF-8");
s.setContentEncoding("UTF-8");
s.setContentType("application/json; charset=UTF-8");
post.setEntity(s);//设置编码,不然模板内容会乱码
HttpResponse response = client.execute(post);//提交POST请求
HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
String content = EntityUtils.toString(result);
System.out.println(content);//打印返回的消息
JSONObject res = JSONObject.fromObject(content);//转为json格式
//把信息封装到map
if (res != null && "ok".equals(res.get("errmsg"))) {
System.out.println("模版消息发送成功");
} else {
//封装一个异常
StringBuilder sb = new StringBuilder("模版消息发送失败\n");
sb.append(map.toString());
throw new Exception(sb.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
关键地方提醒一下:
1. 请求ip必须在APPID对应的公众号的ip白名单,不然导致获取不到access_token
2. IP白名单可以通过换行来添加多个
3. 拼接内容时,换行用 “\n”
4. 最终发送的json串必须与文档的key保持一致
{
"touser":"OPENID",
"msgtype":"text",
"text":
{
"content":"Hello World"
}
}