微信公眾號發送客服消息【文本、圖片】


微信公眾號發送客服消息【文本、圖片】

/// <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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM