WEBAPI 使用微信公众号中的回调模式

1.首先创建一个WEBAPI项目

2.在VehicleController.cs中加入方法VerifyURL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using Vehicle.Util.MessageHandlers;
using Tencent;
using System.Configuration;
using System.Web.Security;
using System.Text;

namespace Vehicle.API.Controllers
{
    public class VehicleController : ApiController
    {
        [HttpGet]
        public string Test()
        {
            VerifyURL();
            return "OK";
        } 

[HttpGet] public HttpResponseMessage Get(string signature, string timestamp, string nonce, string echostr) { string TOKEN = ConfigurationManager.AppSettings["WXCorpToken"].ToString(); string[] ArrTmp = { TOKEN, timestamp, nonce }; Array.Sort(ArrTmp); string tmpStr = string.Join("", ArrTmp); var result = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1").ToLower(); return new HttpResponseMessage() { Content = new StringContent(result, Encoding.GetEncoding("UTF-8"), "application/x-www-form-urlencoded") }; } [HttpGet] public void VerifyURL() { // 本文顶部说的四个参数,最好进行URL解码 var signature = HttpUtility.UrlDecode(HttpContext.Current.Request["msg_signature"] ?? string.Empty); var timestamp = HttpUtility.UrlDecode(HttpContext.Current.Request["timestamp"] ?? string.Empty); var nonce = HttpUtility.UrlDecode(HttpContext.Current.Request["nonce"] ?? string.Empty); var echo = HttpUtility.UrlDecode(HttpContext.Current.Request["echostr"] ?? string.Empty); // 验证结束后的返回值,一定不要带引号!!! var echoResult = string.Empty; // 微信提供的验证对象(参数为AppSetting中的三个值) string WX_CORP_TOKEN = ConfigurationManager.AppSettings["WXCorpToken"].ToString(); string WX_CORP_AES_KEY = ConfigurationManager.AppSettings["WXCorpAESKey"].ToString(); string WX_CORP_ID = ConfigurationManager.AppSettings["WXCorpID"].ToString(); var crypt = new WXBizMsgCrypt(WX_CORP_TOKEN, WX_CORP_AES_KEY, WX_CORP_ID); // 微信提供的验证方法 var result = crypt.VerifyURL(signature, timestamp, nonce, echo, ref echoResult); if (result != 0) { return; } // 将验证后的返回值写入响应流,这样可以去掉引号!!! HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Write(echoResult); HttpContext.Current.Response.End(); } } }

2.1 下面的是下载需要的微信解密文件

http://qydev.weixin.qq.com/wiki/index.php?title=%E5%8A%A0%E8%A7%A3%E5%AF%86%E5%BA%93%E4%B8%8B%E8%BD%BD%E4%B8%8E%E8%BF%94%E5%9B%9E%E7%A0%81

 

 3.修改Web.config 增加如下内容 

<add key="WXCorpID" value="wx 53e6" />
<add key="WXCorpToken" value="y al" />
<add key="WXCorpAESKey" value="jpyJu0 iWTD" />

 

 3.1 其中WXCorpID 获取在公众号的设置可以看到账号信息

 

 3.2  URL是WEBAPI调用地址

例如:http://10.1.1.211:8886/api/Vehicle/VerifyURL
Token和Web.config中的相同
EncodingAESKey和web.config中的相同

 

 3.3 点击保存,如果调用成功则返回如下图的结果。

 

posted on 2017-05-18 16:33  易宝1  阅读(957)  评论(0)    收藏  举报