天天看點

SKIT.FlurlHttpClient.Wechat實作微信接口開發-伺服器驗證回調

1. 在微信公衆背景配置

設定以下内容

  • 開發者密碼(AppSecret)
  • IP白名單,就是使用哪一個伺服器來控制目前公衆号
  • l令牌
  • 伺服器位址(URL) : 使用哪一個Url來驗證伺服器是可以進行開發
  • 令牌(Token)
  • 消息加解密密鑰
SKIT.FlurlHttpClient.Wechat實作微信接口開發-伺服器驗證回調

伺服器設定

SKIT.FlurlHttpClient.Wechat實作微信接口開發-伺服器驗證回調

設定完成後,先不要點選送出

2. 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 是業務上的資料,主要定義,AppId, AppSecret, Token等微信公衆号的基本資訊

MpEntity定義如下

SKIT.FlurlHttpClient.Wechat實作微信接口開發-伺服器驗證回調

3. 編寫微信公衆号需要驗簽的接口控制器

對應的Url是 這樣的控制器代碼

/// <summary>
        /// 驗證微信伺服器配置
        /// </summary>
        /// <returns></returns>
        public IActionResult Check()
        {
            WechatApiClient wechatApiClient = SourceCodeWebPlugInService.GetWechatApiClient();

            //得到目前請求的方法
            String curMethod = Request.Method.ToLower();
            LogHelper.WriteLog(#34;請求方法:{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方法隻有訂閱号過來,其他都是Post

//得到訂閱号服務送出的url參數

4. 微信公衆号與應用開發伺服器的之間的關系

  • 微信公衆号伺服器配置點選送出
  • 微信公衆号的伺服器程式,會向開發的伺服器進行一個Get請求,請求的位址如下
  • wechatApiClient.VerifyEventSignatureForEcho 根據伺服器的token以及相關的請求參數進行驗證
  • 驗證如果是正确的,則向服務傳回echostr,向伺服器說明,我已經驗證通過了。
  • 微信關于開發伺服器驗簽的文檔如下:

繼續閱讀