微信公众号开发 asp.net mvc 如何验证服务器地址

一、假设在微信公众平台的 开发 - 基础配置 - 服务器配置 参数如下

        服务器地址(URL):http://weixin.abc.com/weixin/events

       令牌(Token):86243390821108800

二、后台代码 ( WeixinController.cs )

  using System;
  using System.Web.Mvc;
  using System.Security.Cryptography;

  namespace Wechat.Controllers
  {
    public class WeixinController : Controller
    {
      [HttpGet]
      [AllowAnonymous]
      public ActionResult Events(string AccountId)
      {
        string echoStr = Request.QueryString["echoStr"];
        string signature = Request.QueryString["signature"];
        string timestamp = Request.QueryString["timestamp"];
        string nonce = Request.QueryString["nonce"];

        // 令牌,时间戳,随机数 组成签名字典,排序,拼接,sha1签名
        string[] arrData = { "86243390821108800", timestamp, nonce };
        Array.Sort(arrData);
        string strData = string.Join("", arrData);
        SHA1 sha1 = SHA1.Create("SHA1");
        byte[] shabytes = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strData));
        strData = "";
        for (int i = 0; i < shabytes.Length; i++)
        {
          strData = strData + shabytes[i].ToString("x2").ToUpperInvariant();
        }

        // 判断签名是否相等,是则返回 echoStr 
        if (strData != null)

        {
          strData = strData.ToLower();
          if (strData == signature)
          {
            Response.Write(echoStr);
            Response.End();
          }
        }
        return View();
      }

  }

猜你喜欢

转载自www.cnblogs.com/xmhelp/p/9746240.html