目录
3. 使用.net 操作 微信公众平台 —— 接收并回复用户消息
接入
1. 登录微信公众平台(https://mp.weixin.qq.com)
2. 开发 => 基本配置 => 服务器配置
3. EncodingAESKey 点 随机生成 即可
4. 在项目中新建CheckWxToken.aspx
-
using System;
-
using System.Web.Security;
-
-
namespace DianQun.Users
-
{
-
public partial
class CheckWxToken : System.Web.UI.Page
-
{
-
const
string Token =
"WeixinToken";
//你的token
-
-
// 验证
-
protected void Page_Load(object sender, EventArgs e)
-
{
-
string postStr =
"";
-
if (Request.HttpMethod.ToLower() ==
"post")
-
{
-
System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
-
byte[] b =
new byte[s.Length];
-
s.Read(b,
0, (
int)s.Length);
-
postStr = System.Text.Encoding.UTF8.GetString(b);
-
if (!
string.IsNullOrEmpty(postStr))
-
{
-
Response.End();
-
}
-
}
-
else
-
{
-
Valid();
-
}
-
}
-
-
/// <summary>
-
/// 验证微信签名
-
/// </summary>
-
/// * 将token、timestamp、nonce三个参数进行字典序排序
-
/// * 将三个参数字符串拼接成一个字符串进行sha1加密
-
/// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
-
/// <returns></returns>
-
private bool CheckSignature()
-
{
-
string signature = Request.QueryString[
"signature"].ToString();
-
string timestamp = Request.QueryString[
"timestamp"].ToString();
-
string nonce = Request.QueryString[
"nonce"].ToString();
-
string[] ArrTmp = { Token, timestamp, nonce };
-
Array.Sort(ArrTmp);
//字典排序
-
string tmpStr =
string.Join(
"", ArrTmp);
-
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr,
"SHA1");
-
tmpStr = tmpStr.ToLower();
-
if (tmpStr == signature)
-
{
-
return
true;
-
}
-
else
-
{
-
return
false;
-
}
-
}
-
-
private void Valid()
-
{
-
string echoStr = Request.QueryString[
"echoStr"].ToString();
-
if (CheckSignature())
-
{
-
if (!
string.IsNullOrEmpty(echoStr))
-
{
-
Response.Write(echoStr);
-
Response.End();
-
}
-
}
-
}
-
}
-
}