.NET Integration

Integrate the Trustist Ecommerce API into your .NET applications using standard HTTP requests with Hawk authentication.

1. Installation

For .NET integration, you'll need to install HTTP client libraries for making authenticated API calls.

# Using NuGet Package Manager
Install-Package System.Net.Http

You'll also need to install a Hawk authentication library:

# Install a Hawk authentication library
# Example using a community library
Install-Package HawkNet

2. Configuration

Create a client class to handle authenticated API calls to the Trustist Ecommerce API.

public class TrustistEcommerceClient
{
    private readonly HttpClient _httpClient;
    private readonly string _clientId;
    private readonly string _privateKey;
    private readonly string _baseUrl;

    public TrustistEcommerceClient(string clientId, string privateKey, bool useSandbox = true)
    {
        _clientId = clientId;
        _privateKey = privateKey;
        _baseUrl = useSandbox
            ? "https://api-sandbox.trustistecommerce.com"
            : "https://api.trustistecommerce.com";

        _httpClient = new HttpClient();
    }

    // Authentication and request methods will be added in the next sections
}

3. Adding Authentication

Add Hawk authentication to your client class for secure API calls.

// Add this method to your TrustistEcommerceClient class
private string GenerateHawkHeader(string url, string method, string? payload = null)
{
    // Use a Hawk library to generate the authentication header
    // This is a simplified example - use a proper Hawk library
    var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
    var nonce = Guid.NewGuid().ToString("N").Substring(0, 6);

    // Generate MAC using your private key
    var mac = GenerateMac($"{timestamp}\\n{nonce}\\n{method}\\n{url}\\n{GetHost(url)}\\n443\\n{payload}\\n");

    return $"Hawk id=\"{_clientId}\", ts=\"{timestamp}\", nonce=\"{nonce}\", mac=\"{mac}\"";
}

4. Creating a Payment

To create a new payment, call the CreateAsync method on the Payments property of the ITrustistEcommerceClient instance.

var paymentRequest = new TrustistEcommercePaymentCreateRequest
{
    Amount = 100.00m,
    Reference = "your-order-reference",
    Description = "Short description", // optional but advisable
    ReturnUrl = "https://your-return-url.com",
    CustomerDetails = "Name and/or address" // optional
};

var paymentResponse = await _trustistEcommerceClient.Payments.CreateAsync(
    paymentRequest, 
    cancellationToken);

Required Fields

  • Amount - Payment amount (decimal)
  • Reference - Your unique order reference

Optional Fields

  • Description - Payment description (advisable)
  • ReturnUrl - URL to redirect customer after payment
  • CustomerDetails - Customer name and/or address

Response

The response includes:

  • Id - Unique payment identifier
  • PayLink - URL to redirect customer for payment

5. Retrieving a Payment

To retrieve the details of an existing payment, call the GetAsync method on the Payments property.

var paymentId = "your-payment-id";
var payment = await _trustistEcommerceClient.Payments.GetAsync(
    paymentId, 
    cancellationToken);

Response

The payment object includes:

  • Id - Payment identifier
  • Status - Current status (PENDING, COMPLETE, FAILED, etc.)
  • Amount - Payment amount
  • Reference - Your order reference

Example: Complete Payment Flow

[ApiController]
[Route("[controller]")]
public class PaymentsController : ControllerBase
{
    private readonly ITrustistEcommerceClient _trustistClient;

    public PaymentsController(ITrustistEcommerceClient trustistClient)
    {
        _trustistClient = trustistClient;
    }

    [HttpPost]
    public async Task CreatePayment(
        [FromBody] CreatePaymentRequest request)
    {
        var payment = await _trustistClient.Payments.CreateAsync(
            new TrustistEcommercePaymentCreateRequest
            {
                Amount = request.Amount,
                Reference = request.OrderId,
                Description = request.Description,
                ReturnUrl = $"{Request.Scheme}://{Request.Host}/payment/complete"
            },
            HttpContext.RequestAborted);

        return Ok(new
        {
            payment.Id,
            payment.PayLink
        });
    }

    [HttpGet("{id}")]
    public async Task GetPayment(string id)
    {
        var payment = await _trustistClient.Payments.GetAsync(
            id,
            HttpContext.RequestAborted);

        return Ok(payment);
    }

    [HttpGet("complete")]
    public async Task PaymentComplete([FromQuery] string paymentId)
    {
        // Verify payment status after customer returns
        var payment = await _trustistClient.Payments.GetAsync(
            paymentId,
            HttpContext.RequestAborted);

        if (payment.Status == "COMPLETE")
        {
            // Process successful payment
            return RedirectToAction("Success");
        }

        // Handle failed payment
        return RedirectToAction("Failed");
    }
}

Best Practices

  • Always verify payment status server-side before fulfilling orders
  • Store payment IDs in your database for tracking and reconciliation
  • Use descriptive references to easily identify payments
  • Implement webhooks for real-time payment notifications
  • Handle errors gracefully with try-catch blocks
  • Use cancellation tokens for better async operation control

Error Handling

try
{
    var payment = await _trustistClient.Payments.CreateAsync(
        paymentRequest,
        cancellationToken);
    
    return Ok(payment);
}
catch (TrustistEcommerceException ex)
{
    _logger.LogError(ex, "Payment creation failed");
    return BadRequest(new { error = ex.Message });
}
catch (Exception ex)
{
    _logger.LogError(ex, "Unexpected error");
    return StatusCode(500, "An error occurred");
}

Next Steps