微信公众号开发之发送模板消息

在我们做微信公众号开发时,发送模板消息往往是必不可少的功能。今天我们就来说说吧!

1、申请模板消息

首先我们应该知道,模板消息是需要申请的。这个申请就其本身来说是很easy的(我前一天晚上申请的,显示需要2--3个工作日,结果第二天早上就发现已经开通了,所以说腾讯官方还是比较给力的哈)。

但是我们在申请时还是有一些东西要注意,这个在官方的文档有非常详细的说明。

这个我建议你好好看看。选择行业的时候可要谨慎些,因为这个一个月只可以修改一次。

那么,我们来看看在哪里申请?

这里我已经申请过了。

申请之后就耐心等待,审核通过之后再功能这一栏里就会出现模板消息的菜单。你可以看看我上面的截图,就在第三项。

2、添加模板消息

审核通过之后,我们就可以添加模板消息,进行开发了。

这个很简单:

我们点击模板消息进入后,直接在模板库中选择你需要的消息模板添加就可以了,添加之后就会在我的模板中。会有一个模板id,这个模板id在我们发送消息的时候会用到。

3、消息发送功能开发

接下来我们就看看如何发送模板消息:

这个是官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277

我呢,也来说说我的实现吧。为了更方便,我会直接将相关代码贴出来。

文档中我们可以看到接口地址如下:

http请求方式: POST
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN

这里我们首先需要的就是access_token了,这个在这里就不多说了。通过你的appid和secret就可以获取。

【获取access_token : https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183

关于相关参数,我直接就将官方文档贴来了(文档写的很清楚):

POST数据示例如下:

{
           "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"
                   }
           }
       }

参数说明

参数 是否必填 说明
touser 接收者openid
template_id 模板ID
url 模板跳转链接(海外帐号没有跳转能力)
miniprogram 跳小程序所需数据,不需跳小程序可不用传该数据
appid 所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系,暂不支持小游戏)
pagepath 所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar),暂不支持小游戏
data 模板数据
color 模板内容字体颜色,不填默认为黑色

注:url和miniprogram都是非必填字段,若都不传则模板无跳转;若都传,会优先跳转至小程序。开发者可根据实际需要选择其中一种跳转方式即可。当用户的微信客户端版本不支持跳小程序时,将会跳转至url。

返回码说明

在调用模板消息接口后,会返回JSON数据包。正常时的返回JSON数据包示例:

{
           "errcode":0,
           "errmsg":"ok",
           "msgid":200228332
       }

相信看完以上文档,基本上没有什么问题了。

以下是我的部分代码:

// 获取token
        String token = saveAndFlushAccessTokenUtil.getToken();

        String postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", "发送到用户的openid");   // openid
        jsonObject.put("template_id", "你的模板id");
        jsonObject.put("url", "http://www.baidu.com");

        JSONObject data = new JSONObject();
        JSONObject first = new JSONObject();
        first.put("value", "hello");
        first.put("color", "#173177");
        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", "hello");
        keyword1.put("color", "#173177");
        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", "hello");
        keyword2.put("color", "#173177");
        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", "hello");
        keyword3.put("color", "#173177");
        JSONObject remark = new JSONObject();
        remark.put("value", "hello");
        remark.put("color", "#173177");
        
        data.put("first",first);
        data.put("keyword1",keyword1);
        data.put("keyword2",keyword2);
        data.put("keyword3",keyword3);
        data.put("remark",remark);

        jsonObject.put("data", data);

        String string = HttpClientUtils.sendPostJsonStr(postUrl, jsonObject.toJSONString());
        JSONObject result = JSON.parseObject(string);
        int errcode = result.getIntValue("errcode");
        if(errcode == 0){
            // 发送成功
            System.out.println("发送成功");
        } else {
            // 发送失败
            System.out.println("发送失败");
        }

下面是http请求工具类:

package car.repair.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
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.io.IOException;

/**
 * @author zhuzhe
 * @date 2017/12/11
 * HttpClient工具类
 */
@Slf4j
public class HttpClientUtils {

    /**
     * 以jsonString形式发送HttpPost的Json请求,String形式返回响应结果
     *
     * @param url
     * @param jsonString
     * @return
     */
    public static String sendPostJsonStr(String url, String jsonString) throws IOException {
        if (jsonString == null || jsonString.isEmpty()) {
            return sendPost(url);
        }
        String resp = "";
        StringEntity entityStr = new StringEntity(jsonString,
                ContentType.create("text/plain", "UTF-8"));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entityStr);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
        } catch (ClientProtocolException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
        if (resp == null || resp.equals("")) {
            return "";
        }
        return resp;
    }

    /**
     * 发送不带参数的HttpPost请求
     *
     * @param url
     * @return
     */
    public static String sendPost(String url) throws IOException {
        // 1.获得一个httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 2.生成一个post请求
        HttpPost httppost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            // 3.执行get请求并返回结果
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        // 4.处理结果,这里将结果返回为字符串
        HttpEntity entity = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity);
        } catch (ParseException | IOException e) {
            log.error(e.getMessage());
        }
        return result;
    }
}

 

收到消息,我就不自己弄图了。这里附上官方图片一张:

 

转载请务必保留此出处(原作者):https://blog.csdn.net/zhuzhezhuzhe1/article/details/83927016

 

版权声明:本文为原创文章,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。

https://blog.csdn.net/zhuzhezhuzhe1