java开发微信模板消息推送

完整demo下载
概述

微信公众平台开始支持前端网页,大家可能看到很多网页上都有分享到朋友圈,关注微信等按钮,点击它们都会弹出一个窗口让你分享和关注,这个是怎么实现的呢?今天就给大家讲解下如何在微信公众平台前端网页上添加分享到朋友圈,关注微信号等按钮。

1 ,基本需求
微信模板消息推送订单购买成功推送
三、项目结构

在这里插入图片描述
四、使用规则
所有服务号都可以在功能->添加功能插件处看到申请模板消息功能的入口
需要选择公众账号服务所处的2个行业,每月可更改1次所选行业
在所选择行业的模板库中选用已有的模板进行调用
每个账号可以同时使用25个模板
当前每个账号的模板消息的日调用上限为10万次,单个模板没有特殊限制,以公众号MP后台开发者中心页面中标明的数字为准

五、接口文档规范
模板消息调用时主要需要模板ID和模板中各参数的赋值内容
模板中参数内容必须以".DATA"结尾,否则视为保留字
模板保留符号"{{ }}"
测试公众号可以随意定义,正式的必须用模板库中的

以下是我使用的模板消息示例

package cn.demo.Template;
 
/**
 * 模板详细信息 
 */
public class Data_first {
 
    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;
    }
       /**
        * 获取acctoken
        * @return
        */
       private String getAccessToken() {
            if (access_token != null && (access_token_updateTime + 5400000) > new Date().getTime())
                return access_token;
            AccessTokenResult accessTokenResult = restTemplate.getForObject(String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", APPID, SECRET), AccessTokenResult.class);
            if (accessTokenResult.getErrcode() == null || accessTokenResult.getErrcode().equals("0")) {
                access_token_updateTime = new Date().getTime();
                access_token = accessTokenResult.getAccess_token();
            } else 
                System.out.println("error:" + accessTokenResult);
            return accessTokenResult.getAccess_token();
         
}
/**
 * 微信请求 - 信任管理器
 */
public class MyX509TrustManager implements X509TrustManager {
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }
 
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }
 
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}
    * 发送https请求
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
 
public class WeixinUtil {
 
     public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)
      {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try
        {
          TrustManager[] tm = { new MyX509TrustManager() };
          SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
          sslContext.init(null, tm, new SecureRandom());
 
          SSLSocketFactory ssf = sslContext.getSocketFactory();
 
          URL url = new URL(requestUrl);
          HttpsURLConnection httpUrlConn = (HttpsURLConnection)url.openConnection();
          httpUrlConn.setSSLSocketFactory(ssf);
 
          httpUrlConn.setDoOutput(true);
          httpUrlConn.setDoInput(true);
          httpUrlConn.setUseCaches(false);
 
          httpUrlConn.setRequestMethod(requestMethod);
 
          if ("GET".equalsIgnoreCase(requestMethod)) {
            httpUrlConn.connect();
          }
 
          if (outputStr != null) {
            OutputStream outputStream = httpUrlConn.getOutputStream();
 
            outputStream.write(outputStr.getBytes("UTF-8"));
            outputStream.close();
          }
 
          InputStream inputStream = httpUrlConn.getInputStream();
          InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
          BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
 
          String str = null;
          while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
          }
          bufferedReader.close();
          inputStreamReader.close();
 
          inputStream.close();
          inputStream = null;
          httpUrlConn.disconnect();
          jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
         // logger.error("Weixin server connection timed out.");
        } catch (Exception e) {
         // logger.error("https request error:{}", e);
        }
        return jsonObject;
      }
 
}

下面请求微信发送模板消息

  /**
     *  * 发送模板消息  
     * appId 公众账号的唯一标识 
     * appSecret 公众账号的密钥  
     * openId 用户标识     
     */
    public void send_template_message(String appId, String openId) {
        String access_token = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
        NewOrdersTemplate temp = new NewOrdersTemplate();
        Data data = new Data();
        Data_first first = new Data_first();
        Data_Day Day = new Data_Day();
        Data_orderId orderId = new Data_orderId();
        Data_orderType orderType = new Data_orderType();
        Data_customerName customerName = new Data_customerName();
        Data_customerPhone customerPhone = new Data_customerPhone();
        Data_remark remark = new Data_remark();
 
        first.setValue("收到一个新的订单");
        first.setColor("#173177");
        Day.setValue("14时56分");
        Day.setColor("#173177");
        orderId.setValue("1002");
        orderId.setColor("#173177");
        orderType.setValue("订位");
        orderType.setColor("#173177");
        customerName.setValue("陈丑丑");
        customerName.setColor("#173177");
        customerPhone.setValue("13222222222");
        customerPhone.setColor("#173177");
        remark.setValue("请及时处理您的订单");
        remark.setColor("#173177");
 
        data.setFirst(first);
        data.setDay(Day);
        data.setOrderId(orderId);
        data.setOrderType(orderType);
        data.setCustomerName(customerName);
        data.setCustomerPhone(customerPhone);
        data.setRemark(remark);
        temp.setTouser(openId);
        temp.setTemplate_id("C0BHxo_YLQ9TV2XytzqucHI7dNJytq0aAxYkBkqZTiw");
        temp.setUrl("http://weixin.qq.com/download");
        temp.setTopcolor("#173177");
        temp.setData(data);
 
        String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day");
        JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST", jsonString);
        System.out.println(jsonObject);
 
        int result = 0;
 
        // logger.info("模板消息发送结果:"+result};
 
    }

下一步请求conterller因为我参数写死在conterller里面

@RequestMapping("/test")
@ResponseBody
public String testDemo() {
    String openId = "oJilVv4k-DXciUhIsC2wSXJs2J";
    String appId = "wx1ff244a71563c";
    send_template_message(appId, openId);
    return appId;
 
}

六、运行效果
访问这地址 http://localhost:8080/app/tetst 测试结果如图
在这里插入图片描述
在这里插入图片描述

demo下载完整demo下载

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值