调用接口发送模板消息
public string SendTemplate(string openId, string templateId, object data, string url, string topcolor = "#173177")
{
var msgData = new
{
touser = openId,
template_id = templateId,
topcolor = topcolor,
url = url,
data = data
};
JavaScriptSerializer Jss = new JavaScriptSerializer();
string postData = Jss.Serialize(msgData);
return WebRequestPostOrGet("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + this.getAccessToken(CommomConst.APPID, CommomConst.SECRET), postData);
}
/// <summary>
/// 带参数的Http请求
/// </summary>
/// <param name="posturl"></param>
/// <param name="postData"></param>
/// <returns></returns>
public string WebRequestPostOrGet(string posturl, string postData)
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(postData);
// 准备请求...
try
{
// 设置参数
request = WebRequest.Create(posturl) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
outstream = request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Close();
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
string err = string.Empty;
return content;
}
catch (Exception ex)
{
string err = ex.Message;
return string.Empty;
}
}
//{{first.DATA}}
//会员姓名:{{keyword1.DATA}}
//会员卡号:{{keyword2.DATA}}
//签到时间:{{keyword3.DATA}}
//班级:{{keyword4.DATA}}
//校区:{{keyword5.DATA}}
//{{remark.DATA}}
var data = new
{
first = new
{
value = "恭喜你签到成功!",
color = "#173177"
},
keyword1 = new
{
value = "巧克力",
color = "#173177"
},
keyword2 = new
{
value = "A0001",
color = "#173177"
},
keyword3 = new
{
value = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"),
color = "#173177"
},
keyword4 = new
{
value = "一班",
color = "#173177"
},
keyword5 = new
{
value = "总校",
color = "#173177"
},
remark = new
{
value = "下次记得签到哦!",
color = "#173177"
}
};
WeiXin wx= new WeiXin ();
wx.SendTemplate("OpenId", "模板ID", data, "https://mp.weixin.qq.com");