In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail about C #. Net Wechat development example analysis, the editor thinks it is very practical, so share it for everyone to do a reference, I hope you can get something after reading this article.
Become developer string [] ArrTmp = {"token", Request ["timestamp"], Request ["nonce"]}; Array.Sort (ArrTmp); / / dictionary sort string tmpStr = string.Join ("", ArrTmp); tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile (tmpStr, "SHA1"); tmpStr = tmpStr.ToLower (); if (tmpStr! = Request ["signature"]. ToLower ()) {Response.Write (Request ["echostr"]) } follow account, trigger message, automatic reply, event response
Namespace ElegantWM.WebUI.Areas.WeiXin.Controllers {/ / public class RobotController / Wechat Public Service Class / public class RobotController: BaseController {/ receive Wechat request API, authentication API / public ContentResult Index () {string result = AnalyzeXmlFromWeiXin (); return Content (result) } / analyze the XML data from Wechat POST to this server / private string AnalyzeXmlFromWeiXin () {StreamReader reader = new StreamReader (Request.InputStream); string xml = reader.ReadToEnd (); / / get MsgType log.Info (xml) String msgType = XmlHelper.ReadXmlStr (xml, "/ xml/MsgType", "); switch (msgType) {case" event ": / / if it is an event return OnAttention (xml); case" text ": / / if it is a text message return OnReceiveTextMsg (xml) Default: return "unsupported keywords!" ;} / response text message / private string OnReceiveTextMsg (string xml) {WxTextMsg msg = XmlEntityExchange.ConvertXml2Entity (xml); / / return message, interchange user string toUser = msg.FromUserName Msg.FromUserName = msg.ToUserName; msg.ToUserName = toUser; switch (msg.Content.Trim ()) {case "?": msg.Content = HelpDocument (); break; case "?" : msg.Content = HelpDocument (); break; case "1": msg.Content = DateTime.Now.ToString ("yyyy-MM-dd HH:mm:ss"); break Case "2": msg.Content = Tools.HttpCrossDomain.Get ("http://www.weather.com.cn/data/sk/101210301.html"); break; case" 3 ": msg.Content =" come on, what do you want to talk about? [chuckles]; break; case "you are a man and a woman": msg.Content = "A girl [chuckles]"; break; default: msg.Content = "Sorry, I don't know the command you entered. / shy /:, @-D "; break;} return XmlEntityExchange.ConvertEntity2Xml (msg);} / get help menu documentation / private string HelpDocument () {StringBuilder sb = new StringBuilder () Sb.Append ("HI, please reply to the number, select service"). Append ("\ n\ n"); sb.Append ("1. Current time "). Append ("\ n "); sb.Append (" 2. Append ("\ n"); sb.Append ("3. Append ("\ n"); sb.Append ("n. More services are under development. Append ("\ n"); sb.Append ("reply [?] Show this help menu"); return sb.ToString () Event response / private string OnAttention (string xml) {WxEvent wxevent = XmlEntityExchange.ConvertXml2Entity (xml); WxTextMsg msg = new WxTextMsg (); msg.ToUserName = wxevent.FromUserName; msg.FromUserName = wxevent.ToUserName when the user follows the Wechat account Msg.CreateTime = DateTime.Now.Ticks; msg.MsgType = "text"; / / if it is a follow, send a welcome message switch (wxevent.Event) {case "subscribe": msg.Content = System.Configuration.ConfigurationManager.AppSettings ["DefaultWxMsg"]; break Case "CLICK": msg.Content = "what you clicked is:" + wxevent.EventKey; break; default: msg.Content = "unhandled event: Event" + wxevent.Event + "; EventKey:" + wxevent.EventKey; break } string rst = XmlEntityExchange.ConvertEntity2Xml (msg); log.Info (rst); return rst;}
Auxiliary class
/ / entity public class WxEvent {/ recipient / public string ToUserName {get; set;} / public string FromUserName {get; set;} / time / public string CreateTime {get; set } / Type / public string MsgType {get; set;} / event / public string Event {get; set;} public string EventKey {get; set }} public class WxTextMsg {/ recipient / public string ToUserName {get; set;} / public string FromUserName {get; set;} / time / public long CreateTime {get; set } / Type / public string MsgType {get; set;} / content / public string Content {get; set }} / / Mutual conversion between XML and entity objects namespace ElegantWM.WebUI.Areas.WeiXin {public class XmlEntityExchange where T: new () {/ public static T ConvertXml2Entity (string xml) {XmlDocument doc = new XmlDocument (); PropertyInfo [] propinfos = null Doc.LoadXml (xml); XmlNodeList nodelist = doc.SelectNodes ("/ xml"); T entity = new T (); foreach (XmlNode node in nodelist) {/ / initialize propertyinfo if (propinfos = = null) {Type objtype = entity.GetType () Propinfos = objtype.GetProperties ();} / / populate the properties of the entity class foreach (PropertyInfo pi in propinfos) {XmlNode cnode = node.SelectSingleNode (pi.Name); pi.SetValue (entity, Convert.ChangeType (cnode.InnerText, pi.PropertyType), null) }} return entity;} / construct Wechat message / object entity / return Wechat message xml format public static string ConvertEntity2Xml (T t) {StringBuilder builder = new StringBuilder () Builder.Append (""); Type objtype = t.GetType (); / / populate the property of the entity class foreach (PropertyInfo pi in objtype.GetProperties ()) {object obj = pi.GetValue (t); string value = obj = = null? ": obj.ToString () If (pi.PropertyType.Name.ToLower () = "int64") builder.Append ("" + value + ""); else builder.Append ("");} builder.Append (""); return builder.ToString ();}
Basic class: http request
/ * Copyright ©2013 CCT All Rights Reserved * author: JackChain * time: 18:21:23 on 2013-8-23 * function: cross-domain access * version: V1.0 * * modifier: * * / namespace ElegantWM.Tools {public class HttpCrossDomain {/ Cross-domain access / / public static string Post (string url String param, int time = 60000) {Uri address = new Uri (url) HttpWebRequest request = WebRequest.Create (address) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/json;charset=utf-8"; / / "application/x-www-form-urlencoded"; request.Timeout = time; byte [] byteData = UTF8Encoding.UTF8.GetBytes (param = = null? ": param); request.ContentLength = byteData.Length Using (Stream postStream = request.GetRequestStream ()) {postStream.Write (byteData, 0, byteData.Length);} string result = ""; using (HttpWebResponse response = request.GetResponse () as HttpWebResponse) {StreamReader reader = new StreamReader (response.GetResponseStream ()); result = reader.ReadToEnd () } return (result);} / Cross-domain access / public static string Get (string url, int time = 60000) {Uri address = new Uri (url); HttpWebRequest request = WebRequest.Create (address) as HttpWebRequest Request.Method = "GET"; request.ContentType = "application/json;charset=utf-8"; / / "application/x-www-form-urlencoded"; request.Timeout = time; string result = ""; using (HttpWebResponse response = request.GetResponse () as HttpWebResponse) {StreamReader reader = new StreamReader (response.GetResponseStream ()) Result = reader.ReadToEnd ();} return (result);}
Get Token:
Public class CommonController: Controller {/ obtain Wechat credential / public JsonResult GetWxCredential () {string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";" Url = string.Format (url, ConfigurationManager.AppSettings ["AppId"], ConfigurationManager.AppSettings ["AppSecret"]); string rst = HttpCrossDomain.Get (url); if (rst.Contains ("access_token")) {string tokenId=rst.Replace ("{\" access_token\ ":\", "). Replace ("\ ",\" expires_in\ ": 7200}", ") CacheHelper.CacheInsertAddMinutes ("access_token", tokenId,120); return Json (tokenId, JsonRequestBehavior.AllowGet);} else return Json (rst, JsonRequestBehavior.AllowGet);}}
Get and update menus
/ get Wechat menu / public JsonResult Get () {string url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=";" If (CacheHelper.CacheValue ("access_token")! = null) {url = url + CacheHelper.CacheValue ("access_token") .ToString ();} string rst = HttpCrossDomain.Get (url); return Json (rst,JsonRequestBehavior.AllowGet) } / create Menu / [HttpPost] public JsonResult Create (string json) {string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="; If (CacheHelper.CacheValue ("access_token")! = null) {url = url+CacheHelper.CacheValue ("access_token") .ToString ();} string rst = HttpCrossDomain.Post (url, json); return Json (rst) } this is the end of the article on "sample Analysis of net Wechat Development in C #". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.