-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseClient.cs
More file actions
305 lines (272 loc) · 12.1 KB
/
Copy pathBaseClient.cs
File metadata and controls
305 lines (272 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
namespace Mediumart.MobileMoney;
/// <summary>
/// Abstract base client for all MTN Mobile Money API services.
/// Integrates the shared API methods (token, balance, userinfo, etc.) and user data management.
/// </summary>
public abstract class BaseClient
{
private readonly HttpClient _client;
private string _baseUrl;
// User data storage (equivalent to PHP HasUserData trait)
private string? _userId;
private string? _apiKey;
private string? _subscriptionKey;
/// <summary>
/// Gets or sets the user reference ID.
/// </summary>
public string? UserId
{
get => _userId;
set => _userId = value;
}
/// <summary>
/// Gets or sets the API key.
/// </summary>
public string? ApiKey
{
get => _apiKey;
set => _apiKey = value;
}
/// <summary>
/// Gets or sets the subscription key.
/// </summary>
public string? SubscriptionKey
{
get => _subscriptionKey;
set => _subscriptionKey = value;
}
/// <summary>
/// Initializes a new instance of <see cref="BaseClient"/>.
/// </summary>
/// <param name="client">The HTTP client to use for requests.</param>
/// <param name="baseUrl">The base URL for the API endpoints.</param>
protected BaseClient(HttpClient client, string baseUrl)
{
_client = client;
_baseUrl = baseUrl;
}
/// <summary>
/// Sets the base URL for this client.
/// </summary>
/// <param name="baseUrl">The new base URL.</param>
public void SetBaseUrl(string baseUrl)
{
_baseUrl = baseUrl;
}
/// <summary>
/// Gets the current base URL for this client.
/// </summary>
/// <returns>The base URL string.</returns>
public string GetBaseUrl() => _baseUrl;
/// <summary>
/// Sets user data from a <see cref="User"/> instance.
/// </summary>
/// <param name="user">The user whose credentials to store.</param>
/// <returns>This client instance for method chaining.</returns>
public BaseClient WithUser(User user)
{
ArgumentNullException.ThrowIfNull(user);
_userId = user.UserId;
_apiKey = user.ApiKey;
_subscriptionKey = user.SubscriptionKey;
return this;
}
/// <summary>
/// Gets the underlying HTTP client.
/// </summary>
protected HttpClient Client => _client;
/// <summary>
/// Gets the current base URL.
/// </summary>
protected string BaseUrl => _baseUrl;
// ========================================================================
// SharedApi methods (equivalent to PHP SharedApi trait)
// ========================================================================
/// <summary>
/// Creates an access token using Basic authentication.
/// </summary>
/// <param name="subscriptionKey">The product subscription key.</param>
/// <param name="userReferenceId">The user reference ID.</param>
/// <param name="apiKey">The API key.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The HTTP response.</returns>
public async Task<HttpResponseMessage> CreateAccessTokenAsync(
string subscriptionKey,
string userReferenceId,
string apiKey,
CancellationToken cancellationToken = default)
{
var request = new HttpRequestMessage(HttpMethod.Post, $"{_baseUrl}/token/");
var credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{userReferenceId}:{apiKey}"));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", credentials);
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
return await _client.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Checks if an account holder is registered and active in the system.
/// </summary>
/// <param name="accountHolderId">The account holder identifier.</param>
/// <param name="accountHolderIdType">The type of the party ID. Allowed values: msisdn, email, party_code.</param>
/// <param name="subscriptionKey">The product subscription key.</param>
/// <param name="targetEnv">The target environment.</param>
/// <param name="token">The bearer token.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The HTTP response.</returns>
public async Task<HttpResponseMessage> ValidateAccountHolderStatusAsync(
string accountHolderId,
string accountHolderIdType,
string subscriptionKey,
string targetEnv,
string token,
CancellationToken cancellationToken = default)
{
var request = new HttpRequestMessage(HttpMethod.Get,
$"{_baseUrl}/v1_0/accountholder/{accountHolderIdType}/{accountHolderId}/active");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Headers.Add("X-Target-Environment", targetEnv);
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
return await _client.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the account balance.
/// </summary>
/// <param name="subscriptionKey">The product subscription key.</param>
/// <param name="targetEnv">The target environment.</param>
/// <param name="token">The bearer token.</param>
/// <param name="currency">Optional currency code to get balance for a specific currency.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The HTTP response.</returns>
public async Task<HttpResponseMessage> GetAccountBalanceAsync(
string subscriptionKey,
string targetEnv,
string token,
string? currency = null,
CancellationToken cancellationToken = default)
{
var path = currency != null
? $"/v1_0/account/balance/{currency}"
: "/v1_0/account/balance";
var request = new HttpRequestMessage(HttpMethod.Get, $"{_baseUrl}{path}");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Headers.Add("X-Target-Environment", targetEnv);
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
return await _client.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns personal information of the account holder.
/// The operation does not need any consent by the account holder.
/// </summary>
/// <param name="msisdn">The phone number (MSISDN).</param>
/// <param name="subscriptionKey">The product subscription key.</param>
/// <param name="targetEnv">The target environment.</param>
/// <param name="token">The bearer token.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The HTTP response.</returns>
public async Task<HttpResponseMessage> GetBasicUserInfoAsync(
string msisdn,
string subscriptionKey,
string targetEnv,
string token,
CancellationToken cancellationToken = default)
{
var request = new HttpRequestMessage(HttpMethod.Get,
$"{_baseUrl}/v1_0/accountholder/msisdn/{msisdn}/basicuserinfo");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Headers.Add("X-Target-Environment", targetEnv);
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
return await _client.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sends an additional notification to an end user.
/// </summary>
/// <param name="message">The notification message (max 160 characters).</param>
/// <param name="subscriptionKey">The product subscription key.</param>
/// <param name="requestId">The reference ID of the request to pay.</param>
/// <param name="targetEnv">The target environment.</param>
/// <param name="token">The bearer token.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The HTTP response.</returns>
/// <exception cref="ArgumentException">Thrown when the message exceeds 160 characters.</exception>
public async Task<HttpResponseMessage> RequestToPayDeliveryNotificationAsync(
string message,
string subscriptionKey,
string requestId,
string targetEnv,
string token,
CancellationToken cancellationToken = default)
{
if (message.Length > 160)
{
throw new ArgumentException("Notification message should be 160 characters max.", nameof(message));
}
var request = new HttpRequestMessage(HttpMethod.Post,
$"{_baseUrl}/v1_0/requesttopay/{requestId}/deliverynotification");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Headers.Add("notificationMessage", message);
request.Headers.Add("X-Target-Environment", targetEnv);
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
var body = JsonSerializer.Serialize(new { notificationMessage = message });
request.Content = new StringContent(body, Encoding.UTF8, "application/json");
return await _client.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates an OAuth2 token.
/// </summary>
/// <param name="token">The bearer token.</param>
/// <param name="targetEnv">The target environment.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The HTTP response.</returns>
public async Task<HttpResponseMessage> CreateOauth2TokenAsync(
string token,
string targetEnv,
CancellationToken cancellationToken = default)
{
var request = new HttpRequestMessage(HttpMethod.Post, $"{_baseUrl}/oauth2/token/");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Headers.Add("X-Target-Environment", targetEnv);
return await _client.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Claims a consent by the account holder for the requested scopes (bc-authorize).
/// </summary>
/// <param name="token">The bearer token.</param>
/// <param name="targetEnv">The target environment.</param>
/// <param name="callbackUrl">Optional callback URL.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The HTTP response.</returns>
public async Task<HttpResponseMessage> BcAuthorizeAsync(
string token,
string targetEnv,
string? callbackUrl = null,
CancellationToken cancellationToken = default)
{
var request = new HttpRequestMessage(HttpMethod.Post, $"{_baseUrl}/v1_0/bc-authorize");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Headers.Add("X-Target-Environment", targetEnv);
if (!string.IsNullOrEmpty(callbackUrl))
{
request.Headers.Add("X-Callback-Url", callbackUrl);
}
return await _client.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets user info with consent (OAuth2 userinfo endpoint).
/// </summary>
/// <param name="token">The bearer token.</param>
/// <param name="targetEnv">The target environment.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The HTTP response.</returns>
public async Task<HttpResponseMessage> GetUserInfoWithConsentAsync(
string token,
string targetEnv,
CancellationToken cancellationToken = default)
{
var request = new HttpRequestMessage(HttpMethod.Get, $"{_baseUrl}/oauth2/v1_0/userinfo");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Headers.Add("X-Target-Environment", targetEnv);
return await _client.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}