| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374 |
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Threading.Tasks;
- using BeiJingComService.Infrastructure;
- namespace BeiJingComService.Core
- {
- /// <summary>
- /// 读卡编排:把 HIS 的读卡序列封装成一个入口。
- /// 序列:open(由 ComGateway 自动完成)→ GetPersonClass_Multimedia
- /// → 依 card_class 选 GetPersonInfo(Nation)_Multimedia。
- ///
- /// 调用约定沿用 HIS:ReadCardObj 传两个 byref 参数、值相同,取第 2 个作输出,
- /// 故每笔都传 new[] { payload, payload }。
- ///
- /// 【Round49】不设任何本地缓存:每次读卡都完整走一遍,结果只由调用方传入的报文体决定。
- /// </summary>
- public static class CardReaderFlow
- {
- public const string FuncPersonClass = "GetPersonClass_Multimedia";
- public const string FuncPersonInfo = "GetPersonInfo_Multimedia";
- public const string FuncPersonInfoNation = "GetPersonInfoNation_Multimedia";
- /// <summary>
- /// 把内层 XML 包装为 COM 入参,等价于 HIS JsonHelper.GetinPar(Appmsg, 0)。
- /// </summary>
- public static string WrapInput(string innerXml)
- {
- return "<?xml version=\"1.0\" encoding=\"UTF-16\" standalone=\"yes\" ?><root version=\"2.003\" sender=\"capinfo\"><input>"
- + innerXml + "</input></root>";
- }
- /// <summary>
- /// 执行一次读卡。
- /// payload 为最终送入 COM 的完整 XML;cardClass 为可选入参:
- /// 调用方显式指定人员类别("1" 本市 / "2" 异地)时跳过 GetPersonClass_Multimedia,
- /// 直接调用对应地区的参保信息接口;不传则完整跑「人员类别 → 参保信息」两笔。
- ///
- /// 【Round49】本方法不再读写任何本地缓存,也不依赖会话历史:
- /// 同样的入参必然产生同样的调用序列(纯函数性质)。
- ///
- /// keepSession=true 表示整段读卡序列结束后不空闲关会话(只 Open 一次,测试用);
- /// 该标志随本笔请求走,不会影响其它入口。
- /// </summary>
- public static async Task<CardReadResult> ReadAsync(string payload, string cardClass = null,
- bool keepSession = false)
- {
- var steps = new List<CardReadStep>();
- var stopwatch = Stopwatch.StartNew();
- if (string.IsNullOrWhiteSpace(payload))
- {
- stopwatch.Stop();
- return LogAndReturn(CardReadResult.Fail(-4, "读卡入参为空",
- stopwatch.ElapsedMilliseconds, steps), steps);
- }
- // ---- 调用方显式指定人员类别:跳过 GetPersonClass,直接调参保信息 ----
- // 与已下线的「缓存命中」分支的本质区别:
- // 缓存命中 → 一笔 COM 都不调,中心端没有人员信息上下文,随后的 divide 必被 9002/1912 拒绝;
- // 本分支 → 调的是 GetPersonInfo(_Nation)_Multimedia,本身就是「获取人员信息」,上下文能建立。
- if (!string.IsNullOrWhiteSpace(cardClass))
- {
- Logger.Info("调用方指定人员类别=" + cardClass + ",跳过 " + FuncPersonClass
- + ",直接调用参保信息接口");
- PersonInfoCallResult preset = await ExecutePersonInfoAsync(
- payload, cardClass, steps, keepSession).ConfigureAwait(false);
- ComResult presetResult = preset.Result;
- stopwatch.Stop();
- if (presetResult.Success && IsSuccess(presetResult.Output))
- {
- return LogAndReturn(new CardReadResult
- {
- Code = 0,
- Message = "读卡成功(调用方指定人员类别=" + cardClass + ",已跳过人员类别查询)",
- ElapsedMs = stopwatch.ElapsedMilliseconds,
- CardClass = preset.CardClass,
- FuncName = preset.Func,
- Output = presetResult.Output,
- Steps = steps.ToArray(),
- CardNo = ExtractNodeText(presetResult.Output, "card_no")
- }, steps);
- }
- return LogAndReturn(new CardReadResult
- {
- Code = presetResult.Success ? -1 : presetResult.Code,
- Message = FailurePrefix(presetResult, preset.Func, "读取参保信息")
- + Summarize(presetResult),
- ElapsedMs = stopwatch.ElapsedMilliseconds,
- CardClass = preset.CardClass,
- FuncName = preset.Func,
- Steps = steps.ToArray()
- }, steps);
- }
- // ---- 完整流程:open → GetPersonClass → GetPersonInfo ----
- // 第 1 笔:读取人员类别(判断本地/异地)
- ComResult classResult = await GatewayHost.Instance.ExecuteAsync(
- FuncPersonClass, new[] { payload, payload }, 0, keepSession).ConfigureAwait(false);
- steps.Add(ToStep(FuncPersonClass, classResult));
- if (!classResult.Success)
- {
- stopwatch.Stop();
- return LogAndReturn(CardReadResult.Fail(classResult.Code,
- FailurePrefix(classResult, FuncPersonClass, "读取卡信息") + Summarize(classResult),
- stopwatch.ElapsedMilliseconds, steps), steps);
- }
- if (!IsSuccess(classResult.Output))
- {
- stopwatch.Stop();
- return LogAndReturn(CardReadResult.Fail(-1,
- "调用【" + FuncPersonClass + "】返回失败:" + Summarize(classResult),
- stopwatch.ElapsedMilliseconds, steps), steps);
- }
- string detectedClass = ExtractNodeText(classResult.Output, "card_class");
- // 第 2 笔:读取参保信息(异地接口被中心拒绝时自动回退本地接口重试一次)
- PersonInfoCallResult info = await ExecutePersonInfoAsync(
- payload, detectedClass, steps, keepSession).ConfigureAwait(false);
- ComResult infoResult = info.Result;
- string funcName = info.Func;
- string usedClass = info.CardClass;
- if (!infoResult.Success)
- {
- stopwatch.Stop();
- return LogAndReturn(CardReadResult.Fail(infoResult.Code,
- FailurePrefix(infoResult, funcName, "读取参保信息") + Summarize(infoResult),
- stopwatch.ElapsedMilliseconds, steps), steps);
- }
- if (!IsSuccess(infoResult.Output))
- {
- stopwatch.Stop();
- return LogAndReturn(CardReadResult.Fail(-1,
- "调用【" + funcName + "】返回失败:" + Summarize(infoResult),
- stopwatch.ElapsedMilliseconds, steps), steps);
- }
- stopwatch.Stop();
- string message = string.IsNullOrEmpty(usedClass)
- ? "读卡成功(未取到 card_class,已按本地处理)"
- : "读卡成功";
- return LogAndReturn(new CardReadResult
- {
- Code = 0,
- Message = message,
- ElapsedMs = stopwatch.ElapsedMilliseconds,
- CardClass = detectedClass,
- FuncName = funcName,
- Output = infoResult.Output,
- Steps = steps.ToArray(),
- CardNo = ExtractNodeText(infoResult.Output, "card_no")
- }, steps);
- }
- /// <summary>
- /// 调用参保信息接口:按人员类别选 GetPersonInfo_Multimedia(本地)/ GetPersonInfoNation_Multimedia(异地)。
- /// 若本地/异地判定错误导致北京本地卡被异地接口拒绝(2011「该接口不支持使用北京社保卡」),
- /// 自动回退本地接口重试一次,并把实际类别修正为本地,避免读卡整体失败。
- /// 注:async 方法不允许 out 参数,故用 <see cref="PersonInfoCallResult"/> 承载返回值。
- /// </summary>
- private static async Task<PersonInfoCallResult> ExecutePersonInfoAsync(string payload, string cardClass,
- List<CardReadStep> steps, bool keepSession)
- {
- var call = new PersonInfoCallResult
- {
- CardClass = cardClass,
- Func = cardClass == "2" ? FuncPersonInfoNation : FuncPersonInfo
- };
- call.Result = await GatewayHost.Instance.ExecuteAsync(
- call.Func, new[] { payload, payload }, 0, keepSession).ConfigureAwait(false);
- steps.Add(ToStep(call.Func, call.Result));
- if (call.Func == FuncPersonInfoNation
- && !(call.Result.Success && IsSuccess(call.Result.Output))
- && IsNotSupportLocalCard(call.Result.Output))
- {
- call.Func = FuncPersonInfo;
- call.CardClass = "1";
- Logger.Info("异地接口被中心拒绝(该接口不支持使用北京社保卡),自动回退【" + FuncPersonInfo + "】重试");
- call.Result = await GatewayHost.Instance.ExecuteAsync(
- call.Func, new[] { payload, payload }, 0, keepSession).ConfigureAwait(false);
- steps.Add(ToStep(call.Func, call.Result));
- }
- return call;
- }
- /// <summary>参保信息接口的调用结果(实际使用的接口名与人员类别,兜底回退后会与入参不同)。</summary>
- private sealed class PersonInfoCallResult
- {
- public ComResult Result { get; set; }
- /// <summary>实际调用的接口名。</summary>
- public string Func { get; set; }
- /// <summary>实际人员类别(1 本地 / 2 异地)。</summary>
- public string CardClass { get; set; }
- }
- /// <summary>中心对北京本地卡调用异地接口时的固定拒绝信息。只认文案,不认错误码(2011 历史上也出现过通讯异常)。</summary>
- private static bool IsNotSupportLocalCard(string xml)
- {
- return !string.IsNullOrEmpty(xml)
- && xml.IndexOf("该接口不支持使用北京社保卡", StringComparison.Ordinal) >= 0;
- }
- /// <summary>
- /// 记录一次读卡的汇总耗时(总耗时 + 各步耗时),便于观察每次读卡速度;
- /// 日志失败绝不影响读卡结果返回。
- /// </summary>
- private static CardReadResult LogAndReturn(CardReadResult result, List<CardReadStep> steps)
- {
- try
- {
- var parts = new List<string>();
- if (steps != null)
- {
- foreach (CardReadStep step in steps)
- {
- parts.Add(step.Func + "=" + step.ElapsedMs + "ms(码" + step.Code + ")");
- }
- }
- Logger.Info("读卡" + (result.Code == 0 ? "完成" : "失败")
- + ":总耗时=" + result.ElapsedMs + "ms"
- + ",card_no=" + (string.IsNullOrEmpty(result.CardNo) ? "(无)" : result.CardNo)
- + ",步骤=[" + string.Join(", ", parts.ToArray()) + "]"
- + ",结果=" + result.Message);
- }
- catch
- {
- // 日志记录失败不影响读卡主流程
- }
- return result;
- }
- private static CardReadStep ToStep(string func, ComResult result)
- {
- return new CardReadStep
- {
- Func = func,
- Code = result.Code,
- Message = result.Message,
- Output = result.Output,
- ElapsedMs = result.ElapsedMs
- };
- }
- /// <summary>报文里的 state 元素用属性 success="true" 表示成功。</summary>
- private static bool IsSuccess(string xml)
- {
- string value = ExtractAttributeValue(xml, "success");
- return string.Equals(value, "true", StringComparison.OrdinalIgnoreCase);
- }
- /// <summary>取形如 <card_class>1</card_class> 的节点文本,取不到返回 null。</summary>
- private static string ExtractNodeText(string xml, string nodeName)
- {
- if (string.IsNullOrEmpty(xml)) return null;
- string openTag = "<" + nodeName + ">";
- string closeTag = "</" + nodeName + ">";
- int start = xml.IndexOf(openTag, StringComparison.OrdinalIgnoreCase);
- if (start < 0) return null;
- start += openTag.Length;
- int end = xml.IndexOf(closeTag, start, StringComparison.OrdinalIgnoreCase);
- if (end < 0) return null;
- return xml.Substring(start, end - start).Trim();
- }
- /// <summary>取 XML 里某个属性的值(报文可能不规范,故用手写扫描而非 XmlDocument)。</summary>
- private static string ExtractAttributeValue(string xml, string attributeName)
- {
- if (string.IsNullOrEmpty(xml)) return null;
- int searchFrom = 0;
- while (true)
- {
- int index = xml.IndexOf(attributeName, searchFrom, StringComparison.OrdinalIgnoreCase);
- if (index < 0) return null;
- int i = index + attributeName.Length;
- while (i < xml.Length && char.IsWhiteSpace(xml[i])) i++;
- if (i < xml.Length && xml[i] == '=')
- {
- i++;
- while (i < xml.Length && char.IsWhiteSpace(xml[i])) i++;
- if (i < xml.Length && (xml[i] == '"' || xml[i] == '\''))
- {
- char quote = xml[i];
- i++;
- int end = i;
- while (end < xml.Length && xml[end] != quote) end++;
- if (end < xml.Length) return xml.Substring(i, end - i);
- }
- }
- searchFrom = index + attributeName.Length;
- }
- }
- /// <summary>
- /// 失败文案的固定前缀。
- /// open 失败时**不能**挂在读卡方法名下 —— 9008「不允许重复打开设备」是 open 报的,
- /// 这一笔根本没进 COM,挂错名字会把排查引到读卡接口上去(Round43 事故就栽在这里)。
- /// </summary>
- private static string FailurePrefix(ComResult result, string func, string action)
- {
- if (result != null && string.Equals(result.Stage, ComResult.StageOpen, StringComparison.Ordinal))
- {
- return "打开读卡设备失败:";
- }
- return "调用【" + func + "】" + action + "失败:";
- }
- /// <summary>失败时给出便于排查的报文片段(过长则截断)。</summary>
- private static string Summarize(ComResult result)
- {
- string text = result.Output;
- if (string.IsNullOrEmpty(text))
- {
- return string.IsNullOrEmpty(result.Message) ? ("结果码 " + result.Code) : result.Message;
- }
- const int limit = 500;
- if (text.Length > limit) text = text.Substring(0, limit) + "...(已截断)";
- return text;
- }
- }
- /// <summary>读卡结果。</summary>
- public sealed class CardReadResult
- {
- public int Code { get; set; }
- public string Message { get; set; }
- public long ElapsedMs { get; set; }
- public string CardClass { get; set; }
- public string FuncName { get; set; }
- public string Output { get; set; }
- public CardReadStep[] Steps { get; set; }
- /// <summary>本次涉及/命中的社保卡号(取不到时为空)。</summary>
- public string CardNo { get; set; }
- public static CardReadResult Fail(int code, string message, long elapsedMs = 0, List<CardReadStep> steps = null)
- {
- return new CardReadResult
- {
- Code = code,
- Message = message,
- ElapsedMs = elapsedMs,
- Steps = steps == null ? null : steps.ToArray()
- };
- }
- }
- /// <summary>读卡序列中的单步结果。</summary>
- public sealed class CardReadStep
- {
- public string Func { get; set; }
- public int Code { get; set; }
- public string Message { get; set; }
- public string Output { get; set; }
- public long ElapsedMs { get; set; }
- }
- }
|