接口介绍
当用户主动发消息给公众号的时候(包括发送信息、点击自定义菜单、订阅事件、扫描二维码事件、支付成功事件、用户维权),微信将会把消息数据推送给开发者,开发者在一段时间内(目前修改为48小时)可以调用客服消息接口,通过POST一个JSON数据包来发送消息给普通用户,在48小时内不限制发送次数。此接口主要用于客服等有人工消息处理环节的功能,方便开发者为用户提供更加优质的服务。
http请求方式: POST
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
ACCESS_TOKEN获取方法可以在这里查看
POST数据示例如下:
{
"touser":"OPENID",//客户openid
"template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",//模板id,可在公众号设置消息模板那里获取
"url":"http://weixin.qq.com/download",
"data":{
"first": {
"value":"恭喜你购买成功!",
"color":"#173177"
},
"keynote1":{
"value":"巧克力",
"color":"#173177"
},
"keynote2": {
"value":"39.8元",
"color":"#173177"
},
"keynote3": {
"value":"2014年9月22日",
"color":"#173177"
},
"remark":{
"value":"欢迎再次购买!",
"color":"#173177"
}
}
}
返回码说明
在调用模板消息接口后,会返回JSON数据包。正常时的返回JSON数据包示例:
{
"errcode":0,
"errmsg":"ok",
"msgid":200228332
}
C#调用客服接口给客户主动发送信息:
/// <summary>
/// 调用客服接口给客户主动发送信息
/// </summary>
/// <param name="responseJson">请求Json</param>
private void sendServiceMsg(string responseJson)
{
try
{
//声明一个HttpWebRequest请求
string interfaceUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + AccessToken;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(interfaceUrl);
//设置连接超时时间
request.Timeout = 30000;
request.KeepAlive = true;
Encoding encodeType = Encoding.GetEncoding("UTF-8");
request.Headers.Set("Pragma", "no-cache");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; Maxthon; .NET CLR 1.1.4322); Http STdns";
request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
request.CookieContainer = new CookieContainer();
byte[] Bytes = encodeType.GetBytes(responseJson);
request.ContentLength = Bytes.Length;
request.AllowAutoRedirect = true;
//发送数据
using (Stream writer = request.GetRequestStream())
{
writer.Write(Bytes, 0, Bytes.Length);
writer.Close();
}
StringBuilder strb = new StringBuilder();
//接收数据
using (Stream reader = request.GetResponse().GetResponseStream())
{
StreamReader sr = new StreamReader(reader, encodeType);
strb.Append(sr.ReadToEnd());
sr.Close();
reader.Close();
}
if ((strb.ToString().IndexOf("\"errcode\":42001") != -1) || (strb.ToString().IndexOf("\"errcode\":40001") != -1) || (strb.ToString().IndexOf("\"errcode\":40014") != -1) || (strb.ToString().IndexOf("\"errcode\":41001") != -1))
{
//access_token错误
}
}
catch
{
}
}