asp.net web api集成微信服務(使用Senparc微信SDK)

    /// <summary>/// 微信請求轉發控制器/// </summary>[RoutePrefix("weixin")]public class WeixinController : ApiController{#region 創建微信菜單/// <summary>/// 創建微信菜單/// </summary>/// <returns></returns>
        [HttpPost][Route("menu")]public string CreateMenu(){#region 菜單結構構建ButtonGroup bg = new ButtonGroup();string websiteUrl = WebConfigurationManager.AppSettings["WebsiteUrl"];bg.button.Add(new SingleViewButton(){//url = MenuHelper.GetMenuUrl("Weixin/Index"),url = string.Format("{0}/{1}", websiteUrl, WebConfigurationManager.AppSettings["mainPage"]),name = "我要借款",});bg.button.Add(new SingleViewButton(){url = string.Format("{0}/{1}", websiteUrl, "FrontendMobile/public/view/main.html#appeal"),name = "投訴建議",});#endregionstring result = string.Empty;try{CommonApi.CreateMenu(WeixinConfig.APPID, bg);result = "菜單生成成功,一般有24小時緩存時間,也可以直接取消關注再關注直接查看效果";}catch (WeixinException e){result = e.Message;}return result;}/// <summary>/// 獲取微信菜單/// </summary>/// <returns></returns>
        [HttpGet][Route("menu")]public HttpResponseMessage GetMenu(){try{GetMenuResult result = CommonApi.GetMenu(WeixinConfig.APPID);return Request.CreateResponse(HttpStatusCode.OK, result);}catch (WeixinException e){return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);}}/// <summary>/// 刪除菜單方法/// </summary>/// <returns></returns>
        [HttpDelete][Route("menu")]public string DeleteMenu(){try{CommonApi.DeleteMenu(WeixinConfig.APPID);return "刪除成功,一般有24小時緩存時間,也可以直接取消關注再關注直接查看效果";}catch (WeixinException e){return e.Message;}}#endregion#region 微信服務器消息接收及處理/// <summary>/// 微信后臺驗證地址(使用Get),微信后臺的“接口配置信息”的Url填寫如:http://weixin.senparc.com/weixin/// </summary>
        [HttpGet][Route("")]public HttpResponseMessage Get(string signature, string timestamp, string nonce, string echostr){if (CheckSignature.Check(signature, timestamp, nonce, WeixinConfig.TOKEN)){var result = new StringContent(echostr, UTF8Encoding.UTF8, "application/x-www-form-urlencoded");var response = new HttpResponseMessage { Content = result };return response;}return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, WeixinConfig.TOKEN) + "。" +"如果你在瀏覽器中看到這句話,說明此地址可以被作為微信公眾賬號后臺的Url,請注意保持Token一致。");}/// <summary>/// 用戶發送消息后,微信平臺自動Post一個請求到這里,并等待響應XML。/// PS:此方法為簡化方法,效果與OldPost一致。/// v0.8之后的版本可以結合Senparc.Weixin.MP.MvcExtension擴展包,使用WeixinResult,見MiniPost方法。/// </summary>
        [HttpPost][Route("")]public HttpResponseMessage Post(){var requestQueryPairs = Request.GetQueryNameValuePairs().ToDictionary(k => k.Key, v => v.Value);if (requestQueryPairs.Count == 0|| !requestQueryPairs.ContainsKey("timestamp")|| !requestQueryPairs.ContainsKey("signature")|| !requestQueryPairs.ContainsKey("nonce")|| !CheckSignature.Check(requestQueryPairs["signature"], requestQueryPairs["timestamp"], requestQueryPairs["nonce"], WeixinConfig.TOKEN)){return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "未授權請求");}PostModel postModel = new PostModel{Signature = requestQueryPairs["signature"],Timestamp = requestQueryPairs["timestamp"],Nonce = requestQueryPairs["nonce"]};postModel.Token = WeixinConfig.TOKEN;postModel.EncodingAESKey = WeixinConfig.ENCODINGAESKEY;//根據自己后臺的設置保持一致postModel.AppId = WeixinConfig.APPID;//根據自己后臺的設置保持一致//v4.2.2之后的版本,可以設置每個人上下文消息儲存的最大數量,防止內存占用過多,如果該參數小于等于0,則不限制var maxRecordCount = 10;//自定義MessageHandler,對微信請求的詳細判斷操作都在這里面。var messageHandler = new CusMessageHandler(Request.Content.ReadAsStreamAsync().Result, postModel, maxRecordCount);try{
#if DEBUG             Log.Logger.Debug(messageHandler.RequestDocument.ToString());if (messageHandler.UsingEcryptMessage){Log.Logger.Debug(messageHandler.EcryptRequestDocument.ToString());}
#endif/* 如果需要添加消息去重功能,只需打開OmitRepeatedMessage功能,SDK會自動處理。* 收到重復消息通常是因為微信服務器沒有及時收到響應,會持續發送2-5條不等的相同內容的RequestMessage*/messageHandler.OmitRepeatedMessage = true;//執行微信處理過程
                messageHandler.Execute();#if DEBUGif (messageHandler.ResponseDocument != null){Log.Logger.Debug(messageHandler.ResponseDocument.ToString());}if (messageHandler.UsingEcryptMessage){//記錄加密后的響應信息
                    Log.Logger.Debug(messageHandler.FinalResponseDocument.ToString());}
