微信公众号模板消息推送

前段时间,有个微信模板消息推送的需求,整理了下,做个笔记,仅供大家参考

首先我们查阅微信公众号官方文档,原链接:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html#5

通过查阅官方文档,可以知道请求的json串是这个样子的:

{

           "touser":"OPENID",

           "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",

           "url":"http://weixin.qq.com/download",  

           "miniprogram":{

             "appid":"xiaochengxuappid12345",

             "pagepath":"index?foo=bar"

           },          

           "data":{

                   "first": {

                       "value":"恭喜你购买成功!",

                       "color":"#173177"

                   },

                   "keyword1":{

                       "value":"巧克力",

                       "color":"#173177"

                   },

                   "keyword2": {

                       "value":"39.8元",

                       "color":"#173177"

                   },

                   "keyword3": {

                       "value":"2014年9月22日",

                       "color":"#173177"

                   },

                   "remark":{

                       "value":"欢迎再次购买!",

                       "color":"#173177"

                   }

           }

       }

好了,到这里我们已经知道请求的数据格式了,下一步进行代码封装。


首先创建一个微信推送的枚举:

/**

 * @Author: Hou_fx

 * @Date: 2019/7/18 11:25

 * @Description: 微信推送模板类型

 */

public enum WeChatPushType {

    /**

     * 微信推送模板

     */

    W001("eoq31s", "请通知", "/app/wx/push", new String[]{"first", "keyword1", "keyword2", "remark"}),

    W002("-t0H5M", "度评估结果通知", "/app/wx/push", new String[]{"first", "keyword1", "keyword2", "remark"}),

    W004("qavnP4", "名成功通知", "/app/wx/push", new String[]{"first", "keyword1", "keyword2", "keyword3", "keyword4", "keyword5", "remark"}),

    W005("74R4tA", "功通知", "/app/wx/push", new String[]{"first", "keyword1", "keyword2", "keyword3", "remark"}),

    W006("FQ2F68", "通提醒", "/app/wx/push", new String[]{"first", "name", "time", "remark"}),

    W007("oFDj8c", "败通知", "/app/wx/push", new String[]{"first", "keyword1", "keyword2", "remark"}),

    W008("SMtEKk", "款进度", "/app/wx/push", new String[]{"first", "keyword1", "keyword2", "keyword3", "keyword4", "keyword5", "remark"}),

    W009("p0iLug", "醒", "/app/wx/push", new String[]{"first", "keyword1", "keyword2", "remark"}),

    W010("68nFn0", "作信息提醒", "/app/wx/push", new String[]{"first", "keyword1", "keyword2", "keyword3", "remark"}),

    W011("iV2o9s", "理通知", "/app/wx/push", new String[]{"first", "appellationtime", "publicproductname", "apptype", "amount", "remark"}),

    W012("evmZCw", "定通知", "/app/wx/push", new String[]{"first", "name1", "time", "remark"}),

    W013("zoPrek", "醒", "/app/wx/push", new String[]{"first", "keyword1", "keyword2", "remark"}),

    W014("ExJ6z4", "态通知", "/app/wx/push", new String[]{"first", "keyword1", "keyword2", "keyword3", "remark"}),

    W016("EuNOAc", "功通知", "/app/wx/push", new String[]{"first", "keyword1", "keyword2", "keyword3", "keyword4", "remark"}),

    W017("obpfy8", "败提醒", "/app/wx/push", new String[]{"first", "keyword1", "keyword2", "remark"}),

    W018("_okeDE", "功通知", "/app/wx/push", new String[]{"first", "keyword1", "keyword2", "remark"}),

    ;



    private String templateId;

    private String desc;

    private String url;

    private String[] keys;



    WeChatPushType(String templateId, String desc, String url, String[] keys) {

        this.desc = desc;

        this.templateId = templateId;

        this.url = url;

        this.keys = keys;

    }



    public String getTemplateId() {

        return templateId;

    }



    public String getDesc() {

        return desc;

    }



    public String[] getKeys() {

        return keys;

    }



    public String getUrl() {

        return url;

    }



    public void setTemplateId(String templateId) {

        this.templateId = templateId;

    }



    public void setDesc(String desc) {

        this.desc = desc;

    }



    public void setUrl(String url) {

        this.url = url;

    }



    public void setKeys(String[] keys) {

        this.keys = keys;

    }}


由于涉及到公众号模板id,在此将微信id修改了,数据仅供参考,以实际模板id为主

参数说明:

templateId:微信模板id

desc:描述

url:点击消息调整的链接

keys:微信模板对应的key


第二步:创建一个微信推送的接口

