You can try this, the PayPalConfigDto
contains some basic stuff that you need to provide. Please bear in mind that the values should be stored in the app settings file of your app and this is only a simple example:
public class PayPalConfigDto
{
public string BaseUrl { get; set; }
public string TokenUrl => $"{BaseUrl}/v1/oauth2/token";
public string ClientId { get; set; }
public string ClientSecret { get; set; }
}
The PayPal API response object:
public class TokenDto
{
public string Scope { get; set; }
public string Access_token { get; set; }
public string Token_type { get; set; }
public string App_id { get; set; }
public string Expires_in { get; set; }
public string Nonce { get; set; }
}
The PayPalContext class:
public class PayPalContext
{
private HttpClient _httpClient;
private PayPalConfigDto _payPalConfig;
public PayPalContext(HttpClient httpClient, PayPalConfigDto payPalConfig)
{
_httpClient = httpClient;
_payPalConfig = payPalConfig;
}
public virtual async Task<string> GetToken()
{
var url = $"{_payPalConfig.TokenUrl}?grant_type=client_credentials";
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_payPalConfig.ClientId}:{_payPalConfig.ClientSecret}")));
var responseTask = _httpClient.PostAsync(url, null);
responseTask.Wait();
var response = responseTask.Result;
var result = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
var errorMessage = response.ToString();
throw new Exception($"An issue occurred during the trial of getting PayPal token. {errorMessage}");
}
var tokenDto = JsonConvert.DeserializeObject<TokenDto>(result);
return tokenDto.Access_token;
}
}
The GetToken
method needs to encode the credentials and based on this answer
you can do this quite easily with
new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_payPalConfig.ClientId}:{_payPalConfig.ClientSecret}")));
To test all the stuff you can just create a simple test class e.g.:
//[Ignore]
public class PayPalContextTests
{
readonly PayPalConfigDto PayPalConfig = new PayPalConfigDto()
{
BaseUrl = "https://api.sandbox.paypal.com",
ClientId = "your ClientId",
ClientSecret = "your ClientSecret"
};
[Test]
public async Task Should_return_valid_token()
{
var httpClient = new HttpClient();
var context = new PayPalContext(httpClient, PayPalConfig);
var token = await context.GetToken();
Assert.IsFalse(string.IsNullOrEmpty(token));
}
}
I also think this can be helpful if you'd like to get a token via Postman, which is a tip to the thing you can find in the main PayPal documentation