微信小程序模板消息发送功能实现

前言:发送微信模板消息首先需要用户去绑定openId和serverOpenId才能推送模板消息.

1.微信配置项

 

1.微信小程序根据前端返回的code去获取unionId和openid 通过type=0的接口去请求

 

 

2.用户获取到unionId和openId之后插入表中 就是用户登录微信小程序时 请求的是type=0的接口

 3.得到用户的open和unionId之后 去请求type=1的接口 获取到serverOpenId(重点),通过unionId找到用户并且插入serverOpenId进去

4.做完准备工作之后,我们就需要完成下面真正的功能了  发送微信模板公众号 ,请求三方接口的工具类

 

package cn.abtu.config;


import cn.abtu.parent.mapper.TaskMapper;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class WechatApi {
    @Value("${wechat.server.appid}")
    private String appid;

    @Value("${wechat.server.secret}")
    private String secret;

    @Value("${wechat.template_id0}")
    private String template_id0;

    @Value("${wechat.template_id1}")
    private String template_id1;

    @Value("${wechat.template_id2}")
    private String template_id2;

    @Value("${wechat.template_id3}")
    private String template_id3;
    @Autowired
    public RedisTemplate redisTemplate;

  /*  @Autowired
    private ITaskService taskService;

    @Autowired
    private AsyncTaskManager asyncTaskManager;*/

    @Autowired
    private TaskMapper taskMapper;

    public static void main(String[] args) {
        System.out.println("====");
        WechatApi wa = new WechatApi();
        wa.appid = "wx43a4c47b16c76ff2";
        wa.secret = "5ebdcd41ebb802eeb2057c6d5a221243";
        wa.get_access_token();

    }

    public static String sendRequest(String urlParam,String requestType) {

        HttpURLConnection con = null;

        BufferedReader buffer = null;
        StringBuffer resultBuffer = null;

        try {
            URL url = new URL(urlParam);
            //得到连接对象
            con = (HttpURLConnection) url.openConnection();
            //设置请求类型
            con.setRequestMethod(requestType);
            //设置请求需要返回的数据类型和字符集类型
            con.setRequestProperty("Content-Type", "application/json;charset=GBK");
            //允许写出
            con.setDoOutput(true);
            //允许读入
            con.setDoInput(true);
            //不使用缓存
            con.setUseCaches(false);
            //得到响应码
            int responseCode = con.getResponseCode();

            if(responseCode == HttpURLConnection.HTTP_OK){
                //得到响应流
                InputStream inputStream = con.getInputStream();
                //将响应流转换成字符串
                resultBuffer = new StringBuffer();
                String line;
                buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
                while ((line = buffer.readLine()) != null) {
                    resultBuffer.append(line);
                }
                return resultBuffer.toString();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public String get_access_token() {
        try {
            // 如果redis有,直接走redis
            Object access_token = redisTemplate.opsForValue().get("access_token");
            System.err.println(access_token);
            if(access_token != null){
                return access_token.toString();
            }
            Integer t=7000;
            // 没有验证数据库
            JSONObject wx_access_token = taskMapper.getWxAccessToken();
            if (wx_access_token == null){
                if(taskMapper.checkWxAccessToken() == 0){
                    taskMapper.insertAccessToken("");
                }
                String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
                String req = sendRequest(url,"GET");
                JSONObject object = JSONObject.parseObject(req);
                System.out.println(object);
                if(object.get("access_token") == null){
                    return null;
                }
                access_token = object.getString("access_token");
                taskMapper.setWxAccessToken((String)access_token);
                redisTemplate.opsForValue().set("access_token", access_token, 6900, TimeUnit.SECONDS);
                return (String) access_token;
            }else{
                access_token = wx_access_token.get("config_value");
                // 获取剩余过期时间戳
                t = wx_access_token.getInteger("t");
                if(t > 60){
                    redisTemplate.opsForValue().set("access_token", access_token, t, TimeUnit.SECONDS);
                }
                return (String) access_token;
            }


        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
            return null;
        }
    }
    /**
     * 示例json格式如下
     {
         "first": {
             "value": "test",
             "color": "#173177"
         },
         "keyword1": {
             "value": "aaa",
             "color": "#173177"
         }
         "remark":{
             "value":"TEST",
             "color":"#173177"
         }
     }
     {
         "touser":"o3Yg26IyKm_7CwsxU7Y1SmWzhZe8",
         "template_id":"o2Fi5wI-H5s2ca3e5Iw0cBK_bM22egafOnrrvjWSAjk",
         "url":"http://weixin.qq.com/download",
         "topcolor":"#FF0000",
         "data":{
             "first": {
                 "value": "test",
                 "color": "#173177"
             },
             "keyword1": {
                 "value": "aaa",
                 "color": "#173177"
             }
             "remark":{
                 "value":"TEST",
                 "color":"#173177"
             }
        }
     }
     */
    /**
     * 直接发送消息的方法
     * @param openid  用的openid
     * @param data 模板消息的data
     * 示例格式如下,根据模板需求传具体的值,一般会有多个keyword, 如keyword1, keyword2
     *       {
     *          "first": {
     *              "value": "test",
     *              "color": "#173177"
     *          },
     *          "keyword1": {
     *              "value": "aaa",
     *              "color": "#173177"
     *          }
     *          "remark":{
     *              "value":"TEST",
     *              "color":"#173177"
     *          }
     *      }
     * @param url 模板消息跳转的地址,可以为空或null
     * @param topcolor 颜色 可以为空或null
     * @return
     */
    public String send_temp_msg(String openid, JSONObject data, String url, String topcolor, Integer type){
        String[] msgtype = {template_id0, template_id1,template_id2,template_id3};
        JSONObject jsonobj =new JSONObject();
        jsonobj.put("touser", openid);
        jsonobj.put("template_id", msgtype[type]);
        jsonobj.put("url", url != null ? url :"");
        jsonobj.put("topcolor", topcolor != null ? topcolor :"#173177");
        jsonobj.put("data", data);
        try {
            String access_token = get_access_token();
            //System.err.println("access_token"+ access_token);
            if (access_token == null) {
                return "access_token获取失败";
            }
            String baseurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
            //System.err.println(baseurl);
            HttpClient httpClient = new HttpClient();
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
            PostMethod postMethod = new PostMethod(baseurl);
            postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
            //System.out.println(jsonobj);
            System.err.println(jsonobj.toString());
            postMethod.setRequestBody(jsonobj.toString());
            postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
            httpClient.executeMethod(postMethod);
            String result = postMethod.getResponseBodyAsString();
            postMethod.releaseConnection();
            System.out.println(result);
            return result;
        }catch (Exception e){
            System.err.println("send_temp_msg error:"+e.getMessage());
            return e.getMessage();
        }
    }

   /* public String SendMsg(List<WxTemplateContent> list){
        if(list.size() ==0){
            return "";
        }
        String taskId = UUID.randomUUID().toString();
        Task task = new Task();
        task.setTaskId(taskId);
        task.setStatus(0);
        task.setMsg("开始执行任务");
        String tousers= list.stream().map(WxTemplateContent::getTouser).collect(Collectors.toList()).toString();
        JSONObject send_data = new JSONObject();
        send_data.put("to_users", tousers);
        send_data.put("count", list.size());
        task.setInfo(send_data.toString());
        task.setProgress(0);
        if(taskService.insertTask(task) == 1){
            Task task1 = asyncTaskManager.submit(() -> {
                Task asynctask =  taskService.get_task(taskId);
                asynctask.setStatus(1);
                System.out.println("_____start_____");
                List<JSONObject> info = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    JSONObject result = new JSONObject();
                    String res = send_temp_msg(list.get(i).getTouser(), new JSONObject(list.get(i).getData()),list.get(i).getUrl(),list.get(i).getTopcolor(), 0);
                    asynctask.setTaskId(taskId);
                    asynctask.setMsg("正在执行第!"+(i+1)+"个");
                    asynctask.setProgress(((i+1)/list.size()* 100));
                    taskService.updateTask(asynctask);
                    result.put("openid", list.get(i).getTouser());
                    result.put("res", res);
                    info.add(result);
                }
                asynctask.setMsg("任务执行完成");
                asynctask.setStatus(3);
                asynctask.setRes(info.toString());
                taskService.updateTask(asynctask);
                System.out.println("_____end_____");
            }, taskId);

        }
        return taskId;
    }*/

}
 

5.根据业务场景去发送模板消息这里就举例子一个万能模板 wechatApi.send_temp_msg

if (wechatApi.get_access_token() != null) {
    JSONObject res = new JSONObject();
    res.put("openid", teacher != null ? teacher.getServerOpenId() : "");
    res.put("book_name", kidBook != null ? bookName : "");
    res.put("kid_name", logininfo != null ? logininfo.getName() : "");
    if (res != null) {

        System.err.println(res);
        String openid = res.getString("openid");
        String book_name = res.getString("book_name");
        String kid_name = res.getString("kid_name");
        if (openid != null ) {
            //调用任务管理器中的submit去提交一个异步任务
            String taskId = UUID.randomUUID().toString();
            Task task = new Task();
            task.setTaskId(taskId);
            task.setStatus(0);
            task.setMsg("开始发送微信模板消息");
            task.setInfo("");
            task.setProgress(0);
            if (taskService.insertTask(task) == 1) {
                Task task1 = asyncTaskManager.submit(() -> {
                    System.out.println("_____start_____");
                    Task asynctask = taskService.get_task(taskId);
                    JSONObject data = new JSONObject();
                    data.put("first", new WxMsg("请审核学生的预约借书", null));
                    data.put("keyword1", new WxMsg(kid_name, null));
                    data.put("keyword2", new WxMsg(cn.abtu.config.DateUtil.getTime(), null));
                    data.put("keyword3", new WxMsg("发起了"+book_name+"预约借书", null));
                    //data.put("time", new WxMsg("尽快", null));
                    // data.put("location", new WxMsg("借阅地点", null));
                    data.put("remark", new WxMsg(kid_name + "发起了图书:" + book_name + "的预约审核", null));
                    asynctask.setMsg("已执行发送");
                    asynctask.setStatus(3);
                    asynctask.setRes(wechatApi.send_temp_msg(openid, data, "", "", 3));
                    taskService.updateTask(asynctask);
                    System.out.println("_____end_____");
                }, taskId);
                if (task1 == null) {
                    throw new BusinessExeption("201", "微信模板消息发送失败!");
                }
            }
        }
    }

6.模板配置

# 模板消息 0催还通知 1活动未完成提醒
wechat.template_id0: 
wechat.template_id1: 90O9OofmDvCXRt-
#万能模板
wechat.template_id2: -3Ww
#借还书模板三
wechat.template_id3: 

7.万能模板的模板 根据 模板的详情内容编写代码就可以了

 

编辑不易,一键三连

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值