summaryrefslogtreecommitdiffstats
path: root/src/IOL.VippsEcommerce/VippsEcommerceService.cs
blob: 1611809eacfa725d73e39d98ac89614af34e5e74 (plain) (blame)
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using IOL.VippsEcommerce.Models;
using IOL.VippsEcommerce.Models.Api;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace IOL.VippsEcommerce
{
	/// <summary>
	/// The main class for interacting with the vipps api.
	/// </summary>
	public class VippsEcommerceService : IVippsEcommerceService
	{
		private readonly HttpClient _client;
		private readonly ILogger<VippsEcommerceService> _logger;
		private readonly string _vippsClientId;
		private readonly string _vippsClientSecret;
		private readonly string _vippsMsn;
		private readonly string _cacheEncryptionKey;
		private readonly string _cacheDirectoryPath;

		private readonly JsonSerializerOptions _requestJsonSerializerOptions = new() {
			IgnoreNullValues = true
		};

		private const string VIPPS_CACHE_FILE_NAME = "vipps_ecommerce_credentials.json";
		private string CacheFilePath => Path.Combine(_cacheDirectoryPath, VIPPS_CACHE_FILE_NAME);

		public VippsConfiguration Configuration { get; }

		public VippsEcommerceService(
			HttpClient client,
			ILogger<VippsEcommerceService> logger,
			IOptions<VippsConfiguration> options
		) {
			Configuration = options.Value;
			Configuration.Verify();
			var vippsApiUrl = Configuration.GetValue(VippsConfigurationKeyNames.VIPPS_API_URL);
			client.BaseAddress = new Uri(vippsApiUrl);
			_client = client;
			_logger = logger;
			_vippsClientId = Configuration.GetValue(VippsConfigurationKeyNames.VIPPS_CLIENT_ID);
			_vippsClientSecret = Configuration.GetValue(VippsConfigurationKeyNames.VIPPS_CLIENT_SECRET);
			client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key",
			                                 Configuration.GetValue(VippsConfigurationKeyNames
				                                                        .VIPPS_SUBSCRIPTION_KEY_PRIMARY)
			                                 ?? Configuration.GetValue(VippsConfigurationKeyNames
				                                                           .VIPPS_SUBSCRIPTION_KEY_SECONDARY));

			var msn = Configuration.GetValue(VippsConfigurationKeyNames.VIPPS_MSN);
			if (msn.IsPresent()) {
				client.DefaultRequestHeaders.Add("Merchant-Serial-Number", msn);
				_vippsMsn = msn;
			}

			var systemName = Configuration.GetValue(VippsConfigurationKeyNames.VIPPS_SYSTEM_NAME);
			if (systemName.IsPresent()) {
				client.DefaultRequestHeaders.Add("Vipps-System-Name", systemName);
			}

			var systemVersion = Configuration.GetValue(VippsConfigurationKeyNames.VIPPS_SYSTEM_VERSION);
			if (systemVersion.IsPresent()) {
				client.DefaultRequestHeaders.Add("Vipps-System-Version", systemVersion);
			}

			var systemPluginName = Configuration.GetValue(VippsConfigurationKeyNames.VIPPS_SYSTEM_PLUGIN_NAME);
			if (systemPluginName.IsPresent()) {
				client.DefaultRequestHeaders.Add("Vipps-System-Plugin-Name", systemPluginName);
			}

			var systemPluginVersion = Configuration.GetValue(VippsConfigurationKeyNames.VIPPS_SYSTEM_PLUGIN_VERSION);
			if (systemPluginVersion.IsPresent()) {
				client.DefaultRequestHeaders.Add("Vipps-System-Plugin-Version", systemPluginVersion);
			}

			_cacheEncryptionKey = Configuration.GetValue(VippsConfigurationKeyNames.VIPPS_CACHE_KEY);
			_cacheDirectoryPath = Configuration.GetValue(VippsConfigurationKeyNames.VIPPS_CACHE_PATH);
			if (_cacheDirectoryPath.IsPresent()) {
				if (!_cacheDirectoryPath.IsDirectoryWritable()) {
					_logger.LogError("Could not write to cache file directory ("
					                 + _cacheDirectoryPath
					                 + "). Disabling caching.");
					_cacheDirectoryPath = default;
					_cacheEncryptionKey = default;
				}
			}

			_logger.LogInformation("VippsEcommerceService was successfully initialised with api url: " + vippsApiUrl);
		}

		/// <summary>
		/// The access token endpoint is used to get the JWT (JSON Web Token) that must be passed in every API request in the Authorization header.
		/// The access token is a base64-encoded string value that must be aquired first before making any Vipps api calls.
		/// The access token is valid for 1 hour in the test environment and 24 hours in the production environment.
		/// </summary>
		/// <returns></returns>
		/// <exception cref="HttpRequestException">Throws if the api returns unsuccessfully</exception>
		private async Task<VippsAuthorizationTokenResponse> GetAuthorizationTokenAsync(
			bool forceRefresh = false,
			CancellationToken ct = default
		) {
			if (!forceRefresh) {
				if (_cacheDirectoryPath.IsPresent() && File.Exists(CacheFilePath)) {
					var fileContents = await File.ReadAllTextAsync(CacheFilePath, ct);

					if (fileContents.IsPresent()) {
						VippsAuthorizationTokenResponse credentials = default;
						try {
							credentials = JsonSerializer.Deserialize<VippsAuthorizationTokenResponse>(fileContents);
						} catch (Exception e) {
							if (e is JsonException && _cacheEncryptionKey.IsPresent()) {
								// most likely encrypted, try to decrypt
								var decryptedContents = fileContents.DecryptWithAes(_cacheEncryptionKey);
								credentials =
									JsonSerializer.Deserialize<VippsAuthorizationTokenResponse>(decryptedContents);
							}
						}

						if (credentials != default) {
							var currentEpoch = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
							if (long.TryParse(credentials.ExpiresOn, out var expires)
							    && credentials.AccessToken.IsPresent()) {
								if (expires - 600 > currentEpoch) {
									_logger.LogDebug("VippsEcommerceService: Got tokens from cache");
									return credentials;
								}
							}
						}
					}
				}
			}

			var requestMessage = new HttpRequestMessage {
				Headers = {
					{
						"client_id", _vippsClientId
					}, {
						"client_secret", _vippsClientSecret
					},
				},
				RequestUri = new Uri(_client.BaseAddress + "accesstoken/get"),
				Method = HttpMethod.Post
			};
			var response = await _client.SendAsync(requestMessage, ct);

			try {
				response.EnsureSuccessStatusCode();
				var credentials = await response.Content.ReadAsStringAsync(ct);

				if (_cacheDirectoryPath.IsPresent()) {
					await File.WriteAllTextAsync(CacheFilePath,
					                             _cacheEncryptionKey.IsPresent()
						                             ? credentials.EncryptWithAes(_cacheEncryptionKey)
						                             : credentials,
					                             ct);
				}

				_logger.LogDebug("VippsEcommerceService: Got tokens from " + requestMessage.RequestUri);
				return JsonSerializer.Deserialize<VippsAuthorizationTokenResponse>(credentials);
			} catch (Exception e) {
				var exception =
					new VippsRequestException("Vipps get token request returned unsuccessfully.", e);
				if (e is HttpRequestException) {
					try {
						exception.ErrorResponse =
							await response.Content.ReadFromJsonAsync<VippsErrorResponse>(cancellationToken: ct);
						_logger.LogError("ErrorResponse: " + JsonSerializer.Serialize(response.Content));
					} catch (Exception e1) {
						_logger.LogError("Unknown ErrorResponse: " + JsonSerializer.Serialize(response.Content));
						Console.WriteLine(e1);
					}
				}

				Console.WriteLine(e);
				throw exception;
			}
		}


		/// <summary>
		/// This API call allows the merchants to initiate payments.
		/// The merchantSerialNumber (MSN) specifies which sales unit the payments is for.
		/// Payments are uniquely identified with the merchantSerialNumber and orderId together.
		/// The merchant-provided orderId must be unique per sales channel.
		/// Once the transaction is successfully initiated in Vipps, you will receive a response with a fallBack URL which will direct the customer to the Vipps landing page.
		/// The landing page detects if the request comes from a mobile or laptop/desktop device, and if on a mobile device automatically switches to the Vipps app if it is intalled.
		/// The merchant may also pass the 'isApp: true' parameter that will make Vipps respond with a app-switch deeplink that will take the customer directly to the Vipps app.
		/// URLs passed to Vipps must validate with the Apache Commons UrlValidator.
		/// </summary>
		/// <returns></returns>
		/// <exception cref="HttpRequestException">Throws if the api returns unsuccessfully</exception>
		public async Task<VippsInitiatePaymentResponse> InitiatePaymentAsync(
			VippsInitiatePaymentRequest payload,
			CancellationToken ct = default
		) {
			if (_client.DefaultRequestHeaders.Authorization?.Parameter.IsNullOrWhiteSpace() ?? true) {
				var credentials = await GetAuthorizationTokenAsync(false, ct);
				_client.DefaultRequestHeaders.Authorization =
					new AuthenticationHeaderValue("Bearer", credentials.AccessToken);
			}

			var response = await _client.PostAsJsonAsync("ecomm/v2/payments",
			                                             payload,
			                                             _requestJsonSerializerOptions,
			                                             ct);

			try {
				response.EnsureSuccessStatusCode();
				_logger.LogDebug("VippsEcommerceService: Sent InitiatePaymentRequest");
				return await response.Content
				                     .ReadFromJsonAsync<VippsInitiatePaymentResponse>(cancellationToken: ct);
			} catch (Exception e) {
				var exception =
					new VippsRequestException("Vipps initiate payment request returned unsuccessfully.", e);
				if (e is HttpRequestException) {
					try {
						exception.ErrorResponse =
							await response.Content.ReadFromJsonAsync<VippsErrorResponse>(cancellationToken: ct);
						_logger.LogError("ErrorResponse: " + JsonSerializer.Serialize(response.Content));
					} catch (Exception e1) {
						_logger.LogError("Unknown ErrorResponse: " + JsonSerializer.Serialize(response.Content));
						Console.WriteLine(e1);
					}
				}

				Console.WriteLine(e);
				throw exception;
			}
		}

		/// <summary>
		/// This API call allows merchant to capture the reserved amount.
		/// Amount to capture cannot be higher than reserved.
		/// The API also allows capturing partial amount of the reserved amount.
		/// Partial capture can be called as many times as required so long there is reserved amount to capture.
		/// Transaction text is not optional and is used as a proof of delivery (tracking code, consignment number etc.).
		/// In a case of direct capture, both fund reservation and capture are executed in a single operation.
		/// It is important to check the response, and the capture is only successful when the response is HTTP 200 OK.
		/// </summary>
		/// <returns></returns>
		/// <exception cref="HttpRequestException">Throws if the api returns unsuccessfully</exception>
		public async Task<VippsPaymentActionResponse> CapturePaymentAsync(
			string orderId,
			VippsPaymentActionRequest payload,
			CancellationToken ct = default
		) {
			if (_client.DefaultRequestHeaders.Authorization?.Parameter.IsNullOrWhiteSpace() ?? true) {
				var credentials = await GetAuthorizationTokenAsync(false, ct);
				_client.DefaultRequestHeaders.Authorization =
					new AuthenticationHeaderValue("Bearer", credentials.AccessToken);
			}


			if (payload.MerchantInfo?.MerchantSerialNumber.IsNullOrWhiteSpace() ?? false) {
				payload.MerchantInfo = new TMerchantInfoPayment {
					MerchantSerialNumber = _vippsMsn
				};
			}

			var response = await _client.PostAsJsonAsync("ecomm/v2/payments/" + orderId + "/capture",
			                                             payload,
			                                             _requestJsonSerializerOptions,
			                                             ct);

			try {
				response.EnsureSuccessStatusCode();
				_logger.LogDebug("VippsEcommerceService: Sent CapturePaymentRequest");
				return await response.Content.ReadFromJsonAsync<VippsPaymentActionResponse>(cancellationToken: ct);
			} catch (Exception e) {
				var exception =
					new VippsRequestException("Vipps capture payment request returned unsuccessfully.", e);
				if (e is HttpRequestException) {
					try {
						exception.ErrorResponse =
							await response.Content.ReadFromJsonAsync<VippsErrorResponse>(cancellationToken: ct);
						_logger.LogError("ErrorResponse: " + JsonSerializer.Serialize(response.Content));
					} catch (Exception e1) {
						_logger.LogError("Unknown ErrorResponse: " + JsonSerializer.Serialize(response.Content));
						Console.WriteLine(e1);
					}
				}

				Console.WriteLine(e);
				throw exception;
			}
		}


		/// <summary>
		/// The API call allows merchant to cancel the reserved or initiated transaction.
		/// The API will not allow partial cancellation which has the consequence that partially captured transactions cannot be cancelled.
		/// Please note that in a case of communication errors during initiate payment service call between Vipps and PSP/Acquirer/Issuer; even in a case that customer has confirmed a payment, the payment will be cancelled by Vipps.
		/// Note this means you can not cancel a captured payment.
		/// </summary>
		/// <returns></returns>
		/// <exception cref="HttpRequestException">Throws if the api returns unsuccessfully</exception>
		public async Task<VippsPaymentActionResponse> CancelPaymentAsync(
			string orderId,
			VippsPaymentActionRequest payload,
			CancellationToken ct = default
		) {
			if (_client.DefaultRequestHeaders.Authorization?.Parameter.IsNullOrWhiteSpace() ?? true) {
				var credentials = await GetAuthorizationTokenAsync(false, ct);
				_client.DefaultRequestHeaders.Authorization =
					new AuthenticationHeaderValue("Bearer", credentials.AccessToken);
			}

			if (payload.MerchantInfo?.MerchantSerialNumber.IsNullOrWhiteSpace() ?? false) {
				payload.MerchantInfo = new TMerchantInfoPayment {
					MerchantSerialNumber = _vippsMsn
				};
			}

			var response = await _client.PutAsJsonAsync("ecomm/v2/payments/" + orderId + "/cancel",
			                                            payload,
			                                            _requestJsonSerializerOptions,
			                                            ct);

			try {
				response.EnsureSuccessStatusCode();
				_logger.LogDebug("VippsEcommerceService: Sent CancelPaymentRequest");
				return await response.Content.ReadFromJsonAsync<VippsPaymentActionResponse>(cancellationToken: ct);
			} catch (Exception e) {
				var exception =
					new VippsRequestException("Vipps cancel payment request returned unsuccessfully.", e);
				if (e is HttpRequestException) {
					try {
						exception.ErrorResponse =
							await response.Content.ReadFromJsonAsync<VippsErrorResponse>(cancellationToken: ct);
						_logger.LogError("ErrorResponse: " + JsonSerializer.Serialize(response.Content));
					} catch (Exception e1) {
						_logger.LogError("Unknown ErrorResponse: " + JsonSerializer.Serialize(response.Content));
						Console.WriteLine(e1);
					}
				}


				Console.WriteLine(e);
				throw exception;
			}
		}

		/// <summary>
		/// The API call allows merchant to refresh the authorizations of the payment.
		/// A reservation's lifetime is defined by the scheme. Typically 7 days for Visa, and 30 days for Mastercard.
		/// This is currently not live in production and will be added shortly.
		/// </summary>
		/// <returns></returns>
		/// <exception cref="HttpRequestException">Throws if the api returns unsuccessfully</exception>
		public async Task<VippsPaymentActionResponse> AuthorizePaymentAsync(
			string orderId,
			VippsPaymentActionRequest payload,
			CancellationToken ct = default
		) {
			if (_client.DefaultRequestHeaders.Authorization?.Parameter.IsNullOrWhiteSpace() ?? true) {
				var credentials = await GetAuthorizationTokenAsync(false, ct);
				_client.DefaultRequestHeaders.Authorization =
					new AuthenticationHeaderValue("Bearer", credentials.AccessToken);
			}

			if (payload.MerchantInfo?.MerchantSerialNumber.IsNullOrWhiteSpace() ?? false) {
				payload.MerchantInfo = new TMerchantInfoPayment {
					MerchantSerialNumber = _vippsMsn
				};
			}

			var response = await _client.PutAsJsonAsync("ecomm/v2/payments/" + orderId + "/authorize",
			                                            payload,
			                                            _requestJsonSerializerOptions,
			                                            ct);

			try {
				response.EnsureSuccessStatusCode();
				_logger.LogDebug("VippsEcommerceService: Sent AuthorizePaymentRequest");
				return await response.Content.ReadFromJsonAsync<VippsPaymentActionResponse>(cancellationToken: ct);
			} catch (Exception e) {
				var exception =
					new VippsRequestException("Vipps authorize payment request returned unsuccessfully.", e);
				if (e is HttpRequestException) {
					try {
						exception.ErrorResponse =
							await response.Content.ReadFromJsonAsync<VippsErrorResponse>(cancellationToken: ct);
						_logger.LogError("ErrorResponse: " + JsonSerializer.Serialize(response.Content));
					} catch (Exception e1) {
						_logger.LogError("Unknown ErrorResponse: " + JsonSerializer.Serialize(response.Content));
						Console.WriteLine(e1);
					}
				}


				Console.WriteLine(e);
				throw exception;
			}
		}

		/// <summary>
		/// The API allows a merchant to do a refund of already captured transaction.
		/// There is an option to do a partial refund of the captured amount.
		/// Refunded amount cannot be larger than captured.
		/// Timeframe for issuing a refund for a payment is 365 days from the date payment has been captured.
		/// If the refund payment service call is called after the refund timeframe, service call will respond with an error.
		/// Refunded funds will be transferred from the merchant account to the customer credit card that was used in payment flow.
		/// Pay attention that in order to perform refund, there must be enough funds at merchant settlements account.
		/// </summary>
		/// <returns></returns>
		/// <exception cref="HttpRequestException">Throws if the api returns unsuccessfully</exception>
		public async Task<VippsPaymentActionResponse> RefundPaymentAsync(
			string orderId,
			VippsPaymentActionRequest payload,
			CancellationToken ct = default
		) {
			if (_client.DefaultRequestHeaders.Authorization?.Parameter.IsNullOrWhiteSpace() ?? true) {
				var credentials = await GetAuthorizationTokenAsync(false, ct);
				_client.DefaultRequestHeaders.Authorization =
					new AuthenticationHeaderValue("Bearer", credentials.AccessToken);
			}

			if (payload.MerchantInfo?.MerchantSerialNumber.IsNullOrWhiteSpace() ?? false) {
				payload.MerchantInfo = new TMerchantInfoPayment {
					MerchantSerialNumber = _vippsMsn
				};
			}

			var response = await _client.PostAsJsonAsync("ecomm/v2/payments/" + orderId + "/refund",
			                                             payload,
			                                             _requestJsonSerializerOptions,
			                                             ct);
			try {
				response.EnsureSuccessStatusCode();
				_logger.LogDebug("VippsEcommerceService: Sent RefundPaymentRequest");
				return await response.Content.ReadFromJsonAsync<VippsPaymentActionResponse>(cancellationToken: ct);
			} catch (Exception e) {
				var exception =
					new VippsRequestException("Vipps refund payment request returned unsuccessfully.", e);
				if (e is HttpRequestException) {
					try {
						exception.ErrorResponse =
							await response.Content.ReadFromJsonAsync<VippsErrorResponse>(cancellationToken: ct);
						_logger.LogError("ErrorResponse: " + JsonSerializer.Serialize(response.Content));
					} catch (Exception e1) {
						_logger.LogError("Unknown ErrorResponse: " + JsonSerializer.Serialize(response.Content));
						Console.WriteLine(e1);
					}
				}


				Console.WriteLine(e);
				throw exception;
			}
		}


		/// <summary>
		/// This endpoint allows developers to approve a payment through the Vipps eCom API without the use of the Vipps app.
		/// This is useful for automated testing.
		/// Express checkout is not supported for this endpoint.
		/// The endpoint is only available in our Test environment.
		/// Attempted use of the endpoint in production is not allowed, and will fail.
		/// </summary>
		/// <returns></returns>
		/// <exception cref="HttpRequestException">Throws if the api returns unsuccessfully</exception>
		public async Task<bool> ForceApprovePaymentAsync(
			string orderId,
			VippsForceApproveRequest payload,
			CancellationToken ct = default
		) {
			if (_client.DefaultRequestHeaders.Authorization?.Parameter.IsNullOrWhiteSpace() ?? true) {
				var credentials = await GetAuthorizationTokenAsync(false, ct);
				_client.DefaultRequestHeaders.Authorization =
					new AuthenticationHeaderValue("Bearer", credentials.AccessToken);
			}


			var response =
				await _client.PostAsJsonAsync("ecomm/v2/integration-test/payments/" + orderId + "/approve",
				                              payload,
				                              _requestJsonSerializerOptions,
				                              ct);

			try {
				response.EnsureSuccessStatusCode();
				_logger.LogDebug("VippsEcommerceService: Sent ForceApprovePaymentRequest");
				return true;
			} catch (Exception e) {
				var exception =
					new VippsRequestException("Vipps force approve payment request returned unsuccessfully.", e);
				if (e is HttpRequestException) {
					try {
						exception.ErrorResponse =
							await response.Content.ReadFromJsonAsync<VippsErrorResponse>(cancellationToken: ct);
						_logger.LogError("ErrorResponse: " + JsonSerializer.Serialize(response.Content));
					} catch (Exception e1) {
						_logger.LogError("Unknown ErrorResponse: " + JsonSerializer.Serialize(response.Content));
						Console.WriteLine(e1);
					}
				}

				Console.WriteLine(e);
				throw exception;
			}
		}

		/// <summary>
		/// This API call allows merchant to get the details of a payment transaction.
		/// Service call returns detailed transaction history of given payment where events are sorted from newest to oldest for when the transaction occurred.
		/// </summary>
		/// <returns></returns>
		/// <exception cref="HttpRequestException">Throws if the api returns unsuccessfully</exception>
		public async Task<VippsGetPaymentDetailsResponse> GetPaymentDetailsAsync(
			string orderId,
			CancellationToken ct = default
		) {
			if (_client.DefaultRequestHeaders.Authorization?.Parameter.IsNullOrWhiteSpace() ?? true) {
				var credentials = await GetAuthorizationTokenAsync(false, ct);
				_client.DefaultRequestHeaders.Authorization =
					new AuthenticationHeaderValue("Bearer", credentials.AccessToken);
			}

			var response = await _client.GetAsync("ecomm/v2/payments/" + orderId + "/details", ct);

			try {
				response.EnsureSuccessStatusCode();
				_logger.LogDebug("VippsEcommerceService: Sent GetPaymentDetailsRequest");
				return await
					response.Content.ReadFromJsonAsync<VippsGetPaymentDetailsResponse>(cancellationToken: ct);
			} catch (Exception e) {
				var exception =
					new VippsRequestException("Vipps get payment detailsG request returned unsuccessfully.", e);
				if (e is HttpRequestException) {
					try {
						exception.ErrorResponse =
							await response.Content.ReadFromJsonAsync<VippsErrorResponse>(cancellationToken: ct);
						_logger.LogError("ErrorResponse: " + JsonSerializer.Serialize(response.Content));
					} catch (Exception e1) {
						_logger.LogError("Unknown ErrorResponse: " + JsonSerializer.Serialize(response.Content));
						Console.WriteLine(e1);
					}
				}


				Console.WriteLine(e);
				throw exception;
			}
		}
	}
}