using Microsoft.Win32; using AllBase.Helper; using System; using System.Security.Cryptography; using System.Text; namespace Work.Store.Api; /// 全局共用一个用户会话与请求出口,窗体通过 Instance 访问。 public sealed class StoreApiClient { private static readonly string BaseUrl = EnvironmentHelper.IsProduction ? "http://103.90.155.78:9001/api/" : "http://localhost:14312/api/"; public static StoreApiClient Instance { get; } = new StoreApiClient(); public ApiTransport Transport { get; } public AuthApi Auth { get; } public CloudGoodsApi CloudGoods { get; } //public GoodsComplianceApi GoodsCompliance { get; } public ImageCacheApi ImageCache { get; } /// 当前 Windows 安装的 SHA-256 设备指纹,登录时作为 DeviceId 发送。 public string DeviceId { get; } private StoreApiClient() { DeviceId = CreateDeviceId(); Transport = new ApiTransport(BaseUrl); Auth = new AuthApi(Transport, DeviceId); CloudGoods = new CloudGoodsApi(Transport); //GoodsCompliance = new GoodsComplianceApi(Transport); ImageCache = new ImageCacheApi(Transport); } private static string CreateDeviceId() { using (var machine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) using (var key = machine.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography")) { if (!Guid.TryParse(key?.GetValue("MachineGuid") as string, out var machineGuid) || machineGuid == Guid.Empty) throw new InvalidOperationException("无法读取有效的 Windows MachineGuid,不能生成设备指纹。"); using (var sha256 = SHA256.Create()) return BitConverter.ToString(sha256.ComputeHash( Encoding.UTF8.GetBytes("Store.Api:" + machineGuid.ToString("D")))).Replace("-", ""); } } /// 清除内存中的 Token 和自动登录凭据,不调用服务端退出接口。 public void ClearSession() => Transport.Token = null; }