微信信息处理 微信公众平台开发教程(1)
生活随笔
收集整理的這篇文章主要介紹了
微信信息处理 微信公众平台开发教程(1)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?Senparc.Weixin SDK 是由盛派網絡(Senparc)團隊自主研發的針對微信各模塊的
開發套件(C# SDK),
已全面支持微信公眾號、微信支付、企業號、開放平臺、JSSDK、搖一搖周邊等模塊。
快使用 Senparc.Weixin SDK 輕松打造微信各平臺的擴展應用吧!
? ? 如何把SDK引入到項目中 ?看http://www.cnblogs.com/szw/p/3414732.html
? ? ?引入到項目中過后我們開始進行微信的信息處理。
? ? ?示例項目為ASP.NET MVC。 ?
? ? ? 1.登陸公眾號,然后打開基本配置。
? ? ? ?2.創建一個控制器用于接收微信post過來的數據
public class WebChartAutoController : Controller{public static readonly string Token = Config.Token;//與微信公眾賬號后臺的Token設置保持一致,區分大小寫。public static readonly string EncodingAESKey =Config.EncodingAESKey;//與微信公眾賬號后臺的EncodingAESKey設置保持一致,區分大小寫。public static readonly string AppId = Config.AppID;//與微信公眾賬號后臺的AppId設置保持一致,區分大小寫。[HttpGet][ActionName("Index")]public ActionResult Get(PostModel postModel, string echostr){if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)){return Content(echostr); //返回隨機字符串則表示驗證通過}else{return Content("failed:" + postModel.Signature + "," + Senparc.Weixin.MP.CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, Token) + "。" +"如果你在瀏覽器中看到這句話,說明此地址可以被作為微信公眾賬號后臺的Url,請注意保持Token一致。");}}/// <summary>/// 最簡化的處理流程(不加密)/// </summary>[HttpPost][ActionName("Index")]public ActionResult Index(PostModel postModel){if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)){//return Content("參數錯誤!");//v0.7-return new WeixinResult("參數錯誤!");//v0.8+}postModel.Token = Token;postModel.EncodingAESKey = EncodingAESKey;//根據自己后臺的設置保持一致postModel.AppId = AppId;//根據自己后臺的設置保持一致 var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, 10); messageHandler.Execute();//執行微信處理過程//return Content(messageHandler.ResponseDocument.ToString());//v0.7-return new FixWeixinBugWeixinResult(messageHandler);//v0.8+}}} ?3.創建一個CustomMessageHandler信息處理機制來處理微信客戶端POST過來的數據。 /// <summary>/// 自定義MessageHandler/// 把MessageHandler作為基類,重寫對應請求的處理方法/// </summary>public partial class CustomMessageHandler : MessageHandler<CustomMessageContext>{/** 重要提示:v1.5起,MessageHandler提供了一個DefaultResponseMessage的抽象方法,* DefaultResponseMessage必須在子類中重寫,用于返回沒有處理過的消息類型(也可以用于默認消息,如幫助信息等);* 其中所有原OnXX的抽象方法已經都改為虛方法,可以不必每個都重寫。若不重寫,默認返回DefaultResponseMessage方法中的結果。*/#if DEBUGstring agentUrl = "http://localhost:12222/App/Weixin/4";string agentToken = "27C455F496044A87";string wiweihiKey = "CNadjJuWzyX5bz5Gn+/XoyqiqMa5DjXQ"; #else//下面的Url和Token可以用其他平臺的消息,或者到www.weiweihi.com注冊微信用戶,將自動在“微信營銷工具”下得到private string agentUrl = WebConfigurationManager.AppSettings["WeixinAgentUrl"];//這里使用了www.weiweihi.com微信自動托管平臺private string agentToken = WebConfigurationManager.AppSettings["WeixinAgentToken"];//Tokenprivate string wiweihiKey = WebConfigurationManager.AppSettings["WeixinAgentWeiweihiKey"];//WeiweihiKey專門用于對接www.Weiweihi.com平臺,獲取方式見:http://www.weiweihi.com/ApiDocuments/Item/25#51 #endifprivate string appId = WebConfigurationManager.AppSettings["WeixinAppId"];private string appSecret = WebConfigurationManager.AppSettings["WeixinAppSecret"];/// <summary>/// 模板消息集合(Key:checkCode,Value:OpenId)/// </summary>public static Dictionary<string, string> TemplateMessageCollection = new Dictionary<string, string>();public CustomMessageHandler(Stream inputStream, PostModel postModel, int maxRecordCount = 0): base(inputStream, postModel, maxRecordCount){//這里設置僅用于測試,實際開發可以在外部更全局的地方設置,//比如MessageHandler<MessageContext>.GlobalWeixinContext.ExpireMinutes = 3。WeixinContext.ExpireMinutes = 3;if (!string.IsNullOrEmpty(postModel.AppId)){appId = postModel.AppId;//通過第三方開放平臺發送過來的請求}//在指定條件下,不使用消息去重base.OmitRepeatedMessageFunc = requestMessage =>{var textRequestMessage = requestMessage as RequestMessageText;if (textRequestMessage != null && textRequestMessage.Content == "容錯"){return false;}return true;};}public override void OnExecuting(){//測試MessageContext.StorageDataif (CurrentMessageContext.StorageData == null){CurrentMessageContext.StorageData = 0;}base.OnExecuting();}public override void OnExecuted(){base.OnExecuted();CurrentMessageContext.StorageData = ((int)CurrentMessageContext.StorageData) + 1;}/// <summary>/// 處理文字請求/// </summary>/// <returns></returns>public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage){//TODO:這里的邏輯可以交給Service處理具體信息,參考OnLocationRequest方法或/Service/LocationSercice.cs//書中例子//if (requestMessage.Content == "你好")//{// var responseMessage = base.CreateResponseMessage<ResponseMessageNews>();// var title = "Title";// var description = "Description";// var picUrl = "PicUrl";// var url = "Url";// responseMessage.Articles.Add(new Article()// {// Title = title,// Description = description,// PicUrl = picUrl,// Url = url// });// return responseMessage;//}//else if (requestMessage.Content == "Senparc")//{// //相似處理邏輯//}//else//{// //...//}//方法一(v0.1),此方法調用太過繁瑣,已過時(但仍是所有方法的核心基礎),建議使用方法二到四//var responseMessage =// ResponseMessageBase.CreateFromRequestMessage(RequestMessage, ResponseMsgType.Text) as// ResponseMessageText;//方法二(v0.4)//var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(RequestMessage);//方法三(v0.4),擴展方法,需要using Senparc.Weixin.MP.Helpers;//var responseMessage = RequestMessage.CreateResponseMessage<ResponseMessageText>();//方法四(v0.6+),僅適合在HandlerMessage內部使用,本質上是對方法三的封裝//注意:下面泛型ResponseMessageText即返回給客戶端的類型,可以根據自己的需要填寫ResponseMessageNews等不同類型。var responseMessage = base.CreateResponseMessage<ResponseMessageText>();LogHelper.WriteLog(null, "CustomMessageHandler"+ requestMessage.Content);if (requestMessage.Content == null){}else if (requestMessage.Content == "約束"){responseMessage.Content =@"您正在進行微信內置瀏覽器約束判斷測試。。";}else if (requestMessage.Content == "托管" || requestMessage.Content == "代理"){//開始用代理托管,把請求轉到其他服務器上去,然后拿回結果//甚至也可以將所有請求在DefaultResponseMessage()中托管到外部。DateTime dt1 = DateTime.Now; //計時開始var responseXml = MessageAgent.RequestXml(this, agentUrl, agentToken, RequestDocument.ToString());//獲取返回的XML//上面的方法也可以使用擴展方法:this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString());/* 如果有WeiweihiKey,可以直接使用下面的這個MessageAgent.RequestWeiweihiXml()方法。* WeiweihiKey專門用于對接www.weiweihi.com平臺,獲取方式見:http://www.weiweihi.com/ApiDocuments/Item/25#51*///var responseXml = MessageAgent.RequestWeiweihiXml(weiweihiKey, RequestDocument.ToString());//獲取Weiweihi返回的XMLDateTime dt2 = DateTime.Now; //計時結束//轉成實體。/* 如果要寫成一行,可以直接用:* responseMessage = MessageAgent.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());* 或**/var msg = string.Format("\r\n\r\n代理過程總耗時:{0}毫秒", (dt2 - dt1).Milliseconds);var agentResponseMessage = responseXml.CreateResponseMessage();if (agentResponseMessage is ResponseMessageText){(agentResponseMessage as ResponseMessageText).Content += msg;}else if (agentResponseMessage is ResponseMessageNews){(agentResponseMessage as ResponseMessageNews).Articles[0].Description += msg;}return agentResponseMessage;//可能出現多種類型,直接在這里返回}else if (requestMessage.Content == "測試" || requestMessage.Content == "退出"){/** 這是一個特殊的過程,此請求通常來自于微微嗨(http://www.weiweihi.com)的“盛派網絡小助手”應用請求(http://www.weiweihi.com/User/App/Detail/1),* 用于演示微微嗨應用商店的處理過程,由于微微嗨的應用內部可以單獨設置對話過期時間,所以這里通常不需要考慮對話狀態,只要做最簡單的響應。*/if (requestMessage.Content == "測試"){//進入APP測試responseMessage.Content = "您已經進入。";}else{//退出APP測試responseMessage.Content = "您已經退出。";}}else if (requestMessage.Content == "AsyncTest"){//異步并發測試(提供給單元測試使用)DateTime begin = DateTime.Now;int t1, t2, t3;System.Threading.ThreadPool.GetAvailableThreads(out t1, out t3);System.Threading.ThreadPool.GetMaxThreads(out t2, out t3);System.Threading.Thread.Sleep(TimeSpan.FromSeconds(4));DateTime end = DateTime.Now;var thread = System.Threading.Thread.CurrentThread;responseMessage.Content = string.Format("TId:{0}\tApp:{1}\tBegin:{2:mm:ss,ffff}\tEnd:{3:mm:ss,ffff}\tTPool:{4}",thread.ManagedThreadId,HttpContext.Current != null ? HttpContext.Current.ApplicationInstance.GetHashCode() : -1,begin,end,t2 - t1);}else if (requestMessage.Content.ToUpper() == "OPEN"){var openResponseMessage = requestMessage.CreateResponseMessage<ResponseMessageNews>();openResponseMessage.Articles.Add(new Article(){Title = "開放平臺微信授權測試",Description = @"點擊進入Open授權頁面。。",Url = "http://sdk.weixin.senparc.com/OpenOAuth/JumpToMpOAuth"});return openResponseMessage;}else if (requestMessage.Content == "錯誤"){var errorResponseMessage = requestMessage.CreateResponseMessage<ResponseMessageText>();//因為沒有設置errorResponseMessage.Content,所以這小消息將無法正確返回。return errorResponseMessage;}else if (requestMessage.Content == "容錯"){Thread.Sleep(1500);//故意延時1.5秒,讓微信多次發送消息過來,觀察返回結果var faultTolerantResponseMessage = requestMessage.CreateResponseMessage<ResponseMessageText>();faultTolerantResponseMessage.Content = string.Format("測試容錯,MsgId:{0},Ticks:{1}", requestMessage.MsgId,DateTime.Now.Ticks);return faultTolerantResponseMessage;}else if (requestMessage.Content.ToUpper() == "TM")//異步模板消息設置{var openId = requestMessage.FromUserName;var checkCode = Guid.NewGuid().ToString("n").Substring(0, 3);//為了防止openId泄露造成騷擾,這里啟用驗證碼TemplateMessageCollection[checkCode] = openId;responseMessage.Content = string.Format(@"新的驗證碼為:{0},請在網頁上輸入", checkCode);}else if (requestMessage.Content.ToUpper() == "OPENID") //返回OpenId及用戶信息{var openId = requestMessage.FromUserName;//獲取OpenIdvar userInfo = AdvancedAPIs.UserApi.Info(appId, openId, Language.zh_CN);responseMessage.Content = string.Format("您的OpenID為:{0}\r\n昵稱:{1}\r\n性別:{2}\r\n地區(國家/省/市):{3}/{4}/{5}\r\n關注時間:{6}\r\n關注狀態:{7}",requestMessage.FromUserName, userInfo.nickname, (Sex)userInfo.sex, userInfo.country, userInfo.province, userInfo.city, DateTimeHelper.GetDateTimeFromXml(userInfo.subscribe_time), userInfo.subscribe);}else if (requestMessage.Content.ToUpper() == "EX"){var ex = new WeixinException("openid:" + requestMessage.FromUserName + ":這是一條測試異常信息");//回調過程在global的ConfigWeixinTraceLog()方法中responseMessage.Content = "請等待異步模板消息發送到此界面上(自動延時數秒)。\r\n當前時間:" + DateTime.Now.ToString();}else{var result = new StringBuilder();result.AppendFormat("您剛才發送了文字信息:{0}\r\n\r\n", requestMessage.Content);if (CurrentMessageContext.RequestMessages.Count > 1){result.AppendFormat("您剛才還發送了如下消息({0}/{1}):\r\n", CurrentMessageContext.RequestMessages.Count,CurrentMessageContext.StorageData);for (int i = CurrentMessageContext.RequestMessages.Count - 2; i >= 0; i--){var historyMessage = CurrentMessageContext.RequestMessages[i];result.AppendFormat("{0} 【{1}】{2}\r\n",historyMessage.CreateTime.ToShortTimeString(),historyMessage.MsgType.ToString(),(historyMessage is RequestMessageText)? (historyMessage as RequestMessageText).Content: "[非文字類型]");}result.AppendLine("\r\n");}result.AppendFormat("如果您在{0}分鐘內連續發送消息,記錄將被自動保留(當前設置:最多記錄{1}條)。過期后記錄將會自動清除。\r\n",WeixinContext.ExpireMinutes, WeixinContext.MaxRecordCount);result.AppendLine("\r\n");result.AppendLine("您還可以發送【位置】【圖片】【語音】【視頻】等類型的信息(注意是這幾種類型,不是這幾個文字),查看不同格式的回復。\r\nSDK官方地址:http://sdk.weixin.senparc.com");responseMessage.Content = result.ToString();}return responseMessage;}/// <summary>/// 處理位置請求/// </summary>/// <param name="requestMessage"></param>/// <returns></returns>public override IResponseMessageBase OnLocationRequest(RequestMessageLocation requestMessage){var locationService = new LocationService();var responseMessage = locationService.GetResponseMessage(requestMessage as RequestMessageLocation);return responseMessage;}public override IResponseMessageBase OnShortVideoRequest(RequestMessageShortVideo requestMessage){var responseMessage = this.CreateResponseMessage<ResponseMessageText>();responseMessage.Content = "您剛才發送的是小視頻";return responseMessage;}/// <summary>/// 處理圖片請求/// </summary>/// <param name="requestMessage"></param>/// <returns></returns>public override IResponseMessageBase OnImageRequest(RequestMessageImage requestMessage){var responseMessage = CreateResponseMessage<ResponseMessageNews>();responseMessage.Articles.Add(new Article(){Title = "您剛才發送了圖片信息",Description = "您發送的圖片將會顯示在邊上",PicUrl = requestMessage.PicUrl,Url = "http://sdk.weixin.senparc.com"});responseMessage.Articles.Add(new Article(){Title = "第二條",Description = "第二條帶連接的內容",PicUrl = requestMessage.PicUrl,Url = "http://sdk.weixin.senparc.com"});return responseMessage;}/// <summary>/// 處理語音請求/// </summary>/// <param name="requestMessage"></param>/// <returns></returns>public override IResponseMessageBase OnVoiceRequest(RequestMessageVoice requestMessage){var responseMessage = CreateResponseMessage<ResponseMessageMusic>();//上傳縮略圖var accessToken = Containers.AccessTokenContainer.TryGetAccessToken(appId, appSecret);var uploadResult = AdvancedAPIs.MediaApi.UploadTemporaryMedia(accessToken, UploadMediaFileType.image, System.Web.HttpContext.Current.Server.MapPath("~/Images/Logo.jpg"));//設置音樂信息responseMessage.Music.Title = "天籟之音";responseMessage.Music.Description = "播放您上傳的語音";responseMessage.Music.MusicUrl = "http://sdk.weixin.senparc.com/Media/GetVoice?mediaId=" + requestMessage.MediaId;responseMessage.Music.HQMusicUrl = "http://sdk.weixin.senparc.com/Media/GetVoice?mediaId=" + requestMessage.MediaId;responseMessage.Music.ThumbMediaId = uploadResult.media_id;return responseMessage;}/// <summary>/// 處理視頻請求/// </summary>/// <param name="requestMessage"></param>/// <returns></returns>public override IResponseMessageBase OnVideoRequest(RequestMessageVideo requestMessage){var responseMessage = CreateResponseMessage<ResponseMessageText>();responseMessage.Content = "您發送了一條視頻信息,ID:" + requestMessage.MediaId;return responseMessage;}/// <summary>/// 處理鏈接消息請求/// </summary>/// <param name="requestMessage"></param>/// <returns></returns>public override IResponseMessageBase OnLinkRequest(RequestMessageLink requestMessage){var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);responseMessage.Content = string.Format(@"您發送了一條連接信息: Title:{0} Description:{1} Url:{2}", requestMessage.Title, requestMessage.Description, requestMessage.Url);return responseMessage;}/// <summary>/// 處理事件請求(這個方法一般不用重寫,這里僅作為示例出現。除非需要在判斷具體Event類型以外對Event信息進行統一操作/// </summary>/// <param name="requestMessage"></param>/// <returns></returns>public override IResponseMessageBase OnEventRequest(IRequestMessageEventBase requestMessage){var eventResponseMessage = base.OnEventRequest(requestMessage);//對于Event下屬分類的重寫方法,見:CustomerMessageHandler_Events.cs//TODO: 對Event信息進行統一操作return eventResponseMessage;}public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage){/* 所有沒有被處理的消息會默認返回這里的結果,* 因此,如果想把整個微信請求委托出去(例如需要使用分布式或從其他服務器獲取請求),* 只需要在這里統一發出委托請求,如:* var responseMessage = MessageAgent.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());* return responseMessage;*/var responseMessage = this.CreateResponseMessage<ResponseMessageText>();responseMessage.Content = "這條消息來自DefaultResponseMessage。";return responseMessage;}} }這兒是針對于Event下屬分類的重寫方法 /*----------------------------------------------------------------Copyright (C) 2017 Senparc文件名:CustomMessageHandler_Events.cs文件功能描述:自定義MessageHandler創建標識:Senparc - 20150312 ----------------------------------------------------------------*/using System; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using System.Web; using Senparc.Weixin.MP.Agent; using Senparc.Weixin.Context; using Senparc.Weixin.Exceptions; using Senparc.Weixin.HttpUtility; using Senparc.Weixin.MP.Entities; using Senparc.Weixin.MP.Helpers; using Senparc.Weixin.MP.MessageHandlers; using Senparc.Weixin.MP.Sample.CommonService.Download;namespace Senparc.Weixin.MP.Sample.CommonService.CustomMessageHandler {/// <summary>/// 自定義MessageHandler/// </summary>public partial class CustomMessageHandler{private string GetWelcomeInfo(){//獲取Senparc.Weixin.MP.dll版本信息var fileVersionInfo = FileVersionInfo.GetVersionInfo(HttpContext.Current.Server.MapPath("~/bin/Senparc.Weixin.MP.dll"));var version = string.Format("{0}.{1}.{2}", fileVersionInfo.FileMajorPart, fileVersionInfo.FileMinorPart, fileVersionInfo.FileBuildPart);return string.Format( @"歡迎關注【Senparc.Weixin.MP 微信公眾平臺SDK】,當前運行版本:v{0}。 您可以發送【文字】【位置】【圖片】【語音】等不同類型的信息,查看不同格式的回復。您也可以直接點擊菜單查看各種類型的回復。 還可以點擊菜單體驗微信支付。SDK官方地址:https://weixin.senparc.com SDK Demo:http://sdk.weixin.senparc.com 源代碼及Demo下載地址:https://github.com/JeffreySu/WeiXinMPSDK Nuget地址:https://www.nuget.org/packages/Senparc.Weixin.MP QQ群:342319110=============== 更多:1、JSSDK測試:http://sdk.weixin.senparc.com/WeixinJSSDK2、開放平臺測試(建議PC上打開):http://sdk.weixin.senparc.com/OpenOAuth/JumpToMpOAuth3、回復關鍵字:【open】 進入第三方開放平臺(Senparc.Weixin.Open)測試【tm】 測試異步模板消息【openid】 獲取OpenId等用戶信息【約束】 測試微信瀏覽器約束【AsyncTest】 異步并發測試【錯誤】 體驗發生錯誤無法返回正確信息【容錯】 體驗去重容錯【ex】 體驗錯誤日志推送提醒 ",version);}public string GetDownloadInfo(CodeRecord codeRecord){return string.Format(@"您已通過二維碼驗證,瀏覽器即將開始下載 Senparc.Weixin SDK 幫助文檔。 當前選擇的版本:v{0}({1})我們期待您的意見和建議,客服熱線:400-031-8816。感謝您對盛派網絡的支持!? 2016 Senparc", codeRecord.Version, codeRecord.IsWebVersion ? "網頁版" : ".chm文檔版");}public override IResponseMessageBase OnTextOrEventRequest(RequestMessageText requestMessage){// 預處理文字或事件類型請求。// 這個請求是一個比較特殊的請求,通常用于統一處理來自文字或菜單按鈕的同一個執行邏輯,// 會在執行OnTextRequest或OnEventRequest之前觸發,具有以下一些特征:// 1、如果返回null,則繼續執行OnTextRequest或OnEventRequest// 2、如果返回不為null,則終止執行OnTextRequest或OnEventRequest,返回最終ResponseMessage// 3、如果是事件,則會將RequestMessageEvent自動轉為RequestMessageText類型,其中RequestMessageText.Content就是RequestMessageEvent.EventKeyif (requestMessage.Content == "OneClick"){var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();strongResponseMessage.Content = "您點擊了底部按鈕。\r\n為了測試微信軟件換行bug的應對措施,這里做了一個——\r\n換行";return strongResponseMessage;}return null;//返回null,則繼續執行OnTextRequest或OnEventRequest}public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage){IResponseMessageBase reponseMessage = null;//菜單點擊,需要跟創建菜單時的Key匹配switch (requestMessage.EventKey){case "OneClick":{//這個過程實際已經在OnTextOrEventRequest中完成,這里不會執行到。var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();reponseMessage = strongResponseMessage;strongResponseMessage.Content = "您點擊了底部按鈕。\r\n為了測試微信軟件換行bug的應對措施,這里做了一個——\r\n換行";}break;case "SubClickRoot_Text":{var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();reponseMessage = strongResponseMessage;strongResponseMessage.Content = "您點擊了子菜單按鈕。";}break;case "SubClickRoot_News":{var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();reponseMessage = strongResponseMessage;strongResponseMessage.Articles.Add(new Article(){Title = "您點擊了子菜單圖文按鈕",Description = "您點擊了子菜單圖文按鈕,這是一條圖文信息。",PicUrl = "http://sdk.weixin.senparc.com/Images/qrcode.jpg",Url = "http://sdk.weixin.senparc.com"});}break;case "SubClickRoot_Music":{//上傳縮略圖var accessToken = Containers.AccessTokenContainer.TryGetAccessToken(appId, appSecret);var uploadResult = AdvancedAPIs.MediaApi.UploadTemporaryMedia(accessToken, UploadMediaFileType.thumb,System.Web.HttpContext.Current.Server.MapPath("~/Images/Logo.jpg"));//設置音樂信息var strongResponseMessage = CreateResponseMessage<ResponseMessageMusic>();reponseMessage = strongResponseMessage;strongResponseMessage.Music.Title = "天籟之音";strongResponseMessage.Music.Description = "真的是天籟之音";strongResponseMessage.Music.MusicUrl = "http://sdk.weixin.senparc.com/Content/music1.mp3";strongResponseMessage.Music.HQMusicUrl = "http://sdk.weixin.senparc.com/Content/music1.mp3";strongResponseMessage.Music.ThumbMediaId = uploadResult.thumb_media_id;}break;case "SubClickRoot_Image":{//上傳圖片var accessToken = Containers.AccessTokenContainer.TryGetAccessToken(appId, appSecret);var uploadResult = AdvancedAPIs.MediaApi.UploadTemporaryMedia(accessToken, UploadMediaFileType.image,System.Web.HttpContext.Current.Server.MapPath("~/Images/Logo.jpg"));//設置圖片信息var strongResponseMessage = CreateResponseMessage<ResponseMessageImage>();reponseMessage = strongResponseMessage;strongResponseMessage.Image.MediaId = uploadResult.media_id;}break;case "SubClickRoot_Agent"://代理消息{//獲取返回的XMLDateTime dt1 = DateTime.Now;reponseMessage = MessageAgent.RequestResponseMessage(this, agentUrl, agentToken, RequestDocument.ToString());//上面的方法也可以使用擴展方法:this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString());DateTime dt2 = DateTime.Now;if (reponseMessage is ResponseMessageNews){(reponseMessage as ResponseMessageNews).Articles[0].Description += string.Format("\r\n\r\n代理過程總耗時:{0}毫秒", (dt2 - dt1).Milliseconds);}}break;case "Member"://托管代理會員信息{//原始方法為:MessageAgent.RequestXml(this,agentUrl, agentToken, RequestDocument.ToString());//獲取返回的XMLreponseMessage = this.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());}break;case "OAuth"://OAuth授權測試{var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();strongResponseMessage.Articles.Add(new Article(){Title = "OAuth2.0測試",Description = "選擇下面兩種不同的方式進行測試,區別在于授權成功后,最后停留的頁面。",//Url = "http://sdk.weixin.senparc.com/oauth2",//PicUrl = "http://sdk.weixin.senparc.com/Images/qrcode.jpg"});strongResponseMessage.Articles.Add(new Article(){Title = "OAuth2.0測試(不帶returnUrl),測試環境可使用",Description = "OAuth2.0測試(不帶returnUrl)",Url = "http://sdk.weixin.senparc.com/oauth2",PicUrl = "http://sdk.weixin.senparc.com/Images/qrcode.jpg"});var returnUrl = "/OAuth2/TestReturnUrl";strongResponseMessage.Articles.Add(new Article(){Title = "OAuth2.0測試(帶returnUrl),生產環境強烈推薦使用",Description = "OAuth2.0測試(帶returnUrl)",Url = "http://sdk.weixin.senparc.com/oauth2?returnUrl=" + returnUrl.UrlEncode(),PicUrl = "http://sdk.weixin.senparc.com/Images/qrcode.jpg"});reponseMessage = strongResponseMessage;}break;case "Description":{var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();strongResponseMessage.Content = GetWelcomeInfo();reponseMessage = strongResponseMessage;}break;case "SubClickRoot_PicPhotoOrAlbum":{var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();reponseMessage = strongResponseMessage;strongResponseMessage.Content = "您點擊了【微信拍照】按鈕。系統將會彈出拍照或者相冊發圖。";}break;case "SubClickRoot_ScancodePush":{var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();reponseMessage = strongResponseMessage;strongResponseMessage.Content = "您點擊了【微信掃碼】按鈕。";}break;case "ConditionalMenu_Male":{var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();reponseMessage = strongResponseMessage;strongResponseMessage.Content = "您點擊了個性化菜單按鈕,您的微信性別設置為:男。";}break;case "ConditionalMenu_Femle":{var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();reponseMessage = strongResponseMessage;strongResponseMessage.Content = "您點擊了個性化菜單按鈕,您的微信性別設置為:女。";}break;default:{var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();strongResponseMessage.Content = "您點擊了按鈕,EventKey:" + requestMessage.EventKey;reponseMessage = strongResponseMessage;}break;}return reponseMessage;}public override IResponseMessageBase OnEvent_EnterRequest(RequestMessageEvent_Enter requestMessage){var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);responseMessage.Content = "您剛才發送了ENTER事件請求。";return responseMessage;}public override IResponseMessageBase OnEvent_LocationRequest(RequestMessageEvent_Location requestMessage){//這里是微信客戶端(通過微信服務器)自動發送過來的位置信息var responseMessage = CreateResponseMessage<ResponseMessageText>();responseMessage.Content = "這里寫什么都無所謂,比如:上帝愛你!";return responseMessage;//這里也可以返回null(需要注意寫日志時候null的問題)}public override IResponseMessageBase OnEvent_ScanRequest(RequestMessageEvent_Scan requestMessage){//通過掃描關注var responseMessage = CreateResponseMessage<ResponseMessageText>();//下載文檔//if (!string.IsNullOrEmpty(requestMessage.EventKey))//{// var sceneId = long.Parse(requestMessage.EventKey.Replace("qrscene_", ""));// //var configHelper = new ConfigHelper(new HttpContextWrapper(HttpContext.Current));// var codeRecord =// ConfigHelper.CodeCollection.Values.FirstOrDefault(z => z.QrCodeTicket != null && z.QrCodeId == sceneId);// if (codeRecord != null)// {// //確認可以下載// codeRecord.AllowDownload = true;// responseMessage.Content = GetDownloadInfo(codeRecord);// }//}responseMessage.Content = responseMessage.Content ?? string.Format("通過掃描二維碼進入,場景值:{0}", requestMessage.EventKey);return responseMessage;}public override IResponseMessageBase OnEvent_ViewRequest(RequestMessageEvent_View requestMessage){//說明:這條消息只作為接收,下面的responseMessage到達不了客戶端,類似OnEvent_UnsubscribeRequestvar responseMessage = CreateResponseMessage<ResponseMessageText>();responseMessage.Content = "您點擊了view按鈕,將打開網頁:" + requestMessage.EventKey;return responseMessage;}public override IResponseMessageBase OnEvent_MassSendJobFinishRequest(RequestMessageEvent_MassSendJobFinish requestMessage){var responseMessage = CreateResponseMessage<ResponseMessageText>();responseMessage.Content = "接收到了群發完成的信息。";return responseMessage;}/// <summary>/// 訂閱(關注)事件/// </summary>/// <returns></returns>public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage){var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);responseMessage.Content = GetWelcomeInfo();if (!string.IsNullOrEmpty(requestMessage.EventKey)){responseMessage.Content += "\r\n============\r\n場景值:" + requestMessage.EventKey;}//推送消息//下載文檔if (requestMessage.EventKey.StartsWith("qrscene_")){var sceneId = long.Parse(requestMessage.EventKey.Replace("qrscene_", ""));//var configHelper = new ConfigHelper(new HttpContextWrapper(HttpContext.Current));//var codeRecord =// ConfigHelper.CodeCollection.Values.FirstOrDefault(z => z.QrCodeTicket != null && z.QrCodeId == sceneId);//if (codeRecord != null)//{// if (codeRecord.AllowDownload)// {// Task.Factory.StartNew(() => AdvancedAPIs.CustomApi.SendTextAsync(null, WeixinOpenId, "下載已經開始,如需下載其他版本,請刷新頁面后重新掃一掃。"));// }// else// {// //確認可以下載// codeRecord.AllowDownload = true;// Task.Factory.StartNew(() => AdvancedAPIs.CustomApi.SendTextAsync(null, WeixinOpenId, GetDownloadInfo(codeRecord)));// }//}}return responseMessage;}/// <summary>/// 退訂/// 實際上用戶無法收到非訂閱賬號的消息,所以這里可以隨便寫。/// unsubscribe事件的意義在于及時刪除網站應用中已經記錄的OpenID綁定,消除冗余數據。并且關注用戶流失的情況。/// </summary>/// <returns></returns>public override IResponseMessageBase OnEvent_UnsubscribeRequest(RequestMessageEvent_Unsubscribe requestMessage){var responseMessage = base.CreateResponseMessage<ResponseMessageText>();responseMessage.Content = "有空再來";return responseMessage;}/// <summary>/// 事件之掃碼推事件(scancode_push)/// </summary>/// <param name="requestMessage"></param>/// <returns></returns>public override IResponseMessageBase OnEvent_ScancodePushRequest(RequestMessageEvent_Scancode_Push requestMessage){var responseMessage = base.CreateResponseMessage<ResponseMessageText>();responseMessage.Content = "事件之掃碼推事件";return responseMessage;}/// <summary>/// 事件之掃碼推事件且彈出“消息接收中”提示框(scancode_waitmsg)/// </summary>/// <param name="requestMessage"></param>/// <returns></returns>public override IResponseMessageBase OnEvent_ScancodeWaitmsgRequest(RequestMessageEvent_Scancode_Waitmsg requestMessage){var responseMessage = base.CreateResponseMessage<ResponseMessageText>();responseMessage.Content = "事件之掃碼推事件且彈出“消息接收中”提示框";return responseMessage;}/// <summary>/// 事件之彈出拍照或者相冊發圖(pic_photo_or_album)/// </summary>/// <param name="requestMessage"></param>/// <returns></returns>public override IResponseMessageBase OnEvent_PicPhotoOrAlbumRequest(RequestMessageEvent_Pic_Photo_Or_Album requestMessage){var responseMessage = base.CreateResponseMessage<ResponseMessageText>();responseMessage.Content = "事件之彈出拍照或者相冊發圖";return responseMessage;}/// <summary>/// 事件之彈出系統拍照發圖(pic_sysphoto)/// 實際測試時發現微信并沒有推送RequestMessageEvent_Pic_Sysphoto消息,只能接收到用戶在微信中發送的圖片消息。/// </summary>/// <param name="requestMessage"></param>/// <returns></returns>public override IResponseMessageBase OnEvent_PicSysphotoRequest(RequestMessageEvent_Pic_Sysphoto requestMessage){var responseMessage = base.CreateResponseMessage<ResponseMessageText>();responseMessage.Content = "事件之彈出系統拍照發圖";return responseMessage;}/// <summary>/// 事件之彈出微信相冊發圖器(pic_weixin)/// </summary>/// <param name="requestMessage"></param>/// <returns></returns>public override IResponseMessageBase OnEvent_PicWeixinRequest(RequestMessageEvent_Pic_Weixin requestMessage){var responseMessage = base.CreateResponseMessage<ResponseMessageText>();responseMessage.Content = "事件之彈出微信相冊發圖器";return responseMessage;}/// <summary>/// 事件之彈出地理位置選擇器(location_select)/// </summary>/// <param name="requestMessage"></param>/// <returns></returns>public override IResponseMessageBase OnEvent_LocationSelectRequest(RequestMessageEvent_Location_Select requestMessage){var responseMessage = base.CreateResponseMessage<ResponseMessageText>();responseMessage.Content = "事件之彈出地理位置選擇器";return responseMessage;}/// <summary>/// 事件之發送模板消息返回結果/// </summary>/// <param name="requestMessage"></param>/// <returns></returns>public override IResponseMessageBase OnEvent_TemplateSendJobFinishRequest(RequestMessageEvent_TemplateSendJobFinish requestMessage){switch (requestMessage.Status){case "success"://發送成功break;case "failed:user block"://送達由于用戶拒收(用戶設置拒絕接收公眾號消息)而失敗break;case "failed: system failed"://送達由于其他原因失敗break;default:throw new WeixinException("未知模板消息狀態:" + requestMessage.Status);}//注意:此方法內不能再發送模板消息,否則會造成無限循環!//無需回復文字內容//return requestMessage// .CreateResponseMessage<ResponseMessageNoResponse>();return null;}} }
然后就行了,~~~~
?
總結
以上是生活随笔為你收集整理的微信信息处理 微信公众平台开发教程(1)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【测试】用例篇2(黑盒测试的测试用例)
- 下一篇: 输电线路导线舞动预警装置