调用微信公众平台官方Api 验证检测网络情况
为了帮助开发者排查回调连接失败的问题,微信官方提供了网络检测的API。它可以对开发者URL做域名解析,然后对所有IP进行一次ping操作,得到丢包率和耗时。
接口文档地址:
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Network_Detection.html
接着上一篇:微信公众平台C#开发系列(五):获取微信服务器IP地址
部分使用类方法详情 请参考系列四 ,本文不再重复赘述
根据文档我们先定义一个NetworkDetectionResponse类继承 ErrorMessage 用于解析接口结果
ErrorMessage 公共类参考 : 微信公众平台C#开发系列(四):获取access token凭证
namespace YuanTK.WeiXin.Wrapper { ////// 网络检测结果 /// public class NetworkDetectionResponse : ErrorMessage { /// /// dns结果列表 /// public Dns[] dns { get; set; } /// /// ping结果列表 /// public Ping[] ping { get; set; } } /// /// dns结果 /// public class Dns { /// /// 解析出来的ip /// public string ip { get; set; } /// /// ip对应的运营商 /// public string real_operator { get; set; } } /// /// ping结果 /// public class Ping { /// /// ping的ip,执行命令为ping ip –c 1-w 1 -q /// public string ip { get; set; } /// /// ping的源头的运营商,由请求中的check_operator控制 /// public string from_operator { get; set; } /// /// ping的丢包率,0%表示无丢包,100%表示全部丢包。因为目前仅发送一个ping包,因此取值仅有0%或者100%两种可能。 /// public string package_loss { get; set; } /// /// ping的耗时,取ping结果的avg耗时。 /// public string time { get; set; } } }
定义一个NetworkDetection方法类继承WeiXinRequest 和接口IWeiXin 和NetworkDetectionRequest 请求参数类
namespace YuanTK.WeiXin { ////// 接口请求参数类 /// public class NetworkDetectionRequest { /// /// 执行的检测动作 /// public enum Action { /// /// 域名解析 /// dns, /// /// ping检测 /// ping, /// /// dns和ping都做 /// all } /// /// 指定平台从某个运营商进行检测 /// public enum CheckOperator { /// /// 电信出口 /// CHINANET, /// /// 联通出口 /// UNICOM, /// /// 腾讯自建出口 /// CAP, /// /// 根据ip来选择运营商 /// DEFAULT } [JsonConverter(typeof(StringEnumConverter))] /// /// 执行的检测动作,允许的值:dns(做域名解析)、ping(做ping检测)、all(dns和ping都做) /// public Action action { get; set; } [JsonConverter(typeof(StringEnumConverter))] /// /// 指定平台从某个运营商进行检测,允许的值:CHINANET(电信出口)、UNICOM(联通出口)、CAP(腾讯自建出口)、DEFAULT(根据ip来选择运营商) /// public CheckOperator check_operator { get; set; } } /// /// 网络故障检测 /// public class NetworkDetection : WeiXinRequest , IWeiXin { /// /// 接口地址 /// String api; NetworkDetectionRequest RequestData; /// /// /// /// 执行的检测动作 /// 指定平台从某个运营商进行检测 /// 授权凭证 public NetworkDetection(NetworkDetectionRequest RequestData, string access_token) { this.RequestData = RequestData; ///初始化接口地址 api = $"https://api.weixin.qq.com/cgi-bin/callback/check?access_token={access_token}"; } /// /// 调用接口获取结果 /// /// public NetworkDetectionResponse GetResponse() { if (this.RequestData is null) { throw new Exception("请求参数不能为空"); } string poststr = Newtonsoft.Json.JsonConvert.SerializeObject(this.RequestData); return this.Post(api, poststr); } } }
调用代码例子
string access_token = token.access_token;
///封装请求参数
NetworkDetectionRequest request = new NetworkDetectionRequest()
{
action = NetworkDetectionRequest.Action.ping,
check_operator = NetworkDetectionRequest.CheckOperator.DEFAULT
};
IWeiXin api = new NetworkDetection(request, access_token);
NetworkDetectionResponse networkDetection = api.GetResponse();
调用成功的效果