#endifvar resMessage = Request.CreateResponse(HttpStatusCode.OK); resMessage.Content = new StringContent(messageHandler.ResponseDocument.ToString());resMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");            return resMessage;}catch (Exception ex){Log.Logger.Error("處理微信請求出錯:", ex);return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "處理微信請求出錯");}}#endregion#region JSSDK相關/// <summary>/// 獲取JSSDK參數信息/// </summary>/// <param name="url">獲取簽名所用的URL</param>/// <returns></returns>
        [HttpGet][Route("JSSDK/{*url}")]public HttpResponseMessage GetJSSDK(string url){if (!HttpContext.Current.SideInWeixinBroswer()){return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "請通過微信端登錄");}try{//獲取時間戳var timestamp = JSSDKHelper.GetTimestamp();//獲取隨機碼var nonceStr = JSSDKHelper.GetNoncestr();string ticket = AccessTokenContainer.TryGetJsApiTicket(WeixinConfig.APPID, WeixinConfig.APPSECRET);//獲取簽名var signature = JSSDKHelper.GetSignature(ticket, nonceStr, timestamp, HttpUtility.UrlDecode(url));return Request.CreateResponse(HttpStatusCode.OK, new{appId = WeixinConfig.APPID,timestamp = timestamp,nonceStr = nonceStr,signature = signature});}catch (Exception e){Log.Logger.Error("獲取JSSDK信息出錯:", e);return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "獲取JSSDK信息出錯");}}#endregion/// <summary>/// 微信菜單導航/// </summary>/// <param name="code"></param>/// <param name="state"></param>/// <returns></returns>
        [HttpGet][Route("index")]public HttpResponseMessage Index(string code, string state){var response = Request.CreateResponse(HttpStatusCode.Redirect);try{var result = OAuthApi.GetAccessToken(WeixinConfig.APPID, WeixinConfig.APPSECRET, code);                response.Headers.Location = new Uri(string.Format("{0}?openId={1}", WebConfigurationManager.AppSettings["mainPage"], result.openid), UriKind.Relative);}catch (WeixinException e){Log.Logger.Error("OAuth2授權失敗:", e);response.Headers.Location = new Uri(WebConfigurationManager.AppSettings["mainPage"], UriKind.Relative);}return response;}}

?

轉載于:https://www.cnblogs.com/guokun/p/5843735.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/254510.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/254510.shtml
英文地址,請注明出處:http://en.pswp.cn/news/254510.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

1.SoapUI接口測試--創建項目

1、點擊File-->New soapUI Project 2、填寫項目名稱&#xff0c;接口服務地址后單擊【OK】按鈕后就成功創建了一個項目 3、模擬發送請求 4、創建請求 或者直接Copy一個請求 5、保存項目 6、項目是以xml的格式保存的&#xff0c;下次用的時候可以直接導入&#xff0c;點擊Fil…

Misc混合halcon算子,持續更新

目錄convol_imageexpand_domain_graygray_insidegray_skeletonlut_transsymmetrytopographic_sketchdeviation_nconvol_image 功能&#xff1a;用一個任意濾波掩碼對一個圖像卷積。 expand_domain_gray 功能&#xff1a;擴大圖像區域并且在擴大的區域中設置灰度值。 gray_i…

C/C++ 函數指針調用函數

01//C/C 函數指針調用函數 02#include<iostream> 03using namespace std; 04 05void site1() 06{ 07 cout<<"www.ok2002.com"<<endl; 08} 09 10void site2() 11{ 12 cout<<"www.ok1700.com"<<endl; 13} 14 15void…

漢字編碼

漢字編碼 一、漢字所占的字節數 對于一個字符串sizeof("請放手")&#xff0c;結果值是4。測試操作系統&#xff1a;Centos 6.4&#xff0c;硬件平臺&#xff1a;Windows 7 32位 VirtualBox 4.3.12。看來用sizeof()來計算漢字所占用的字節或空間是不準確的。strlen(&…

Noise噪音halcon算子,持續更新

目錄add_noise_distributionadd_noise_whitegauss_distributionnoise_distribution_meansp_distributionadd_noise_distribution 功能&#xff1a;向一個圖像添加噪聲。 add_noise_white 功能&#xff1a;向一個圖像添加噪聲。 gauss_distribution 功能&#xff1a;產生一…

sublime text3 package control 報錯

安裝sublime text3之后&#xff0c;安裝package control 報錯&#xff0c;錯誤信息&#xff1a;There are no packages available for installation 根據提示&#xff0c;找到錯誤解決辦法&#xff1a;https://packagecontrol.io/doc... 其實意思就是你的電腦代理出了問題&…

HTML圖片元素(標記)

<html> <head> <title>第一個網頁</title> </head> <body> ***************圖片元素******************</br> <img srcmm.jpg /> </body> </html> 新建一個文件夾“text”,在text文件夾內新建index.html并放入一張…

