由于最近要做微信服务号的开发,所以开始找相关说明和接口文档开始学,故把学习过程及注意事项记录一下,帮助想学习的快速上手.废话不多少了,直接上干货!
1.申请微信公众号
这个就不需要多说了吧,大家直接照着提示步骤走就行
2.建立服务器和微信端的链接
这一步的操作其实就是确认一下你的公众号跟你的服务器匹配成功了,所要做的工作其实很简单,就是微信会给你的服务器发一个请求,传过去几个参数,然后你把其中的timestamp,nonce参数获取到,在把你在微信设置服务器的页面填写的token这三个值按字典排序之后拼接到一起去跟传过来的signature参数值对比,如果一致则证明匹配成功!字典排序当时不知道啥意思,其实很简单就是把这三个值放在数组中,然后把他们按字符串排序就行,然后把排序后的三个值拼在一起,中间不加东西,然后再进行shar1加密之后把所有字符都转为小写就ok了,他的机制其实是有问题的,因为他需要你回传回去他传过来的echostr参数值,也就是说你就算什么也不处理,直接把获取到的echostr回传回去也是可以验证通过的.代码我贴下来供参考:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string token = "ll2017"; string timestamp = string.Empty; string nonce = string.Empty; string echostr = string.Empty; string signature = string.Empty; if (!string.IsNullOrEmpty(Request.Params["timestamp"])) { timestamp = Request.Params["timestamp"]; } if (!string.IsNullOrEmpty(Request.Params["signature"])) { signature = Request.Params["signature"]; } if (!string.IsNullOrEmpty(Request.Params["nonce"])) { nonce = Request.Params["nonce"]; } if (!string.IsNullOrEmpty(Request.Params["echostr"])) { echostr = Request.Params["echostr"]; } string[] strs = { token, timestamp, nonce }; Array.Sort(strs); //字典排序 string str = string.Join("", strs); str = SHA1(str, System.Text.UTF8Encoding.UTF8); str = str.ToLower(); if (str.Equals(signature)) { Response.Clear(); Response.Write(echostr); Response.End(); } } } /// <summary> /// SHA1 加密,返回大写字符串 /// </summary> /// <param name="content">需要加密字符串</param> /// <param name="encode">指定加密编码</param> /// <returns>返回40位大写字符串</returns> public static string SHA1(string content, Encoding encode) { try { SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] bytes_in = encode.GetBytes(content); byte[] bytes_out = sha1.ComputeHash(bytes_in); sha1.Dispose(); string result = BitConverter.ToString(bytes_out); result = result.Replace("-", ""); return result; } catch (Exception ex) { throw new Exception("SHA1加密出错:" + ex.Message); } }