springmvc微信发送模板消息java

springmvc微信发送模板消息java

直接上代码
1.首先需要申请formId,并且清楚自己的模板样式
在这里插入图片描述

  1. 创建模板实体类(Data,Content)

    	public class Data {
    	    private  Content keyword1;
    	    private  Content keyword2;
    	    private  Content keyword3;
    	    private  Content keyword4;
    	    private  Content keyword5;
    		public Content getKeyword1() {
    			return keyword1;
    		}
    		public void setKeyword1(Content keyword1) {
    			this.keyword1 = keyword1;
    		}
    		public Content getKeyword2() {
    			return keyword2;
    		}
    		public void setKeyword2(Content keyword2) {
    			this.keyword2 = keyword2;
    		}
    		public Content getKeyword3() {
    			return keyword3;
    		}
    		public void setKeyword3(Content keyword3) {
    			this.keyword3 = keyword3;
    		}
    		public Content getKeyword4() {
    			return keyword4;
    		}
    		public void setKeyword4(Content keyword4) {
    			this.keyword4 = keyword4;
    		}
    		public Content getKeyword5() {
    			return keyword5;
    		}
    		public void setKeyword5(Content keyword5) {
    			this.keyword5 = keyword5;
    		}	
    	}
    	public class Content {
    		//消息内容
    	    private String value;
    	
    	    //消息字体颜色
    	    private String color;
    	
    		public String getValue() {
    			return value;
    		}
    
    	public void setValue(String value) {
    		this.value = value;
    	}
    
    	public String getColor() {
    		return color;
    	}
    
    	public void setColor(String color) {
    		this.color = color;
    	} 
    }
    
    
    
  2. controller层代码

    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import com.alibaba.fastjson.JSON;
    import com.sxt.entity.PageResult;
    import com.sxt.service.SendTemplateService;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import io.swagger.annotations.ApiParam;
    
    @Controller
    public class SendTemplateController {
    
    	@Autowired
    	private SendTemplateService sendTemplateService;
    	
    	/**
    	 * 消息模板推送
    	 */
    	@RequestMapping(value="/sendTemplate",method=RequestMethod.POST)
    	@ResponseBody
    	public PageResult sendTemplate(@RequestParam Integer userId,
    			@RequestParam(required=false) String value1,
    			@RequestParam String value2,
    			@RequestParam String value3,
    			@RequestParam String value4
    			){
    		
    		Data data=new Data();
    	
    		Content content1=new Content();
    		
    		content1.setValue(value1);
    		
    		data.setKeyword1(content1);
    		
    		Content content2=new Content();
    		
    		content2.setValue(value2);
    		
    		data.setKeyword2(content2);
    		
    		
    		Content content3=new Content();
    		
    		DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		
    		String dateStr = format.format(new Date());
    		
    		content3.setValue(dateStr);
    		
    		data.setKeyword3(content3);
    		
    		Content content4=new Content();
    		
    		content4.setValue(value3);
    		
    		data.setKeyword4(content4);
    		
    		Content content5=new Content();
    		
    		content5.setValue(value4);
    		
    		data.setKeyword5(content5);
    	
    	
    	return sendTemplateService.sendTemplateService(id, data);
    		
    		
    		
    	}
    }
    
    

4.service层(这里access_token是从数据库中存储和查找的,通过判断创建时间是否大于7200秒,mapper层用的是mybatis逆向工程)

	
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.sxt.domain.TbAccessToken;
import com.sxt.domain.TbAccessTokenExample;
import com.sxt.domain.TbFormid;
import com.sxt.domain.TbFormidExample;
import com.sxt.domain.TbFormidExample.Criteria;
import com.sxt.domain.TbWxuser;
import com.sxt.entity.PageResult;
import com.sxt.mapper.TbAccessTokenMapper;
import com.sxt.mapper.TbFormidMapper;
import com.sxt.mapper.TbWxuserMapper;
import com.sxt.service.SendTemplateService;
import com.sxt.util.ResourceUtil;
import com.sxt.util.WxUtil;
@Service
public class SendTemplateServiceImpl implements SendTemplateService {

	@Autowired
	private TbAccessTokenMapper tbAccessTokenMapper;
	
	@Autowired
	private TbWxuserMapper tbWxuserMapper;
	
