### Minimal API example with Nafath Source: https://github.com/arahimx/nafath.net/blob/master/ReadMe.md A complete minimal API example showing how to start a Nafath session and verify its status using INafathService. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddNafath(options => { options.BaseUrl = "https://auth.nafath.sa"; options.ClientId = builder.Configuration["Nafath:ClientId"]; options.ClientSecret = builder.Configuration["Nafath:ClientSecret"]; }); var app = builder.Build(); app.MapPost("/nafath/start", async (INafathService nafath, string idNumber, string requestId) => { var result = await nafath.StartSessionAsync(idNumber, requestId); return Results.Ok(result); }); app.MapGet("/nafath/verify/{transactionId}", async (INafathService nafath, string transactionId) => { var result = await nafath.VerifyStatusAsync(transactionId); return Results.Ok(result); }); app.Run(); ``` -------------------------------- ### Install Nafath.Net from NuGet Source: https://github.com/arahimx/nafath.net/blob/master/ReadMe.md Install the SDK from NuGet once it is available. ```bash dotnet add package Nafath.Net ``` -------------------------------- ### Add local project reference Source: https://github.com/arahimx/nafath.net/blob/master/ReadMe.md Install the SDK by adding a local project reference until it is published to NuGet. ```bash dotnet add reference ../Nafath.Net/Nafath.Net.csproj ``` -------------------------------- ### GET /api/v1/auth/verify example URL Source: https://github.com/arahimx/nafath.net Example URL for polling verification status. The transactionId query parameter is required and comes from a prior initiate call. ```text https://auth.nafath.sa/api/v1/auth/verify?transactionId=abc123 ``` -------------------------------- ### VerifyStatusAsync usage example Source: https://github.com/arahimx/nafath.net Example of calling VerifyStatusAsync with a transaction ID and handling the verification result. On failure, the response has Success=false and Status/Message set according to the exception type. ```csharp var verification = await service.VerifyStatusAsync(result.TransactionId); if (verification.Success) { Console.WriteLine($"User accepted: {verification.Status} — {verification.Message}"); } else { Console.WriteLine($"Not yet verified ({verification.Status}): {verification.Message}"); } ``` -------------------------------- ### Register Nafath with DI using AddNafath Source: https://github.com/arahimx/nafath.net Recommended setup: registers options and typed client via AddNafath. Reads BaseUrl, ClientId, and ClientSecret from configuration. ```csharp using Nafath.Net.Extensions; builder.Services.AddNafath(options => { options.BaseUrl = "https://auth.nafath.sa"; options.ClientId = builder.Configuration["Nafath:ClientId"]; options.ClientSecret = builder.Configuration["Nafath:ClientSecret"]; }); ``` -------------------------------- ### Sample unit test for NafathService Source: https://github.com/arahimx/nafath.net/blob/master/ReadMe.md A unit test example using a mock HttpMessageHandler to test StartSessionAsync. It verifies that the result is not null and has no error. ```csharp public class NafathServiceTests { [Fact] public async Task StartSessionAsync_Returns_ValidResponse() { // Arrange var httpClient = new HttpClient(new MockHttpMessageHandler()); var options = Options.Create(new NafathOptions { BaseUrl = "https://fake.api" }); var logger = new LoggerFactory().CreateLogger(); var service = new NafathService(httpClient, options, logger); // Act var result = await service.StartSessionAsync("1234567890", "test-req"); // Assert Assert.NotNull(result); Assert.True(string.IsNullOrEmpty(result.Error)); } } ``` -------------------------------- ### Consumer example for StartSessionAsync Source: https://github.com/arahimx/nafath.net Example of a consumer depending on the INafathService interface. Uses StartSessionAsync with a generated requestId and returns the TransactionId only if no error is present. ```csharp using Nafath.Net.Interfaces; public class NafathFlowRunner { private readonly INafathService _nafath; public NafathFlowRunner(INafathService nafath) => _nafath = nafath; public async Task StartOrNullAsync(string idNumber) { var response = await _nafath.StartSessionAsync(idNumber, Guid.NewGuid().ToString("N")); return string.IsNullOrEmpty(response.Error) ? response.TransactionId : null; } } ``` -------------------------------- ### Direct construction of NafathService Source: https://github.com/arahimx/nafath.net Example of constructing NafathService without DI, suitable for console apps or unit tests. Requires creating HttpClient, Options.Create with NafathOptions (BaseUrl set to https://auth.nafath.sa), and a logger from LoggerFactory. ```csharp using System.Net.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Nafath.Net; using Nafath.Net.Services; var httpClient = new HttpClient(); var options = Options.Create(new NafathOptions { BaseUrl = "https://auth.nafath.sa" }); var logger = new LoggerFactory().CreateLogger(); var service = new NafathService(httpClient, options, logger); ``` -------------------------------- ### StartSessionAsync usage with error handling Source: https://github.com/arahimx/nafath.net Example of calling StartSessionAsync and checking the Error property. On failure, prints the error and returns; otherwise prints the RedirectUrl and TransactionId for redirecting the user to the Nafath login page. ```csharp var result = await service.StartSessionAsync("1012345678", "order-42"); if (!string.IsNullOrEmpty(result.Error)) { Console.WriteLine($"Session failed: {result.Error}"); return; } // Redirect the user to the Nafath login page Console.WriteLine($"Verify at: {result.RedirectUrl} (transaction {result.TransactionId})"); ``` -------------------------------- ### Usage in ASP.NET Core minimal API Source: https://github.com/arahimx/nafath.net Example of registering Nafath in a minimal API Program.cs. Configures BaseUrl, ClientId, and ClientSecret from configuration, then maps endpoints for starting and verifying sessions. ```csharp using Nafath.Net.Extensions; var builder = WebApplication.CreateBuilder(args); builder.Services.AddNafath(options => { options.BaseUrl = "https://auth.nafath.sa"; options.ClientId = builder.Configuration["Nafath:ClientId"]; options.ClientSecret = builder.Configuration["Nafath:ClientSecret"]; }); var app = builder.Build(); app.MapPost("/nafath/start", async (INafathService nafath, string idNumber, string requestId) => { var result = await nafath.StartSessionAsync(idNumber, requestId); return Results.Ok(result); }); app.MapGet("/nafath/verify/{transactionId}", async (INafathService nafath, string transactionId) => { var result = await nafath.VerifyStatusAsync(transactionId); return Results.Ok(result); }); app.Run(); ``` -------------------------------- ### Usage with error-observing handler Source: https://github.com/arahimx/nafath.net Two-part example: first registers Nafath with a fallback BaseUrl, then shows a service that uses INafathService to start a session and verify status, throwing exceptions on errors. ```csharp using Nafath.Net.Extensions; services.AddNafath(options => { options.BaseUrl = config["Nafath:BaseUrl"] ?? "https://auth.nafath.sa"; }); ``` ```csharp public interface ISessionOrchestrator { Task CompleteAsync(string idNumber); } public class SessionOrchestrator : ISessionOrchestrator { private readonly INafathService _nafath; public SessionOrchestrator(INafathService nafath) => _nafath = nafath; public async Task CompleteAsync(string idNumber) { var session = await _nafath.StartSessionAsync(idNumber, Guid.NewGuid().ToString()); if (session.Error is not null) { throw new InvalidOperationException($"Nafath unavailable: {session.Error}"); } var verification = await _nafath.VerifyStatusAsync(session.TransactionId); if (!verification.Success && verification.Status == "error") { throw new TimeoutException(verification.Message); } } } ``` -------------------------------- ### StartSessionAsync method signature Source: https://github.com/arahimx/nafath.net Public method signature for starting a Nafath session. Takes the user's Saudi national ID/Iqama number and a caller-supplied request ID. Returns a Task. ```csharp public async Task StartSessionAsync(string idNumber, string requestId) ``` -------------------------------- ### Poller example for VerifyStatusAsync Source: https://github.com/arahimx/nafath.net Example of polling session status. Loops up to attempts times, returns true on Success, false on rejected status, and waits 2 seconds between attempts. The SDK only interprets 'error' and 'timeout' statuses internally; other status meanings come from the Nafath API. ```csharp using Nafath.Net.Interfaces; public class Poller { private readonly INafathService _nafath; public Poller(INafathService nafath) => _nafath = nafath; public async Task WaitForAcceptanceAsync(string transactionId, int attempts = 10) { for (var i = 0; i < attempts; i++) { var result = await _nafath.VerifyStatusAsync(transactionId); if (result.Success) return true; if (result.Status == "rejected") return false; await Task.Delay(2000); } return false; } } ``` -------------------------------- ### NafathService class implementation Source: https://github.com/arahimx/nafath.net HTTP-transport implementation of INafathService. Constructor takes HttpClient, IOptions, and ILogger. StartSessionAsync POSTs to {BaseUrl}/api/v1/auth/initiate; VerifyStatusAsync GETs {BaseUrl}/api/v1/auth/verify?transactionId=... ```csharp public class NafathService : INafathService { public NafathService(HttpClient httpClient, IOptions options, ILogger logger); public Task StartSessionAsync(string idNumber, string requestId); public Task VerifyStatusAsync(string transactionId); } ``` -------------------------------- ### GET /api/v1/auth/verify Source: https://github.com/arahimx/nafath.net Polls the outcome of a session started via the initiate endpoint. This endpoint is called by the SDK's VerifyStatusAsync method and requires a transactionId query parameter. ```APIDOC ## GET /api/v1/auth/verify ### Description Polls the outcome of a session started via the initiate endpoint. ### Method GET ### Endpoint `{BaseUrl}/api/v1/auth/verify` ### Parameters #### Query Parameters - **transactionId** (string) - Required - Value of AuthResponse.TransactionId from a prior initiate call. ### Response #### Success Response (200) - **Success** (bool) - Whether verification succeeded. - **Status** (string) - Nafath-reported status. - **Message** (string) - Human-readable detail. ### Request Example ``` https://auth.nafath.sa/api/v1/auth/verify?transactionId=abc123 ``` ``` -------------------------------- ### VerifyStatusAsync method signature Source: https://github.com/arahimx/nafath.net Polls the status of a previously initiated session. The implementation GETs {BaseUrl}/api/v1/auth/verify?transactionId={transactionId}. Returns Task carrying Success, Status, and Message. ```csharp Task VerifyStatusAsync(string transactionId); ``` -------------------------------- ### VerifyStatusAsync Source: https://github.com/arahimx/nafath.net Polls a session's acceptance status. This method is part of the INafathService interface and is implemented by NafathService, which sends a GET request to {BaseUrl}/api/v1/auth/verify with the transactionId as a query parameter. ```APIDOC ## VerifyStatusAsync ### Description Polls a session's acceptance status. ### Method GET ### Endpoint {BaseUrl}/api/v1/auth/verify?transactionId=... ### Parameters #### Query Parameters - **transactionId** (string) - Required - The transaction ID of the session. ### Response #### Success Response (200) - **VerificationResponse** - The verification response object. ``` -------------------------------- ### VerifyStatusAsync Source: https://github.com/arahimx/nafath.net Polls the status of a previously initiated session — i.e. whether the user accepted or rejected the authentication prompt. The implementation GETs `{BaseUrl}/api/v1/auth/verify?transactionId={transactionId}`. Returns a strongly typed VerificationResponse carrying Success, Status, and Message. ```APIDOC ## VerifyStatusAsync ### Description Polls the status of a previously initiated session — i.e. whether the user accepted or rejected the authentication prompt. The implementation GETs `{BaseUrl}/api/v1/auth/verify?transactionId={transactionId}`. ### Method GET ### Endpoint `{BaseUrl}/api/v1/auth/verify?transactionId={transactionId}` ### Parameters #### Query Parameters - `transactionId` (string) - Required - The transaction identifier returned by `StartSessionAsync` (stored in `AuthResponse.TransactionId`). ### Response #### Success Response (200) - `Success` (boolean) - Indicates whether the authentication was successful. - `Status` (string) - The status of the session (e.g., "success", "rejected", "pending"). - `Message` (string) - Additional message from the API. ### Request Example ```csharp using Nafath.Net.Interfaces; public class Poller { private readonly INafathService _nafath; public Poller(INafathService nafath) => _nafath = nafath; public async Task WaitForAcceptanceAsync(string transactionId, int attempts = 10) { for (var i = 0; i < attempts; i++) { var result = await _nafath.VerifyStatusAsync(transactionId); if (result.Success) return true; if (result.Status == "rejected") return false; await Task.Delay(2000); } return false; } } ``` ``` -------------------------------- ### INafathService interface definition Source: https://github.com/arahimx/nafath.net Defines the contract for starting an authentication session and polling its status. Consumed by NafathService, AddHttpClient() registration, and application code via constructor injection. ```csharp public interface INafathService { Task StartSessionAsync(string idNumber, string requestId); Task VerifyStatusAsync(string transactionId); } ``` -------------------------------- ### Basic construction of NafathOptions Source: https://github.com/arahimx/nafath.net Shows how to instantiate NafathOptions directly when creating NafathService manually. The recommended approach is to use the AddNafath DI extension instead. ```csharp using Microsoft.Extensions.Options; using Nafath.Net; var options = Options.Create(new NafathOptions { BaseUrl = "https://auth.nafath.sa", ClientId = "my-client-id", ClientSecret = "my-client-secret" }); ``` -------------------------------- ### Register SDK in Program.cs Source: https://github.com/arahimx/nafath.net/blob/master/ReadMe.md Configure the Nafath SDK in Program.cs with BaseUrl, ClientId, and ClientSecret. Use User Secrets, environment variables, or Azure Key Vault for secrets. ```csharp builder.Services.AddNafath(options => { options.BaseUrl = "https://auth.nafath.sa"; options.ClientId = "your-client-id"; options.ClientSecret = "your-client-secret"; }); ``` -------------------------------- ### NafathService constructor signature Source: https://github.com/arahimx/nafath.net Constructor signature for NafathService. Parameters: httpClient (HttpClient), options (IOptions), logger (ILogger). All required. When resolved via DI, httpClient is the named/typed client registered by AddHttpClient() with no additional handlers. ```csharp public NafathService(HttpClient httpClient, IOptions options, ILogger logger) ``` -------------------------------- ### StartSessionAsync method signature Source: https://github.com/arahimx/nafath.net Initiates a Nafath authentication session for a national ID holder. The implementation POSTs the credentials to {BaseUrl}/api/v1/auth/initiate. Returns Task carrying TransactionId, RedirectUrl, and Error; never throws for expected failures, returns AuthResponse with populated Error instead. ```csharp Task StartSessionAsync(string idNumber, string requestId); ``` -------------------------------- ### Construct NafathService directly without DI Source: https://github.com/arahimx/nafath.net For console apps or tests: create NafathOptions via Options.Create, a logger, and instantiate NafathService with an HttpClient. ```csharp using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Nafath.Net; using Nafath.Net.Services; var options = Options.Create(new NafathOptions { BaseUrl = "https://auth.nafath.sa", ClientId = "my-client-id", ClientSecret = "my-client-secret" }); var logger = new LoggerFactory().CreateLogger(); var service = new NafathService(new HttpClient(), options, logger); ``` -------------------------------- ### StartSessionAsync Source: https://github.com/arahimx/nafath.net Initiates an authentication session. This method is part of the INafathService interface and is implemented by NafathService, which sends a POST request to {BaseUrl}/api/v1/auth/initiate. ```APIDOC ## StartSessionAsync ### Description Initiates an authentication session. ### Method POST ### Endpoint {BaseUrl}/api/v1/auth/initiate ### Parameters #### Request Body - **idNumber** (string) - Required - The national ID number of the user. - **requestId** (string) - Required - A unique request identifier. ### Response #### Success Response (200) - **AuthResponse** - The authentication response object. ``` -------------------------------- ### AddNafath with configuration binding for BaseUrl Source: https://github.com/arahimx/nafath.net Alternative DI registration that reads BaseUrl from configuration as well, using null-forgiving operator. ```csharp builder.Services.AddNafath(options => { options.BaseUrl = builder.Configuration["Nafath:BaseUrl"]!; options.ClientId = builder.Configuration["Nafath:ClientId"]!; options.ClientSecret = builder.Configuration["Nafath:ClientSecret"]!; }); ``` -------------------------------- ### Consumer check pattern for AuthResponse Source: https://github.com/arahimx/nafath.net Shows how to check for errors after calling StartSessionAsync. If Error is empty, the RedirectUrl is available. ```csharp var result = await nafath.StartSessionAsync(idNumber, requestId); if (string.IsNullOrEmpty(result.Error)) { Console.WriteLine(result.RedirectUrl); } ``` -------------------------------- ### NafathOptions class definition Source: https://github.com/arahimx/nafath.net Defines the configuration options for the Nafath.Net SDK. BaseUrl defaults to "https://auth.nafath.sa"; ClientId and ClientSecret are required per README but not referenced in the current source. ```csharp namespace Nafath.Net; public class NafathOptions { public string BaseUrl { get; set; } = "https://auth.nafath.sa"; public string ClientId { get; set; } public string ClientSecret { get; set; } } ``` -------------------------------- ### appsettings.json binding for Nafath options Source: https://github.com/arahimx/nafath.net JSON configuration file that can be bound to NafathOptions via the options system when using AddNafath. ```json { "Nafath": { "BaseUrl": "https://auth.nafath.sa", "ClientId": "…", "ClientSecret": "…" } } ``` -------------------------------- ### Consumer check pattern for VerificationResponse Source: https://github.com/arahimx/nafath.net Shows how to check verification success and print status and message. ```csharp var verification = await nafath.VerifyStatusAsync(transactionId); if (verification.Success) { Console.WriteLine($"Status: {verification.Status} — {verification.Message}"); } ``` -------------------------------- ### VerifyStatusAsync Source: https://github.com/arahimx/nafath.net Checks the verification status of a transaction initiated by StartSessionAsync. It builds a request to the /api/v1/auth/verify endpoint, logs the URL and response, ensures success, and deserializes the response into a VerificationResponse object. On failure, it returns a VerificationResponse with appropriate error status and message. ```APIDOC ## VerifyStatusAsync ### Description Checks the verification status of a transaction initiated by StartSessionAsync. It builds a request to the /api/v1/auth/verify endpoint, logs the URL and response, ensures success, and deserializes the response into a VerificationResponse object. On failure, it returns a VerificationResponse with appropriate error status and message. ### Method GET ### Endpoint `/api/v1/auth/verify?transactionId={transactionId}` ### Parameters #### Query Parameters - **transactionId** (string) - Required - Transaction ID from a prior `StartSessionAsync` call. ### Response #### Success Response (200) - **Success** (bool) - Indicates whether the request was successful. - **Status** (string) - Status of the verification (e.g., "error", "timeout"). - **Message** (string) - Description of the result or error. #### Error Responses - **HttpRequestException** - Returns `Success=false`, `Status="error"`, `Message="HTTP request failed."` - **TaskCanceledException** - Returns `Success=false`, `Status="timeout"`, `Message="Request timed out."` - **any other Exception** - Returns `Success=false`, `Status="error"`, `Message="An unexpected error occurred."` ### Request Example ```csharp var verification = await service.VerifyStatusAsync(result.TransactionId); ``` ### Response Example ```csharp if (verification.Success) { Console.WriteLine($"User accepted: {verification.Status} — {verification.Message}"); } else { Console.WriteLine($"Not yet verified ({verification.Status}): {verification.Message}"); } ``` ``` -------------------------------- ### Handle StartSessionAsync errors by inspecting AuthResponse.Error Source: https://github.com/arahimx/nafath.net Because the SDK returns errors instead of throwing, check `AuthResponse.Error` after calling `StartSessionAsync`. The error string is one of "HTTP request failed. Please try again later.", "Request timed out.", or "An unexpected error occurred.". A try/catch is only defensive for unexpected conditions like `ObjectDisposedException`. ```csharp try { var result = await nafath.StartSessionAsync(idNumber, requestId); if (!string.IsNullOrEmpty(result.Error)) { Console.WriteLine($"Start failed: {result.Error}"); // result.Error: "HTTP request failed. Please try again later." // | "Request timed out." // | "An unexpected error occurred." return; } } catch (Exception ex) // defensive; the SDK path above typically absorbs everything { Console.WriteLine($"Unexpected: {ex}"); } ``` -------------------------------- ### VerifyStatusAsync method signature Source: https://github.com/arahimx/nafath.net Public method signature for verifying the status of a Nafath transaction. Takes a transactionId from a prior StartSessionAsync call and returns a Task. ```csharp public async Task VerifyStatusAsync(string transactionId) ``` -------------------------------- ### NafathService class definition Source: https://github.com/arahimx/nafath.net Default implementation of INafathService that performs HTTP calls to the Nafath API, logs payloads and responses, and converts failures into error-populated response models. Constructor injects HttpClient, IOptions, and ILogger. ```csharp namespace Nafath.Net.Services; public class NafathService : INafathService { private readonly HttpClient _httpClient; private readonly NafathOptions _options; private readonly ILogger _logger; public NafathService(HttpClient httpClient, IOptions options, ILogger logger) { _httpClient = httpClient; _options = options.Value; _logger = logger; } public async Task StartSessionAsync(string idNumber, string requestId) { ... } public async Task VerifyStatusAsync(string transactionId) { ... } } ``` -------------------------------- ### Handle VerifyStatusAsync errors by inspecting VerificationResponse.Success Source: https://github.com/arahimx/nafath.net Check `VerificationResponse.Success` after calling `VerifyStatusAsync`. When false, `Status` is either "error" or "timeout" (SDK-generated) and `Message` contains the error detail. No try/catch is needed for expected failures. ```csharp var verification = await nafath.VerifyStatusAsync(transactionId); if (!verification.Success) { // verification.Status: "error" | "timeout" (SDK-generated) Console.WriteLine($"Verify failed: {verification.Status} — {verification.Message}"); } ``` -------------------------------- ### POST /api/v1/auth/initiate Source: https://github.com/arahimx/nafath.net Initiates a Nafath authentication session. This endpoint is called by the SDK's StartSessionAsync method and requires an idNumber and requestId in the request body. ```APIDOC ## POST /api/v1/auth/initiate ### Description Initiates a Nafath authentication session. ### Method POST ### Endpoint `{BaseUrl}/api/v1/auth/initiate` ### Parameters #### Request Body - **idNumber** (string) - Required - Saudi national ID / Iqama number. - **requestId** (string) - Required - Caller-supplied request identifier. ### Response #### Success Response (200) - **TransactionId** (string) - Session identifier used for the verify call. - **RedirectUrl** (string) - URL to send the user to. - **Error** (string) - Absent/null on success; the SDK sets this on failure. ### Request Example ```json { "idNumber": "1012345678", "requestId": "order-42" } ``` ``` -------------------------------- ### AddNafath extension method implementation Source: https://github.com/arahimx/nafath.net Static extension method that registers Nafath services in an IServiceCollection. It calls services.Configure(configure) and services.AddHttpClient(). Returns the same IServiceCollection for fluent chaining. ```csharp namespace Nafath.Net.Extensions; public static class ServiceCollectionExtensions { public static IServiceCollection AddNafath(this IServiceCollection services, Action configure) { services.Configure(configure); services.AddHttpClient(); return services; } } ``` -------------------------------- ### Manual serialization of AuthRequest to wire shape Source: https://github.com/arahimx/nafath.net Shows how to serialize AuthRequest to the expected wire payload. Note that default serialization produces PascalCase property names, not the camelCase wire format. ```csharp using System.Text.Json; using Nafath.Net.Models; var request = new AuthRequest { IdNumber = "1012345678", RequestId = "req-1" }; var json = JsonSerializer.Serialize(request); // => {"IdNumber":"1012345678","RequestId":"req-1"} ``` -------------------------------- ### AddNafath method signature Source: https://github.com/arahimx/nafath.net The method signature for AddNafath, showing the extension receiver and configuration callback parameters. ```csharp public static IServiceCollection AddNafath(this IServiceCollection services, Action configure) ``` -------------------------------- ### AuthResponse Source: https://github.com/arahimx/nafath.net Response model returned by StartSessionAsync. Contains transaction ID, redirect URL, and an error field populated on failure. Consumers should check the Error property to determine success. ```APIDOC ## AuthResponse ### Description Response model returned by StartSessionAsync. Contains transaction ID, redirect URL, and an error field populated on failure. Consumers should check the Error property to determine success. ### Properties - **TransactionId** (string) - Optional - Transaction identifier used to poll the session via VerifyStatusAsync. Set from the Nafath API response body when the call succeeds. - **RedirectUrl** (string) - Optional - URL to which the user should be redirected to complete authentication in the Nafath app/browser. - **Error** (string) - Optional - Populated by the SDK on failure ("HTTP request failed. Please try again later.", "Request timed out.", or "An unexpected error occurred."); null on a successful deserialization. ### Response Example ```csharp var result = await nafath.StartSessionAsync(idNumber, requestId); if (string.IsNullOrEmpty(result.Error)) { Console.WriteLine(result.RedirectUrl); } ``` ``` -------------------------------- ### AuthRequest class definition Source: https://github.com/arahimx/nafath.net POCO model for authentication request. Not consumed by the current implementation; NafathService.StartSessionAsync builds its payload from an anonymous object with the same member names. ```csharp namespace Nafath.Net.Models; public class AuthRequest { public string IdNumber { get; set; } public string RequestId { get; set; } } ``` -------------------------------- ### VerificationResponse Source: https://github.com/arahimx/nafath.net Response model returned by VerifyStatusAsync. Contains success flag, status, and message. Consumers should check the Success property to determine verification outcome. ```APIDOC ## VerificationResponse ### Description Response model returned by VerifyStatusAsync. Contains success flag, status, and message. Consumers should check the Success property to determine verification outcome. ### Properties - **Success** (bool) - Optional - Whether the verification/authentication succeeded. On SDK-side failures the SDK forces this to false. - **Status** (string) - Optional - Status reported by the Nafath API (semantics defined by the API; SDAIA statuses such as success/rejected/pending are expected). On SDK-side failures the SDK substitutes "error" or "timeout". - **Message** (string) - Optional - Human-readable detail from the API or SDK error text. ### Response Example ```csharp var verification = await nafath.VerifyStatusAsync(transactionId); if (verification.Success) { Console.WriteLine($"Status: {verification.Status} — {verification.Message}"); } ``` ``` -------------------------------- ### AuthResponse class definition Source: https://github.com/arahimx/nafath.net POCO model for authentication response. Returned by StartSessionAsync. Error property is populated by the SDK on failure with specific messages. ```csharp namespace Nafath.Net.Models; public class AuthResponse { public string TransactionId { get; set; } public string RedirectUrl { get; set; } public string Error { get; set; } } ``` -------------------------------- ### VerificationResponse class definition Source: https://github.com/arahimx/nafath.net POCO model for verification status. Returned by VerifyStatusAsync. Success is forced to false on SDK-side failures; Status may be substituted with "error" or "timeout". ```csharp namespace Nafath.Net.Models; public class VerificationResponse { public bool Success { get; set; } public string Status { get; set; } public string Message { get; set; } } ``` -------------------------------- ### AddNafath Source: https://github.com/arahimx/nafath.net Registers the Nafath SDK services into the dependency injection container. This method configures options and adds a typed HttpClient for INafathService. ```APIDOC ## AddNafath ### Description Registers the Nafath SDK services into the dependency injection container. This method configures options and adds a typed HttpClient for INafathService. ### Method AddNafath ### Signature public static IServiceCollection AddNafath(this IServiceCollection services, Action configure) ### Parameters - **services** (IServiceCollection) - Required - The container being configured. - **configure** (Action) - Required - Callback invoked to populate a NafathOptions instance. ### Returns IServiceCollection - The same instance, enabling fluent chaining. ### Registrations 1. services.Configure(configure) - Registers the NafathOptions configuration delegate. 2. services.AddHttpClient() - Registers INafathService as a typed HttpClient client. ### Usage Example ```csharp using Nafath.Net.Extensions; var builder = WebApplication.CreateBuilder(args); builder.Services.AddNafath(options => { options.BaseUrl = "https://auth.nafath.sa"; options.ClientId = builder.Configuration["Nafath:ClientId"]; options.ClientSecret = builder.Configuration["Nafath:ClientSecret"]; }); var app = builder.Build(); app.MapPost("/nafath/start", async (INafathService nafath, string idNumber, string requestId) => { var result = await nafath.StartSessionAsync(idNumber, requestId); return Results.Ok(result); }); app.MapGet("/nafath/verify/{transactionId}", async (INafathService nafath, string transactionId) => { var result = await nafath.VerifyStatusAsync(transactionId); return Results.Ok(result); }); app.Run(); ``` ``` -------------------------------- ### POST /api/v1/auth/initiate request body Source: https://github.com/arahimx/nafath.net JSON body for initiating a Nafath authentication session. Required fields: idNumber (Saudi national ID/Iqama) and requestId (caller-supplied identifier). ```json { "idNumber": "1012345678", "requestId": "order-42" } ``` -------------------------------- ### AuthRequest Source: https://github.com/arahimx/nafath.net Strongly typed request model for the Nafath API. Contains the user's national ID and a caller-supplied request correlation identifier. Note: The current implementation does not use this class directly but builds an anonymous object with the same member names. ```APIDOC ## AuthRequest ### Description Strongly typed request model for the Nafath API. Contains the user's national ID and a caller-supplied request correlation identifier. Note: The current implementation does not use this class directly but builds an anonymous object with the same member names. ### Properties - **IdNumber** (string) - Required - Saudi national ID / Iqama number of the user being authenticated. - **RequestId** (string) - Required - Caller-supplied request correlation identifier. ### Request Example ```csharp using System.Text.Json; using Nafath.Net.Models; var request = new AuthRequest { IdNumber = "1012345678", RequestId = "req-1" }; var json = JsonSerializer.Serialize(request); // => {"IdNumber":"1012345678","RequestId":"req-1"} ``` ```