using JiDangJia.Contracts; using System.Net.Http.Json; using System.Security.Cryptography; using System.Text.Json; namespace JiDangJia.Services; public sealed record PurchaseReceiptInfo(string PlanId,string OrderId); // A random receipt, held in device secure storage, protects purchases made before login. public sealed class PurchaseClient { public static PurchaseClient Current {get;}=new(); private readonly HttpClient http=new(){Timeout=TimeSpan.FromSeconds(20)}; private static readonly SemaphoreSlim ReceiptLock=new(1,1); private static readonly JsonSerializerOptions Json=new(JsonSerializerDefaults.Web); private sealed record Receipt(string Server,string PlanId,string RequestId,string Key,string OrderId=""); private static string StorageKey(string planId)=>"purchase_receipt_"+planId; private static async Task> History() { var text=await SecureStorage.Default.GetAsync("purchase_order_receipts"); return text is null?[]:JsonSerializer.Deserialize>(text,Json)??[]; } public async Task> Receipts()=> (await History()).Where(r=>r.Server==ServerSettings.BaseUrl).Select(r=>new PurchaseReceiptInfo(r.PlanId,r.OrderId)).Reverse().ToList(); public async Task Past(string id) { var receipt=(await History()).FirstOrDefault(r=>r.Server==ServerSettings.BaseUrl&&r.OrderId==id)??throw new InvalidOperationException("订单查询凭证不可用,请联系客服"); return await Request("/orders/"+id,receipt:receipt.Key); } private async Task Request(string path,object? body=null,string? receipt=null) { using var request=new HttpRequestMessage(body is null?HttpMethod.Get:HttpMethod.Post,ServerSettings.BaseUrl+"/api/purchase"+path); if(body is not null)request.Content=JsonContent.Create(body);if(receipt is not null)request.Headers.Add("X-Purchase-Key",receipt); try { using var response=await http.SendAsync(request);var text=await response.Content.ReadAsStringAsync(); if(!response.IsSuccessStatusCode) { string message="购买服务暂不可用,请联系客服"; try{using var d=JsonDocument.Parse(text);if(d.RootElement.TryGetProperty("error",out var error))message=error.GetString()??message;}catch(JsonException){} throw new InvalidOperationException(response.StatusCode==System.Net.HttpStatusCode.TooManyRequests?"查询频繁,请稍后再试":message); } return JsonSerializer.Deserialize(text,Json)??throw new InvalidOperationException("购买服务返回无效内容"); } catch(Exception ex)when(ex is HttpRequestException or TaskCanceledException or JsonException){throw new InvalidOperationException("无法连接购买服务,可扫码联系客服购买。",ex);} } public Task Offer()=>Request(""); private static async Task Saved(string planId) { var text=await SecureStorage.Default.GetAsync(StorageKey(planId));if(text is null)return null; try{var receipt=JsonSerializer.Deserialize(text,Json);return receipt?.Server==ServerSettings.BaseUrl&&receipt.PlanId==planId?receipt:null;}catch(JsonException){return null;} } public async Task Existing(string planId) { await ReceiptLock.WaitAsync();try { var receipt=await Saved(planId);if(receipt is null)return null; return receipt.OrderId.Length>0?await Request("/orders/"+receipt.OrderId,receipt:receipt.Key):await FinishCreate(receipt); } finally{ReceiptLock.Release();} } public async Task Create(string planId,bool replace=false) { PurchaseCatalog.Plan(planId);await ReceiptLock.WaitAsync();try { var receipt=replace?null:await Saved(planId); if(receipt is null) { receipt=new(ServerSettings.BaseUrl,planId,Guid.NewGuid().ToString("N"),Convert.ToHexString(RandomNumberGenerator.GetBytes(32))); // Save before sending: a lost response can be safely retried with the same request ID. await SecureStorage.Default.SetAsync(StorageKey(planId),JsonSerializer.Serialize(receipt,Json)); } return receipt.OrderId.Length>0?await Request("/orders/"+receipt.OrderId,receipt:receipt.Key):await FinishCreate(receipt); } finally{ReceiptLock.Release();} } private async Task FinishCreate(Receipt receipt) { var order=await Request("/orders",new CreatePurchaseRequest(receipt.PlanId,receipt.RequestId,receipt.Key)); var saved=receipt with{OrderId=order.Id};var history=await History(); if(!history.Any(r=>r.Server==receipt.Server&&r.OrderId==order.Id)){history.Add(saved);await SecureStorage.Default.SetAsync("purchase_order_receipts",JsonSerializer.Serialize(history,Json));} await SecureStorage.Default.SetAsync(StorageKey(receipt.PlanId),JsonSerializer.Serialize(saved,Json));return order; } public async Task Checkout(string planId,string id) { var receipt=await Saved(planId);if(receipt is null||receipt.OrderId!=id)throw new InvalidOperationException("订单查询凭证不可用,请联系客服"); return await Request("/orders/"+id+"/checkout",new{},receipt.Key); } }