使用SKIT.FlurlHttpClient.Wechat对微信公众号接入

sam 2022-11-20 15:45:53

在微信公众后台配置

设置以下内容

开发者密码(AppSecret)

IP白名单,就是使用哪一个服务器来控制当前公众号

令牌

服务器地址(URL) : 使用哪一个Url来验证服务器是可以进行开发

令牌(Token)

消息加解密密钥

服务器设置

设置完成后,先不要点击提交

SKIT.FlurlHttpClient.Wechat 编写WechatApiClient

 public static WechatApiClient GetWechatApiClient()
        {
            MpEntity defaultMpEntity = MpEntity.GetDefault();
            var options = new WechatApiClientOptions()
            {
                AppId = defaultMpEntity.AppId,
                AppSecret = defaultMpEntity.AppSecret,
                PushToken = defaultMpEntity.Token
            };
            var client = new WechatApiClient(options);
 
            return client;
        }

MpEntity

MpEntity  是业务上的数据,主要定义,AppId, AppSecret, Token等微信公众号的基本信息

MpEntity定义如下

编写微信公众号需要验签的接口控制器

对应的Url是 https://www.xx.com/mp/check 这样的控制器代码

        /// <summary>
        /// 验证微信服务器配置
        /// </summary>
        /// <returns></returns>
        public IActionResult Check()
        {
            WechatApiClient wechatApiClient = SourceCodeWebPlugInService.GetWechatApiClient();
 
            //得到当前请求的方法
            String curMethod = Request.Method.ToLower();
            LogHelper.WriteLog($"请求方法:{curMethod},url:{RequestHelper.Url()}");
 
            if (curMethod == "get")
            {
                //如果是get方法只有订阅号过来,其他都是Post
 
                //得到订阅号服务提交的url参数
                string signature = Request.Get("signature");
                string timestamp = Request.Get("timestamp");
                string nonce = Request.Get("nonce");
                string echostr = Request.Get("echostr");
 
                LogHelper.WriteLog("订阅号请求的url" + RequestHelper.Url());
 
                try
                {
                    bool isCheck = wechatApiClient.VerifyEventSignatureForEcho(timestamp, nonce, signature);
                    if (isCheck)
                    {
                        return Content(echostr);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("公众号服务器验证异常" + ex.Message);
                }
                
            }
            else
            {
                //对消息等进行回复
            }
            return Content("无响应");
 
        }

微信公众号与应用开发服务器的之间的关系

微信公众号服务器配置点击提交

微信公众号的服务器程序,会向开发的服务器进行一个Get请求,请求的地址如下

http://www.xxxx.com/mp/check?signature=39c6aa7beeefecc47d2457425b5b1e56ba3fdf&echostr=66071ee623693343322×tamp=1661119432&nonce=1443728737

wechatApiClient.VerifyEventSignatureForEcho 根据服务器的token以及相关的请求参数进行验证

验证如果是正确的,则向服务返回echostr,向服务器说明,我已经验证通过了。

微信关于开发服务器验签的文档如下:

https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html


回帖
  • 消灭零回复
相关文章