最近幾個月本人與團隊一直與小程序打交道,對小程序的實戰開發算比較熟悉,也因一些朋友經常問我各種小程序問題,無不能一一回答,想了很久,決定還是空余時間來寫寫文章吧,偶爾發現一個人安靜的時候寫文章特爽,不信大伙可以試試哦^_^
一般項目開發已快速為主,這時想到了一個小程序開源框架,盛派Senparc,這個項目使用過程中確實很爽,開發速度賊快,想了解底層原理的同學可以下載盛派Senparc開源項目,開原址址附文章底部。
小程序開發系統文章就此誕生了,后面文章會覆蓋小程序的所有功能,希望對剛步入小程序開的同學有所幫助。
目錄
一、微信公眾平台開發者設置
二、新建.netcore 項目與微信服務器牽手
三、開發者服務器自動回復
四、各種消息類型處理
五、總結
微信公眾平台開發者設置
登錄微信公眾平台小程序后台,開發設置-消息推送,啟用開發者,填寫相關信息,如下圖
配置好后,點擊提交,會校驗與服務器牽手動作,此時要保證服務地址能正常訪問。
如不清楚的,請看下一步操作。
新建.netcore 項目與微信服務器牽手
新建.netcore api項目,項目結構如下圖:
引用盛派Senparc組件:
Senparc.Weixin.MP.MVC Senparc.Weixin.WxOpen
使用盛派Senparc組件配置文件如下:
"SenparcWeixinSetting": { //微信全局 "IsDebug": true, //公眾號 "Token": "#Token#", "EncodingAESKey": "#EncodingAESKey#", "WeixinAppId": "#WeixinAppId#", "WeixinAppSecret": "#WeixinAppSecret#", "Items": { "小程序1": { "WxOpenAppId": "#WxOpenAppId#", "WxOpenAppSecret": "#WxOpenAppSecret#", "WxOpenToken": "#WxOpenToken#", "WxOpenEncodingAESKey": "#WxOpenEncodingAESKey#" }, "小程B": { "WxOpenAppId": "#WxOpenAppId#", "WxOpenAppSecret": "#WxOpenAppSecret#", "WxOpenToken": "#WxOpenToken#", "WxOpenEncodingAESKey": "#WxOpenEncodingAESKey#" } } }
使用盛派Senparc組件必須先進行注冊,在Startup類中ConfigureServices方法進行注冊
services.AddSenparcGlobalServices(Configuration)
.AddSenparcWeixinServices(Configuration);
在Startup類中Configure方法進行使用
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<SenparcSetting> senparcSetting, IOptions<SenparcWeixinSetting> senparcWeixinSetting) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwaggerUIV2(); } app.UseStaticHttpContext(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); #region 公眾號,小程序 IRegisterService register = RegisterService.Start(env, senparcSetting.Value).UseSenparcGlobal(false, null); register.UseSenparcWeixin(senparcWeixinSetting.Value, senparcSetting.Value); //配置 var bInfo = senparcWeixinSetting.Value.Items["appid"]; AccessTokenContainer.RegisterAsync(bInfo.WxOpenAppId, bInfo.WxOpenAppSecret, bInfo.WxOpenAppId); //公眾號 AccessTokenContainer.RegisterAsync(senparcWeixinSetting.Value.WeixinAppId, senparcWeixinSetting.Value.WeixinAppSecret, senparcWeixinSetting.Value.WeixinAppId); #endregion }
以上盛派Senparc組件的全局配置基本完成,可以開始寫驗證服務器的接口啦。
新建HomeController類
靜態變量定義如下:
#region static /// <summary> /// 當前小程序的AppId /// </summary> public static readonly string AppId = Senparc.Weixin.Config.SenparcWeixinSetting.Items["appid"].WxOpenAppId; /// <summary> /// /// </summary> public static readonly string Token = Senparc.Weixin.Config.SenparcWeixinSetting.Items[AppId].WxOpenToken; /// <summary> /// /// </summary> public static readonly string EncodingAESKey = Senparc.Weixin.Config.SenparcWeixinSetting.Items[AppId].WxOpenEncodingAESKey; #endregion
驗證接口代碼如下:
[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一致。1"); } }
發布項目到生產環境,在次點擊微信小程序后台開發者配置,點擊提交,驗證成功說明已經與服務器牽手成功。
開發者服務器自動回復
建立與開發者服務器成功后,在公眾號,小程序客服等功能發送的消息都會先經過微信服務器,微信服務器將已POST的請求方式中轉給我們配置的URL地址,收到指令后,我們開發者根據收到的類型消息進行處理。
統一處理消息的入口,代碼如下:
[HttpPost] [ActionName("Index")] public ActionResult Post(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { return Content("參數錯誤!"); } try { postModel.Token = Token;//根據自己后台的設置保持一致 postModel.EncodingAESKey = EncodingAESKey;//根據自己后台的設置保持一致 postModel.AppId = AppId;//根據自己后台的設置保持一致(必須提供) var maxRecordCount = 10; var messageHandler = new CustomWxOpenMessageHandler(Request.GetRequestMemoryStream(), postModel, maxRecordCount); messageHandler.Execute();//執行微信處理過程(關鍵) var result = new FixWeixinBugWeixinResult(messageHandler); return result; } catch (Exception ex) { Logger.Info("異常消息:" + ex.Message); return Content(""); } }
所有消息都會經過管道處理即CustomWxOpenMessageHandler方法,CustomWxOpenMessageHandler主要代碼如下(遇到問題請與我聯系):
public CustomWxOpenMessageHandler(Stream inputStream, PostModel postModel, int maxRecordCount = 0) : base(inputStream, postModel, maxRecordCount) { //這里設置僅用於測試,實際開發可以在外部更全局的地方設置, //比如MessageHandler<MessageContext>.GlobalGlobalMessageContext.ExpireMinutes = 3。 GlobalMessageContext.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 IResponseMessageBase OnEvent_UserEnterTempSessionRequest(RequestMessageEvent_UserEnterTempSession requestMessage) { //進入客服 var msg = @"歡迎您!這條消息來自服務器"; Senparc.Weixin.WxOpen.AdvancedAPIs.CustomApi.SendText(appId, OpenId, msg); return DefaultResponseMessage(requestMessage); }
效果圖如下:

各種消息類型處理
圖片消息處理代碼如下:
public override IResponseMessageBase OnImageRequest(RequestMessageImage requestMessage) { //發來圖片,進行處理 Task.Factory.StartNew(async () => { await Senparc.Weixin.WxOpen.AdvancedAPIs.CustomApi.SendTextAsync(appId, OpenId, "剛才您發送了這張圖片:"); await Senparc.Weixin.WxOpen.AdvancedAPIs.CustomApi.SendImageAsync(appId, OpenId, requestMessage.MediaId); }); return DefaultResponseMessage(requestMessage); }
文字消息處理代碼如下:
public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage) { if (contentUpper == "1") { var uploadResult = Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(appId, UploadMediaFileType.image, ServerUtility.ContentRootMapPath("~/wwwroot/imgs/fwh.jpg")); Senparc.Weixin.WxOpen.AdvancedAPIs.CustomApi.SendImage(appId, OpenId, uploadResult.media_id); } else { var msg = "親,回復“1”,關注服務號。"; Senparc.Weixin.WxOpen.AdvancedAPIs.CustomApi.SendText(appId, OpenId, msg); } return new SuccessResponseMessage(); }
統一默認處理,代碼如下:
public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage) { return new SuccessResponseMessage(); }
總結
盛派Senparc組件適用於快速開發項目,個人覺得還是很方便的,如果想進一步了解底層,可以看底層接口,其實就是請求的微信的相關接口,處理返回的結果進行了封裝,如有在小程序開發過程中遇到任何問題可與我聯系
盛派Senparc開源項目:
https://github.com/JeffreySu/WeiXinMPSDK/
作者:Dylan
公眾號:dotNET名人堂(sharecore)
微信:tangguo_9669
QQ:.NET Core 技術交流(18362376)
出處:https://www.cnblogs.com/hailang8/
本文文章版權歸作者和博客園共有,未經作者同意不得隨意轉載,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。如有問題或建議,請與我聯系。