/**

 * @Author: Hou_fx

 * @Date: 2019/7/22 19:09

 * @Description:

 */

@Service

public interface WeChatPushService {



    /**

     * 微信推送

     * @param openId

     * @param weChatPushType

     * @param list

     * @param urlParam

     * @return

     * @throws ServiceException

     */

    boolean push(String openId, WeChatPushType weChatPushType, List list,String urlParam) throws ServiceException;

}

第三步:实现微信推送接口

/**

 * @Author: Hou_fx

 * @Date: 2019/7/22 19:10

 * @Description:

 */

@Service

public class WeChatPushServiceImpl implements WeChatPushService {

    /** 微信推送接口 */

    private static String PUSH_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

    /**

     * 获取 access_token

     */

    private static String ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";



    public String getAccessToken() {

        String requestUrl = ACCESS_TOKEN.replace("APPID", APPID).replace("APPSECRET", APPSECRET);

        return requestUrl;

    }



    @Value("${weChatPlat.appid}")

    private String APPID;

    @Value("${weChatPlat.appsecret}")

    private String APPSECRET;

    @Value("${weChatPlat.appurl}")

    private String appurl;



    private static final Logger LOG = LoggerFactory.getLogger(WeChatPushServiceImpl.class);





    @Override

    public boolean push(String openId, WeChatPushType weChatPushType, List list,String ualParam) throws ServiceException {

        LOG.info("消息推送start");



        JSONObject param = new JSONObject();

        JSONObject data = new JSONObject();

        param.put("touser", openId);

        param.put("template_id", weChatPushType.getTemplateId());

        Optional.ofNullable(weChatPushType.getUrl()).ifPresent(o -> param.put("url", appurl + weChatPushType.getUrl() + ualParam));

        Map push = new HashMap<>(16);

        list.forEach(f -> {

            JSONObject node = new JSONObject();

            Optional.ofNullable(f.getValue()).ifPresent(o -> node.put("value", f.getValue()));

            Optional.ofNullable(f.getColor()).ifPresent(o -> node.put("color", f.getColor()));

            push.put(f.getKey(), node);

        });

        // 模板数据 start

        push.forEach(data::put);

        param.put("data", data);

        // 模板数据 end

        StringBuilder url = new StringBuilder();

        url.append(PUSH_URL);

        String requestUrl = ACCESS_TOKEN.replace("APPID", APPID).replace("APPSECRET", APPSECRET);

        String accessToken = HttpClientUtil.getInstance().sendHttpsGet(requestUrl);

        JSONObject ass = JSONObject.parseObject(accessToken);

        LOG.info(accessToken);

        url.append(ass.get("access_token"));

        LOG.info(param.toJSONString());

        JSONObject res = HttpClientUtil.httpsRequest(url.toString(), RequestMethod.POST.name(), param.toJSONString());

        LOG.info("消息推送end:{}", res);



        return true;

    }

}

到这里就完成80%了,下面我们来开始发送模板消息

List push = new ArrayList<>();

                    push = WeChatPushUtil.addPush(push, WeChatPushType.W005.getKeys()[0], "恭喜,您的企业账号已认证成功。");

                    push = WeChatPushUtil.addPush(push, WeChatPushType.W005.getKeys()[1], enterpriseInf.getContactsName(), "#3A8ACA");

                    push = WeChatPushUtil.addPush(push, WeChatPushType.W005.getKeys()[2], enterpriseInf.getEnterpriseName(), "#3A8ACA");

                    push = WeChatPushUtil.addPush(push, WeChatPushType.W005.getKeys()[3], String.valueOf(enterpriseInf.getContactsPhone()), "#3A8ACA");

                    push = WeChatPushUtil.addPush(push, WeChatPushType.W005.getKeys()[4], "\n点击可浏览更多融资产品信息,或免费体验一键智能匹配服务。", "#FF0000");

                    weChatPushService.push(enterpriseInf.getOpenId(), WeChatPushType.W005, push,"?redirectType=homepage");

…发现少了个List代码没贴出来,,Push代码如下:

/**

 * @Author: Hou_fx

 * @Date: 2019/7/17 18:52

 * @Description:

 */

@Data

@AllArgsConstructor

public class Push implements Serializable {

    private static final long serialVersionUID = 6579398731585901064L;

    private String value;

    private String key;

    private String color;



    public Push(String value, String key) {

        this.value = value;

        this.key = key;

    }

}

参数说明:

value:模板的值

key: 微信模板的key

color:值的颜色


1024啦,大家节日快乐。

END

你可能感兴趣的:(开发日常,微信模板推送)