	@Autowired
	private TbFormidMapper tbFormidMapper;
	/**
	 * 发送模板消息
	 */
	@Override
	public PageResult sendTemplateService(Integer userId,Map<String, Object> data) {
		// TODO Auto-generated method stub
		//获取最新access_token
		TbAccessTokenExample example=new TbAccessTokenExample();
		
		example.setOrderByClause("create_time desc");
		
		com.sxt.domain.TbAccessTokenExample.Criteria criteria = example.createCriteria();
		
		//type=0为小程序token,1为公众号token
		criteria.andTypeEqualTo(0);
		
		List<TbAccessToken> tokenList = tbAccessTokenMapper.selectByExample(example);
		
		String accessToken=null;
		
		boolean flag=true;
		
		if(tokenList!=null&&tokenList.size()>0){
			TbAccessToken tbAccessToken = tokenList.get(0);
			
			String access_token = tbAccessToken.getAccessToken();
			
			Date createTime = tbAccessToken.getCreateTime();
			
			 long diff = (new Date().getTime() - createTime.getTime())/1000;//这样得到的差值是毫秒级别
			 
			 System.out.println("相隔秒数:"+diff);
			 
			 if(diff<7000){
				 
				accessToken=access_token;
				 
				flag=false;
				 
			 }
		}
		
		//如果没有可用access_token 调微信接口
		if(flag){
			//配置文件中读取appid,secret (代码补充在后面)
			String appid = ResourceUtil.getKey("app", "appid");
			
			String secret = ResourceUtil.getKey("app", "secret");
			//自己封装的rpc get方法工具类WxUtil(代码补充在后面)
			 JSONObject access_tokenJsonObject = WxUtil.wxGetUtil("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret);
			 
			 accessToken = access_tokenJsonObject.getString("access_token");
			 
			 TbAccessToken tbAccessToken=new TbAccessToken();
			 
			 tbAccessToken.setAccessToken(accessToken);
			 
			 tbAccessToken.setType(0);
			 
			 tbAccessTokenMapper.insertSelective(tbAccessToken);
		}
		
		
		
		System.out.println("access_token:"+accessToken);
		//判断用户是否存在
		TbWxuser wxUser = tbWxuserMapper.selectByPrimaryKey(userId);
		
		if(wxUser==null){
			return new PageResult(0, "用户不存在", null);
		}
		//进入正题:调wx模板发送接口
		StringBuilder url = new StringBuilder("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=");
	    url.append(accessToken);//设置accesstoken
	    JSONObject json = new JSONObject();
	   json.put("touser", wxUser.getOpenid());//设置openid
	
	    String templateId = ResourceUtil.getKey("template", "templateId");
	    
	    //查询该用户最近未使用的fromid(也是存在数据库中,有效期7天,设置的是用户点击一次按钮,存一次formid)
	    TbFormidExample example2=new TbFormidExample();
	    
	    example2.setOrderByClause("create_time desc");
	    
	    Criteria criteria2 = example2.createCriteria();
	    
	    criteria2.andUserIdEqualTo(userId);
	    
	    criteria2.andStatusEqualTo(0);
	    
	    List<TbFormid> formList = tbFormidMapper.selectByExample(example2);
	    
	    if(formList==null||formList.size()==0){
	    	return new PageResult(0, "fromid不存在", null);
	    }
	    TbFormid form = formList.get(0);
	    
	   json.put("template_id", templateId);//设置模板id
	    json.put("form_id", form.getFormId());//设置formid
	    json.put("data", data);//设置模板消息内容
	    json.put("page", "/pages/loading/loading");//跳转微信小程序页面路径(非必须)
	   
		try {
		    HttpClient client =HttpClientBuilder.create().build();//构建一个Client
	        HttpPost post = new HttpPost(url.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请求
	        
	        System.out.println("response:"+response);
	        HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
	        
	        System.out.println("result:"+result);
	        String content = EntityUtils.toString(result);        
	        System.out.println(content);//打印返回的消息
	        JSONObject res = JSONObject.parseObject(content);//转为json格式
		    //把信息封装到map
		    //map = MdzwUtils.parseJSON2Map(res);
			if(res != null && "ok".equals(res.getString("errmsg"))) {
				System.out.println("模版消息发送成功");
				
				//formid失效
				form.setStatus(5);
				
				tbFormidMapper.updateByPrimaryKeySelective(form);
				
				
			}else {
				//封装一个异常
				StringBuilder sb = new StringBuilder("模版消息发送失败\n");
				//sb.append(map.toString());
				System.out.println(sb.toString());
				
				System.out.println("res:"+res);
				//throw new Exception(content);
			}
			
			
		} catch (Exception e) {
		        e.printStackTrace();
	    }
		return null;
	}

}

	
  1. 读取properties配置文件工具类

package com.sxt.util;

import java.util.ResourceBundle;

public class ResourceUtil {
	private static ResourceBundle resourceBundle;
	 
	/**
	 * 获取配置文件中的信息
	 * @param path
	 * @param key
	 * @return
	 */
    public static String getKey(String path,String key){
    	
    	resourceBundle = ResourceBundle.getBundle(path);
    
        return resourceBundle.getString(key);
    }
	
}

6.rpc get调用

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

public class WxUtil {
	public static  JSONObject wxGetUtil(String url){
		//RPC调用
		URI uri = URI.create(url);
		HttpClient client = HttpClients.createDefault();
		HttpGet get = new HttpGet(uri);
		
		HttpResponse response;
		try {
			response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				
				BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
				StringBuilder sb = new StringBuilder();
				
				for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
					sb.append(temp);
				}
				JSONObject object = JSON.parseObject(sb.toString());
				
				return object;
				
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block 
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值