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
<PackageReference Include="Hyperswitch.Authentication.Client" Version="1.0.5" />
<PackageVersion Include="Hyperswitch.Authentication.Client" Version="1.0.5" />
<PackageReference Include="Hyperswitch.Authentication.Client" />
paket add Hyperswitch.Authentication.Client --version 1.0.5
#r "nuget: Hyperswitch.Authentication.Client, 1.0.5"
#:package Hyperswitch.Authentication.Client@1.0.5
#addin nuget:?package=Hyperswitch.Authentication.Client&version=1.0.5
#tool nuget:?package=Hyperswitch.Authentication.Client&version=1.0.5
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
- Prerequisites
- Installation
- Configuration
- Core Operations
- Key Models
- Error Handling
- Sample Application
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
Navigate to the sample directory:
cd samples/AuthenticationSample.Console/Configure API Keys and URLs: Open
samples/AuthenticationSample.Console/appsettings.jsonand 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.Run the application:
dotnet runThe 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
NextActionfor 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.csfor various outcomes (frictionless, challenge, exemptions). - Request Building: Shows how to construct
AuthenticationCreateRequestandExternalAuthenticationRequestwith necessary details including billing, card data, and browser information. - Response Handling: Demonstrates parsing of
AuthenticationCreateResponseOpenApi,ExternalAuthenticationResponse, andAuthenticationResponse. - Error Handling: Includes try-catch blocks for
ApiExceptionto manage API errors gracefully. - Logging: Uses a simple
ResponseLoggerto 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:
- Clone the repository (if you haven't already) or ensure you have the
samplesdirectory. - Navigate to
samples/AuthenticationSample.Console/. - Configure your API keys and settings in
appsettings.jsonas described above. - Run the sample:
dotnet run - 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 tohttps://auth.app.hyperswitch.io/api.- If you use
ForEnvironment(Environment.Production)orForEnvironment(Environment.Staging), it will also usehttps://auth.app.hyperswitch.io/api. ForEnvironment(Environment.Local)will usehttp://localhost:8080.
- If you use
- You can also pass a custom
HttpClientinstance to theAuthenticationClientconstructor 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).PaymentMethodDataRequestandPaymentMethodData: Wrappers for payment method specific details (e.g.,Carddetails).AddressandAddressDetails: For billing and shipping addresses.BrowserInformation: Detailed browser and device information.
Response Models
AuthenticationCreateResponseOpenApi: Response from the "Create Authentication" operation. ContainsAuthenticationId,ClientSecret,Status, andNextAction.ExternalAuthenticationResponse: Response from the "Perform Authentication" operation. ContainsTransStatus(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 viaActualInstance.
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.,Yfor Authenticated,Nfor 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 | Versions 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. |
-
net8.0
- JsonSubTypes (>= 2.0.1)
- Newtonsoft.Json (>= 13.0.3)
- Polly (>= 8.1.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Initial release with Create, Perform, and Retrieve authentication methods.