-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathPaymentProviderWorkflow.cs
More file actions
265 lines (201 loc) · 11 KB
/
Copy pathPaymentProviderWorkflow.cs
File metadata and controls
265 lines (201 loc) · 11 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Umbraco.Forms.Core;
using Umbraco.Forms.Core.Enums;
using Umbraco.Forms.Integrations.Commerce.Emerchantpay.Builders;
using Umbraco.Forms.Integrations.Commerce.Emerchantpay.Configuration;
using Umbraco.Forms.Integrations.Commerce.Emerchantpay.ExtensionMethods;
using Umbraco.Forms.Integrations.Commerce.Emerchantpay.Helpers;
using Umbraco.Forms.Integrations.Commerce.Emerchantpay.Models.Dtos;
using Umbraco.Forms.Integrations.Commerce.Emerchantpay.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
namespace Umbraco.Forms.Integrations.Commerce.Emerchantpay
{
public class PaymentProviderWorkflow : WorkflowType
{
private readonly PaymentProviderSettings _paymentProviderSettings;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ConsumerService _consumerService;
private readonly PaymentService _paymentService;
private readonly UrlHelper _urlHelper;
private readonly IMappingService<Mapping> _mappingService;
private readonly ISettingsParser _parser;
private readonly ILogger<PaymentProviderWorkflow> _logger;
#region WorkflowSettings
[Core.Attributes.Setting("Amount",
Description = "Payment amount (without decimals)",
View = "TextField")]
public string Amount { get; set; }
[Core.Attributes.Setting("Currency",
Description = "Payment currency",
View = "~/App_Plugins/UmbracoForms.Integrations/Commerce/Emerchantpay/currency.html")]
public string Currency { get; set; }
[Core.Attributes.Setting("Number of Items",
Description = "Map number of items with form field. If selected, final amount will be Amount x NumberOfItems.",
View = "~/App_Plugins/UmbracoForms.Integrations/Commerce/Emerchantpay/field-picker.html")]
public string NumberOfItems { get; set; }
[Core.Attributes.Setting("Record Status",
Description = "Map payment record status with form field",
View = "~/App_Plugins/UmbracoForms.Integrations/Commerce/Emerchantpay/field-picker.html")]
public string RecordStatus { get; set; }
[Core.Attributes.Setting("Record Payment Unique ID",
Description = "Map payment unique ID with form field",
View = "~/App_Plugins/UmbracoForms.Integrations/Commerce/Emerchantpay/field-picker.html")]
public string UniqueId { get; set; }
[Core.Attributes.Setting("Customer Details",
Description = "Map customer details with form fields",
View = "~/App_Plugins/UmbracoForms.Integrations/Commerce/Emerchantpay/customer-details-mapper.html")]
public string CustomerDetailsMappings { get; set; }
[Core.Attributes.Setting("Success URL",
View = "Pickers.Content")]
public string SuccessUrl { get; set; }
[Core.Attributes.Setting("Failure URL",
View = "Pickers.Content")]
public string FailureUrl { get; set; }
[Core.Attributes.Setting("Cancel URL",
View = "Pickers.Content")]
public string CancelUrl { get; set; }
[Core.Attributes.Setting("Approve Record",
Description = "Approve record when payment is confirmed.",
View = "Checkbox")]
public string Approve { get; set; }
#endregion
public PaymentProviderWorkflow(
IOptions<PaymentProviderSettings> paymentProviderSettings,
IHttpContextAccessor httpContextAccessor,
ConsumerService consumerService, PaymentService paymentService, UrlHelper urlHelper,
IMappingService<Mapping> mappingService,
ISettingsParser parser,
ILogger<PaymentProviderWorkflow> logger)
{
Id = new Guid(Constants.WorkflowId);
Name = "emerchantpay Gateway";
Description = "emerchantpay provider handling form-based payments.";
Icon = "icon-multiple-credit-cards";
_consumerService = consumerService;
_paymentService = paymentService;
_httpContextAccessor = httpContextAccessor;
_urlHelper = urlHelper;
_mappingService = mappingService;
_parser = parser;
_paymentProviderSettings = paymentProviderSettings.Value;
_logger = logger;
}
public override WorkflowExecutionStatus Execute(WorkflowExecutionContext context)
{
if (!_mappingService.TryParse(CustomerDetailsMappings, out var mappings)) return WorkflowExecutionStatus.Failed;
try
{
var mappingBuilder = new MappingBuilder()
.SetValues(context.Record, mappings)
.Build();
// step 1. Create or Retrieve Consumer
var consumer = new ConsumerDto { Email = mappingBuilder.Email };
// step 1. Create Consumer
var createConsumerTask = Task.Run(async () => await _consumerService.Create(consumer));
var result = createConsumerTask.Result;
if (result.Status.Contains("error") && result.Code != Constants.ErrorCode.ConsumerExists)
{
_logger.LogError($"Failed to create consumer: {result.TechnicalMessage}.");
return WorkflowExecutionStatus.Failed;
}
if (result.Code == Constants.ErrorCode.ConsumerExists)
{
// step 1.1. Get Consumer
var retrieveConsumerTask = Task.Run(async () => await _consumerService.Retrieve(consumer));
consumer = retrieveConsumerTask.Result;
}
else
{
consumer.Id = result.Id;
}
// step 2. Create Payment
var random = new Random();
var transactionId = $"uc-{random.Next(1000000, 999999999)}";
var formHelper = new FormHelper(context.Record);
var formId = formHelper.GetFormId();
var recordUniqueId = formHelper.GetRecordUniqueId();
var uniqueIdKey = UniqueId;
var statusKey = RecordStatus;
var numberOfItems = string.IsNullOrEmpty(NumberOfItems)
? 0
: int.Parse(formHelper.GetRecordFieldValue(NumberOfItems));
var payment = new PaymentDto
{
TransactionId = transactionId.ToString(),
Usage = _paymentProviderSettings.Usage,
NotificationUrl = $"{_paymentProviderSettings.UmbracoBaseUrl}umbraco/api/paymentprovider/notifypayment" +
$"?formId={formId}&recordUniqueId={recordUniqueId}&statusFieldId={statusKey}&approve={(bool.TryParse(Approve, out bool approve) ? approve : false)}",
ReturnSuccessUrl = _urlHelper.GetPageUrl(int.Parse(SuccessUrl)),
ReturnFailureUrl = _urlHelper.GetPageUrl(int.Parse(FailureUrl)),
ReturnCancelUrl = _urlHelper.GetPageUrl(int.Parse(CancelUrl)),
Amount = numberOfItems != 0
? numberOfItems * int.Parse(Amount)
: int.Parse(Amount),
Currency = Currency,
ConsumerId = consumer.Id,
CustomerEmail = consumer.Email,
CustomerPhone = mappingBuilder.Phone,
BillingAddress = new AddressDto
{
FirstName = mappingBuilder.FirstName,
LastName = mappingBuilder.LastName,
Address1 = mappingBuilder.Address,
Address2 = string.Empty,
ZipCode = mappingBuilder.ZipCode,
City = mappingBuilder.City,
State = mappingBuilder.State,
Country = mappingBuilder.Country
},
BusinessAttribute = new BusinessAttribute { NameOfTheSupplier = _paymentProviderSettings.Supplier },
TransactionTypes = new TransactionTypeDto
{
TransactionTypes = _parser.AsEnumerable(nameof(PaymentProviderSettings.TransactionTypes))
.Select(p => new TransactionTypeRecordDto { TransactionType = p })
.ToList()
}
};
var createPaymentTask = Task.Run(async () => await _paymentService.Create(payment));
var createPaymentResult = createPaymentTask.Result;
if (createPaymentResult.Status != "error")
{
// add unique ID and status to record
formHelper.UpdateRecordFieldValue(uniqueIdKey, createPaymentResult.UniqueId);
formHelper.UpdateRecordFieldValue(statusKey, createPaymentResult.Status);
_httpContextAccessor.HttpContext.Items[Core.Constants.ItemKeys.RedirectAfterFormSubmitUrl] = createPaymentResult.RedirectUrl;
return WorkflowExecutionStatus.Completed;
}
formHelper.UpdateRecordFieldValue(statusKey, "error");
_logger.LogError($"Failed to create payment: {createPaymentResult.TechnicalMessage}.");
return WorkflowExecutionStatus.Failed;
}
catch(Exception ex)
{
_logger.LogError($"Workflow failed: {ex.Message}.");
return WorkflowExecutionStatus.Failed;
}
}
public override List<Exception> ValidateSettings()
{
var list = new List<Exception>();
if (string.IsNullOrEmpty(Amount) || !int.TryParse(Amount, out _))
list.Add(new Exception("Amount value is not valid."));
if (string.IsNullOrEmpty(Currency)) list.Add(new Exception("Currency field is required."));
if (string.IsNullOrEmpty(RecordStatus)) list.Add(new Exception("Record Status field is required."));
if (string.IsNullOrEmpty(UniqueId)) list.Add(new Exception("Payment Unique ID field is required."));
if (!_mappingService.TryParse(CustomerDetailsMappings, out _))
list.Add(new Exception("Invalid mappings. Please make sure that mandatory fields are mapped."));
if (!SuccessUrl.IsContentValid(nameof(SuccessUrl), out var successError))
list.Add(new Exception(successError));
if (!FailureUrl.IsContentValid(nameof(FailureUrl), out var failureError))
list.Add(new Exception(failureError));
if (!CancelUrl.IsContentValid(nameof(CancelUrl), out var cancelError))
list.Add(new Exception(cancelError));
return list;
}
}
}