packJsonmsg 可按照个人模板需求来进行更改
自己重新封装下方法即可
import java.text.SimpleDateFormat;
import org.apache.tools.ant.parators.Date;
import cn.gatherlife.box.Constant;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
public class WxTemplateMsg {
/**
* @method packJsonmsg
* @描述: TODO(封装微信模板:警告模板)
* @参数@param first 头部
* @参数@param content 内容
* @参数@param occurtime 发生时间
* @参数@param remark 说明
* @参数@return
* @返回类型:JSONObject
* @作者:小川
*/
public static JSONObject packJsonmsg(String first, String content, String remark){
JSONObject json = new JSONObject();
try {
JSONObject jsonFirst = new JSONObject();
jsonFirst.put("value", first);
jsonFirst.put("color", "#173177");
json.put("first", jsonFirst);
JSONObject WarningContent = new JSONObject();
WarningContent.put("value", content);
WarningContent.put("color", "#173177");
json.put("content", WarningContent);
JSONObject occurtime = new JSONObject();
String str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
occurtime.put("value",str);
occurtime.put("color", "#173177");
json.put("occurtime", occurtime);
JSONObject jsonRemark = new JSONObject();
jsonRemark.put("value", remark);
jsonRemark.put("color", "#173177");
json.put("Remark", jsonRemark);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
/**
* @throws Exception
* @method sendWechatmsgToUser
* @描述: TODO(发送模板信息给用户)
* @参数@param touser 用户的openid
* @参数@param templat_id 信息模板id
* @参数@param url 用户点击详情时跳转的url
* @参数@param data 模板详情变量 Json格式
* @参数@return
* @返回类型:String
*/
public static String sendWechatmsgToUser(String touser, String templat_id, String clickurl, JSONObject data) throws Exception{
String url = "https://api./cgi-bin/message/template/send?access_token="+您的Access_token;
System.out.println("请求微信的Url"+url);
JSONObject json = new JSONObject();
try {
json.put("touser", touser);
json.put("template_id", templat_id);
json.put("url", clickurl);
json.put("data", data);
} catch (JSONException e) {
e.printStackTrace();
}
String result = HttpClientUtil.doPost(url, json.toString());
System.out.println("请求微信的Url 返回的结果"+result);
try {
JSONObject parseObject = JSONObject.parseObject(result);
String errmsg = (String) parseObject.get("errmsg");
if(!"ok".equals(errmsg)){ //如果为errmsg为ok,则代表发送成功,公众号推送信息给用户了。
return "error";
}
} catch (JSONException e) {
e.printStackTrace();
}
return "success";
}
public static String sendTempateMsg(String openid,String first, String content, String remark) throws Exception{
String retMsg = sendWechatmsgToUser(openid, "模板id", "跳转的连接", packJsonmsg(first, content, remark));
return retMsg;
}
}
如果觉得《php 公众号指定人发消息 微信公众号发送模板消息 发送消息到某个用户》对你有帮助,请点赞、收藏,并留下你的观点哦!