asp.net webapi 微信接口接入


        /// <summary>
        /// 接口認證
        /// </summary>
        /// <param name="echostr"></param>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<HttpResponseMessage> wx(string echostr, string signature, string timestamp, string nonce)
        {
            string token = "token";
            if (!CheckSignature(token, signature, timestamp, nonce))
                echostr = "驗證不正確";
            HttpResponseMessage responseMessage = new HttpResponseMessage { Content = new StringContent(echostr, Encoding.GetEncoding("UTF-8"), "text/plain") };

            return responseMessage;
        }
        /// <summary>
        /// 接收客服消息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<HttpResponseMessage> wx()
        {
            LogHelper log = new LogHelper();
            var content = await Request.Content.ReadAsStringAsync();
            log.LogError(content);
            HttpResponseMessage responseMessage = new HttpResponseMessage();
            return responseMessage;
        }
        /// <summary>
        /// 驗證微信簽名
        /// </summary>
        private bool CheckSignature(string token, string signature, string timestamp, string nonce)
        {
            string[] ArrTmp = { token, timestamp, nonce };

            Array.Sort(ArrTmp);
            string tmpStr = string.Join("", ArrTmp);
            var data = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(tmpStr));
            var sb = new StringBuilder();
            foreach (var t in data)
            {
                sb.Append(t.ToString("X2"));
            }
            tmpStr = sb.ToString();
            tmpStr = tmpStr.ToLower();

            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

  httpget方法,用於接口接入。

     httpPost方法,用於后面接收消息。然后根據消息內容做解析。

     webapi使用異步可以提高效率。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM