微信公众号模板消息教程

首先,我们可以进去微信公众号的测试平台
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
来进行测试
然后我们需要创建一个模板消息
微信公众号模板消息教程_第1张图片
创建完成后,我们记录下4个数据
首先appid和appsecret
微信公众号模板消息教程_第2张图片
然后就是模板消息的id
微信公众号模板消息教程_第3张图片
最后就是我们微信号的openid
微信公众号模板消息教程_第4张图片
记录下这4个数据后,我们需要构建几个类
代码如下
Template.java 模板消息类

package cn.com.do1.component.activityent.util;

import java.util.List;

public class Template
{
  private String toUser;
  private String templateId;
  private String url;
  private String topColor;
  private List templateParamList;

  public String getToUser()
  {
    return this.toUser;
  }

  public void setToUser(String toUser)
  {
    this.toUser = toUser;
  }

  public String getTemplateId()
  {
    return this.templateId;
  }

  public void setTemplateId(String templateId)
  {
    this.templateId = templateId;
  }

  public String getUrl()
  {
    return this.url;
  }

  public void setUrl(String url)
  {
    this.url = url;
  }

  public String getTopColor()
  {
    return this.topColor;
  }

  public void setTopColor(String topColor)
  {
    this.topColor = topColor;
  }

  public String toJSON()
  {
    StringBuffer buffer = new StringBuffer();
    buffer.append("{");
    buffer.append(String.format("\"touser\":\"%s\"", new Object[] { this.toUser })).append(",");
    buffer.append(String.format("\"template_id\":\"%s\"", new Object[] { this.templateId })).append(",");
    buffer.append(String.format("\"url\":\"%s\"", new Object[] { this.url })).append(",");
    buffer.append(String.format("\"topcolor\":\"%s\"", new Object[] { this.topColor })).append(",");
    buffer.append("\"data\":{");
    TemplateParam param = null;
    for (int i = 0; i < this.templateParamList.size(); i++)
    {
      param = (TemplateParam)this.templateParamList.get(i);
      if (i < this.templateParamList.size() - 1) {
        buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"},", new Object[] { param.getName(), param.getValue(), param.getColor() }));
      } else {
        buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"}", new Object[] { param.getName(), param.getValue(), param.getColor() }));
      }
    }
    buffer.append("}");
    buffer.append("}");
    return buffer.toString();
  }

  public List getTemplateParamList()
  {
    return this.templateParamList;
  }

  public void setTemplateParamList(List templateParamList)
  {
    this.templateParamList = templateParamList;
  }
}

第二个 Token.java accessToken类

package cn.com.do1.component.activityent.util;

public class Token
{
  private String accessToken;
  private int expiresIn;
  private long getTokenTime;

  public long getGetTokenTime()
  {
    return this.getTokenTime;
  }

  public void setGetTokenTime(long getTokenTime)
  {
    this.getTokenTime = getTokenTime;
  }

  public String getAccessToken()
  {
    return this.accessToken;
  }

  public void setAccessToken(String accessToken)
  {
    this.accessToken = accessToken;
  }

  public int getExpiresIn()
  {
    return this.expiresIn;
  }

  public void setExpiresIn(int expiresIn)
  {
    this.expiresIn = expiresIn;
  }
}

第三个 TemplateParam.java 也算是模板消息类吧

package cn.com.do1.component.activityent.util;

public class TemplateParam
{
  private String name;
  private String value;
  private String color;

  public TemplateParam(String name, String value, String color)
  {
    this.name = name;
    this.value = value;
    this.color = color;
  }

  public String getName()
  {
    return this.name;
  }

  public void setName(String name)
  {
    this.name = name;
  }

  public String getValue()
  {
    return this.value;
  }

  public void setValue(String value)
  {
    this.value = value;
  }

  public String getColor()
  {
    return this.color;
  }

  public void setColor(String color)
  {
    this.color = color;
  }
}

第四个微信工具类WxgzhUtil.java

