1、前提条件
1)公众号是服务号,不是订阅号
2)开通消息模板(功能-->添加功能插件-->消息模板)
3)打开消息模板,在模板库添加模板到我的模板,也可以自定义模板(可支持3个)
2、发送微信模板消息给用户(用户需关注公众号)
2.1)http请求方法
/// <summary> /// 后台发送POST请求 /// </summary> /// <param name="url">服务器地址</param> /// <param name="data">发送的数据</param> /// <returns></returns> public string HttpPost(string url, string data) { try { //创建post请求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8"; byte[] payload = Encoding.UTF8.GetBytes(data); request.ContentLength = payload.Length; //发送post的请求 Stream writer = request.GetRequestStream(); writer.Write(payload, 0, payload.Length); writer.Close(); //接受返回来的数据 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream, Encoding.UTF8); string value = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); return value; } catch (Exception) { return ""; } } /// <summary> /// 后台发送GET请求 /// </summary> /// <param name="url">服务器地址</param> /// <param name="data">发送的数据</param> /// <returns></returns> public string HttpGet(string url, string data) { try { //创建Get请求 url = url + (data == "" ? "" : "?") + data; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; //接受返回来的数据 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8")); string retString = streamReader.ReadToEnd(); streamReader.Close(); stream.Close(); response.Close(); return retString; } catch (Exception) { return ""; } }
2.2)微信接口方法
/// <summary> /// 获取基础支持的accessToken /// </summary> /// <param name="appid">公众号凭证ID</param> /// <param name="secret">公众号凭证密码</param> /// <returns></returns> public string GetBaseAcccessToken(string appid, string secret) { string accessToken = string.Empty; string reqUrl = string.Format(@"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret); string resultStr = HttpGet(reqUrl,""); dynamic data = JsonConvert.DeserializeObject(resultStr); if (data["access_token"] != null) { accessToken = data["access_token"].ToString(); } else { accessToken = ""; } return accessToken; } /// <summary> /// 发送微信的模板信息到用户的Openid(用户关注公众号的唯一标识) /// </summary> /// <param name="msgTempId">消息模板Id</param> /// <param name="openId">微信OpenId</param> /// <param name="firstInfo">提示信息</param> /// <param name="keyword1">参数1信息</param> /// <param name="keyword2">参数2信息</param> /// <param name="keyword3">参数3信息</param> /// <param name="keyword4">参数4信息</param> /// <param name="keyword5">参数5信息</param> /// <param name="endInfo">备注信息</param> public bool SendWxMessageToUser(string msgTempId,string openId, string firstInfo,string keyword1, string keyword2, string keyword3, string keyword4, string keyword5, string endInfo) { bool IsSuccess = false; //获取配置文件中参数(公众号ID,密码, 发送模板消息ID) var appid = ConfigurationManager.AppSettings["AppID"].ToString(); var secret = ConfigurationManager.AppSettings["AppSecret"].ToString(); // var msgTempId = ConfigurationManager.AppSettings["MsgTemplateId"].ToString(); //获取基础支持的accessToken string reqAccessToken = GetBaseAcccessToken(appid,secret); //找不到aceessToken(调用失败) if (string.IsNullOrEmpty(reqAccessToken)) { IsSuccess = false; SynLog.Info(string.Format(ErrorLogMsg, "SendWxMessageToUser", "微信发送消息失败,原因:未找到微信令牌accessToken!")); } else { //组成请求的json数据 JObject reqObj = new JObject( new JProperty("touser", openId), new JProperty("template_id",msgTempId), new JProperty("data",new JObject( new JProperty("first",new JObject { new JProperty("value", firstInfo),new JProperty("color", "#173177") }), new JProperty("keyword1", new JObject { new JProperty("value", keyword1), new JProperty("color", "#173177") }), new JProperty("keyword2", new JObject { new JProperty("value", keyword2), new JProperty("color", "#173177") }), new JProperty("keyword3", new JObject { new JProperty("value", keyword3), new JProperty("color", "#173177") }), new JProperty("keyword4", new JObject { new JProperty("value", keyword4), new JProperty("color", "#173177") }), new JProperty("keyword5", new JObject { new JProperty("value", keyword5), new JProperty("color", "#173177") }), new JProperty("remark", new JObject { new JProperty("value", endInfo), new JProperty("color", "#173177") }) )) ); //序列化转成json格式字符串 var jsonStr = JsonConvert.SerializeObject(reqObj); //请求url string reqUrl = string.Format(@"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}", reqAccessToken); string resultStr = HttpPost(reqUrl,jsonStr); //反序列化成对象 dynamic result = JsonConvert.DeserializeObject(resultStr); if (result["errmsg"].ToString() == "ok") { IsSuccess = true; SynLog.Info(string.Format(SuccessLogMsg, "SendWxMessageToUser", "微信发送消息成功!")); } else { IsSuccess = false; SynLog.Info(string.Format(ErrorLogMsg, "SendWxMessageToUser", "微信发送消息失败!")); } } return IsSuccess; }
2.3)调用微信接口方法
2.4)发送消息结果(在公众号查看)
注明:由于用模板库中的模板,列的值可能对不上,因为申请自定义模板(未审批),先用有的模板测试。