-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBamboraCheckout.cs
445 lines (364 loc) · 17.6 KB
/
BamboraCheckout.cs
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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using Rocketjump.PaymentProviders.BamboraCheckout.Api;
using Rocketjump.PaymentProviders.BamboraCheckout.Api.Models;
using TeaCommerce.Api.Common;
using TeaCommerce.Api.Infrastructure.Logging;
using TeaCommerce.Api.Models;
using TeaCommerce.Api.Services;
using TeaCommerce.Api.Web.PaymentProviders;
namespace Rocketjump.PaymentProviders.BamboraCheckout
{
// https://developer.bambora.com/europe/checkout/getting-started/checkout-settings#filter-payment-methods
[PaymentProvider("Bambora Checkout")]
public class BamboraCheckout : APaymentProvider
{
public override bool SupportsRetrievalOfPaymentStatus
{
get { return true; }
}
public override bool SupportsCapturingOfPayment
{
get { return true; }
}
public override bool SupportsRefundOfPayment
{
get { return true; }
}
public override bool SupportsCancellationOfPayment
{
get { return true; }
}
public override IDictionary<string, string> DefaultSettings
{
get
{
Dictionary<string, string> defaultSettings = new Dictionary<string, string>();
defaultSettings["continueUrl"] =
""; //The URL to continue to after this provider has done processing. eg: /continue/
defaultSettings["cancelUrl"] =
""; //The URL to return to if the payment attempt is canceled. eg: /cancel/
defaultSettings["errorUrl"] = ""; //The URL to return to if the payment attempt errors. eg: /error/
defaultSettings["testMerchantNumber"] = ""; //Your Bambora Merchant Number for test transactions.
defaultSettings["testAccessKey"] = ""; //The test API Access Key obtained from the Bambora portal.
defaultSettings["testSecretKey"] = ""; //The test API Secret Key obtained from the Bambora portal.
defaultSettings["testMd5Key"] = ""; //The test MD5 hashing key obtained from the Bambora portal.
defaultSettings["liveMerchantNumber"] = ""; //Your Bambora Merchant Number for live transactions.
defaultSettings["liveAccessKey"] = ""; //The live API Access Key obtained from the Bambora portal.
defaultSettings["liveSecretKey"] = ""; //The live API Secret Key obtained from the Bambora portal.
defaultSettings["liveMd5Key"] = ""; //The live MD5 hashing key obtained from the Bambora portal.
defaultSettings["language"] =
""; //Set the language to use for the payment portal. Can be 'en-GB', 'da-DK', 'sv-SE' or 'nb-NO'.
defaultSettings["capture"] =
"0"; //"Flag indicating whether to immediately capture the payment, or whether to just authorize the payment for later (manual) capture."
defaultSettings["testMode"] = "0"; //"Set whether to process payments in test mode."
defaultSettings["excludedPaymentMethods"] =
""; //"Comma separated list of Payment Method IDs to exclude."
defaultSettings["excludedPaymentGroups"] = ""; //"Comma separated list of Payment Group IDs to exclude."
defaultSettings["excludedPaymentTypes"] = "0"; //"Comma separated list of Payment Type IDs to exclude."
return defaultSettings;
}
}
public override PaymentHtmlForm GenerateHtmlForm(Order order, string teaCommerceContinueUrl,
string teaCommerceCancelUrl,
string teaCommerceCallBackUrl, string teaCommerceCommunicationUrl, IDictionary<string, string> settings)
{
//currency
Currency currency = CurrencyService.Instance.Get(order.StoreId, order.CurrencyId);
if (!Iso4217CurrencyCodes.ContainsKey(currency.IsoCode))
{
throw new Exception("You must specify an ISO 4217 currency code for the " + currency.Name +
" currency");
}
var currencyCode = currency.IsoCode.ToUpperInvariant();
var amount =
Convert.ToInt32(order.TotalPrice.Value.WithVat *
100M); //(order.TotalPrice.Value.WithVat * 100M);//.ToString("0", CultureInfo.InvariantCulture);
var bamboraSettings = new BamboraSettingsBase(settings);
var clientConfig = GetBamboraClientConfig(bamboraSettings);
var client = new BamboraClient(clientConfig);
var checkoutSessionRequest = new BamboraCreateCheckoutSessionRequest
{
InstantCaptureAmount = bamboraSettings.Capture ? amount : 0,
Customer = new BamboraCustomer
{
Email = order.PaymentInformation.Email
},
Order = new BamboraOrder
{
Id = BamboraSafeOrderId(order.CartNumber),
Amount = amount,
Currency = currencyCode
},
Urls = new BamboraUrls
{
Accept = teaCommerceContinueUrl,
Cancel = teaCommerceCancelUrl,
Callbacks = new[]
{
new BamboraUrl {Url = teaCommerceCallBackUrl}
}
},
PaymentWindow = new BamboraPaymentWindow
{
Id = 1,
Language = bamboraSettings.Language
}
};
// Exclude payment methods
if (!string.IsNullOrWhiteSpace(bamboraSettings.ExcludedPaymentMethods))
{
checkoutSessionRequest.PaymentWindow.PaymentMethods = bamboraSettings.ExcludedPaymentMethods
.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => new BamboraPaymentFilter
{ Id = x.Trim(), Action = BamboraPaymentFilter.Actions.Exclude })
.ToArray();
}
// Exclude payment groups
if (!string.IsNullOrWhiteSpace(bamboraSettings.ExcludedPaymentGroups))
{
checkoutSessionRequest.PaymentWindow.PaymentGroups = bamboraSettings.ExcludedPaymentGroups
.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => new BamboraPaymentFilter
{ Id = x.Trim(), Action = BamboraPaymentFilter.Actions.Exclude })
.ToArray();
}
// Exclude payment types
if (!string.IsNullOrWhiteSpace(bamboraSettings.ExcludedPaymentTypes))
{
checkoutSessionRequest.PaymentWindow.PaymentTypes = bamboraSettings.ExcludedPaymentTypes
.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => new BamboraPaymentFilter
{ Id = x.Trim(), Action = BamboraPaymentFilter.Actions.Exclude })
.ToArray();
}
var checkoutSession = client.CreateCheckoutSession(checkoutSessionRequest);
if (checkoutSession.Meta.Result)
return new PaymentHtmlForm()
{
Action = checkoutSession.Url,
Method = HtmlFormMethodAttribute.Get
};
LoggingService.Instance.Warn<BamboraCheckout>("BamboraCheckout GenerateHtmlForm, " +
checkoutSession.Meta.Message.Merchant);
throw new ApplicationException(checkoutSession.Meta.Message.EndUser);
}
public override CallbackInfo ProcessCallback(Order order, HttpRequest request,
IDictionary<string, string> settings)
{
CallbackInfo callbackInfo = null;
try
{
var bamboraSettings = new BamboraSettingsBase(settings);
var clientConfig = GetBamboraClientConfig(bamboraSettings);
var client = new BamboraClient(clientConfig);
if (client.ValidateRequest(request))
{
var txnId = request.QueryString["txnid"];
var orderId = request.QueryString["orderid"];
var amount = int.Parse("0" + request.QueryString["amount"]);
var txnFee = int.Parse("0" + request.QueryString["txnfee"]);
var paymenttype = request.QueryString["paymenttype"];
string cardnopostfix = request.QueryString["cardno"];
// Validate params
if (!string.IsNullOrWhiteSpace(txnId)
&& !string.IsNullOrWhiteSpace(orderId)
&& orderId == BamboraSafeOrderId(order.CartNumber)
&& amount > 0)
{
// Fetch the transaction details so that we can work out
// the status of the transaction as the querystring params
// are not enough on their own
var transactionResp = client.GetTransaction(txnId);
if (transactionResp.Meta.Result)
{
callbackInfo = new CallbackInfo(
AmountFromMinorUnits(amount + txnFee),
transactionResp.Transaction.Id,
!bamboraSettings.Capture ? PaymentState.Authorized : PaymentState.Captured,
paymenttype,
cardnopostfix
);
}
}
}
}
catch (Exception ex)
{
LoggingService.Instance.Error<BamboraCheckout>(
"BamboraCheckout(" + order.CartNumber + ") - Process callback", ex);
throw ex;
}
return callbackInfo;
}
public override ApiInfo GetStatus(Order order, IDictionary<string, string> settings)
{
ApiInfo apiInfo = null;
try
{
var bamboraSettings = new BamboraSettingsBase(settings);
var clientConfig = GetBamboraClientConfig(bamboraSettings);
var client = new BamboraClient(clientConfig);
var transactionResp = client.GetTransaction(order.TransactionInformation.TransactionId);
if (transactionResp.Meta.Result)
{
apiInfo = new ApiInfo(
transactionResp.Transaction.Id.ToString(CultureInfo.InvariantCulture),
GetPaymentStatus(transactionResp.Transaction));
}
}
catch (Exception exp)
{
LoggingService.Instance.Error<BamboraCheckout>("Bambora - FetchPaymentStatus", exp);
}
return apiInfo;
}
public override ApiInfo CapturePayment(Order order, IDictionary<string, string> settings)
{
ApiInfo apiInfo = null;
try
{
var bamboraSettings = new BamboraSettingsBase(settings);
var clientConfig = GetBamboraClientConfig(bamboraSettings);
var client = new BamboraClient(clientConfig);
var transactionResp = client.CaptureTransaction(order.TransactionInformation.TransactionId, new BamboraAmountRequest
{
Amount = (int)AmountToMinorUnits(order.TransactionInformation.AmountAuthorized.Value)
});
if (transactionResp.Meta.Result)
{
apiInfo = new ApiInfo(
order.TransactionInformation.TransactionId,
PaymentState.Captured);
}
}
catch (Exception ex)
{
LoggingService.Instance.Error<BamboraCheckout>("Bambora - CapturePayment", ex);
}
return apiInfo;
}
public override ApiInfo RefundPayment(Order order, IDictionary<string, string> settings)
{
ApiInfo apiInfo = null;
try
{
var bamboraSettings = new BamboraSettingsBase(settings);
var clientConfig = GetBamboraClientConfig(bamboraSettings);
var client = new BamboraClient(clientConfig);
var transactionResp = client.CreditTransaction(order.TransactionInformation.TransactionId, new BamboraAmountRequest
{
Amount = (int)AmountToMinorUnits(order.TransactionInformation.AmountAuthorized.Value)
});
if (transactionResp.Meta.Result)
{
apiInfo = new ApiInfo(
order.TransactionInformation.TransactionId,
PaymentState.Refunded);
}
}
catch (Exception exp)
{
LoggingService.Instance.Error<BamboraCheckout>("Bambora - RefundPayment", exp);
}
return apiInfo;
}
public override ApiInfo CancelPayment(Order order, IDictionary<string, string> settings)
{
ApiInfo apiInfo = null;
try
{
var bamboraSettings = new BamboraSettingsBase(settings);
var clientConfig = GetBamboraClientConfig(bamboraSettings);
var client = new BamboraClient(clientConfig);
var transactionResp = client.DeleteTransaction(order.TransactionInformation.TransactionId);
if (transactionResp.Meta.Result)
{
apiInfo = new ApiInfo(
order.TransactionInformation.TransactionId,
PaymentState.Cancelled);
}
}
catch (Exception exp)
{
LoggingService.Instance.Error<BamboraCheckout>("Bambora - CancelPayment", exp);
}
return apiInfo;
}
/**/
public override string GetContinueUrl(Order order, IDictionary<string, string> settings)
{
settings.MustNotBeNull("settings");
settings.MustContainKey("continueUrl", "settings");
return settings["continueUrl"];
}
public override string GetCancelUrl(Order order, IDictionary<string, string> settings)
{
settings.MustNotBeNull("settings");
settings.MustContainKey("cancelUrl", "settings");
return settings["cancelUrl"];
}
protected BamboraClientConfig GetBamboraClientConfig(BamboraSettingsBase settings)
{
BamboraClientConfig config;
if (settings.TestMode)
{
config = new BamboraClientConfig
{
AccessKey = settings.TestAccessKey,
MerchantNumber = settings.TestMerchantNumber,
SecretKey = settings.TestSecretKey,
MD5Key = settings.TestMd5Key
};
}
else
{
config = new BamboraClientConfig
{
AccessKey = settings.LiveAccessKey,
MerchantNumber = settings.LiveMerchantNumber,
SecretKey = settings.LiveSecretKey,
MD5Key = settings.LiveMd5Key
};
}
var apiKey = GenerateApiKey(config.AccessKey, config.MerchantNumber, config.SecretKey);
config.Authorization = "Basic " + apiKey;
return config;
}
protected string BamboraSafeOrderId(string orderId)
{
return Regex.Replace(orderId, "[^a-zA-Z0-9]", "");
}
private string GenerateApiKey(string accessToken, string merchantNumber, string secretToken)
{
var unencodedApiKey = $"{accessToken}@{merchantNumber}:{secretToken}";
var unencodedApiKeyAsBytes = Encoding.UTF8.GetBytes(unencodedApiKey);
return Convert.ToBase64String(unencodedApiKeyAsBytes);
}
protected static string Base64Encode(string plainText) => Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText));
protected static string Base64Decode(string base64EncodedData) => Encoding.UTF8.GetString(Convert.FromBase64String(base64EncodedData));
protected static long AmountToMinorUnits(Decimal amount) => Convert.ToInt64(Math.Round(amount * 100M, MidpointRounding.AwayFromZero));
protected static Decimal AmountFromMinorUnits(long minorUnits) => (Decimal)minorUnits / 100M;
protected PaymentState GetPaymentStatus(BamboraTransaction transaction)
{
if (transaction.Total.Credited > 0)
return PaymentState.Refunded;
if (transaction.Total.Declined > 0)
return PaymentState.Cancelled;
if (transaction.Total.Captured > 0)
return PaymentState.Captured;
if (transaction.Total.Authorized > 0)
return PaymentState.Authorized;
return PaymentState.Initialized;
}
}
}