Hyperswitch.Authentication.Client 1.0.5

dotnet add package Hyperswitch.Authentication.Client --version 1.0.5
                    
NuGet\Install-Package Hyperswitch.Authentication.Client -Version 1.0.5
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Hyperswitch.Authentication.Client" Version="1.0.5" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Hyperswitch.Authentication.Client" Version="1.0.5" />
                    
Directory.Packages.props
<PackageReference Include="Hyperswitch.Authentication.Client" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Hyperswitch.Authentication.Client --version 1.0.5
                    
#r "nuget: Hyperswitch.Authentication.Client, 1.0.5"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Hyperswitch.Authentication.Client@1.0.5
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Hyperswitch.Authentication.Client&version=1.0.5
                    
Install as a Cake Addin
#tool nuget:?package=Hyperswitch.Authentication.Client&version=1.0.5
                    
Install as a Cake Tool

Hyperswitch Authentication .NET SDK

Welcome to the Hyperswitch Authentication .NET SDK! This SDK provides a convenient way to interact with the Hyperswitch Authentication API, enabling you to seamlessly integrate authentication flows into your .NET applications.

Table of Contents

Overview

The Hyperswitch Authentication .NET SDK simplifies the process of:

  • Initiating authentication sessions.
  • Handling external authentication steps (like 3D Secure).
  • Retrieving the status and details of authentications.

It's designed to be intuitive and to abstract away the complexities of direct API calls.

Prerequisites

  • .NET 8.0 SDK or later.

Installation

This SDK will be available via NuGet. To install it, use the .NET CLI:

dotnet add package Hyperswitch.Authentication.Client --version 1.0.5

Or, via the NuGet Package Manager console in Visual Studio:

PM> Install-Package Hyperswitch.Authentication.Client -Version 1.0.5

Sample Application

This SDK includes a comprehensive console sample application that demonstrates core authentication flows and SDK usage. The sample app is located in the samples/AuthenticationSample.Console/ directory.

Running the Sample App

  1. Navigate to the sample directory:

    cd samples/AuthenticationSample.Console/
    
  2. Configure API Keys and URLs: Open samples/AuthenticationSample.Console/appsettings.json and update the API keys and any other relevant settings for your test environments. The structure is as follows:

    {
      "AppSettings": {
        "DefaultEnvironment": "Local", // Can be Local, Staging, Production
        "ApiKeys": {
          "Local": "your_local_api_key_here",
          "Staging": "your_staging_api_key_here",
          "Production": "your_production_api_key_here"
        },
        "BaseUrls": {
          "Local": "http://localhost:8080", // Your local auth server
          "Staging": "https://auth.app.hyperswitch.io/api",
          "Production": "https://api.hyperswitch.io/api" // Note: Ensure this is the correct prod auth URL
        },
        "DefaultReturnUrl": "https://your-app.com/auth-return", // Replace with your actual return URL
        "AcquirerDetails": { // Optional: if you need to test with specific acquirer details
          "AcquirerBin": "518422",
          "AcquirerMerchantId": "merchant_001",
          "AcquirerCountryCode": "840" // Example: US
        }
      }
    }
    

    Replace "your_..._api_key_here" and other placeholder values with your actual credentials and settings.

  3. Run the application:

    dotnet run
    

    The application will present an interactive menu to select environments, authentication providers, and test card scenarios.

What the Sample Demonstrates

  • Environment Selection: Easily switch between Local, Staging, and Production configurations.
  • Provider Selection: Test authentication flows with different providers like Threedsecureio and Juspaythreedsserver.
  • Complete 3DS Flows:
    • Initiating authentication.
    • Handling NextAction for redirection or 3DS method invocation.
    • Simulating browser interaction for PerformAuthentication (AReq).
    • Retrieving final authentication status.
  • Test Card Scenarios: Utilizes pre-configured test cards from TestCardData.cs for various outcomes (frictionless, challenge, exemptions).
  • Request Building: Shows how to construct AuthenticationCreateRequest and ExternalAuthenticationRequest with necessary details including billing, card data, and browser information.
  • Response Handling: Demonstrates parsing of AuthenticationCreateResponseOpenApi, ExternalAuthenticationResponse, and AuthenticationResponse.
  • Error Handling: Includes try-catch blocks for ApiException to manage API errors gracefully.
  • Logging: Uses a simple ResponseLogger to output request/response details to the console for easy debugging.

