java微信推送模板销消息(微信测试号)

java微信推送模板销消息(微信测试号)

  • 相关jar包(红框内)

在这里插入图片描述

如果仅需推送模板消息,不对用户动作进行处理的话不需进行服务器配置

在这里插入图片描述

下面的操作皆借助于微信的测试号,点击下方链接进入登录页,微信扫描即可进入

测试号链接:点击进入测试号

在这里插入图片描述

1. 新建模板

此处为测试号,正式上线模板只能选择,不能自定义,如需自定义则需申请

在这里插入图片描述
在这里插入图片描述

  • 标题自定义
  • 内容按微信给出的格式输入,可用下面的例子
{{title.DATA}}
登记时间: {{registrationDate.DATA}}
缺货数量: {{shortageQuantity.DATA}}
发货基地: {{deliveryBase.DATA}}
责任部门: {{responsibleDepartment.DATA}}
备注: {{remark.DATA}}

2. 新建模板实体

  • 根据微信给出的接口说明建消息类
    在这里插入图片描述
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Map;

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class WxTemplate {
    private String touser;
    private String template_id;
    private String url;
    private Map<String, TemplateData> data;
}

3. 发送消息

  • 建get和post请求的工具类

    
    import org.apache.http.HttpEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    import java.nio.charset.StandardCharsets;
    
    public class HttpUtil {
        /**
         * 模拟get请求
         * @param url
         * @return
         */
        public static String sendGet(String url) {
            String response = null;
            CloseableHttpClient aDefault = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            try {
                CloseableHttpResponse execute = aDefault.execute(httpGet);
                response = EntityUtils.toString(execute.getEntity(), StandardCharsets.UTF_8);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (aDefault != null) {
                    try {
                        aDefault.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
    
                }
            }
            return response;
        }
    
        /**
         *
         * @param url "http://127.0.0.1:8083/shortageInfo/getSingle"
         * @param data {'shortageInfo': {'id':'105'}}
         * @param mimeType mimeType
         * @param charset charset
         * @return response
         */
        public static String sendPost(String url, String data, String mimeType, String charset) {
            String response = null;
            try {
                CloseableHttpClient httpclient = null;
                CloseableHttpResponse httpResponse = null;
                try {
                    httpclient = HttpClients.createDefault();
                    HttpPost httppost = new HttpPost(url);
                    HttpEntity stringentity = new StringEntity(data, ContentType.create(mimeType, charset));
                    httppost.setEntity(stringentity);
                    httpResponse = httpclient.execute(httppost);
                    response = EntityUtils
                            .toString(httpResponse.getEntity());
                    System.out.println(response);
    
                } finally {
                    if (httpclient != null) {
                        httpclient.close();
                    }
                    if (httpResponse != null) {
                        httpResponse.close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }
    
        /**
         * 模拟post请求
         * @param url url
         * @param data data
         * @return 返回对象字符串
         */
        public static String sendPost(String url, String data) {
            return sendPost(url, data, "application/json", "UTF-8");
        }
    }
    
  • 发送消息


import com.ak.job.entity.WxTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyTest {
    public static final String APP_ID = "wx38ec2eb5f13";
    public static final String APP_SECRET = "bf0f36dd83799be52f";
    public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
    //模板ID
    public static final String TEMPLATE_ID="jSuFd42IenE24OlhigirEVJKmsHNjUPaRa01XKsIMCk";
    //模板消息详情跳转URL
    public static final String TO_URL="http://www.baidu.com";
    public static final String SEND_TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";

	
    public static void executePush(WxTemplate wxTemplate, String accessToken) {
        Object o = JSON.toJSON(wxTemplate);
        String s = HttpUtil.sendPost(String.format(SEND_TEMPLATE_URL, accessToken, o.toString().replace("[", "{").replace("]", "}"));
        System.out.println(s);
    }
    
    @SneakyThrows
    public static void main(String[] args) {
        // 获取access_token
        String s = HttpUtil.sendGet(ACCESS_TOKEN_URL);
        JSONObject jsonObject = JSON.parseObject(s);
        String accessToken = jsonObject.getString("access_token");
        // 构建消息模板
        Map<String, TemplateData> templateData = new HashMap<>();
        templateData.put("title", TemplateData.builder().value("默认标题").color("#000000").build()); // title
        templateData.put("shortageQuantity", TemplateData.builder().value("1000").color("#ff0000").build()); // shortageQuantity
        templateData.put("responsibleDepartment", TemplateData.builder().value("默认部门").color("#ff0045").build()); // responsibleDepartment
        templateData.put("deliveryBase", TemplateData.builder().value("默认基地").color("#000000").build()); // deliveryBase
        templateData.put("registrationDate", TemplateData.builder().value(System.currentTimeMillis() / 10 + "").color("#000000").build()); // registrationDate
        templateData.put("remark", TemplateData.builder().value("默认备注").color("#000000").build()); // remark
        WxTemplate wxTemplate = WxTemplate.builder()
                .template_id(TEMPLATE_ID)
                .data(templateData)
                .url(TO_URL)
                .touser("ojx0a5i32V7AuMiKd5Z4Kjthik1k")
                .build();
    }
	executePush(wxTemplate, accessToken); // 发送消息
}

在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值