Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
InitiateBuyEDaler.cs
1using Paiwise;
2using System;
3using System.Collections.Generic;
4using System.Threading.Tasks;
5using System.Xml;
6using Waher.Content;
7using Waher.Events;
12using Waher.Script;
16
18{
23 {
28 : base("Wallet/InitiateBuyEDaler",
29 new KeyValuePair<Type, Expression>(typeof(Dictionary<string, object>), new Expression(jsonPattern)),
30 new KeyValuePair<Type, Expression>(typeof(XmlDocument), new Expression(xmlPattern)))
31 {
32 }
33
34 private static readonly string jsonPattern = Resources.LoadResourceAsText(typeof(InitiateBuyEDaler).Namespace + ".JSON.InitiateBuyEDaler.req");
35 private static readonly string xmlPattern = Resources.LoadResourceAsText(typeof(InitiateBuyEDaler).Namespace + ".XML.InitiateBuyEDaler.req");
36
45 public override async Task POST(HttpRequest Request, HttpResponse Response, Dictionary<string, IElement> Parameters)
46 {
48
49 LegalIdentity Identity = await XmppServerModule.Legal.GetCurrentApprovedLegalIdentityAsync(User.UserName)
50 ?? throw new ForbiddenException("Account has no approved legal identity.");
51
52 string Country = Identity["COUNTRY"];
53 if (string.IsNullOrEmpty(Country))
54 throw new ForbiddenException("Approved legal identity lacks country specified.");
55
56 string ServiceId = (string)Parameters["PServiceId"].AssociatedObjectValue;
57 string ServiceProvider = (string)Parameters["PServiceProvider"].AssociatedObjectValue;
58 decimal Amount = (decimal)((double)Parameters["PAmount"].AssociatedObjectValue);
59 CaseInsensitiveString Currency = (string)Parameters["PCurrency"].AssociatedObjectValue;
60 string SuccessUrl = Parameters.TryGetValue("PSuccessUrl", out IElement E) ? (string)E?.AssociatedObjectValue : null;
61 string FailureUrl = Parameters.TryGetValue("PFailureUrl", out E) ? (string)E?.AssociatedObjectValue : null;
62 string CancelUrl = Parameters.TryGetValue("PCancelUrl", out E) ? (string)E?.AssociatedObjectValue : null;
63 string TransactionIdStr = Parameters.TryGetValue("PTransactionId", out E) ? (string)E?.AssociatedObjectValue : null;
64 string TabId = Parameters.TryGetValue("PTabId", out E) ? (string)E?.AssociatedObjectValue : null;
65 string FunctionName = Parameters.TryGetValue("PFunctionName", out E) ? (string)E?.AssociatedObjectValue : null;
66 Guid TransactionId;
67
68 if (string.IsNullOrEmpty(TransactionIdStr))
69 TransactionId = Guid.NewGuid();
70 else if (!Guid.TryParse(TransactionIdStr, out TransactionId))
71 throw new BadRequestException("Invalid Transaction ID. Must be a GUID.");
72
73 if (Amount <= 0)
74 throw new BadRequestException("Invalid amount.");
75
77 throw new BadRequestException("Invalid currency.");
78
79 if (string.IsNullOrEmpty(ServiceId))
80 throw new BadRequestException("Service ID not defined.");
81
82 if (string.IsNullOrEmpty(ServiceProvider))
83 throw new BadRequestException("Service Provider not defined.");
84
86 ?? throw new NotFoundException("Service Provider " + ServiceProvider + " not found or installed.");
87
88 if (!typeof(IBuyEDalerServiceProvider).IsAssignableFrom(T) ||
90 {
91 throw new BadRequestException("Service Provider does not support buying of eDaler.");
92 }
93
94 IBuyEDalerService Service = await BuyEDalerServiceProvider.GetServiceForBuyingEDaler(ServiceId, Currency, Country)
95 ?? throw new NotFoundException("Payment Service ID not found.");
96
97 if (!await Service.CanBuyEDaler(User.UserName))
98 new ForbiddenException("Selected service provider cannot perform action.");
99
100 if (!CaseInsensitiveString.IsNullOrEmpty(Currency) && Service.Supports(Currency) == Grade.NotAtAll)
101 throw new ForbiddenException("Selected service provider does not support selected currency (" + Currency + ").");
102
103 if (!string.IsNullOrEmpty(Service.BuyEDalerTemplateContractId))
104 throw new ForbiddenException("Service provider requires a signed contract to perform payment. See associated Contract Template ID.");
105
106 EDaler.Wallet Wallet = await XmppServerModule.EDaler.GetWallet(User.UserName, Gateway.Domain);
107 List<NamedDictionary<string, object>> Providers = new List<NamedDictionary<string, object>>();
108
109 Dictionary<CaseInsensitiveString, object> ContractParameters = new Dictionary<CaseInsensitiveString, object>()
110 {
111 { "Amount", Amount },
112 { "Currency", Currency.Value.ToUpper() }
113 };
114 Dictionary<CaseInsensitiveString, CaseInsensitiveString> BuyerIdParameters = new Dictionary<CaseInsensitiveString, CaseInsensitiveString>();
115
116 foreach (Property P in Identity.Properties)
117 BuyerIdParameters[P.Name] = P.Value;
118
119 BuyEDalerTransaction Transaction = PaymentTransactions.Add<BuyEDalerTransaction>(
120 TransactionId, ServiceId, ServiceProvider, Amount, Currency, SuccessUrl,
121 FailureUrl, CancelUrl, TabId, FunctionName, User.UserName, Service,
122 Identity.Id, ContractParameters, BuyerIdParameters);
123
124 if (!await Transaction.Prepare())
125 throw new ServiceUnavailableException("Unable to initialize transaction.");
126
127 await Response.Return(Transaction.GetInformation());
128
129 Task _ = Task.Run(async () =>
130 {
131 try
132 {
133 await Transaction.Process();
134 }
135 catch (Exception ex)
136 {
137 Log.Exception(ex);
138 }
139 });
140
141 }
142 }
143}
Contains information about a service provider that users can use to buy eDaler.
Contains information about a service provider.
string Id
ID of service provider.
Static class managing loading of resources stored as embedded resources or in content files.
Definition: Resources.cs:15
static string LoadResourceAsText(string ResourceName)
Loads a text resource from an embedded resource.
Definition: Resources.cs:96
Static class managing the application event log. Applications and services log events on this static ...
Definition: Log.cs:13
static void Exception(Exception Exception, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, params KeyValuePair< string, object >[] Tags)
Logs an exception. Event type will be determined by the severity of the exception.
Definition: Log.cs:1647
Static class managing the runtime environment of the IoT Gateway.
Definition: Gateway.cs:126
static CaseInsensitiveString Domain
Domain name.
Definition: Gateway.cs:2354
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repe...
The server understood the request, but is refusing to fulfill it. Authorization will not help and the...
Represents an HTTP request.
Definition: HttpRequest.cs:18
Represets a response of an HTTP client request.
Definition: HttpResponse.cs:21
The server has not found anything matching the Request-URI. No indication is given of whether the con...
The server is currently unable to handle the request due to a temporary overloading or maintenance of...
Represents a case-insensitive string.
string Value
String-representation of the case-insensitive string. (Representation is case sensitive....
static bool IsNullOrEmpty(CaseInsensitiveString value)
Indicates whether the specified string is null or an CaseInsensitiveString.Empty string.
Static class that dynamically manages types and interfaces available in the runtime environment.
Definition: Types.cs:14
static Type GetType(string FullName)
Gets a type, given its full name.
Definition: Types.cs:41
static object Instantiate(Type Type, params object[] Arguments)
Returns an instance of the type Type . If one needs to be created, it is. If the constructor requires...
Definition: Types.cs:1353
Class managing a script expression.
Definition: Expression.cs:39
Retains the current balance of an account.
Definition: Wallet.cs:16
Abstract base class for agent resources supporting the POST method.
static AccountUser AssertUserAuthenticated(HttpRequest Request)
Makes sure the request is made by an authenticated API user.
override async Task POST(HttpRequest Request, HttpResponse Response, Dictionary< string, IElement > Parameters)
Executes the POST method on the resource.
Service Module hosting the XMPP broker and its components.
Interface for information about a service provider that users can use to buy eDaler.
string BuyEDalerTemplateContractId
Contract ID of Template, for buying e-Daler
Task< bool > CanBuyEDaler(CaseInsensitiveString AccountName)
If the service provider can be used to process a request to buy eDaler of a certain amount,...
Interface for information about a service provider that users can use to buy eDaler.
Grade Supports(T Object)
If the interface understands objects such as Object .
Basic interface for all types of elements.
Definition: IElement.cs:20
Grade
Grade enumeration
Definition: Grade.cs:7