给微信小程序发送消息
所用技术:后台:jeecgboot 数据库:oracle 前台:vue2.0
首先登陆微信公众平台
链接: https://mp.weixin.qq.com/
1.登陆之后每个公司 都会有自己得相关参数例如 appid之类得 后面代码里时要用到的
2.然后先择一个适合自己的模板,也可以自己去申请一个但是微信审核时间比较长所以我直接挑选一个比较适合我自己的
3.发送消息主体代码
1.我的需要用到的参数是写在配置文件里的
@Value("${WXxcx.appid}")private String appid;//公众平台的企业appid(微信小程序的)@Value("${WXxcx.secret}")private String secret;//公众平台的企业secret小程序密钥@Value("${WXgzh.appid}")private String appidgzh;//公众号的appid@Value("${WXgzh.template_id}")private String template_id;//模板id
这里解释下:content是前台通过微信提供的接口获取到的传给后台的 ,就类似于微信需要的临时token一样。processname是我的业务需求是个用户名,传值可以根据自己业务需求定义
/*** 推送* @param content = appid* processname 流程名称* @return*/@ResponseBody@RequestMapping(value = "/testPush", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")public String push(@RequestParam(name = "content", required = true) String content,@RequestParam(name = "processname", required = true) String processname) {//获取需要推送的用户openidString openid= content;//获取用户tokenString token = getAccessToken();//封装单独的 方法String resultStatus = "0";//0:成功,1:失败try {//小程序统一消息推送String path = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=" + token;//封装参数JSONObject jsonData = new JSONObject();//小程序用户的openidjsonData.put("touser", openid);JSONObject jsonObject = new JSONObject();//公众号APPIDjsonObject.put("appid", appidgzh);//公众号模板IDjsonObject.put("template_id", template_id);//公众号模板消息所要跳转的url//jsonObject.put("url","https://blog.csdn.net/qq_46122292/article/details/124961251");//公众号模板消息所要跳转的小程序,小程序的必须与公众号具有绑定关系JSONObject miniprogram = new JSONObject();//小程序APPIDminiprogram.put("appid",appid);//跳转到小程序的页面路径//miniprogram.put("pagepath","pages/login/login");jsonObject.put("miniprogram", miniprogram);//公众号消息数据封装JSONObject data = new JSONObject();Date time = new Date();//获取当前时间SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");String strdate = dateformat.format(time);//此处的参数key,需要对照模板中的key来设置remark//data.put("first",getValue("你好"));data.put("keyword1",getValue(processname));data.put("keyword2",getValue("审批中"));data.put("keyword3",getValue(strdate));//data.put("remark",getValue("你好"));jsonObject.put("data", data);jsonData.put("mp_template_msg", jsonObject);System.out.println("请求参数:"+jsonData);String s = HttpUtils.doPost(path, jsonData.toString(),token);System.out.println("返回结果:"+s);resultStatus="发送成功!";} catch (Exception e) {//log.error("微信公众号发送消息失败!",e.getMessage());resultStatus="发送消息失败!";}return resultStatus;}
4.获取token是微信提供的接口只需要用appid 跟secret 两个参数请求就会返回token
/*** @Description: 微信公众号推送消息* @Author: 测试* @Date: 2022-08* @Version: V1.0*/
@Api(tags="微信公众号推送消息")
@RestController
@RequestMapping("/system/weiXinPushMessage")
public class WeiXinPushMessageController {@Value("${WXxcx.appid}")private String appid;//公众平台的企业appid(微信小程序的)@Value("${WXxcx.secret}")private String secret;//公众平台的企业secret小程序密钥@Value("${WXgzh.appid}")private String appidgzh;//公众号的appid@Value("${WXgzh.template_id}")private String template_id;//模板id/*** 获取token* @return*/public String getAccessToken() {RestTemplate restTemplate = new RestTemplate();Map<String, String> params = new HashMap<>();params.put("APPID", appid);params.put("APPSECRET", secret);params.put("grant_type", "client_credential");String tokenUrl="https://api.weixin.qq.com/cgi-bin/token?appid={APPID}&secret={APPSECRET}&grant_type={grant_type}";ResponseEntity<String> responseEntity = restTemplate.getForEntity(tokenUrl, String.class, params);String body = responseEntity.getBody();JSONObject object = JSONObject.fromObject(body);String access_Token = object.getString("access_token");System.err.println("access_Token:"+access_Token);return access_Token;}/*** 推送* @param content* processname 流程名称* @return*/@ResponseBody@RequestMapping(value = "/testPush", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")public String push(@RequestParam(name = "content", required = true) String content,@RequestParam(name = "processname", required = true) String processname) {//获取需要推送的用户openidString openid= content;//获取用户tokenString token = getAccessToken();String resultStatus = "0";//0:成功,1:失败try {//小程序统一消息推送String path = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=" + token;//封装参数JSONObject jsonData = new JSONObject();//小程序用户的openidjsonData.put("touser", openid);JSONObject jsonObject = new JSONObject();//公众号APPIDjsonObject.put("appid", appidgzh);//公众号模板IDjsonObject.put("template_id", template_id);//公众号模板消息所要跳转的url//jsonObject.put("url", "https://blog.csdn.net/qq_46122292/article/details/124961251");//公众号模板消息所要跳转的小程序,小程序的必须与公众号具有绑定关系JSONObject miniprogram = new JSONObject();//小程序APPIDminiprogram.put("appid",appid);//跳转到小程序的页面路径//miniprogram.put("pagepath","pages/login/login");jsonObject.put("miniprogram", miniprogram);//公众号消息数据封装JSONObject data = new JSONObject();Date time = new Date();//获取当前时间SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");String strdate = dateformat.format(time);//此处的参数key,需要对照模板中的key来设置remark//data.put("first",getValue("你好"));data.put("keyword1",getValue(processname));data.put("keyword2",getValue("审批中"));data.put("keyword3",getValue(strdate));//data.put("remark",getValue("你好"));jsonObject.put("data", data);jsonData.put("mp_template_msg", jsonObject);System.out.println("请求参数:"+jsonData);//请求头String s = HttpUtils.doPost(path, jsonData.toString(),token);System.out.println("返回结果:"+s);resultStatus="发送成功!";} catch (Exception e) {//log.error("微信公众号发送消息失败!",e.getMessage());resultStatus="发送消息失败!";}return resultStatus;}/*** 获取data,模板的字体颜色* @param value* @return*/private JSONObject getValue(String value) {// TODO Auto-generated method stubJSONObject json = new JSONObject();json.put("value", value);json.put("color", "#173177");return json;}}
5.最后这个JSONObject 方法只是定义模板的字体颜色跟样式 直接粘过去用就可以 不需要改什么
6.请求头设置
public static String doPost(String url,String json,String token) {String retStr = "";// 创建HttpClientBuilderHttpClientBuilder httpClientBuilder = HttpClientBuilder.create();// HttpClientCloseableHttpClient closeableHttpClient = httpClientBuilder.build();HttpPost httpPost = new HttpPost(url);// 设置请求和传输超时时间RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();httpPost.setConfig(requestConfig);try {//httpPost.setHeader("token", token);StringEntity data = new StringEntity(json,Charset.forName("UTF-8"));data.setContentEncoding("UTF-8");data.setContentType("application/json");httpPost.setEntity(data);CloseableHttpResponse response = closeableHttpClient.execute(httpPost);HttpEntity httpEntity = response.getEntity();if (httpEntity != null) {// 打印响应内容retStr = EntityUtils.toString(httpEntity, "UTF-8");}// 释放资源closeableHttpClient.close();} catch (Exception e) {System.out.println(e);}return retStr;}
此代码本人亲测有效,有什么问题 还请各路大神指点。