Optical-Flow光流halcon算子,持續更新

目錄optical_flow_mgunwarp_image_vector_fieldvector_field_lengthderivate_vector_fieldoptical_flow_mg 功能&#xff1a;計算兩個圖像之間的光流。 unwarp_image_vector_field 功能&#xff1a;使用一個矢量場來展開一個圖像。 vector_field_length 功能&#xff1a;計…

Oracle中procedure和function創建舉例

Procedure創建與執行&#xff1a;Case1&#xff1a; create or replace procedure procedure_name(id user.table_name.columne_name%type)is begin delete from user.table_name where columne_nameid;exception when others then dbms_output.put_line(errors);end&#xff1…

Liunx 中tr的用法

1、將/etc/issue文件中的內容轉換為大寫后保存至/tmp/issue.out文件中cat /etc/issue |tr a-z A-Z > /tmp/issue.out2、將當前系統登錄用戶的信息轉換為大寫后保存至/tmp/who.out文件中who | tr a-z A-Z >> who.out3、一個linux用戶給root發郵件&#xff0c;要who求郵…

ASP.NET Aries 3.0發布(附帶通用API設計及基本教程介紹)

主要更新&#xff1a; 1&#xff1a;升級處理機制&#xff08;js請求由同步變更為異步&#xff09; 2&#xff1a;優化前端JS&#xff1a;包括API和配置方式。 3&#xff1a;增加InputDialog功能。 4&#xff1a;增遠遠程驗證功能。 5&#xff1a;優化權限安全機制。 6&#xf…

多線程并發之原子性(六)

最近在網上找到好多的多線程關于原子性的例子&#xff0c;說的都不是非常的明確&#xff0c;對于剛學習多線程的新手而言很容誤導學員&#xff0c;在這里&#xff0c;我通過多個例子對多線程的原子性加以說明。 例子一&#xff1a;傳統技術自增 package face.thread.volatilep;…

Points角點halcon算子,持續更新

目錄corner_responsedots_imagepoints_foerstnerpoints_harrispoints_harris_binomialpoints_lepetitpoints_sojkacorner_response 功能&#xff1a;在圖像中尋找角點。 dots_image 功能&#xff1a;在一個圖像中增強圓形點。 points_foerstner 功能&#xff1a;使用Frstn…

預編譯頭文件來自編譯器的早期版本,或者預編譯頭為 C++ 而在 C 中使用它(或相反)

當 Visual C 項目啟用了預編譯頭 (Precompiled header) 功能時&#xff0c;如果項目中同時混合有 .c 和 .cpp 源文件&#xff0c;則可能收到 C1853 編譯器錯誤&#xff1a;fatal error C1853: pjtname.pch precompiled header file is from a previous version of the compiler…

甲骨文稱 Java 序列化的存在是個錯誤,計劃刪除

甲骨文計劃從 Java 中去除序列化功能&#xff0c;因其在安全方面一直是一個棘手的問題。 Java 序列化也稱為 Java 對象序列化&#xff0c;該功能用于將對象編碼為字節流...Oracle 的 Java 平臺小組的首席架構師 Mark Reinhold 說&#xff1a;“刪除序列化是一個長期目標&#x…

CreateProcess

Windows 進程創建完整過程&#xff08;除去細節&#xff09; 當前流程是分析WinXP x86得到的&#xff0c;在最新版本Windows上不一定正確&#xff0c;但是可以做一個參考&#xff0c; 由于我這里符號并不全&#xff0c;所以導致我這里有些東西看到的可能是錯誤的&#xff0c;誤…

系統:Centos 7.2 內核3.10.0-327.el7.x86_64 # 內核需要高于2.6.32

系統&#xff1a;Centos 7.2 內核3.10.0-327.el7.x86_64 # 內核需要高于2.6.32 Drbd : 192.168.8.111&#xff1a;node1/dev/drdb0 /mydeta 192.168.8.112 : node2Mysql_vip: 192.168.8.200 #下章實現 # 需要的軟件包&#xff1a;mariadb-5.5.53-linux-i686.tar.gzdrbd84-utils…

Smoothing濾波處理halcon算子,持續更新

目錄anisotropic_diffusionbilateral_filterbinomial_filtereliminate_min_maxeliminate_spfill_interlacegauss_filterguided_filterinfo_smoothisotropic_diffusionmean_imagemean_nmean_spmedian_imagemedian_rectmedian_separate_median_weightedmidrange_imagerank_imager…

日志文件在VS中輸出為亂碼問題

原因&#xff1a;主要是文件文字格式問題&#xff08;使用使用 Unicode 字符集&#xff09;&#xff1a;修改項目/屬性/常規/字符集/ 未設置

初學者電腦編程入門

1、首先要對編程有個比較大概的了解&#xff0c;編程的對象&#xff0c;編程的原理&#xff0c;編程的目的等等。2、在了解編程基本知識后&#xff0c;要想想自己學習編程后到底要干什么以確定學習的方向。比如說是想要開發手機app&#xff0c;網站開發&#xff0c;企業系統等。…