微信公众号发送客服消息【文本、图片】
/// <summary>
/// 微信用户唯一标识OpenId /// </summary> public static string OpenId; /// <summary> /// 返回异常信息 /// </summary> public string StrReturn { get; set; }public class ResultJsonModel
{ public string type { get; set; } public string media_id { get; set; } public string created_at { get; set; } }发送事件:
OpenId = "用户openid";
if (!string.IsNullOrEmpty(Txt_PostSendText.Text.Trim()))
{ try { string Msg = SendText(OpenId, Txt_PostSendText.Text.Trim());//文本 LogUtil.WriteLog(" Msg: " + Msg); if (Msg != null) { Response.Write("<script>alert('【系统提示】消息发送成功!')</script>"); return; } else { Response.Write("<script>alert('【系统提示】消息发送失败!')</script>"); LogUtil.WriteLog("消息发送失败 错误返回结果: " + Msg); } } catch (Exception ex) {StrReturn = ex.Message;
LogUtil.WriteLog(" 返回 StrReturn :" + StrReturn); } } else if (!string.IsNullOrEmpty(this.FileUpload1.FileName))//图片 { if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/SendImagePath/"))) { System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/SendImagePath/")); } string path = HttpContext.Current.Server.MapPath("~/SendImagePath/"+FileUpload1.PostedFile.FileName); string url = GetMedia_id();//获取发送上传媒体标识接口url string UploadFileMsg = HttpUploadFile(url, path);//获取上传后的媒体标识Json字符串 var model = JsonConvert.DeserializeObject<ResultJsonModel>(UploadFileMsg); var Media_id = model.media_id; var SendMsg = SendImage(OpenId, Media_id); object End = (((Newtonsoft.Json.Linq.JValue)(((((Newtonsoft.Json.Linq.JContainer)(JsonConvert.DeserializeObject(SendMsg)))).Last).Last))).Value; string end = End.ToString(); if (end == "ok")//接受返回结果return { Response.Write("<script>alert('【系统提示】消息发送成功!')</script>"); return; } else { Response.Write("<script>alert('【系统提示】消息发送失败!')</script>"); LogUtil.WriteLog("消息发送失败 错误返回结果: " + SendMsg); } } else { Response.Write("<script>alert('【系统提示】请输入需要发送的消息!')</script>"); } }if (!string.IsNullOrEmpty(Txt_PostSendText.Text.Trim()))
{ try { string Msg = SendText(OpenId, Txt_PostSendText.Text.Trim());//文本 LogUtil.WriteLog(" Msg: " + Msg); if (Msg != null) { Response.Write("<script>alert('【系统提示】消息发送成功!')</script>"); return; } else { Response.Write("<script>alert('【系统提示】消息发送失败!')</script>"); LogUtil.WriteLog("消息发送失败 错误返回结果: " + Msg); } } catch (Exception ex) {StrReturn = ex.Message;
LogUtil.WriteLog(" 返回 StrReturn :" + StrReturn); } } else if (!string.IsNullOrEmpty(this.FileUpload1.FileName))//图片 { if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/SendImagePath/"))) { System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/SendImagePath/")); } string path = HttpContext.Current.Server.MapPath("~/SendImagePath/"+FileUpload1.PostedFile.FileName); string url = GetMedia_id();//获取发送上传媒体标识接口url string UploadFileMsg = HttpUploadFile(url, path);//获取上传后的媒体标识Json字符串 var model = JsonConvert.DeserializeObject<ResultJsonModel>(UploadFileMsg); var Media_id = model.media_id; var SendMsg = SendImage(OpenId, Media_id); object End = (((Newtonsoft.Json.Linq.JValue)(((((Newtonsoft.Json.Linq.JContainer)(JsonConvert.DeserializeObject(SendMsg)))).Last).Last))).Value; string end = End.ToString(); if (end == "ok")//接受返回结果return { Response.Write("<script>alert('【系统提示】消息发送成功!')</script>"); return; } else { Response.Write("<script>alert('【系统提示】消息发送失败!')</script>"); LogUtil.WriteLog("消息发送失败 错误返回结果: " + SendMsg); } } else { Response.Write("<script>alert('【系统提示】请输入需要发送的消息!')</script>"); } }#region 获取普通url
public string GetKFSend() { OpenModel open = GetAccess_token(PayConfig.AppId, PayConfig.AppSecret); string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}", open.access_token); return url; } #endregion#region 获取普通url
public string GetKFSend() { OpenModel open = GetAccess_token(PayConfig.AppId, PayConfig.AppSecret); string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}", open.access_token); return url; } #endregion#region 发送文本
/// <summary>
/// 发送文本 /// </summary> /// <param name="openid">用户Openid</param> /// <param name="content">发送内容</param> /// <returns></returns> public string SendText(string openid, string content) { string url = GetKFSend(); JObject data = new JObject(); data.Add("touser", openid); data.Add("msgtype", "text"); data.Add("text", JObject.FromObject(new { content = content })); LogUtil.WriteLog(" data :" + data.ToString()); string result = GetResponseData(data.ToString(), url); return result; } #endregion#region 发送图片
/// <summary>
/// 发送图片 /// </summary> /// <param name="openid">用户OpenId</param> /// <param name="media_id">图片唯一标识</param> /// <returns></returns> public string SendImage(string openid, string media_id) { string url = GetKFSend(); JObject data = new JObject(); data.Add("touser", openid); data.Add("msgtype", "image"); data.Add("image", JObject.FromObject(new { media_id = media_id }));string result = GetResponseData(data.ToString(), url);
return result; } #endregion#region 获取access_token
private OpenModel GetAccess_token(string appid, string secret) { string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;//获取appid及secret OpenModel mode = new OpenModel(); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strUrl); req.Method = "GET"; using (WebResponse wr = req.GetResponse()) { HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse(); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd();//在这里对Access_token 赋值 //如错误需添加白名单以刷新Access_Token OpenModel token = new OpenModel(); token = JsonConvert.DeserializeObject<OpenModel>(content); mode.access_token = token.access_token; mode.expires_in = token.expires_in; } return mode; } #endregion#region Post 请求返回json数据
/// <summary> /// POST请求Json数据 /// </summary> /// <param name="JSONData"></param> /// <param name="Url"></param> /// <returns></returns> public string GetResponseData(string JSONData, string Url) { byte[] bytes = Encoding.UTF8.GetBytes(JSONData); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentLength = bytes.Length; request.ContentType = "json"; Stream reqstream = request.GetRequestStream(); reqstream.Write(bytes, 0, bytes.Length);//声明一个HttpWebRequest请求
request.Timeout = 90000; //设置连接超时时间 request.Headers.Set("Pragma", "no-cache"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream streamReceive = response.GetResponseStream(); Encoding encoding = Encoding.UTF8;StreamReader streamReader = new StreamReader(streamReceive, encoding);
string strResult = streamReader.ReadToEnd(); streamReceive.Dispose(); streamReader.Dispose(); return strResult; } #endregion#region HttpUploadFile上传文件
public static string HttpUploadFile(string url, string path) { try {// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线 request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");int pos = path.LastIndexOf("\\");
string fileName = path.Substring(pos + 1);//请求头部信息
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName)); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] bArr = new byte[fs.Length]; fs.Read(bArr, 0, bArr.Length); fs.Close();Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); postStream.Write(bArr, 0, bArr.Length); postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); postStream.Close();//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream instream = response.GetResponseStream(); StreamReader sr = new StreamReader(instream, Encoding.UTF8); //返回结果网页(html)代码 string content = sr.ReadToEnd(); return content; } catch (Exception ex) { return ex.Message; LogUtil.WriteLog(" HttpUploadFile : "+ex.Message); } } #endregion