https://github.com/truelayer/truelayer-dotnet
The official TrueLayer .NET library provides convenient access to TrueLayer APIs from applications built with .NET.
https://github.com/truelayer/truelayer-dotnet
do-not-auto-tag library payments sdk-dotnet
Last synced: 7 months ago
JSON representation
The official TrueLayer .NET library provides convenient access to TrueLayer APIs from applications built with .NET.
- Host: GitHub
- URL: https://github.com/truelayer/truelayer-dotnet
- Owner: TrueLayer
- License: mit
- Created: 2021-04-23T14:20:34.000Z (about 5 years ago)
- Default Branch: main
- Last Pushed: 2024-04-09T15:48:50.000Z (about 2 years ago)
- Last Synced: 2024-04-26T11:02:19.758Z (about 2 years ago)
- Topics: do-not-auto-tag, library, payments, sdk-dotnet
- Language: C#
- Homepage: https://docs.truelayer.com
- Size: 2.98 MB
- Stars: 8
- Watchers: 21
- Forks: 9
- Open Issues: 16
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
- Codeowners: .github/CODEOWNERS
- Security: SECURITY.md
Awesome Lists containing this project
README
# TrueLayer.NET
[](https://www.nuget.org/packages/TrueLayer.Client)
[](https://www.nuget.org/packages/TrueLayer.Client)
[](https://truelayer.mit-license.org/)

[](https://sonarcloud.io/summary/overall?id=TrueLayer_truelayer-dotnet)
[](https://sonarcloud.io/summary/overall?id=TrueLayer_truelayer-dotnet)
The official [TrueLayer](https://truelayer.com) .NET client provides convenient access to TrueLayer APIs from applications built with .NET.
The library currently supports .NET 9.0 and .NET 8.0.
## Installation
Using the [.NET Core command-line interface (CLI) tools](https://docs.microsoft.com/en-us/dotnet/core/tools/):
```sh
dotnet add package TrueLayer.Client
```
Using the [NuGet Command Line Interface (CLI)](https://docs.microsoft.com/en-us/nuget/tools/nuget-exe-cli-reference)
```sh
nuget install TrueLayer.Client
```
Using the [Package Manager Console](https://docs.microsoft.com/en-us/nuget/tools/package-manager-console):
```powershell
Install-Package TrueLayer.Client
```
From within Visual Studio:
1. Open the Solution Explorer.
2. Right-click on a project within your solution.
3. Click on *Manage NuGet Packages...*
4. Click on the *Browse* tab and search for "TrueLayer.Client".
5. Click on the `TrueLayer.Client` package, select the appropriate version in the
right-tab and click *Install*.
### Pre-release Packages
Pre-release packages can be downloaded from [GitHub Packages](https://github.com/truelayer?tab=packages&repo_name=truelayer-dotnet).
```
dotnet add package TrueLayer.Client --prerelease --source https://nuget.pkg.github.com/TrueLayer/index.json
```
[More information](https://docs.github.com/en/packages/guides/configuring-dotnet-cli-for-use-with-github-packages) on using GitHub packages with .NET.
## Documentation
For a comprehensive list of examples, check out the [API documentation](https://docs.truelayer.com).
## Usage
### Prerequisites
First [sign up](https://console.truelayer.com/) for a developer account. Follow the instructions to set up a new application and obtain your Client ID and Secret. Once the application has been created you must add your application redirected URIs in order to test your integration end-to-end.
Next, generate a signing key pair used to sign API requests.
To generate a private key, run:
```sh
docker run --rm -v ${PWD}:/out -w /out -it alpine/openssl ecparam -genkey -name secp521r1 -noout -out ec512-private-key.pem
```
To obtain the public key, run:
```sh
docker run --rm -v ${PWD}:/out -w /out -it alpine/openssl ec -in ec512-private-key.pem -pubout -out ec512-public-key.pem
```
Navigate to the Payments settings section of the TrueLayer console and upload your public key. Obtain the Key Id.
### Configure Settings
Add your Client ID, Secret and Signing Key ID to `appsettings.json` or any other supported [configuration provider](https://docs.microsoft.com/en-us/dotnet/core/extensions/configuration).
```json
{
"TrueLayer": {
"ClientId": "your id",
"ClientSecret": "your secret",
"UseSandbox": true,
"Payments": {
"SigningKey": {
"KeyId": "85eeb2da-702c-4f4b-bf9a-e98af5fd47c3"
}
}
}
}
```
### Initialize TrueLayer.NET
Register the TrueLayer client in `Startup.cs` or `Program.cs` (.NET 9.0/.NET 8.0):
```c#
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddTrueLayer(configuration, options =>
{
if (options.Payments?.SigningKey != null)
{
// For demo purposes only. Private key should be stored securely
options.Payments.SigningKey.PrivateKey = File.ReadAllText("ec512-private-key.pem");
}
},
// For best performance and reliability we advise to cache the auth token
authCachingStrategy: AuthCachingStrategy.InMemory)
}
```
### Multiple TrueLayer Clients
Use keyed version of TrueLayer client (.NET 9.0/.NET 8.0):
```c#
.AddKeyedTrueLayer("TrueLayerGbp",
configuration,
options =>
{
// For demo purposes only. Private key should be stored securely
var privateKey = File.ReadAllText("ec512-private-key.pem");
if (options.Payments?.SigningKey != null)
{
options.Payments.SigningKey.PrivateKey = privateKey;
}
},
authTokenCachingStrategy: AuthTokenCachingStrategies.InMemory)
.AddKeyedTrueLayer("TrueLayerEur",
configuration,
options =>
{
// For demo purposes only. Private key should be stored securely
var privateKey = File.ReadAllText("ec512-private-key.pem");
if (options.Payments?.SigningKey != null)
{
options.Payments.SigningKey.PrivateKey = privateKey;
}
},
authTokenCachingStrategy: AuthTokenCachingStrategies.InMemory)
```
Use `[FromKeyedServices()]` attribute to retrieve keyed client
```c#
public GbpController([FromKeyedServices("TrueLayerGbp")]ITrueLayerClient trueLayerClient, ...
public EurController([FromKeyedServices("TrueLayerEur")]ITrueLayerClient trueLayerClient, ...
```
Or `GetRequiredKeyedService`
```c#
var GbpClient = ServiceProvider.GetRequiredKeyedService("TrueLayerGbp");
var EurClient = ServiceProvider.GetRequiredKeyedService("TrueLayerEur");
```
### Make a payment
Inject `ITrueLayerClient` into your classes:
```c#
public class MyService
{
private readonly ITrueLayerClient _client;
public MyService(ITrueLayerClient client)
{
_client = client;
}
public async Task MakePayment()
{
var paymentRequest = new CreatePaymentRequest(
amountInMinor: amount.ToMinorCurrencyUnit(2),
currency: Currencies.GBP,
paymentMethod: new CreatePaymentMethod.BankTransfer(
new CreateProviderSelection.UserSelected
{
Filter = new ProviderFilter
{
ProviderIds = new[] { "mock-payments-gb-redirect" }
}
},
new Beneficiary.ExternalAccount(
"TrueLayer",
"truelayer-dotnet",
new AccountIdentifier.SortCodeAccountNumber("567890", "12345678")
)
),
user: new PaymentUserRequest("Jane Doe", "jane.doe@example.com", "0123456789")
);
var apiResponse = await _client.Payments.CreatePayment(
paymentRequest,
idempotencyKey: Guid.NewGuid().ToString()
);
if (!apiResponse.IsSuccessful)
{
return HandleFailure(
apiResponse.StatusCode,
// Includes details of any errors
apiResponse.Problem
);
}
// Pass the ResourceToken to the TrueLayer Web or Mobile SDK
// or, redirect to the TrueLayer Hosted Payment Page
string hostedPaymentPageUrl = _client.Payments.CreateHostedPaymentPageLink(
apiResponse.Data!.Id,
apiResponse.Data!.ResourceToken,
new Uri("https://redirect.yourdomain.com"));
return Redirect(hostedPaymentPageUrl);
}
}
```
For more examples see the [API documentation](https://docs.truelayer.com). Advanced customization options and documentation for contributors can be found in the [Wiki](https://github.com/TrueLayer/truelayer-sdk-net/wiki).
### Retrieve provider details
Inject `ITrueLayerClient` into your classes:
```c#
public class MyService
{
private readonly ITrueLayerClient _client;
public MyService(ITrueLayerClient client)
{
_client = client;
}
public async Task GetProvider(string id)
{
var apiResponse = await _client.PaymentsProviders.GetPaymentsProvider(id);
if (!apiResponse.IsSuccessful)
{
return HandleFailure(
apiResponse.StatusCode,
// Includes details of any errors
apiResponse.Problem
);
}
return Ok(apiResponse.Data.Id);
}
}
```
For more examples see the [API documentation](https://docs.truelayer.com). Advanced customization options and documentation for contributors can be found in the [Wiki](https://github.com/TrueLayer/truelayer-sdk-net/wiki).
### Make a payout
Inject `ITrueLayerClient` into your classes:
```c#
public class MyService
{
private readonly ITrueLayerClient _client;
public MyService(ITrueLayerClient client)
{
_client = client;
}
public async Task MakePayout()
{
var payoutRequest = new CreatePayoutRequest(
merchantAccountId: "VALID_MERCHANT_ID",
amountInMinor: amount.ToMinorCurrencyUnit(2),
currency: Currencies.GBP,
beneficiary: new Beneficiary.ExternalAccount(
"TrueLayer",
"truelayer-dotnet",
new SchemeIdentifier.Iban("VALID_IBAN")
)
);
var apiResponse = await _client.Payouts.CreatePayout(
payoutRequest,
idempotencyKey: Guid.NewGuid().ToString()
);
if (!apiResponse.IsSuccessful)
{
return HandleFailure(
apiResponse.StatusCode,
// Includes details of any errors
apiResponse.Problem
);
}
return Accepted(apiResponse.Data.Id);
}
}
```
For more examples see the [API documentation](https://docs.truelayer.com). Advanced customization options and documentation for contributors can be found in the [Wiki](https://github.com/TrueLayer/truelayer-sdk-net/wiki).
## Testing
This project includes two types of tests:
**Unit Tests** - Run standalone without external dependencies:
```shell
dotnet test test/TrueLayer.Tests/
```
**Acceptance Tests** - End-to-end integration tests that require TrueLayer sandbox credentials:
```shell
# Set credentials via environment variables
TrueLayer__ClientId=your_client_id TrueLayer__ClientSecret=your_client_secret dotnet test
# Or run all tests (will fail without credentials)
dotnet test
```
The acceptance tests make real HTTP calls to TrueLayer's sandbox APIs to validate the entire SDK against live services. See `test/TrueLayer.AcceptanceTests/README.md` for credential setup instructions.
## Building locally
This project uses [Cake](https://cakebuild.net/) to build, test and publish packages.
Run `build.sh` (Mac/Linux) or `build.ps1` (Windows) To build and test the project.
This will output NuGet packages and coverage reports in the `artifacts` directory.
## Contributing
Contributions are always welcome!
Please adhere to this project's [code of conduct](CODE_OF_CONDUCT.md).
## License
[MIT](LICENSE)