Quick Start with Sample App

The fastest way to understand and test the SDK is by running the sample application:

  1. Clone the repository (if you haven't already) or ensure you have the samples directory.
  2. Navigate to samples/AuthenticationSample.Console/.
  3. Configure your API keys and settings in appsettings.json as described above.
  4. Run the sample:
    dotnet run
    
  5. Follow the interactive prompts to select an environment, provider, and test scenario. Observe the console output to see the API interactions and responses.

This hands-on approach will provide valuable insight into the SDK's capabilities and integration patterns before incorporating it into your own application. For more detailed documentation on the sample app's structure and code, please refer to samples/README.md.

Configuration

AuthenticationClientConfiguration

Before making any API calls, you need to configure the SDK. The AuthenticationClientConfiguration class is used for this. You can use its builder pattern for easy setup.

using Authentication.Client;

// Minimum configuration with API Key (uses default production URL)
var configBuilder = AuthenticationClientConfiguration.CreateBuilder()
    .WithApiKey("your_api_key_here");

// For specific environments (like sandbox or local)
// var configBuilder = AuthenticationClientConfiguration.CreateBuilder()
//    .WithApiKey("your_api_key")
//    .WithBaseUrl("https://auth.app.hyperswitch.io/api"); 

// Or using the Environment enum (Production and Staging/Sandbox point to the same URL)
// var configBuilder = AuthenticationClientConfiguration.CreateBuilder()
//    .WithApiKey("your_api_key")
//    .ForEnvironment(Authentication.Client.Environment.Production); // Or .Sandbox / .Staging

AuthenticationClientConfiguration authConfig = configBuilder.Build();

Configuration Options:

  • WithApiKey(string apiKey): (Required) Your secret API key for authenticating requests.
  • WithBaseUrl(string baseUrl): (Optional) The base URL of the Hyperswitch API. Defaults to https://auth.app.hyperswitch.io/api.
    • If you use ForEnvironment(Environment.Production) or ForEnvironment(Environment.Staging), it will also use https://auth.app.hyperswitch.io/api.
    • ForEnvironment(Environment.Local) will use http://localhost:8080.
  • You can also pass a custom HttpClient instance to the AuthenticationClient constructor if you need more control over HTTP requests (e.g., custom headers, proxy, timeout policies).

AuthenticationClient

Once you have an AuthenticationClientConfiguration object, create an instance of AuthenticationClient:

var authClient = new AuthenticationClient(authConfig);

This authClient instance will be used to perform all API operations.

Core Operations

The SDK provides three main asynchronous operations:

1. Create Authentication

This operation initiates an authentication session. It corresponds to the POST /api/authenticate endpoint.

Example: Creating an authentication for a card payment:

using Authentication.Client.Model;
using System.Threading.Tasks;

// ... (authClient initialized as above)

var createRequest = new AuthenticationCreateRequest(
    amount: 14190, // Amount in cents (e.g., $141.90)
    currency: Currency.USD,
    returnUrl: "https://your-app.com/auth-return", // URL to redirect user after authentication
    paymentMethod: PaymentMethod.Card,
    paymentMethodData: new PaymentMethodDataRequest(
        paymentMethodData: new PaymentMethodData( // This is the wrapper for the actual card data
            card: new Card( // This is Card.cs, not Card1.cs
                cardNumber: "424242424242424242", // Use test card numbers for non-production
                cardExpMonth: "03",
                cardExpYear: "2030",
                cardHolderName: "John Smith",
                cardCvc: "737"
            )
        )
    ),
    billing: new Address(
        address: new AddressDetails(
            line1: "1467 Main St",
            city: "San Francisco",
            state: "CA",
            zip: "94122",
            country: CountryAlpha2.US,
            firstName: "John",
            lastName: "Doe"
        ),
        phone: new PhoneDetails(
            number: "8056594427",
            countryCode: "+1"
        )
    ),
    // Optional: Specify authentication provider if needed
    // authenticationProvider: AuthenticationProvider.Threedsecureio,
    // Optional: Specify acquirer details if needed
    // acquirerDetails: new AcquirerDetails(
    //    acquirerBin: "123456",
    //    acquirerMerchantId: "merchantId123"
    // ),
);

try
{
    AuthenticationCreateResponseOpenApi createResponse = await authClient.CreateAuthenticationAsync(createRequest);
    
    Console.WriteLine($"Authentication ID: {createResponse.AuthenticationId}");
    Console.WriteLine($"Client Secret: {createResponse.ClientSecret}"); // Important for client-side operations
    Console.WriteLine($"Status: {createResponse.Status}");

    if (createResponse.NextAction?.ActualInstance is NextActionDataOneOf redirectToUrlAction && 
        redirectToUrlAction.Type == NextActionDataOneOf.TypeEnum.RedirectToUrl)
    {
        Console.WriteLine($"Redirect URL: {redirectToUrlAction.RedirectToUrl}");
        // Redirect the user to this URL in a browser for 3DS or other challenges
    }
    else if (createResponse.NextAction?.ActualInstance is NextActionDataOneOf7 threeDsInvokeAction &&
             threeDsInvokeAction.Type == NextActionDataOneOf7.TypeEnum.ThreeDsInvoke)
    {
        Console.WriteLine("3DS Method Invocation Required.");
        // Handle 3DS Method URL: threeDsInvokeAction.ThreeDsData.ThreeDsMethodDetails.ThreeDsMethodUrl
        // This usually involves an iframe or hidden form submission in the browser.
    }
    // ... handle other next actions or statuses
}
catch (Authentication.Client.Client.ApiException e)
{
    Console.WriteLine($"API Error creating authentication: {e.Message}");
    Console.WriteLine($"Status Code: {e.ErrorCode}");
    Console.WriteLine($"Response Body: {e.ErrorContent}");
}
catch (Exception ex)
{
    Console.WriteLine($"Unexpected error: {ex.Message}");
}

The AuthenticationCreateResponseOpenApi object contains the AuthenticationId, ClientSecret, current Status, and potentially a NextAction if further user interaction is required.

2. Perform Authentication (External 3DS)

After the user is redirected for an external authentication step (like 3D Secure) and returns to your application, or if you need to provide additional browser/device information (often after a 3DS Method URL execution), you use this operation. It corresponds to POST /api/authenticate/{payment_id}/areq.

Note: The payment_id in the URL path remains payment_id as per API contract, but the C# variable is authenticationId.

using Authentication.Client.Model;
using System.Threading.Tasks;

// ... (authClient initialized)
// Assume authenticationId was obtained from the CreateAuthentication step
string authenticationIdFromCreate = createResponse.AuthenticationId; // From previous step

var performRequest = new ExternalAuthenticationRequest(
    deviceChannel: DeviceChannel.BRW, // Browser
    threedsMethodCompInd: ThreeDsCompletionIndicator.U, // Or Y/N based on 3DS method completion
    browserInfo: new BrowserInformation(
        userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        acceptHeader: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        language: "en-US",
        colorDepth: 24,
        screenHeight: 1080,
        screenWidth: 1920,
        varTimeZone: -330, // Timezone offset in minutes (e.g., -330 for IST)
        javaEnabled: true,
        javaScriptEnabled: true,
        ipAddress: "127.0.0.1"
        // Optionally provide deviceModel, osType, osVersion
    )
    // Add other relevant SdkInformation, billing, shipping if needed
);

try
{
    ExternalAuthenticationResponse performResponse = await authClient.PerformAuthenticationAsync(authenticationIdFromCreate, performRequest);
    
    Console.WriteLine($"Perform Authentication Status (Transaction Status): {performResponse.TransStatus}");

    // The 'performResponse' might also contain a 'NextAction' if further steps are needed,
    // though typically after AReq, the next step is to retrieve the final status.
    // Example: performResponse.AcsUrl, performResponse.ChallengeRequest for challenge flows.
}
catch (Authentication.Client.Client.ApiException e)
{
    Console.WriteLine($"API Error performing authentication: {e.Message}");
    // Handle error, potentially retry or inform user
}

3. Retrieve Authentication

To get the latest status and details of an authentication session. This is often called after the "Perform Authentication" step or if you want to check the status of an ongoing authentication. It corresponds to GET /api/authenticate/{payment_id}.

using System.Threading.Tasks;

// ... (authClient initialized)
// Assume authenticationId was obtained from the CreateAuthentication step
string authenticationIdToRetrieve = createResponse.AuthenticationId; 

try
{
    // Note: clientSecret is NOT passed to RetrieveAuthenticationAsync as per current SDK design
    AuthenticationResponse retrieveResponse = await authClient.RetrieveAuthenticationAsync(authenticationIdToRetrieve);
    
    Console.WriteLine($"Retrieve Authentication Status: {retrieveResponse.Status}");
    Console.WriteLine($"Amount: {retrieveResponse.Amount} {retrieveResponse.Currency}");
    // Process other details from retrieveResponse
}
catch (Authentication.Client.Client.ApiException e)
{
    Console.WriteLine($"API Error retrieving authentication: {e.Message}");
}

Key Models

Here are some of the important models you'll work with:

Request Models

  • AuthenticationCreateRequest: Used to provide all necessary details for creating an authentication session (amount, currency, payment method, billing, shipping, etc.).
  • ExternalAuthenticationRequest: Used to provide device and browser information for external authentication steps (like 3DS AReq).
  • PaymentMethodDataRequest and PaymentMethodData: Wrappers for payment method specific details (e.g., Card details).
  • Address and AddressDetails: For billing and shipping addresses.
  • BrowserInformation: Detailed browser and device information.

Response Models

  • AuthenticationCreateResponseOpenApi: Response from the "Create Authentication" operation. Contains AuthenticationId, ClientSecret, Status, and NextAction.
  • ExternalAuthenticationResponse: Response from the "Perform Authentication" operation. Contains TransStatus (transaction status from 3DS), and potentially ACS details for challenge flows.
  • AuthenticationResponse: Comprehensive response from the "Retrieve Authentication" operation, providing the full state of the authentication.
  • NextActionData: A discriminated union representing various next actions (e.g., RedirectToUrl, ThreeDsInvoke). Access the specific action via ActualInstance.

Common Models

  • Currency: Enum for currency codes.
  • CountryAlpha2: Enum for ISO 3166-1 alpha-2 country codes.
  • IntentStatus: Enum representing the status of the authentication intent (e.g., Succeeded, Failed, RequiresCustomerAction).
  • TransactionStatus: Enum representing the transaction status from 3DS (e.g., Y for Authenticated, N for Not Authenticated).

Refer to the Authentication.Client.Model namespace for all available models and their properties. XML documentation comments are provided for most properties.

Error Handling

API errors are thrown as Authentication.Client.Client.ApiException. This exception contains:

  • ErrorCode: The HTTP status code of the error.
  • Message: A general error message.
  • ErrorContent: The raw JSON error response body from the API, which often contains more specific error codes and messages.

Always wrap your API calls in a try-catch block to handle potential ApiExceptions.

try
{
    // ... API call ...
}
catch (Authentication.Client.Client.ApiException apiEx)
{
    Console.WriteLine($"API Error: {apiEx.Message}");
    Console.WriteLine($"Status Code: {apiEx.ErrorCode}");
    // Deserialize apiEx.ErrorContent for detailed error info if needed
    // Example: var errorDetails = Newtonsoft.Json.JsonConvert.DeserializeObject<YourErrorModel>(apiEx.ErrorContent);
    Console.WriteLine($"Details: {apiEx.ErrorContent}");
}
catch (Exception ex) // Catch other unexpected exceptions
{
    Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.5 379 6/10/2025
1.0.4 354 6/10/2025
1.0.3 355 6/9/2025
1.0.2 340 6/9/2025
1.0.1 343 6/9/2025
1.0.0 341 6/9/2025

Initial release with Create, Perform, and Retrieve authentication methods.