package cn.com.do1.component.activityent.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.net.ssl.HttpsURLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.do1.component.activityent.activityent.vo.AccessTokenVO;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class WxgzhUtil {
     

    private static final Logger log = LoggerFactory.getLogger(WeixinUtils.class);
    private static Token token = null;

    /**http请求方法
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     */
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);

            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            if (outputStr != null) {
                OutputStream outputStream = conn.getOutputStream();

                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            System.out.println("连接超时:{}");
        } catch (Exception e) {
            System.out.println("https请求异常:{}");
        }
        return null;
    }

    /**url编码
     * @param source
     * @return
     */
    public static String urlEncodeUTF8(String source) {
        String result = source;
        try {
            result = URLEncoder.encode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**将模板消息打包成json
     * @param first
     * @param keyword1
     * @param keyword2
     * @param remark
     * @return
     */
    public static JSONObject packJsonmsg(String first, String keyword1, String keyword2, String remark) {
        JSONObject json = new JSONObject();
        try {
            JSONObject jsonFirst = new JSONObject();
            jsonFirst.put("value", first);
            jsonFirst.put("color", "#173177");
            json.put("first", jsonFirst);

            JSONObject jsonKeyword1 = new JSONObject();
            jsonKeyword1.put("value", keyword1);
            jsonKeyword1.put("color", "#173177");
            json.put("keyword1", jsonKeyword1);

            JSONObject jsonKeyword2 = new JSONObject();
            jsonKeyword2.put("value", keyword2);
            jsonKeyword2.put("color", "#173177");
            json.put("keyword1", jsonKeyword2);

            JSONObject jsonRemark = new JSONObject();
            jsonRemark.put("value", remark);
            jsonRemark.put("color", "#173177");
            json.put("remark", jsonRemark);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

    /**发送模板消息
     * @param template
     * @return
     */
    public static boolean sendTemplateMsg(Template template) {
        boolean flag = false;

        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", getToken().getAccessToken());
        System.out.println(requestUrl);
        System.out.println(template.toJSON());
        String Result = httpsRequest(requestUrl, "POST", template.toJSON());
        System.out.println(Result);
        new JSONObject();
        JSONObject jsonResult = JSONObject.fromObject(Result);
        if (jsonResult != null) {
            int errorCode = jsonResult.getInt("errcode");
            String errorMessage = jsonResult.getString("errmsg");
            if (errorCode == 0) {
                flag = true;
            } else {
                System.out.println("模板消息发送失败:" + errorCode + "," + errorMessage);
                flag = false;
            }
        }
        return flag;
    }

    /**构建消息内容  url为点击消息后跳转的网页
     * @param openid
     * @param url
     * @param activityName
     * @param name
     * @param startTime
     * @param address
     */
    public static void sendMessage(String openid, String url, String activityName, String name, String startTime, String address) {
        Template tem = new Template();
        //模板消息id
        tem.setTemplateId("QK1y41Zi-0IiQeOcGUh6EkBZ9g2rdbj4AW6Q1RkarNs");
        tem.setTopColor("#00DD00");
        tem.setToUser(openid);
        tem.setUrl(url);

        List paras = new ArrayList();
        paras.add(new TemplateParam("first", "欢迎你参加" + activityName + ",你已报名成功!", "#0044BB"));
        paras.add(new TemplateParam("keyword1", activityName, "#0044BB"));
        paras.add(new TemplateParam("keyword2", name, "#0044BB"));
        paras.add(new TemplateParam("remark", "活动将于" + startTime + "在" + address + "举行,请准时参加!", "#0044BB"));

        tem.setTemplateParamList(paras);

        sendTemplateMsg(tem);
    }

    /**获取有效的token
     * @return
     */
    public static Token getToken() {
        if (token != null) {
            if (token.getGetTokenTime() + token.getExpiresIn() > new Date()
                    .getTime()) {

                return token;
            }
        }
        //记得补充上appid和appsecret
        String result = httpsRequest(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=&secret=",
                "GET", null);
        new JSONObject();
        JSONObject jsonObject = JSONObject.fromObject(result);
        if (jsonObject != null) {
            try {
                token = new Token();
                token.setGetTokenTime(new Date().getTime());
                token.setAccessToken(jsonObject.getString("access_token"));
                token.setExpiresIn(jsonObject.getInt("expires_in"));
            } catch (JSONException e) {
                token = null;

                log.error("获取token失败 errcode:{} errmsg:{}",
                        Integer.valueOf(jsonObject.getInt("errcode")),
                        jsonObject.getString("errmsg"));
            }
        }
        return token;
    }



    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //第一个字符串是我们微信的openid
        sendMessage("oXZWR1MH1k0d1rw5zMA6Q1IPoRiY", "", "测试", "测试", sdf.format(new Date()), "测试");
    }
}

发送成功微信公众号模板消息教程_第5张图片
微信公众号模板消息教程_第6张图片

你可能感兴趣的:(微信公众号模板消息教程)