using System;
using RestSharp;
using Newtonsoft.Json;
using MTWorkHR.Core.Global;
using MTWorkHR.Application.Services.Interfaces;
namespace MTWorkHR.Application.Services.Payment
{
public class MatchMoveService: IMatchMoveService
{
private readonly string _baseUrl;
private readonly string _clientId;
private readonly string _clientSecret;
private readonly AppSettingsConfiguration _configuration;
public MatchMoveService(AppSettingsConfiguration configuration)
{
_configuration = configuration;
_baseUrl = configuration.MatchMoveSettings.BaseUrl;
_clientId = configuration.MatchMoveSettings.ClientId;
_clientSecret = configuration.MatchMoveSettings.ClientSecret;
}
///
/// Retrieves an OAuth token from MatchMove.
///
/// Access token string.
public async Task GetAccessTokenAsync()
{
var client = new RestClient(_baseUrl);
var request = new RestRequest("/oauth/token")
{
Method = Method.Post
};
// Add required headers and body parameters
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", _clientId);
request.AddParameter("client_secret", _clientSecret);
var response = await client.ExecuteAsync(request);
if (!response.IsSuccessful)
{
throw new Exception($"Error retrieving access token: {response.StatusCode} - {response.ErrorMessage}");
}
var token = response.Content; // Parse JSON response to extract the token if needed
return token;
}
///
/// Processes a payment using MatchMove's API.
///
/// OAuth token.
/// Payment details as an object.
/// Response from MatchMove API.
public async Task ProcessPaymentAsync(string token, object paymentRequest)
{
var client = new RestClient(_baseUrl);
var request = new RestRequest("/payments")
{
Method = Method.Post
};
// Add required headers
request.AddHeader("Authorization", $"Bearer {token}");
request.AddHeader("Content-Type", "application/json");
// Add JSON body
request.AddJsonBody(paymentRequest);
var response = await client.ExecuteAsync(request);
if (!response.IsSuccessful)
{
throw new Exception($"Error processing payment: {response.StatusCode} - {response.ErrorMessage}");
}
return response.Content;
}
}
}