CardReaderFlow.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Threading.Tasks;
  5. using BeiJingComService.Infrastructure;
  6. namespace BeiJingComService.Core
  7. {
  8. /// <summary>
  9. /// 读卡编排:把 HIS 的读卡序列封装成一个入口。
  10. /// 序列:open(由 ComGateway 自动完成)→ GetPersonClass_Multimedia
  11. /// → 依 card_class 选 GetPersonInfo(Nation)_Multimedia。
  12. ///
  13. /// 调用约定沿用 HIS:ReadCardObj 传两个 byref 参数、值相同,取第 2 个作输出,
  14. /// 故每笔都传 new[] { payload, payload }。
  15. ///
  16. /// 【Round49】不设任何本地缓存:每次读卡都完整走一遍,结果只由调用方传入的报文体决定。
  17. /// </summary>
  18. public static class CardReaderFlow
  19. {
  20. public const string FuncPersonClass = "GetPersonClass_Multimedia";
  21. public const string FuncPersonInfo = "GetPersonInfo_Multimedia";
  22. public const string FuncPersonInfoNation = "GetPersonInfoNation_Multimedia";
  23. /// <summary>
  24. /// 把内层 XML 包装为 COM 入参,等价于 HIS JsonHelper.GetinPar(Appmsg, 0)。
  25. /// </summary>
  26. public static string WrapInput(string innerXml)
  27. {
  28. return "<?xml version=\"1.0\" encoding=\"UTF-16\" standalone=\"yes\" ?><root version=\"2.003\" sender=\"capinfo\"><input>"
  29. + innerXml + "</input></root>";
  30. }
  31. /// <summary>
  32. /// 执行一次读卡。
  33. /// payload 为最终送入 COM 的完整 XML;cardClass 为可选入参:
  34. /// 调用方显式指定人员类别("1" 本市 / "2" 异地)时跳过 GetPersonClass_Multimedia,
  35. /// 直接调用对应地区的参保信息接口;不传则完整跑「人员类别 → 参保信息」两笔。
  36. ///
  37. /// 【Round49】本方法不再读写任何本地缓存,也不依赖会话历史:
  38. /// 同样的入参必然产生同样的调用序列(纯函数性质)。
  39. ///
  40. /// keepSession=true 表示整段读卡序列结束后不空闲关会话(只 Open 一次,测试用);
  41. /// 该标志随本笔请求走,不会影响其它入口。
  42. /// </summary>
  43. public static async Task<CardReadResult> ReadAsync(string payload, string cardClass = null,
  44. bool keepSession = false)
  45. {
  46. var steps = new List<CardReadStep>();
  47. var stopwatch = Stopwatch.StartNew();
  48. if (string.IsNullOrWhiteSpace(payload))
  49. {
  50. stopwatch.Stop();
  51. return LogAndReturn(CardReadResult.Fail(-4, "读卡入参为空",
  52. stopwatch.ElapsedMilliseconds, steps), steps);
  53. }
  54. // ---- 调用方显式指定人员类别:跳过 GetPersonClass,直接调参保信息 ----
  55. // 与已下线的「缓存命中」分支的本质区别:
  56. // 缓存命中 → 一笔 COM 都不调,中心端没有人员信息上下文,随后的 divide 必被 9002/1912 拒绝;
  57. // 本分支 → 调的是 GetPersonInfo(_Nation)_Multimedia,本身就是「获取人员信息」,上下文能建立。
  58. if (!string.IsNullOrWhiteSpace(cardClass))
  59. {
  60. Logger.Info("调用方指定人员类别=" + cardClass + ",跳过 " + FuncPersonClass
  61. + ",直接调用参保信息接口");
  62. PersonInfoCallResult preset = await ExecutePersonInfoAsync(
  63. payload, cardClass, steps, keepSession).ConfigureAwait(false);
  64. ComResult presetResult = preset.Result;
  65. stopwatch.Stop();
  66. if (presetResult.Success && IsSuccess(presetResult.Output))
  67. {
  68. return LogAndReturn(new CardReadResult
  69. {
  70. Code = 0,
  71. Message = "读卡成功(调用方指定人员类别=" + cardClass + ",已跳过人员类别查询)",
  72. ElapsedMs = stopwatch.ElapsedMilliseconds,
  73. CardClass = preset.CardClass,
  74. FuncName = preset.Func,
  75. Output = presetResult.Output,
  76. Steps = steps.ToArray(),
  77. CardNo = ExtractNodeText(presetResult.Output, "card_no")
  78. }, steps);
  79. }
  80. return LogAndReturn(new CardReadResult
  81. {
  82. Code = presetResult.Success ? -1 : presetResult.Code,
  83. Message = FailurePrefix(presetResult, preset.Func, "读取参保信息")
  84. + Summarize(presetResult),
  85. ElapsedMs = stopwatch.ElapsedMilliseconds,
  86. CardClass = preset.CardClass,
  87. FuncName = preset.Func,
  88. Steps = steps.ToArray()
  89. }, steps);
  90. }
  91. // ---- 完整流程:open → GetPersonClass → GetPersonInfo ----
  92. // 第 1 笔:读取人员类别(判断本地/异地)
  93. ComResult classResult = await GatewayHost.Instance.ExecuteAsync(
  94. FuncPersonClass, new[] { payload, payload }, 0, keepSession).ConfigureAwait(false);
  95. steps.Add(ToStep(FuncPersonClass, classResult));
  96. if (!classResult.Success)
  97. {
  98. stopwatch.Stop();
  99. return LogAndReturn(CardReadResult.Fail(classResult.Code,
  100. FailurePrefix(classResult, FuncPersonClass, "读取卡信息") + Summarize(classResult),
  101. stopwatch.ElapsedMilliseconds, steps), steps);
  102. }
  103. if (!IsSuccess(classResult.Output))
  104. {
  105. stopwatch.Stop();
  106. return LogAndReturn(CardReadResult.Fail(-1,
  107. "调用【" + FuncPersonClass + "】返回失败:" + Summarize(classResult),
  108. stopwatch.ElapsedMilliseconds, steps), steps);
  109. }
  110. string detectedClass = ExtractNodeText(classResult.Output, "card_class");
  111. // 第 2 笔:读取参保信息(异地接口被中心拒绝时自动回退本地接口重试一次)
  112. PersonInfoCallResult info = await ExecutePersonInfoAsync(
  113. payload, detectedClass, steps, keepSession).ConfigureAwait(false);
  114. ComResult infoResult = info.Result;
  115. string funcName = info.Func;
  116. string usedClass = info.CardClass;
  117. if (!infoResult.Success)
  118. {
  119. stopwatch.Stop();
  120. return LogAndReturn(CardReadResult.Fail(infoResult.Code,
  121. FailurePrefix(infoResult, funcName, "读取参保信息") + Summarize(infoResult),
  122. stopwatch.ElapsedMilliseconds, steps), steps);
  123. }
  124. if (!IsSuccess(infoResult.Output))
  125. {
  126. stopwatch.Stop();
  127. return LogAndReturn(CardReadResult.Fail(-1,
  128. "调用【" + funcName + "】返回失败:" + Summarize(infoResult),
  129. stopwatch.ElapsedMilliseconds, steps), steps);
  130. }
  131. stopwatch.Stop();
  132. string message = string.IsNullOrEmpty(usedClass)
  133. ? "读卡成功(未取到 card_class,已按本地处理)"
  134. : "读卡成功";
  135. return LogAndReturn(new CardReadResult
  136. {
  137. Code = 0,
  138. Message = message,
  139. ElapsedMs = stopwatch.ElapsedMilliseconds,
  140. CardClass = detectedClass,
  141. FuncName = funcName,
  142. Output = infoResult.Output,
  143. Steps = steps.ToArray(),
  144. CardNo = ExtractNodeText(infoResult.Output, "card_no")
  145. }, steps);
  146. }
  147. /// <summary>
  148. /// 调用参保信息接口:按人员类别选 GetPersonInfo_Multimedia(本地)/ GetPersonInfoNation_Multimedia(异地)。
  149. /// 若本地/异地判定错误导致北京本地卡被异地接口拒绝(2011「该接口不支持使用北京社保卡」),
  150. /// 自动回退本地接口重试一次,并把实际类别修正为本地,避免读卡整体失败。
  151. /// 注:async 方法不允许 out 参数,故用 <see cref="PersonInfoCallResult"/> 承载返回值。
  152. /// </summary>
  153. private static async Task<PersonInfoCallResult> ExecutePersonInfoAsync(string payload, string cardClass,
  154. List<CardReadStep> steps, bool keepSession)
  155. {
  156. var call = new PersonInfoCallResult
  157. {
  158. CardClass = cardClass,
  159. Func = cardClass == "2" ? FuncPersonInfoNation : FuncPersonInfo
  160. };
  161. call.Result = await GatewayHost.Instance.ExecuteAsync(
  162. call.Func, new[] { payload, payload }, 0, keepSession).ConfigureAwait(false);
  163. steps.Add(ToStep(call.Func, call.Result));
  164. if (call.Func == FuncPersonInfoNation
  165. && !(call.Result.Success && IsSuccess(call.Result.Output))
  166. && IsNotSupportLocalCard(call.Result.Output))
  167. {
  168. call.Func = FuncPersonInfo;
  169. call.CardClass = "1";
  170. Logger.Info("异地接口被中心拒绝(该接口不支持使用北京社保卡),自动回退【" + FuncPersonInfo + "】重试");
  171. call.Result = await GatewayHost.Instance.ExecuteAsync(
  172. call.Func, new[] { payload, payload }, 0, keepSession).ConfigureAwait(false);
  173. steps.Add(ToStep(call.Func, call.Result));
  174. }
  175. return call;
  176. }
  177. /// <summary>参保信息接口的调用结果(实际使用的接口名与人员类别,兜底回退后会与入参不同)。</summary>
  178. private sealed class PersonInfoCallResult
  179. {
  180. public ComResult Result { get; set; }
  181. /// <summary>实际调用的接口名。</summary>
  182. public string Func { get; set; }
  183. /// <summary>实际人员类别(1 本地 / 2 异地)。</summary>
  184. public string CardClass { get; set; }
  185. }
  186. /// <summary>中心对北京本地卡调用异地接口时的固定拒绝信息。只认文案,不认错误码(2011 历史上也出现过通讯异常)。</summary>
  187. private static bool IsNotSupportLocalCard(string xml)
  188. {
  189. return !string.IsNullOrEmpty(xml)
  190. && xml.IndexOf("该接口不支持使用北京社保卡", StringComparison.Ordinal) >= 0;
  191. }
  192. /// <summary>
  193. /// 记录一次读卡的汇总耗时(总耗时 + 各步耗时),便于观察每次读卡速度;
  194. /// 日志失败绝不影响读卡结果返回。
  195. /// </summary>
  196. private static CardReadResult LogAndReturn(CardReadResult result, List<CardReadStep> steps)
  197. {
  198. try
  199. {
  200. var parts = new List<string>();
  201. if (steps != null)
  202. {
  203. foreach (CardReadStep step in steps)
  204. {
  205. parts.Add(step.Func + "=" + step.ElapsedMs + "ms(码" + step.Code + ")");
  206. }
  207. }
  208. Logger.Info("读卡" + (result.Code == 0 ? "完成" : "失败")
  209. + ":总耗时=" + result.ElapsedMs + "ms"
  210. + ",card_no=" + (string.IsNullOrEmpty(result.CardNo) ? "(无)" : result.CardNo)
  211. + ",步骤=[" + string.Join(", ", parts.ToArray()) + "]"
  212. + ",结果=" + result.Message);
  213. }
  214. catch
  215. {
  216. // 日志记录失败不影响读卡主流程
  217. }
  218. return result;
  219. }
  220. private static CardReadStep ToStep(string func, ComResult result)
  221. {
  222. return new CardReadStep
  223. {
  224. Func = func,
  225. Code = result.Code,
  226. Message = result.Message,
  227. Output = result.Output,
  228. ElapsedMs = result.ElapsedMs
  229. };
  230. }
  231. /// <summary>报文里的 state 元素用属性 success="true" 表示成功。</summary>
  232. private static bool IsSuccess(string xml)
  233. {
  234. string value = ExtractAttributeValue(xml, "success");
  235. return string.Equals(value, "true", StringComparison.OrdinalIgnoreCase);
  236. }
  237. /// <summary>取形如 &lt;card_class&gt;1&lt;/card_class&gt; 的节点文本,取不到返回 null。</summary>
  238. private static string ExtractNodeText(string xml, string nodeName)
  239. {
  240. if (string.IsNullOrEmpty(xml)) return null;
  241. string openTag = "<" + nodeName + ">";
  242. string closeTag = "</" + nodeName + ">";
  243. int start = xml.IndexOf(openTag, StringComparison.OrdinalIgnoreCase);
  244. if (start < 0) return null;
  245. start += openTag.Length;
  246. int end = xml.IndexOf(closeTag, start, StringComparison.OrdinalIgnoreCase);
  247. if (end < 0) return null;
  248. return xml.Substring(start, end - start).Trim();
  249. }
  250. /// <summary>取 XML 里某个属性的值(报文可能不规范,故用手写扫描而非 XmlDocument)。</summary>
  251. private static string ExtractAttributeValue(string xml, string attributeName)
  252. {
  253. if (string.IsNullOrEmpty(xml)) return null;
  254. int searchFrom = 0;
  255. while (true)
  256. {
  257. int index = xml.IndexOf(attributeName, searchFrom, StringComparison.OrdinalIgnoreCase);
  258. if (index < 0) return null;
  259. int i = index + attributeName.Length;
  260. while (i < xml.Length && char.IsWhiteSpace(xml[i])) i++;
  261. if (i < xml.Length && xml[i] == '=')
  262. {
  263. i++;
  264. while (i < xml.Length && char.IsWhiteSpace(xml[i])) i++;
  265. if (i < xml.Length && (xml[i] == '"' || xml[i] == '\''))
  266. {
  267. char quote = xml[i];
  268. i++;
  269. int end = i;
  270. while (end < xml.Length && xml[end] != quote) end++;
  271. if (end < xml.Length) return xml.Substring(i, end - i);
  272. }
  273. }
  274. searchFrom = index + attributeName.Length;
  275. }
  276. }
  277. /// <summary>
  278. /// 失败文案的固定前缀。
  279. /// open 失败时**不能**挂在读卡方法名下 —— 9008「不允许重复打开设备」是 open 报的,
  280. /// 这一笔根本没进 COM,挂错名字会把排查引到读卡接口上去(Round43 事故就栽在这里)。
  281. /// </summary>
  282. private static string FailurePrefix(ComResult result, string func, string action)
  283. {
  284. if (result != null && string.Equals(result.Stage, ComResult.StageOpen, StringComparison.Ordinal))
  285. {
  286. return "打开读卡设备失败:";
  287. }
  288. return "调用【" + func + "】" + action + "失败:";
  289. }
  290. /// <summary>失败时给出便于排查的报文片段(过长则截断)。</summary>
  291. private static string Summarize(ComResult result)
  292. {
  293. string text = result.Output;
  294. if (string.IsNullOrEmpty(text))
  295. {
  296. return string.IsNullOrEmpty(result.Message) ? ("结果码 " + result.Code) : result.Message;
  297. }
  298. const int limit = 500;
  299. if (text.Length > limit) text = text.Substring(0, limit) + "...(已截断)";
  300. return text;
  301. }
  302. }
  303. /// <summary>读卡结果。</summary>
  304. public sealed class CardReadResult
  305. {
  306. public int Code { get; set; }
  307. public string Message { get; set; }
  308. public long ElapsedMs { get; set; }
  309. public string CardClass { get; set; }
  310. public string FuncName { get; set; }
  311. public string Output { get; set; }
  312. public CardReadStep[] Steps { get; set; }
  313. /// <summary>本次涉及/命中的社保卡号(取不到时为空)。</summary>
  314. public string CardNo { get; set; }
  315. public static CardReadResult Fail(int code, string message, long elapsedMs = 0, List<CardReadStep> steps = null)
  316. {
  317. return new CardReadResult
  318. {
  319. Code = code,
  320. Message = message,
  321. ElapsedMs = elapsedMs,
  322. Steps = steps == null ? null : steps.ToArray()
  323. };
  324. }
  325. }
  326. /// <summary>读卡序列中的单步结果。</summary>
  327. public sealed class CardReadStep
  328. {
  329. public string Func { get; set; }
  330. public int Code { get; set; }
  331. public string Message { get; set; }
  332. public string Output { get; set; }
  333. public long ElapsedMs { get; set; }
  334. }
  335. }