diff --git a/PAYNLFormsApp/DebugForm.cs b/PAYNLFormsApp/DebugForm.cs index 68a224e..36f729b 100644 --- a/PAYNLFormsApp/DebugForm.cs +++ b/PAYNLFormsApp/DebugForm.cs @@ -31,7 +31,6 @@ private void DebugForm_Load(object sender, EventArgs e) public void dumpPaymentmethods() { - APISettings.InitAPI(); ClearDebug(); PAYNLSDK.API.PaymentMethod.GetAll.Request request = new PAYNLSDK.API.PaymentMethod.GetAll.Request(); InitRequestDebug(request); @@ -41,20 +40,18 @@ public void dumpPaymentmethods() } public void dumpTransactionGetService() - { - APISettings.InitAPI(); + { ClearDebug(); - PAYNLSDK.API.Transaction.GetService.Request request = new PAYNLSDK.API.Transaction.GetService.Request(); + PAYNLSDK.API.Transaction.GetService.Request request = new PAYNLSDK.API.Transaction.GetService.Request(); InitRequestDebug(request); - APISettings.Client.PerformRequest(request); + APISettings.Client.PerformRequest(request); DebugRawResponse(request); - tbMain.Text = request.Response.ToString(); + tbMain.Text = request.Response.ToString(); - } + } public void dumpTransactionGetLast() { - APISettings.InitAPI(); ClearDebug(); PAYNLSDK.API.Transaction.GetLastTransactions.Request request = new PAYNLSDK.API.Transaction.GetLastTransactions.Request(); InitRequestDebug(request); @@ -70,7 +67,6 @@ public void Approve(string transactionID) try { - APISettings.InitAPI(); ClearDebug(); if (transactionID == "") @@ -104,7 +100,6 @@ public void Decline(string transactionID) try { - APISettings.InitAPI(); ClearDebug(); if (transactionID == "") @@ -141,11 +136,10 @@ public void TransactionRefund(string transactionID, string amount, string exchan try { - APISettings.InitAPI(); ClearDebug(); int numValue; - bool parsed = Int32.TryParse(amount, out numValue); + bool parsed = int.TryParse(amount, out numValue); if (!parsed || transactionID == "") { if (!parsed) @@ -163,11 +157,10 @@ public void TransactionRefund(string transactionID, string amount, string exchan else if (exchangeUrl != "") { - APISettings.InitAPI(); AddDebug("-----"); AddDebug("Working with modified version of call"); - PAYNLSDK.API.Transaction.Refund.Response response = Transaction.Refund(transactionID, null, numValue, null, exchangeUrl); + PAYNLSDK.API.Transaction.Refund.Response response = Transaction.Refund(APISettings.Client, transactionID, null, numValue, null, exchangeUrl); tbMain.Text = response.RefundId; } @@ -186,7 +179,7 @@ public void TransactionRefund(string transactionID, string amount, string exchan tbMain.Text = request.Response.RefundId; } - + } catch (ErrorException ee) @@ -202,11 +195,10 @@ public void RefundAdd(string bankAccountName, string bankAccountNumber, string a try { - APISettings.InitAPI(); ClearDebug(); int numValue; - bool parsed = Int32.TryParse(amount, out numValue); + bool parsed = int.TryParse(amount, out numValue); if (!parsed) { @@ -241,7 +233,6 @@ public void TransactionRefundInfo(string refundID) try { - APISettings.InitAPI(); ClearDebug(); PAYNLSDK.API.Refund.Info.Request request = new PAYNLSDK.API.Refund.Info.Request(refundID); @@ -277,14 +268,13 @@ private void AddDebug(string value) } private void InitRequestDebug(RequestBase request) { - APISettings.InitAPI(); AddDebug(string.Format("Calling API {0} / {1}", request.Controller, request.Method)); AddDebug(string.Format("Requires TOKEN? {0}", request.RequiresApiToken)); AddDebug(string.Format("Requires SERVICEID? {0}", request.RequiresServiceId)); AddDebug("-----"); AddDebug("Initializing..."); AddDebug(string.Format("URL : {0}", request.Url)); - AddDebug(string.Format("PARAMS : {0}", request.ToQueryString())); + AddDebug(string.Format("PARAMS : {0}", request.ToQueryString(APISettings.ApiToken, APISettings.ServiceID))); AddDebug("-----"); } private void DebugRawResponse(RequestBase request) diff --git a/PAYNLFormsApp/Fixtures/RefundInfo.cs b/PAYNLFormsApp/Fixtures/RefundInfo.cs index 6573c4b..654d0bb 100644 --- a/PAYNLFormsApp/Fixtures/RefundInfo.cs +++ b/PAYNLFormsApp/Fixtures/RefundInfo.cs @@ -10,14 +10,14 @@ public class TransactionRefundInfo { static public PAYNLSDK.Objects.RefundInfo GetRefundInfoFixture() { - String json = GetJsonFixture(); + string json = GetJsonFixture(); PAYNLSDK.Objects.RefundInfo info = JsonConvert.DeserializeObject(json); return info; } - static public String GetJsonFixture() + static public string GetJsonFixture() { - String json = "{ \"request\": {\"result\": \"1\",\"errorId\": \"\",\"errorMessage\": \"\"},\"refund\": {\"paymentSessionId\": \"915930241\",\"amount\": \"2\",\"description\": \"EX-1234-4567-0000\",\"bankaccountHolder\": \"F. Lastname\",\"bankaccountNumber\": \"NL12RABO0123456789\",\"bankaccountBic\": \"RABONL2U\",\"statusCode\": \"316\",\"statusName\": \"Verwerkt\",\"processedDate\": \"2018-01-22\"},\"refundId\": \"RF-1234-4567-1234\"}"; + string json = "{ \"request\": {\"result\": \"1\",\"errorId\": \"\",\"errorMessage\": \"\"},\"refund\": {\"paymentSessionId\": \"915930241\",\"amount\": \"2\",\"description\": \"EX-1234-4567-0000\",\"bankaccountHolder\": \"F. Lastname\",\"bankaccountNumber\": \"NL12RABO0123456789\",\"bankaccountBic\": \"RABONL2U\",\"statusCode\": \"316\",\"statusName\": \"Verwerkt\",\"processedDate\": \"2018-01-22\"},\"refundId\": \"RF-1234-4567-1234\"}"; return json; } diff --git a/PAYNLFormsApp/Form1.cs b/PAYNLFormsApp/Form1.cs index de45c27..c8753cb 100644 --- a/PAYNLFormsApp/Form1.cs +++ b/PAYNLFormsApp/Form1.cs @@ -57,14 +57,13 @@ private void AddDebug(string value) } private void InitRequestDebug(RequestBase request) { - APISettings.InitAPI(); AddDebug(string.Format("Calling API {0} / {1}", request.Controller, request.Method)); AddDebug(string.Format("Requires TOKEN? {0}", request.RequiresApiToken)); AddDebug(string.Format("Requires SERVICEID? {0}", request.RequiresServiceId)); AddDebug("-----"); AddDebug("Initializing..."); AddDebug(string.Format("URL : {0}", request.Url)); - AddDebug(string.Format("PARAMS : {0}", request.ToQueryString())); + AddDebug(string.Format("PARAMS : {0}", request.ToQueryString(APISettings.ApiToken, APISettings.ServiceID))); AddDebug("-----"); } private void DebugRawResponse(RequestBase request) @@ -93,7 +92,6 @@ private void dumpTransactionGetLastToolStripMenuItem_Click(object sender, EventA private void txinfo(string id) { //619204633Xc4027e - APISettings.InitAPI(); ClearDebug(); PAYNLSDK.API.Transaction.Info.Request request = new PAYNLSDK.API.Transaction.Info.Request(); request.TransactionId = id; @@ -120,59 +118,57 @@ private void xd83303CANCELToolStripMenuItem_Click(object sender, EventArgs e) private void transActionStartToolStripMenuItem_Click(object sender, EventArgs e) { - APISettings.InitAPI(); ClearDebug(); PAYNLSDK.API.Transaction.Start.Request fixture = TransactionStart.GetFixture(); AddDebug("Fixture loaded."); AddDebug("JSON:"); AddDebug(fixture.ToString()); AddDebug("PARAMS:"); - AddDebug(fixture.ToQueryString()); + AddDebug(fixture.ToQueryString(APISettings.ApiToken, APISettings.ServiceID)); AddDebug("-----"); AddDebug("DONE"); } private void transactionStartproductsToolStripMenuItem_Click(object sender, EventArgs e) { - APISettings.InitAPI(); ClearDebug(); PAYNLSDK.API.Transaction.Start.Request fixture = TransactionStart.GetFixtureNoProductLines(); AddDebug("Fixture loaded."); AddDebug("JSON:"); AddDebug(fixture.ToString()); AddDebug("PARAMS:"); - string qs = fixture.ToQueryString(); + string qs = fixture.ToQueryString(APISettings.ApiToken, APISettings.ServiceID); AddDebug(qs); - NameValueCollection nvc = HttpUtility.ParseQueryString(qs); - string json = JsonConvert.SerializeObject(NvcToDictionary(nvc, true)); + var parameters = HttpUtility.ParseQueryString(qs); + // string json = JsonConvert.SerializeObject(parametersToDictionary(parameters, true)); AddDebug("-----"); //AddDebug("PARAMS AS JSON"); //AddDebug(json); - DumpNvc(nvc); + Dumpparameters(parameters); AddDebug("-----"); AddDebug("DONE"); } - void DumpNvc(NameValueCollection nvc) + void Dumpparameters(NameValueCollection parameters) { - foreach (string key in nvc.Keys) + foreach (string key in parameters.Keys) { - string[] values = nvc.GetValues(key); - foreach (string value in nvc.GetValues(key)) + string[] values = parameters.GetValues(key); + foreach (string value in parameters.GetValues(key)) { AddDebug(string.Format("'{0}' : '{1}'", key, value)); } } } - private Dictionary NvcToDictionary(NameValueCollection nvc, bool handleMultipleValuesPerKey) + private Dictionary parametersToDictionary(NameValueCollection parameters, bool handleMultipleValuesPerKey) { var result = new Dictionary(); - foreach (string key in nvc.Keys) + foreach (string key in parameters.Keys) { if (handleMultipleValuesPerKey) { - string[] values = nvc.GetValues(key); + string[] values = parameters.GetValues(key); if (values.Length == 1) { result.Add(key, values[0]); @@ -184,7 +180,7 @@ private Dictionary NvcToDictionary(NameValueCollection nvc, bool } else { - result.Add(key, nvc[key]); + result.Add(key, parameters[key]); } } @@ -195,11 +191,10 @@ private void startuseFixtureToolStripMenuItem_Click(object sender, EventArgs e) { try { - APISettings.InitAPI(); ClearDebug(); PAYNLSDK.API.Transaction.Start.Request fixture = TransactionStart.GetFixtureNoProductLines(); InitRequestDebug(fixture); - DumpNvc(fixture.GetParameters()); + Dumpparameters(fixture.GetParameters(APISettings.ApiToken, APISettings.ServiceID)); APISettings.Client.PerformRequest(fixture); DebugRawResponse(fixture); @@ -235,11 +230,11 @@ private void frm_FormClosed(object sender, FormClosedEventArgs e) AddDebug("CANCELLED!"); return; } - APISettings.InitAPI(); + ClearDebug(); PAYNLSDK.API.Transaction.Start.Request fixture = LastRequests.LastTransactionStart; InitRequestDebug(fixture); - DumpNvc(fixture.GetParameters()); + Dumpparameters(fixture.GetParameters(APISettings.ApiToken, APISettings.ServiceID)); APISettings.Client.PerformRequest(fixture); DebugRawResponse(fixture); @@ -271,11 +266,10 @@ private void paymentProfilesToolStripMenuItem_Click(object sender, EventArgs e) { try { - APISettings.InitAPI(); ClearDebug(); PAYNLSDK.API.PaymentProfile.GetAll.Request fixture = new PAYNLSDK.API.PaymentProfile.GetAll.Request(); InitRequestDebug(fixture); - DumpNvc(fixture.GetParameters()); + Dumpparameters(fixture.GetParameters(APISettings.ApiToken, APISettings.ServiceID)); APISettings.Client.PerformRequest(fixture); DebugRawResponse(fixture); @@ -292,11 +286,10 @@ private void serviceCategoriesToolStripMenuItem_Click(object sender, EventArgs e { try { - APISettings.InitAPI(); ClearDebug(); PAYNLSDK.API.Service.GetCategories.Request fixture = new PAYNLSDK.API.Service.GetCategories.Request(); InitRequestDebug(fixture); - DumpNvc(fixture.GetParameters()); + Dumpparameters(fixture.GetParameters(APISettings.ApiToken, APISettings.ServiceID)); APISettings.Client.PerformRequest(fixture); DebugRawResponse(fixture); @@ -392,11 +385,11 @@ private void testDateTimeConversionToolStripMenuItem_Click(object sender, EventA try { TestYMD testObj = JsonConvert.DeserializeObject(dateString); - AddDebug(String.Format("Converted '{0}' to {1}.", dateString, testObj.DT.ToString())); + AddDebug(string.Format("Converted '{0}' to {1}.", dateString, testObj.DT.ToString())); } catch (Exception e0) { - AddDebug(String.Format("Error converting '{0}' using YMD.", dateString)); + AddDebug(string.Format("Error converting '{0}' using YMD.", dateString)); AddDebug(e0.Message); } } @@ -405,11 +398,11 @@ private void testDateTimeConversionToolStripMenuItem_Click(object sender, EventA try { TestDMY testObj = JsonConvert.DeserializeObject(dateString); - AddDebug(String.Format("Converted '{0}' to {1}.", dateString, testObj.DT.ToString())); + AddDebug(string.Format("Converted '{0}' to {1}.", dateString, testObj.DT.ToString())); } catch (Exception e1) { - AddDebug(String.Format("Error converting '{0}' using YMD.", dateString)); + AddDebug(string.Format("Error converting '{0}' using YMD.", dateString)); AddDebug(e1.Message); } } @@ -418,11 +411,11 @@ private void testDateTimeConversionToolStripMenuItem_Click(object sender, EventA try { TestYMDHIS testObj = JsonConvert.DeserializeObject(dateString); - AddDebug(String.Format("Converted '{0}' to {1}.", dateString, testObj.DT.ToString())); + AddDebug(string.Format("Converted '{0}' to {1}.", dateString, testObj.DT.ToString())); } catch (Exception e2) { - AddDebug(String.Format("Error converting '{0}' using YMD.", dateString)); + AddDebug(string.Format("Error converting '{0}' using YMD.", dateString)); AddDebug(e2.Message); } } @@ -431,42 +424,40 @@ private void testDateTimeConversionToolStripMenuItem_Click(object sender, EventA private void refundtransactionToolStripMenuItem_Click(object sender, EventArgs e) { - APISettings.InitAPI(); ClearDebug(); PAYNLSDK.API.Refund.Transaction.Request fixture = RefundTransaction.GetFixtureNoProductLines(); AddDebug("Fixture loaded."); AddDebug("JSON:"); AddDebug(fixture.ToString()); AddDebug("PARAMS:"); - string qs = fixture.ToQueryString(); + string qs = fixture.ToQueryString(APISettings.ApiToken, APISettings.ServiceID); AddDebug(qs); - NameValueCollection nvc = HttpUtility.ParseQueryString(qs); - string json = JsonConvert.SerializeObject(NvcToDictionary(nvc, true)); + var parameters = HttpUtility.ParseQueryString(qs); + // string json = JsonConvert.SerializeObject(parametersToDictionary(parameters, true)); AddDebug("-----"); //AddDebug("PARAMS AS JSON"); //AddDebug(json); - DumpNvc(nvc); + Dumpparameters(parameters); AddDebug("-----"); AddDebug("DONE"); } private void refundTrasactionProductsToolStripMenuItem_Click(object sender, EventArgs e) { - APISettings.InitAPI(); ClearDebug(); PAYNLSDK.API.Refund.Transaction.Request fixture = RefundTransaction.GetFixture(); AddDebug("Fixture loaded."); AddDebug("JSON:"); AddDebug(fixture.ToString()); AddDebug("PARAMS:"); - string qs = fixture.ToQueryString(); + string qs = fixture.ToQueryString(APISettings.ApiToken, APISettings.ServiceID); AddDebug(qs); - NameValueCollection nvc = HttpUtility.ParseQueryString(qs); - string json = JsonConvert.SerializeObject(NvcToDictionary(nvc, true)); + var parameters = HttpUtility.ParseQueryString(qs); + // string json = JsonConvert.SerializeObject(parametersToDictionary(parameters, true)); AddDebug("-----"); //AddDebug("PARAMS AS JSON"); //AddDebug(json); - DumpNvc(nvc); + Dumpparameters(parameters); AddDebug("-----"); AddDebug("DONE"); } @@ -474,7 +465,7 @@ private void refundTrasactionProductsToolStripMenuItem_Click(object sender, Even private void transactionRefundInofromJsonFixtureToolStripMenuItem_Click(object sender, EventArgs e) { ClearDebug(); - String json = TransactionRefundInfo.GetJsonFixture(); + string json = TransactionRefundInfo.GetJsonFixture(); PAYNLSDK.Objects.RefundInfo fixture = TransactionRefundInfo.GetRefundInfoFixture(); AddDebug("Fixture loaded."); AddDebug("JSON:"); diff --git a/PAYNLFormsApp/Program.cs b/PAYNLFormsApp/Program.cs index 6cfff47..0edf3c3 100644 --- a/PAYNLFormsApp/Program.cs +++ b/PAYNLFormsApp/Program.cs @@ -30,22 +30,14 @@ class APISettings public static string ApiToken { get; set; } public static string ServiceID { get; set; } - public static void InitAPI() - { - RequestBase.ApiToken = ApiToken; - RequestBase.ServiceId = ServiceID; - } - private static IClient client; public static IClient Client { get { if (client == null) - { - client = new Client(); - } - InitAPI(); + client = new Client(ApiToken, ServiceID); + return client; } } diff --git a/PAYNLFormsApp/StartTransaction.cs b/PAYNLFormsApp/StartTransaction.cs index 56de8c2..b409213 100644 --- a/PAYNLFormsApp/StartTransaction.cs +++ b/PAYNLFormsApp/StartTransaction.cs @@ -47,11 +47,11 @@ private void StartTransaction_Load(object sender, EventArgs e) void Set() { // load - LastRequests.LastTransactionStart.Amount = Int32.Parse(tbAmount.Text); + LastRequests.LastTransactionStart.Amount = int.Parse(tbAmount.Text); LastRequests.LastTransactionStart.IPAddress = tbIP.Text; LastRequests.LastTransactionStart.ReturnUrl = tbReturn.Text; LastRequests.LastTransactionStart.Transaction.OrderExchangeUrl = tbExchange.Text; - LastRequests.LastTransactionStart.PaymentOptionId = Int32.Parse(tbPaymentOption.Text); + LastRequests.LastTransactionStart.PaymentOptionId = int.Parse(tbPaymentOption.Text); LastRequests.LastTransactionStart.Transaction.Description = tbDesc.Text; LastRequests.LastTransactionStart.Enduser.Language = tbUserlang.Text; @@ -66,11 +66,13 @@ void Set() private void button1_Click(object sender, EventArgs e) { - try { + try + { Set(); OK = true; } - catch { + catch + { } Close(); } diff --git a/PAYNLSDK.sln b/PAYNLSDK.sln index 64ed9a5..5f8a085 100644 --- a/PAYNLSDK.sln +++ b/PAYNLSDK.sln @@ -5,7 +5,7 @@ VisualStudioVersion = 15.0.26124.0 MinimumVisualStudioVersion = 15.0.26124.0 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PAYNLSDK", "PAYNLSDK\PAYNLSDK.csproj", "{AFA4C5D6-CA5F-4365-9D9C-38173BED16F7}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PAYNLFormsCoreApp", "PAYNLFormsCoreApp\PAYNLFormsCoreApp.csproj", "{5C1835C9-580C-4B0E-A9D0-E5A6E6E31AD4}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PAYNLFormsApp", "PAYNLFormsApp\PAYNLFormsApp.csproj", "{509C5CD8-87CE-4A46-AA5D-50CFE8040C3D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -32,17 +32,17 @@ Global {AFA4C5D6-CA5F-4365-9D9C-38173BED16F7}.Release|x64.Build.0 = Release|Any CPU {AFA4C5D6-CA5F-4365-9D9C-38173BED16F7}.Release|x86.ActiveCfg = Release|Any CPU {AFA4C5D6-CA5F-4365-9D9C-38173BED16F7}.Release|x86.Build.0 = Release|Any CPU - {5C1835C9-580C-4B0E-A9D0-E5A6E6E31AD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5C1835C9-580C-4B0E-A9D0-E5A6E6E31AD4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5C1835C9-580C-4B0E-A9D0-E5A6E6E31AD4}.Debug|x64.ActiveCfg = Debug|Any CPU - {5C1835C9-580C-4B0E-A9D0-E5A6E6E31AD4}.Debug|x64.Build.0 = Debug|Any CPU - {5C1835C9-580C-4B0E-A9D0-E5A6E6E31AD4}.Debug|x86.ActiveCfg = Debug|Any CPU - {5C1835C9-580C-4B0E-A9D0-E5A6E6E31AD4}.Debug|x86.Build.0 = Debug|Any CPU - {5C1835C9-580C-4B0E-A9D0-E5A6E6E31AD4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5C1835C9-580C-4B0E-A9D0-E5A6E6E31AD4}.Release|Any CPU.Build.0 = Release|Any CPU - {5C1835C9-580C-4B0E-A9D0-E5A6E6E31AD4}.Release|x64.ActiveCfg = Release|Any CPU - {5C1835C9-580C-4B0E-A9D0-E5A6E6E31AD4}.Release|x64.Build.0 = Release|Any CPU - {5C1835C9-580C-4B0E-A9D0-E5A6E6E31AD4}.Release|x86.ActiveCfg = Release|Any CPU - {5C1835C9-580C-4B0E-A9D0-E5A6E6E31AD4}.Release|x86.Build.0 = Release|Any CPU + {509C5CD8-87CE-4A46-AA5D-50CFE8040C3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {509C5CD8-87CE-4A46-AA5D-50CFE8040C3D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {509C5CD8-87CE-4A46-AA5D-50CFE8040C3D}.Debug|x64.ActiveCfg = Debug|Any CPU + {509C5CD8-87CE-4A46-AA5D-50CFE8040C3D}.Debug|x64.Build.0 = Debug|Any CPU + {509C5CD8-87CE-4A46-AA5D-50CFE8040C3D}.Debug|x86.ActiveCfg = Debug|Any CPU + {509C5CD8-87CE-4A46-AA5D-50CFE8040C3D}.Debug|x86.Build.0 = Debug|Any CPU + {509C5CD8-87CE-4A46-AA5D-50CFE8040C3D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {509C5CD8-87CE-4A46-AA5D-50CFE8040C3D}.Release|Any CPU.Build.0 = Release|Any CPU + {509C5CD8-87CE-4A46-AA5D-50CFE8040C3D}.Release|x64.ActiveCfg = Release|Any CPU + {509C5CD8-87CE-4A46-AA5D-50CFE8040C3D}.Release|x64.Build.0 = Release|Any CPU + {509C5CD8-87CE-4A46-AA5D-50CFE8040C3D}.Release|x86.ActiveCfg = Release|Any CPU + {509C5CD8-87CE-4A46-AA5D-50CFE8040C3D}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/PAYNLSDK/API/Banktransfer/Add/Request.cs b/PAYNLSDK/API/Banktransfer/Add/Request.cs index 437465b..aab46da 100644 --- a/PAYNLSDK/API/Banktransfer/Add/Request.cs +++ b/PAYNLSDK/API/Banktransfer/Add/Request.cs @@ -1,9 +1,10 @@ using System; -using Newtonsoft.Json; -using PAYNLSDK.Utilities; using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; -using PAYNLSDK.Objects; +using PAYNLSDK.Utilities; namespace PAYNLSDK.API.Banktransfer.Add { @@ -15,54 +16,54 @@ public Request(int amount, string bankAccountHolder, string bankAccountNumber, s this.BankAccountHolder = bankAccountHolder; this.BankAccountNumber = bankAccountNumber; this.BankAccountBic = bankAccountBic; - } - - /// - /// The amount to be paid should be given in cents. For example € 3.50 becomes 350. - /// - public int Amount { get; set; } - - /// - /// The name of the customer. - /// - public string BankAccountHolder { get; set; } - - /// - /// The bankaccount number of the customer. - /// - public string BankAccountNumber { get; set; } - - /// - /// The BIC of the bank. - /// - public string BankAccountBic { get; set; } - - /// - /// The description to include with the payment. - /// - public string Description { get; set; } - - /// + } + + /// + /// The amount to be paid should be given in cents. For example € 3.50 becomes 350. + /// + public int Amount { get; set; } + + /// + /// The name of the customer. + /// + public string BankAccountHolder { get; set; } + + /// + /// The bankaccount number of the customer. + /// + public string BankAccountNumber { get; set; } + + /// + /// The BIC of the bank. + /// + public string BankAccountBic { get; set; } + + /// + /// The description to include with the payment. + /// + public string Description { get; set; } + + /// /// The id of a promotor / affiliate. /// In general, you won't use this unless you know the ID's of your affiliate's /// - public int? PromotorId { get; set; } - - /// - /// The used tool code. - /// + public int? PromotorId { get; set; } + + /// + /// The used tool code. + /// public string Tool { get; set; } /// /// The used info code which can be tracked in the stats /// - public string Info { get; set; } - + public string Info { get; set; } + /// /// The used object. /// - public string Object { get; set; } - + public string Object { get; set; } + /// /// The first free value which can be tracked in the stats /// @@ -76,13 +77,13 @@ public Request(int amount, string bankAccountHolder, string bankAccountNumber, s /// /// The third free value which can be tracked in the stats /// - public string Extra3 { get; set; } - + public string Extra3 { get; set; } + /// /// The currency of the amount, default is EUR. /// - public string Currency { get; set; } - + public string Currency { get; set; } + /// /// The currency of the amount, default is EUR. /// @@ -106,94 +107,68 @@ public override string Method public override string Querystring { get { return ""; } - } - + } + public override bool RequiresApiToken { - get - { - - - return true; - } + get { return true; } } public override bool RequiresServiceId { - get - { - return true; - } + get { return true; } } - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotNull(Amount, "Amount"); - nvc.Add("amount", Amount.ToString()); - + parameters.Add("amount", Amount.ToString()); + ParameterValidator.IsNotNull(BankAccountHolder, "BankAccountHolder"); - nvc.Add("bankAccountHolder", BankAccountHolder); - + parameters.Add("bankAccountHolder", BankAccountHolder); + ParameterValidator.IsNotNull(BankAccountNumber, "BankAccountNumber"); - nvc.Add("bankAccountNumber", BankAccountNumber); - + parameters.Add("bankAccountNumber", BankAccountNumber); + ParameterValidator.IsNotNull(BankAccountBic, "BankAccountBic"); - nvc.Add("bankAccountBic", BankAccountBic); - - if (!ParameterValidator.IsEmpty(Description)) - { - nvc.Add("description", Description); - } - - if (!ParameterValidator.IsNonEmptyInt(PromotorId)) - { - nvc.Add("promotorId", PromotorId.Value.ToString()); - } - - if (!ParameterValidator.IsEmpty(Tool)) - { - nvc.Add("tool", Tool); - } - - if (!ParameterValidator.IsEmpty(Info)) - { - nvc.Add("info", Info); - } - - if (!ParameterValidator.IsEmpty(Object)) - { - nvc.Add("object", Object); - } - - if (!ParameterValidator.IsEmpty(Extra1)) - { - nvc.Add("extra1", Extra1); - } - if (!ParameterValidator.IsEmpty(Extra2)) - { - nvc.Add("extra2", Extra2); - } - if (!ParameterValidator.IsEmpty(Extra3)) - { - nvc.Add("extra3", Extra3); - } - - if (!ParameterValidator.IsEmpty(Currency)) - { - nvc.Add("currency", Currency); - } - - if (this.ProcessDate.HasValue) - { - nvc.Add("processDate", this.ProcessDate.Value.ToString("yyyy-MM-dd")); - } + parameters.Add("bankAccountBic", BankAccountBic); - return nvc; - } - - public override void SetResponse() - { + if (!ParameterValidator.IsEmpty(Description)) + parameters.Add("description", Description); + + if (!ParameterValidator.IsNonEmptyInt(PromotorId)) + parameters.Add("promotorId", PromotorId.Value.ToString()); + + if (!ParameterValidator.IsEmpty(Tool)) + parameters.Add("tool", Tool); + + if (!ParameterValidator.IsEmpty(Info)) + parameters.Add("info", Info); + + if (!ParameterValidator.IsEmpty(Object)) + parameters.Add("object", Object); + + if (!ParameterValidator.IsEmpty(Extra1)) + parameters.Add("extra1", Extra1); + + if (!ParameterValidator.IsEmpty(Extra2)) + parameters.Add("extra2", Extra2); + + if (!ParameterValidator.IsEmpty(Extra3)) + parameters.Add("extra3", Extra3); + + if (!ParameterValidator.IsEmpty(Currency)) + parameters.Add("currency", Currency); + + if (ProcessDate.HasValue) + parameters.Add("processDate", this.ProcessDate.Value.ToString("yyyy-MM-dd")); + + return parameters; + } + + public override void SetResponse() + { if (ParameterValidator.IsEmpty(rawResponse)) { throw new ErrorException("rawResponse is empty!"); @@ -203,9 +178,9 @@ public override void SetResponse() { // toss throw new ErrorException(Response.Request.Message); - } - } - + } + } + public Response Response { get { return (Response)response; } } } } diff --git a/PAYNLSDK/API/PaymentMethod/Get/Request.cs b/PAYNLSDK/API/PaymentMethod/Get/Request.cs index 50941b0..03d1f41 100644 --- a/PAYNLSDK/API/PaymentMethod/Get/Request.cs +++ b/PAYNLSDK/API/PaymentMethod/Get/Request.cs @@ -1,8 +1,9 @@ -using System; +using System.Collections.Specialized; + using Newtonsoft.Json; -using PAYNLSDK.Utilities; -using System.Collections.Specialized; + using PAYNLSDK.Exceptions; +using PAYNLSDK.Utilities; namespace PAYNLSDK.API.PaymentMethod.Get { @@ -31,14 +32,14 @@ public override string Querystring get { return ""; } } - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotNull(PaymentMethodId, "PaymentMethodId"); - nvc.Add("paymentMethodId", PaymentMethodId.ToString()); + parameters.Add("paymentMethodId", PaymentMethodId.ToString()); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } @@ -47,13 +48,12 @@ public override System.Collections.Specialized.NameValueCollection GetParameters public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } - PAYNLSDK.Objects.PaymentMethod pm = JsonConvert.DeserializeObject(RawResponse); - Response r = new Response(); - r.PaymentMethod = pm; - response = r; + + response = new Response + { + PaymentMethod = JsonConvert.DeserializeObject(RawResponse) + }; } } } diff --git a/PAYNLSDK/API/PaymentMethod/GetAll/Request.cs b/PAYNLSDK/API/PaymentMethod/GetAll/Request.cs index 7fefe66..3a35cc9 100644 --- a/PAYNLSDK/API/PaymentMethod/GetAll/Request.cs +++ b/PAYNLSDK/API/PaymentMethod/GetAll/Request.cs @@ -1,7 +1,6 @@ -using System; -using Newtonsoft.Json; +using Newtonsoft.Json; + using PAYNLSDK.Utilities; -using System.Collections.Specialized; using PAYNLSDK.Exceptions; namespace PAYNLSDK.API.PaymentMethod.GetAll @@ -33,13 +32,12 @@ public override string Querystring public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } - PAYNLSDK.Objects.PaymentMethod[] pm = JsonConvert.DeserializeObject(RawResponse); - Response r = new Response(); - r.PaymentMethods = pm; - response = r; + + response = new Response + { + PaymentMethods = JsonConvert.DeserializeObject(RawResponse) + }; } } } diff --git a/PAYNLSDK/API/PaymentProfile/Get/Request.cs b/PAYNLSDK/API/PaymentProfile/Get/Request.cs index 5089b27..77c1494 100644 --- a/PAYNLSDK/API/PaymentProfile/Get/Request.cs +++ b/PAYNLSDK/API/PaymentProfile/Get/Request.cs @@ -1,8 +1,9 @@ -using System; +using System.Collections.Specialized; + using Newtonsoft.Json; -using PAYNLSDK.Utilities; -using System.Collections.Specialized; + using PAYNLSDK.Exceptions; +using PAYNLSDK.Utilities; namespace PAYNLSDK.API.PaymentProfile.Get { @@ -31,29 +32,27 @@ public override string Querystring get { return ""; } } - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotNull(PaymentProfileId, "PaymentProfileId"); - nvc.Add("paymentProfileId", PaymentProfileId.ToString()); + parameters.Add("paymentProfileId", PaymentProfileId.ToString()); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } - public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } - PAYNLSDK.Objects.PaymentProfile pm = JsonConvert.DeserializeObject(RawResponse); - Response r = new Response(); - r.PaymentProfile = pm; - response = r; + + response = new Response + { + PaymentProfile = JsonConvert.DeserializeObject(RawResponse) + }; } } } diff --git a/PAYNLSDK/API/PaymentProfile/GetAll/Request.cs b/PAYNLSDK/API/PaymentProfile/GetAll/Request.cs index 9a46ab3..7902fd1 100644 --- a/PAYNLSDK/API/PaymentProfile/GetAll/Request.cs +++ b/PAYNLSDK/API/PaymentProfile/GetAll/Request.cs @@ -1,8 +1,7 @@ -using System; -using Newtonsoft.Json; -using PAYNLSDK.Utilities; -using System.Collections.Specialized; +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; +using PAYNLSDK.Utilities; namespace PAYNLSDK.API.PaymentProfile.GetAll { @@ -33,13 +32,12 @@ public override string Querystring public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } - PAYNLSDK.Objects.PaymentProfile[] pm = JsonConvert.DeserializeObject(RawResponse); - Response r = new Response(); - r.PaymentProfiles = pm; - response = r; + + response = new Response + { + PaymentProfiles = JsonConvert.DeserializeObject(RawResponse) + }; } } } diff --git a/PAYNLSDK/API/PaymentProfile/GetAvailable/Request.cs b/PAYNLSDK/API/PaymentProfile/GetAvailable/Request.cs index 27fd29d..cc9280d 100644 --- a/PAYNLSDK/API/PaymentProfile/GetAvailable/Request.cs +++ b/PAYNLSDK/API/PaymentProfile/GetAvailable/Request.cs @@ -1,9 +1,10 @@ -using System; +using System.Collections.Specialized; + using Newtonsoft.Json; -using PAYNLSDK.Utilities; -using System.Collections.Specialized; + using PAYNLSDK.Converters; using PAYNLSDK.Exceptions; +using PAYNLSDK.Utilities; namespace PAYNLSDK.API.PaymentProfile.GetAvailable { @@ -18,7 +19,7 @@ public class Request : RequestBase [JsonProperty("paymentMethodId")] public int? PaymentMethodId { get; set; } - [JsonProperty("showNotAllowedOnRegistration"),JsonConverter(typeof(BooleanConverter))] + [JsonProperty("showNotAllowedOnRegistration"), JsonConverter(typeof(BooleanConverter))] public bool? ShowNotAllowedOnRegistration { get; set; } public override int Version @@ -41,29 +42,23 @@ public override string Querystring get { return ""; } } - public override NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotNull(CategoryId, "CategoryId"); - nvc.Add("categoryId", CategoryId.ToString()); + parameters.Add("categoryId", CategoryId.ToString()); if (!ParameterValidator.IsNonEmptyInt(ProgramId)) - { - nvc.Add("programId", ProgramId.ToString()); - } + parameters.Add("programId", ProgramId.ToString()); if (!ParameterValidator.IsNonEmptyInt(PaymentMethodId)) - { - nvc.Add("paymentMethodId", PaymentMethodId.ToString()); - } + parameters.Add("paymentMethodId", PaymentMethodId.ToString()); if (!ParameterValidator.IsNull(ShowNotAllowedOnRegistration)) - { - nvc.Add("ShowNotAllowedOnRegistration", ((bool)ShowNotAllowedOnRegistration) ? "1" : "0" ); - } + parameters.Add("ShowNotAllowedOnRegistration", ((bool)ShowNotAllowedOnRegistration) ? "1" : "0"); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } @@ -71,13 +66,12 @@ public override NameValueCollection GetParameters() public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } - PAYNLSDK.Objects.PaymentProfile[] pm = JsonConvert.DeserializeObject(RawResponse); - Response r = new Response(); - r.PaymentProfiles = pm; - response = r; + + response = new Response + { + PaymentProfiles = JsonConvert.DeserializeObject(RawResponse) + }; } } } diff --git a/PAYNLSDK/API/Refund/Add/Request.cs b/PAYNLSDK/API/Refund/Add/Request.cs index 012eb71..809f3b5 100644 --- a/PAYNLSDK/API/Refund/Add/Request.cs +++ b/PAYNLSDK/API/Refund/Add/Request.cs @@ -1,9 +1,10 @@ using System; -using Newtonsoft.Json; -using PAYNLSDK.Utilities; using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; -using PAYNLSDK.Objects; +using PAYNLSDK.Utilities; namespace PAYNLSDK.API.Refund.Add { @@ -26,7 +27,7 @@ public Request(int amount, string bankAccountHolder, string bankAccountNumber, s this.BankAccountNumber = bankAccountNumber; this.BankAccountBic = bankAccountBic; } - + /// /// The amount to be paid should be given in cents. For example € 3.50 becomes 350. /// @@ -103,7 +104,7 @@ public Request(int amount, string bankAccountHolder, string bankAccountNumber, s /// public DateTime? ProcessDate { get; set; } -/* overrides */ + /* overrides */ /// /// /// @@ -141,98 +142,70 @@ public override string Querystring /// public override bool RequiresApiToken { - get - { - - - return true; - } + get { return true; } } /// /// /// public override bool RequiresServiceId { - get - { - return true; - } + get { return true; } } /// /// /// /// - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotNull(Amount, "Amount"); - nvc.Add("amount", Amount.ToString()); + parameters.Add("amount", Amount.ToString()); ParameterValidator.IsNotNull(BankAccountHolder, "BankAccountHolder"); - nvc.Add("bankAccountHolder", BankAccountHolder); + parameters.Add("bankAccountHolder", BankAccountHolder); ParameterValidator.IsNotNull(BankAccountNumber, "BankAccountNumber"); - nvc.Add("bankAccountNumber", BankAccountNumber); + parameters.Add("bankAccountNumber", BankAccountNumber); ParameterValidator.IsNotNull(BankAccountBic, "BankAccountBic"); - nvc.Add("bankAccountBic", BankAccountBic); + parameters.Add("bankAccountBic", BankAccountBic); if (!ParameterValidator.IsEmpty(Description)) - { - nvc.Add("description", Description); - } + parameters.Add("description", Description); if (!ParameterValidator.IsNonEmptyInt(PromotorId)) - { - nvc.Add("promotorId", PromotorId.Value.ToString()); - } + parameters.Add("promotorId", PromotorId.Value.ToString()); if (!ParameterValidator.IsEmpty(Tool)) - { - nvc.Add("tool", Tool); - } + parameters.Add("tool", Tool); if (!ParameterValidator.IsEmpty(Info)) - { - nvc.Add("info", Info); - } + parameters.Add("info", Info); if (!ParameterValidator.IsEmpty(Object)) - { - nvc.Add("object", Object); - } + parameters.Add("object", Object); if (!ParameterValidator.IsEmpty(Extra1)) - { - nvc.Add("extra1", Extra1); - } + parameters.Add("extra1", Extra1); + if (!ParameterValidator.IsEmpty(Extra2)) - { - nvc.Add("extra2", Extra2); - } + parameters.Add("extra2", Extra2); + if (!ParameterValidator.IsEmpty(Extra3)) - { - nvc.Add("extra3", Extra3); - } + parameters.Add("extra3", Extra3); if (!ParameterValidator.IsEmpty(Currency)) - { - nvc.Add("currency", Currency); - } + parameters.Add("currency", Currency); if (!ParameterValidator.IsEmpty(OrderId)) - { - nvc.Add("orderId", OrderId); - } + parameters.Add("orderId", OrderId); - if (this.ProcessDate.HasValue) - { - nvc.Add("processDate", this.ProcessDate.Value.ToString("yyyy-MM-dd")); - } + if (ProcessDate.HasValue) + parameters.Add("processDate", ProcessDate.Value.ToString("yyyy-MM-dd")); - return nvc; + return parameters; } /// @@ -241,15 +214,12 @@ public override System.Collections.Specialized.NameValueCollection GetParameters public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); + if (!Response.Request.Result) - { - // toss throw new ErrorException(Response.Request.Message); - } } /// diff --git a/PAYNLSDK/API/Refund/Info/Request.cs b/PAYNLSDK/API/Refund/Info/Request.cs index b8cb1e5..75953e1 100644 --- a/PAYNLSDK/API/Refund/Info/Request.cs +++ b/PAYNLSDK/API/Refund/Info/Request.cs @@ -1,9 +1,9 @@ -using System; +using System.Collections.Specialized; + using Newtonsoft.Json; -using PAYNLSDK.Utilities; -using System.Collections.Specialized; + using PAYNLSDK.Exceptions; -using PAYNLSDK.Objects; +using PAYNLSDK.Utilities; namespace PAYNLSDK.API.Refund.Info { @@ -64,34 +64,28 @@ public override string Querystring /// public override bool RequiresApiToken { - get - { - return true; - } + get { return true; } } /// /// /// public override bool RequiresServiceId { - get - { - return true; - } + get { return true; } } /// /// /// /// - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotNull(RefundId, "RefundId"); - nvc.Add("refundId", RefundId); + parameters.Add("refundId", RefundId); - return nvc; + return parameters; } /// @@ -100,15 +94,12 @@ public override System.Collections.Specialized.NameValueCollection GetParameters public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); + if (!Response.Request.Result) - { - // toss throw new ErrorException(Response.Request.Message); - } } /// diff --git a/PAYNLSDK/API/Refund/Transaction/Request.cs b/PAYNLSDK/API/Refund/Transaction/Request.cs index c1fdcd5..d8baf42 100644 --- a/PAYNLSDK/API/Refund/Transaction/Request.cs +++ b/PAYNLSDK/API/Refund/Transaction/Request.cs @@ -1,11 +1,12 @@ using System; -using Newtonsoft.Json; -using PAYNLSDK.Utilities; +using System.Collections.Generic; using System.Collections.Specialized; -using PAYNLSDK.Exceptions; -using PAYNLSDK.Objects; + +using Newtonsoft.Json; + using PAYNLSDK.Converters; -using System.Collections.Generic; +using PAYNLSDK.Exceptions; +using PAYNLSDK.Utilities; namespace PAYNLSDK.API.Refund.Transaction { @@ -68,13 +69,9 @@ public Request(string transactionId) public void AddProduct(string productId, int amount) { if (Products.ContainsKey(productId)) - { Products[productId] += amount; - } else - { Products[productId] = amount; - } } /* overrides */ @@ -115,59 +112,43 @@ public override string Querystring /// public override bool RequiresApiToken { - get - { - return true; - } + get { return true; } } /// /// /// public override bool RequiresServiceId { - get - { - return true; - } + get { return true; } } /// /// /// /// - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotNull(TransactionId, "TransactionId"); - nvc.Add("transactionId", TransactionId.ToString()); + parameters.Add("transactionId", TransactionId.ToString()); if (ParameterValidator.IsNonEmptyInt(Amount)) - { - nvc.Add("amount", Amount.Value.ToString()); - } + parameters.Add("amount", Amount.Value.ToString()); if (!ParameterValidator.IsEmpty(Description)) - { - nvc.Add("description", Description); - } + parameters.Add("description", Description); - if (this.ProcessDate.HasValue) - { - nvc.Add("processDate", this.ProcessDate.Value.ToString("yyyy-MM-dd")); - } + if (ProcessDate.HasValue) + parameters.Add("processDate", ProcessDate.Value.ToString("yyyy-MM-dd")); if (Products.Count > 0) - { - nvc.Add("products", JsonConvert.SerializeObject(Products)); - } + parameters.Add("products", JsonConvert.SerializeObject(Products)); if (!ParameterValidator.IsEmpty(ExchangeUrl)) - { - nvc.Add("exchangeUrl", ExchangeUrl); - } + parameters.Add("exchangeUrl", ExchangeUrl); - return nvc; + return parameters; } /// @@ -176,15 +157,12 @@ public override System.Collections.Specialized.NameValueCollection GetParameters public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); + if (!Response.Request.Result) - { - // toss throw new ErrorException(Response.Request.Message); - } } /// @@ -192,26 +170,24 @@ public override void SetResponse() /// public Response Response { get { return (Response)response; } } - private static Dictionary NvcToDictionary(NameValueCollection nvc, bool handleMultipleValuesPerKey) + private static Dictionary NvcToDictionary(NameValueCollection parameters, bool handleMultipleValuesPerKey) { var result = new Dictionary(); - foreach (string key in nvc.Keys) + + foreach (string key in parameters.Keys) { if (handleMultipleValuesPerKey) { - string[] values = nvc.GetValues(key); + string[] values = parameters.GetValues(key); + if (values.Length == 1) - { result.Add(key, values[0]); - } else - { result.Add(key, values); - } } else { - result.Add(key, nvc[key]); + result.Add(key, parameters[key]); } } diff --git a/PAYNLSDK/API/RequestBase.cs b/PAYNLSDK/API/RequestBase.cs index 621062e..3871db2 100644 --- a/PAYNLSDK/API/RequestBase.cs +++ b/PAYNLSDK/API/RequestBase.cs @@ -1,4 +1,5 @@ using Newtonsoft.Json; +using PAYNLSDK.Net; using PAYNLSDK.Utilities; using System; using System.Collections.Specialized; @@ -18,16 +19,6 @@ public abstract class RequestBase /// public virtual bool RequiresServiceId { get { return false; } } - /// - /// PAYNL API TOKEN - /// - public static string ApiToken { get; set; } - - /// - /// PAYNL Service ID - /// - public static string ServiceId { get; set; } - /// /// Return as JSON /// @@ -70,47 +61,48 @@ public string Url /// Returns a NameValueCollection of all paramaters used for this call. /// /// Name Value collection of parameters - public virtual NameValueCollection GetParameters() + public virtual NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = new NameValueCollection(); + var parameters = new NameValueCollection(); + if (RequiresApiToken) { - ParameterValidator.IsNotEmpty(ApiToken, "ApiToken"); - nvc.Add("token", ApiToken); + ParameterValidator.IsNotEmpty(apiToken, "ApiToken"); + parameters.Add("token", apiToken); } + if (RequiresServiceId) { - ParameterValidator.IsNotEmpty(ServiceId, "ServiceId"); - nvc.Add("serviceId", ServiceId); + ParameterValidator.IsNotEmpty(serviceId, "ServiceId"); + parameters.Add("serviceId", serviceId); } - return nvc; + return parameters; } + /// /// Transform NameValueCollection to a querystring /// /// appendable querystring - public string ToQueryString() + public string ToQueryString(string apiToken, string serviceId = null) { - NameValueCollection nvc = GetParameters(); - if (nvc.Count == 0) - { + var parameters = GetParameters(apiToken, serviceId); + + if (parameters.Count == 0) return ""; - } - StringBuilder sb = new StringBuilder(); + + var sb = new StringBuilder(); // TODO: add "?" if GET? - bool first = true; + var first = true; - foreach (string key in nvc.AllKeys) + foreach (string key in parameters.AllKeys) { - foreach (string value in nvc.GetValues(key)) + foreach (string value in parameters.GetValues(key)) { if (!first) - { sb.Append("&"); - } sb.AppendFormat("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value)); @@ -136,9 +128,9 @@ public string ToQueryString() /// public string RawResponse { - get + get { - return rawResponse; + return rawResponse; } set { diff --git a/PAYNLSDK/API/SMS/BulkMessage/Request.cs b/PAYNLSDK/API/SMS/BulkMessage/Request.cs index f0f97b8..6b56bd9 100644 --- a/PAYNLSDK/API/SMS/BulkMessage/Request.cs +++ b/PAYNLSDK/API/SMS/BulkMessage/Request.cs @@ -1,12 +1,9 @@ -using Newtonsoft.Json; +using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; using PAYNLSDK.Utilities; -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace PAYNLSDK.API.SMS.BulkMessage { @@ -44,29 +41,28 @@ public override string Querystring get { return ""; } } - public override NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotEmpty(Sender, "Sender"); - nvc.Add("org", Sender); + parameters.Add("org", Sender); ParameterValidator.IsNotEmpty(Recipient, "Recipient"); - nvc.Add("dest", Recipient); + parameters.Add("dest", Recipient); ParameterValidator.IsNotEmpty(Message, "Message"); - nvc.Add("body", Message); + parameters.Add("body", Message); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } } diff --git a/PAYNLSDK/API/SMS/BulkMessage/Response.cs b/PAYNLSDK/API/SMS/BulkMessage/Response.cs index f2304e8..1942051 100644 --- a/PAYNLSDK/API/SMS/BulkMessage/Response.cs +++ b/PAYNLSDK/API/SMS/BulkMessage/Response.cs @@ -1,16 +1,12 @@ using Newtonsoft.Json; + using PAYNLSDK.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace PAYNLSDK.API.SMS.BulkMessage { public class Response : ResponseBase { - [JsonProperty("result"),JsonConverter(typeof(BooleanConverter))] - public bool result { get; protected set; } + [JsonProperty("result"), JsonConverter(typeof(BooleanConverter))] + public bool Result { get; protected set; } } } diff --git a/PAYNLSDK/API/SMS/PremiumMessage/Request.cs b/PAYNLSDK/API/SMS/PremiumMessage/Request.cs index b393968..0501f03 100644 --- a/PAYNLSDK/API/SMS/PremiumMessage/Request.cs +++ b/PAYNLSDK/API/SMS/PremiumMessage/Request.cs @@ -1,12 +1,9 @@ -using Newtonsoft.Json; +using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; using PAYNLSDK.Utilities; -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace PAYNLSDK.API.SMS.PremiumMessage { @@ -42,31 +39,29 @@ public override string Querystring get { return ""; } } - public override NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotEmpty(SmsId, "SmsId"); - nvc.Add("sms_id", SmsId); + parameters.Add("sms_id", SmsId); ParameterValidator.IsNotEmpty(Secret, "secret"); - nvc.Add("secret", Secret); + parameters.Add("secret", Secret); ParameterValidator.IsNotEmpty(Message, "message"); - nvc.Add("message", Message); + parameters.Add("message", Message); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } - } } diff --git a/PAYNLSDK/API/SMS/PremiumMessage/Response.cs b/PAYNLSDK/API/SMS/PremiumMessage/Response.cs index c354f8d..e39fee5 100644 --- a/PAYNLSDK/API/SMS/PremiumMessage/Response.cs +++ b/PAYNLSDK/API/SMS/PremiumMessage/Response.cs @@ -7,6 +7,6 @@ namespace PAYNLSDK.API.SMS.PremiumMessage public class Response : ResponseBase { [JsonProperty("result"), JsonConverter(typeof(BooleanConverter))] - public bool result { get; protected set; } + public bool Result { get; protected set; } } } diff --git a/PAYNLSDK/API/Service/GetCategories/Request.cs b/PAYNLSDK/API/Service/GetCategories/Request.cs index 6bdd5bd..4bb77fe 100644 --- a/PAYNLSDK/API/Service/GetCategories/Request.cs +++ b/PAYNLSDK/API/Service/GetCategories/Request.cs @@ -1,9 +1,10 @@ -using System; +using System.Collections.Specialized; + using Newtonsoft.Json; -using PAYNLSDK.Utilities; -using System.Collections.Specialized; -using PAYNLSDK.Converters; + using PAYNLSDK.Exceptions; +using PAYNLSDK.Utilities; + namespace PAYNLSDK.API.Service.GetCategories { @@ -32,14 +33,14 @@ public override string Querystring get { return ""; } } - public override NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); + if (!ParameterValidator.IsNonEmptyInt(PaymentOptionId)) - { - nvc.Add("paymentOptionId", PaymentOptionId.ToString()); - } - return nvc; + parameters.Add("paymentOptionId", PaymentOptionId.ToString()); + + return parameters; } public Response Response { get { return (Response)response; } } @@ -47,13 +48,12 @@ public override NameValueCollection GetParameters() public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } - PAYNLSDK.Objects.ServiceCategory[] pm = JsonConvert.DeserializeObject(RawResponse); - Response r = new Response(); - r.ServiceCategories = pm; - response = r; + + response = new Response + { + ServiceCategories = JsonConvert.DeserializeObject(RawResponse) + }; } } } diff --git a/PAYNLSDK/API/Transaction/Approve/Request.cs b/PAYNLSDK/API/Transaction/Approve/Request.cs index 20d2fb1..3d2c222 100644 --- a/PAYNLSDK/API/Transaction/Approve/Request.cs +++ b/PAYNLSDK/API/Transaction/Approve/Request.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using PAYNLSDK.Converters; -using PAYNLSDK.Exceptions; -using PAYNLSDK.Utilities; -using System; -using System.Collections.Specialized; +using System.Collections.Specialized; + +using Newtonsoft.Json; + +using PAYNLSDK.Exceptions; +using PAYNLSDK.Utilities; namespace PAYNLSDK.API.Transaction.Approve { @@ -15,61 +15,60 @@ public class Request : RequestBase /// /// /// - [JsonProperty("transactionId")] + [JsonProperty("transactionId")] public string TransactionId { get; set; } /// /// not implemented /// - // [JsonProperty("entranceCode")] - // public string EntranceCode { get; set; } - - /* overrides */ + // [JsonProperty("entranceCode")] + // public string EntranceCode { get; set; } + + /* overrides */ /// /// /// - public override int Version - { - get { return 7; } - } - + public override int Version + { + get { return 7; } + } + /// /// /// - public override string Controller - { - get { return "Transaction"; } - } - + public override string Controller + { + get { return "Transaction"; } + } + /// /// /// - public override string Method - { - get { return "approve"; } - } - + public override string Method + { + get { return "approve"; } + } + /// /// /// - public override string Querystring - { - get { return ""; } + public override string Querystring + { + get { return ""; } } /// /// /// /// - public override NameValueCollection GetParameters() - { - NameValueCollection nvc = base.GetParameters(); + public override NameValueCollection GetParameters(string apiToken, string serviceId) + { + var parameters = base.GetParameters(apiToken, serviceId); - ParameterValidator.IsNotEmpty(TransactionId, "TransactionId"); - nvc.Add("orderId", TransactionId); + ParameterValidator.IsNotEmpty(TransactionId, "TransactionId"); + parameters.Add("orderId", TransactionId); - return nvc; - + return parameters; } /// @@ -80,13 +79,12 @@ public override NameValueCollection GetParameters() /// /// /// - public override void SetResponse() - { - if (ParameterValidator.IsEmpty(rawResponse)) - { - throw new ErrorException("rawResponse is empty!"); - } - response = JsonConvert.DeserializeObject(RawResponse); + public override void SetResponse() + { + if (ParameterValidator.IsEmpty(rawResponse)) + throw new ErrorException("rawResponse is empty!"); + + response = JsonConvert.DeserializeObject(RawResponse); } } } diff --git a/PAYNLSDK/API/Transaction/Decline/Request.cs b/PAYNLSDK/API/Transaction/Decline/Request.cs index c59fa9b..dc990e0 100644 --- a/PAYNLSDK/API/Transaction/Decline/Request.cs +++ b/PAYNLSDK/API/Transaction/Decline/Request.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using PAYNLSDK.Converters; -using PAYNLSDK.Exceptions; -using PAYNLSDK.Utilities; -using System; -using System.Collections.Specialized; +using System.Collections.Specialized; + +using Newtonsoft.Json; + +using PAYNLSDK.Exceptions; +using PAYNLSDK.Utilities; namespace PAYNLSDK.API.Transaction.Decline { @@ -15,7 +15,7 @@ public class Request : RequestBase /// /// /// - [JsonProperty("transactionId")] + [JsonProperty("transactionId")] public string TransactionId { get; set; } /// @@ -28,52 +28,50 @@ public class Request : RequestBase /// /// /// - public override int Version - { - get { return 7; } - } - + public override int Version + { + get { return 7; } + } + /// /// /// - public override string Controller - { - get { return "Transaction"; } - } - + public override string Controller + { + get { return "Transaction"; } + } + /// /// /// - public override string Method - { - get { return "decline"; } - } - + public override string Method + { + get { return "decline"; } + } + /// /// /// - public override string Querystring - { - get { return ""; } + public override string Querystring + { + get { return ""; } } /// /// /// /// - public override NameValueCollection GetParameters() - { - NameValueCollection nvc = base.GetParameters(); - - ParameterValidator.IsNotEmpty(TransactionId, "TransactionId"); - nvc.Add("orderId", TransactionId); + public override NameValueCollection GetParameters(string apiToken, string serviceId) + { + var parameters = base.GetParameters(apiToken, serviceId); + + ParameterValidator.IsNotEmpty(TransactionId, "TransactionId"); + parameters.Add("orderId", TransactionId); // if (!ParameterValidator.IsEmpty(EntranceCode)) - // { - // nvc.Add("entranceCode", EntranceCode); - // } + // parameters.Add("entranceCode", EntranceCode); - return nvc; + return parameters; } /// @@ -84,14 +82,12 @@ public override NameValueCollection GetParameters() /// /// /// - public override void SetResponse() - { - if (ParameterValidator.IsEmpty(rawResponse)) - { - throw new ErrorException("rawResponse is empty!"); - } - response = JsonConvert.DeserializeObject(RawResponse); + public override void SetResponse() + { + if (ParameterValidator.IsEmpty(rawResponse)) + throw new ErrorException("rawResponse is empty!"); + + response = JsonConvert.DeserializeObject(RawResponse); } } } - diff --git a/PAYNLSDK/API/Transaction/GetLastTransactions/Request.cs b/PAYNLSDK/API/Transaction/GetLastTransactions/Request.cs index e2a42ee..1762ad5 100644 --- a/PAYNLSDK/API/Transaction/GetLastTransactions/Request.cs +++ b/PAYNLSDK/API/Transaction/GetLastTransactions/Request.cs @@ -1,8 +1,9 @@ -using System; +using System.Collections.Specialized; + using Newtonsoft.Json; -using PAYNLSDK.Utilities; -using System.Collections.Specialized; + using PAYNLSDK.Exceptions; +using PAYNLSDK.Utilities; namespace PAYNLSDK.API.Transaction.GetLastTransactions { @@ -19,10 +20,7 @@ public class Request : RequestBase public override bool RequiresServiceId { - get - { - return true; - } + get { return true; } } public override int Version @@ -45,32 +43,29 @@ public override string Querystring get { return ""; } } - public override NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); + if (!ParameterValidator.IsNull(MerchantId)) - { - nvc.Add("merchantId", MerchantId); - } + parameters.Add("merchantId", MerchantId); + if (!ParameterValidator.IsNull(Paid)) - { - nvc.Add("paid", ((bool)Paid) ? "1" : "0"); - } + parameters.Add("paid", ((bool)Paid) ? "1" : "0"); + if (!ParameterValidator.IsNull(Limit)) - { - nvc.Add("limit", Limit.ToString()); - } - return nvc; + parameters.Add("limit", Limit.ToString()); + + return parameters; } - + public Response Response { get { return (Response)response; } } public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } } diff --git a/PAYNLSDK/API/Transaction/GetService/Request.cs b/PAYNLSDK/API/Transaction/GetService/Request.cs index e260246..50503a8 100644 --- a/PAYNLSDK/API/Transaction/GetService/Request.cs +++ b/PAYNLSDK/API/Transaction/GetService/Request.cs @@ -1,8 +1,9 @@ -using Newtonsoft.Json; +using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; using PAYNLSDK.Utilities; -using System; -using System.Collections.Specialized; namespace PAYNLSDK.API.Transaction.GetService { @@ -10,14 +11,11 @@ public class Request : RequestBase { public override bool RequiresServiceId { - get - { - return true; - } + get { return true; } } [JsonProperty("paymentMethodId")] - public PAYNLSDK.Enums.PaymentMethodId? PaymentMethodId { get; set; } + public Enums.PaymentMethodId? PaymentMethodId { get; set; } public override int Version { @@ -39,23 +37,22 @@ public override string Querystring get { return ""; } } - public override NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); + if (!ParameterValidator.IsNull(PaymentMethodId)) - { - nvc.Add("paymentMethodId", ((int)PaymentMethodId).ToString()); - } - return nvc; + parameters.Add("paymentMethodId", ((int)PaymentMethodId).ToString()); + + return parameters; } public Response Response { get { return (Response)response; } } public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } } diff --git a/PAYNLSDK/API/Transaction/Info/Request.cs b/PAYNLSDK/API/Transaction/Info/Request.cs index 1f7fae5..93f480d 100644 --- a/PAYNLSDK/API/Transaction/Info/Request.cs +++ b/PAYNLSDK/API/Transaction/Info/Request.cs @@ -1,14 +1,14 @@ -using Newtonsoft.Json; +using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; using PAYNLSDK.Utilities; -using System; -using System.Collections.Specialized; namespace PAYNLSDK.API.Transaction.Info { public class Request : RequestBase { - public string TransactionId { get; set; } public string EntranceCode { get; set; } @@ -33,29 +33,27 @@ public override string Querystring get { return ""; } } - public override NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); - + var parameters = base.GetParameters(apiToken, serviceId); + ParameterValidator.IsNotEmpty(TransactionId, "TransactionId"); - nvc.Add("transactionId", TransactionId); + parameters.Add("transactionId", TransactionId); if (!ParameterValidator.IsEmpty(EntranceCode)) - { - nvc.Add("entranceCode", EntranceCode); - } - return nvc; + parameters.Add("entranceCode", EntranceCode); + + return parameters; } + public Response Response { get { return (Response)response; } } public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } - } } diff --git a/PAYNLSDK/API/Transaction/Refund/Request.cs b/PAYNLSDK/API/Transaction/Refund/Request.cs index 2bcae89..303d4ea 100644 --- a/PAYNLSDK/API/Transaction/Refund/Request.cs +++ b/PAYNLSDK/API/Transaction/Refund/Request.cs @@ -18,7 +18,7 @@ public class Request : RequestBase [JsonProperty("description")] public string Description { get; set; } - [JsonProperty("processDate"),JsonConverter(typeof(DMYConverter))] + [JsonProperty("processDate"), JsonConverter(typeof(DMYConverter))] public DateTime? ProcessDate { get; set; } public override int Version @@ -41,38 +41,31 @@ public override string Querystring get { return ""; } } - public override NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotEmpty(TransactionId, "TransactionId"); - nvc.Add("transactionId", TransactionId); + parameters.Add("transactionId", TransactionId); if (!ParameterValidator.IsNull(Amount)) - { - nvc.Add("amount", Amount.ToString()); - } + parameters.Add("amount", Amount.ToString()); if (!ParameterValidator.IsEmpty(Description)) - { - nvc.Add("description", Description); - } + parameters.Add("description", Description); if (!ParameterValidator.IsNull(ProcessDate)) - { - nvc.Add("processDate", ((DateTime)ProcessDate).ToString("dd-MM-yyyy")); - } + parameters.Add("processDate", ((DateTime)ProcessDate).ToString("dd-MM-yyyy")); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } } diff --git a/PAYNLSDK/API/Transaction/Start/Request.cs b/PAYNLSDK/API/Transaction/Start/Request.cs index c026228..2072e25 100644 --- a/PAYNLSDK/API/Transaction/Start/Request.cs +++ b/PAYNLSDK/API/Transaction/Start/Request.cs @@ -1,10 +1,12 @@ using System; -using Newtonsoft.Json; using System.Collections.Specialized; -using PAYNLSDK.Utilities; -using PAYNLSDK.Objects; + +using Newtonsoft.Json; + using PAYNLSDK.Enums; using PAYNLSDK.Exceptions; +using PAYNLSDK.Objects; +using PAYNLSDK.Utilities; namespace PAYNLSDK.API.Transaction.Start { @@ -12,19 +14,11 @@ public class Request : RequestBase { public override bool RequiresApiToken { - get - { - - - return true; - } + get { return true; } } public override bool RequiresServiceId { - get - { - return true; - } + get { return true; } } public int Amount { get; set; } @@ -61,37 +55,33 @@ public override string Querystring get { return ""; } } - public override NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); // Basic params ParameterValidator.IsNotNull(Amount, "Amount"); - nvc.Add("amount", Amount.ToString()); + parameters.Add("amount", Amount.ToString()); ParameterValidator.IsNotNull(IPAddress, "IPAddress"); - nvc.Add("ipAddress", IPAddress); + parameters.Add("ipAddress", IPAddress); ParameterValidator.IsNotNull(ReturnUrl, "ReturnUrl"); - nvc.Add("finishUrl", ReturnUrl); + parameters.Add("finishUrl", ReturnUrl); if (ParameterValidator.IsNonEmptyInt(PaymentOptionId)) - { - nvc.Add("paymentOptionId", PaymentOptionId.ToString()); - } + parameters.Add("paymentOptionId", PaymentOptionId.ToString()); + if (!ParameterValidator.IsEmpty(PaymentOptionSubId)) - { - nvc.Add("paymentOptionSubId", PaymentOptionSubId.ToString()); - } + parameters.Add("paymentOptionSubId", PaymentOptionSubId.ToString()); if (!ParameterValidator.IsEmpty(TransferValue)) { - if (TransferType == "transaction" || TransferType == "merchant") { - nvc.Add("transferType", TransferType); - nvc.Add("transferValue", TransferValue); + parameters.Add("transferType", TransferType); + parameters.Add("transferValue", TransferValue); } else { @@ -103,223 +93,167 @@ public override NameValueCollection GetParameters() if (Transaction != null) { if (!ParameterValidator.IsNull(Transaction.Currency)) - { - nvc.Add("transaction[currency]", Transaction.Currency); - } + parameters.Add("transaction[currency]", Transaction.Currency); + if (ParameterValidator.IsNonEmptyInt(Transaction.CostsVat)) - { - nvc.Add("transaction[costsVat]", Transaction.CostsVat.ToString()); - } + parameters.Add("transaction[costsVat]", Transaction.CostsVat.ToString()); + // TODO: exclude cost? if (!ParameterValidator.IsEmpty(Transaction.OrderExchangeUrl)) - { - nvc.Add("transaction[orderExchangeUrl]", Transaction.OrderExchangeUrl); - } + parameters.Add("transaction[orderExchangeUrl]", Transaction.OrderExchangeUrl); + if (!ParameterValidator.IsEmpty(Transaction.Description)) - { - nvc.Add("transaction[description]", Transaction.Description); - } - /* - if (!ParameterValidator.IsNonEmptyInt(Transaction.EnduserId)) - { - nvc.Add("transaction[enduserId]", Transaction.EnduserId.ToString()); - } - * */ + parameters.Add("transaction[description]", Transaction.Description); + + // if (!ParameterValidator.IsNonEmptyInt(Transaction.EnduserId)) + // parameters.Add("transaction[enduserId]", Transaction.EnduserId.ToString()); + if (!ParameterValidator.IsNull(Transaction.ExpireDate)) - { - nvc.Add("transaction[expireDate]", ((DateTime)Transaction.ExpireDate).ToString("dd-MM-yyyy hh:mm:ss")); - } + parameters.Add("transaction[expireDate]", ((DateTime)Transaction.ExpireDate).ToString("dd-MM-yyyy hh:mm:ss")); + // TODO: Are these right? SHouldn't this be BOOL / INT? - /* - if (!ParameterValidator.IsEmpty(Transaction.SendReminderEmail)) - { - nvc.Add("transaction[sendReminderEmail]", Transaction.SendReminderEmail); - } - if (!ParameterValidator.IsEmpty(Transaction.ReminderMailTemplateId)) - { - nvc.Add("transaction[reminderMailTemplateId]", Transaction.ReminderMailTemplateId); - } - */ + // if (!ParameterValidator.IsEmpty(Transaction.SendReminderEmail)) + // parameters.Add("transaction[sendReminderEmail]", Transaction.SendReminderEmail); + + // if (!ParameterValidator.IsEmpty(Transaction.ReminderMailTemplateId)) + // parameters.Add("transaction[reminderMailTemplateId]", Transaction.ReminderMailTemplateId); + if (!ParameterValidator.IsNull(Transaction.OrderNumber)) - { - nvc.Add("transaction[orderNumber]", Transaction.OrderNumber); - } + parameters.Add("transaction[orderNumber]", Transaction.OrderNumber); } // StatsData if (StatsData != null) { if (ParameterValidator.IsNonEmptyInt(StatsData.PromotorId)) - { - nvc.Add("statsData[promotorId]", StatsData.PromotorId.ToString()); - } + parameters.Add("statsData[promotorId]", StatsData.PromotorId.ToString()); + if (!ParameterValidator.IsEmpty(StatsData.Info)) - { - nvc.Add("statsData[info]", StatsData.Info); - } + parameters.Add("statsData[info]", StatsData.Info); + if (!ParameterValidator.IsEmpty(StatsData.Tool)) - { - nvc.Add("statsData[tool]", StatsData.Tool); - } + parameters.Add("statsData[tool]", StatsData.Tool); + if (!ParameterValidator.IsEmpty(StatsData.Extra1)) - { - nvc.Add("statsData[extra1]", StatsData.Extra1); - } + parameters.Add("statsData[extra1]", StatsData.Extra1); + if (!ParameterValidator.IsEmpty(StatsData.Extra2)) - { - nvc.Add("statsData[extra2]", StatsData.Extra2); - } + parameters.Add("statsData[extra2]", StatsData.Extra2); + if (!ParameterValidator.IsEmpty(StatsData.Extra3)) - { - nvc.Add("statsData[extra3]", StatsData.Extra3); - } + parameters.Add("statsData[extra3]", StatsData.Extra3); + //if (!ParameterValidator.IsEmpty(StatsData.TransferData)) - //{ - // nvc.Add("statsData[transferData]", StatsData.TransferData); - //} + // parameters.Add("statsData[transferData]", StatsData.TransferData); } // End user if (Enduser != null) { - /* - if (!ParameterValidator.IsEmpty(Enduser.AccessCode)) - { - nvc.Add("enduser[accessCode]", Enduser.AccessCode); - } - * */ + // if (!ParameterValidator.IsEmpty(Enduser.AccessCode)) + // parameters.Add("enduser[accessCode]", Enduser.AccessCode); + if (!ParameterValidator.IsEmpty(Enduser.Language)) - { - nvc.Add("enduser[language]", Enduser.Language); - } + parameters.Add("enduser[language]", Enduser.Language); + if (!ParameterValidator.IsEmpty(Enduser.Initials)) - { - nvc.Add("enduser[initials]", Enduser.Initials); - } + parameters.Add("enduser[initials]", Enduser.Initials); + if (!ParameterValidator.IsEmpty(Enduser.Lastname)) - { - nvc.Add("enduser[lastName]", Enduser.Lastname); - } + parameters.Add("enduser[lastName]", Enduser.Lastname); + if (!ParameterValidator.IsNull(Enduser.Gender)) - { - nvc.Add("enduser[gender]", EnumUtil.ToEnumString((Gender)Enduser.Gender)); - } + parameters.Add("enduser[gender]", EnumUtil.ToEnumString((Gender)Enduser.Gender)); + if (!ParameterValidator.IsNull(Enduser.BirthDate)) - { - nvc.Add("enduser[dob]", ((DateTime)Enduser.BirthDate).ToString("dd-MM-yyyy")); - } + parameters.Add("enduser[dob]", ((DateTime)Enduser.BirthDate).ToString("dd-MM-yyyy")); + if (!ParameterValidator.IsEmpty(Enduser.PhoneNumber)) - { - nvc.Add("enduser[phoneNumber]", Enduser.PhoneNumber); - } + parameters.Add("enduser[phoneNumber]", Enduser.PhoneNumber); + if (!ParameterValidator.IsEmpty(Enduser.EmailAddress)) - { - nvc.Add("enduser[emailAddress]", Enduser.EmailAddress); - } + parameters.Add("enduser[emailAddress]", Enduser.EmailAddress); + if (!ParameterValidator.IsEmpty(Enduser.BankAccount)) - { - nvc.Add("enduser[bankAccount]", Enduser.BankAccount); - } + parameters.Add("enduser[bankAccount]", Enduser.BankAccount); + if (!ParameterValidator.IsEmpty(Enduser.IBAN)) - { - nvc.Add("enduser[iban]", Enduser.IBAN); - } - /* - if (!ParameterValidator.IsNull(Enduser.SendConfirmMail)) - { - nvc.Add("enduser[sendConfirmMail]", ((bool)Enduser.SendConfirmMail) ? "1" : "0"); - } - if (!ParameterValidator.IsEmpty(Enduser.ConfirmMailTemplate)) - { - nvc.Add("enduser[confirmMailTemplate]", Enduser.ConfirmMailTemplate); - } - * */ + parameters.Add("enduser[iban]", Enduser.IBAN); + + // if (!ParameterValidator.IsNull(Enduser.SendConfirmMail)) + // parameters.Add("enduser[sendConfirmMail]", ((bool)Enduser.SendConfirmMail) ? "1" : "0"); + + // if (!ParameterValidator.IsEmpty(Enduser.ConfirmMailTemplate)) + // parameters.Add("enduser[confirmMailTemplate]", Enduser.ConfirmMailTemplate); + if (!ParameterValidator.IsEmpty(Enduser.CustomerReference)) - { - nvc.Add("enduser[customerReference]", Enduser.CustomerReference); - } + parameters.Add("enduser[customerReference]", Enduser.CustomerReference); + // Address if (Enduser.Address != null) { if (!ParameterValidator.IsEmpty(Enduser.Address.StreetName)) - { - nvc.Add("enduser[address][streetName]", Enduser.Address.StreetName); - } + parameters.Add("enduser[address][streetName]", Enduser.Address.StreetName); + if (!ParameterValidator.IsEmpty(Enduser.Address.StreetNumber)) - { - nvc.Add("enduser[address][streetNumber]", Enduser.Address.StreetNumber); - } + parameters.Add("enduser[address][streetNumber]", Enduser.Address.StreetNumber); + if (!ParameterValidator.IsEmpty(Enduser.Address.ZipCode)) - { - nvc.Add("enduser[address][zipCode]", Enduser.Address.ZipCode); - } + parameters.Add("enduser[address][zipCode]", Enduser.Address.ZipCode); + if (!ParameterValidator.IsEmpty(Enduser.Address.City)) - { - nvc.Add("enduser[address][city]", Enduser.Address.City); - } + parameters.Add("enduser[address][city]", Enduser.Address.City); + if (!ParameterValidator.IsEmpty(Enduser.Address.CountryCode)) - { - nvc.Add("enduser[address][countryCode]", Enduser.Address.CountryCode); - } + parameters.Add("enduser[address][countryCode]", Enduser.Address.CountryCode); } // InvoiceAddress if (Enduser.InvoiceAddress != null) { if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.Initials)) - { - nvc.Add("enduser[invoiceAddress][initials]", Enduser.InvoiceAddress.Initials); - } + parameters.Add("enduser[invoiceAddress][initials]", Enduser.InvoiceAddress.Initials); + if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.LastName)) - { - nvc.Add("enduser[invoiceAddress][lastName]", Enduser.InvoiceAddress.LastName); - } + parameters.Add("enduser[invoiceAddress][lastName]", Enduser.InvoiceAddress.LastName); + if (!ParameterValidator.IsNull(Enduser.InvoiceAddress.Gender)) { - string gender = EnumUtil.ToEnumString((Gender)Enduser.InvoiceAddress.Gender); - nvc.Add("enduser[invoiceAddress][gender]", gender); + string gender = EnumUtil.ToEnumString((Gender)Enduser.InvoiceAddress.Gender); + + parameters.Add("enduser[invoiceAddress][gender]", gender); } + if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.StreetName)) - { - nvc.Add("enduser[invoiceAddress][streetName]", Enduser.InvoiceAddress.StreetName); - } + parameters.Add("enduser[invoiceAddress][streetName]", Enduser.InvoiceAddress.StreetName); + if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.StreetNumber)) - { - nvc.Add("enduser[invoiceAddress][streetNumber]", Enduser.InvoiceAddress.StreetNumber); - } + parameters.Add("enduser[invoiceAddress][streetNumber]", Enduser.InvoiceAddress.StreetNumber); + if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.ZipCode)) - { - nvc.Add("enduser[invoiceAddress][zipCode]", Enduser.InvoiceAddress.ZipCode); - } + parameters.Add("enduser[invoiceAddress][zipCode]", Enduser.InvoiceAddress.ZipCode); + if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.City)) - { - nvc.Add("enduser[invoiceAddress][city]", Enduser.InvoiceAddress.City); - } + parameters.Add("enduser[invoiceAddress][city]", Enduser.InvoiceAddress.City); + if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.CountryCode)) - { - nvc.Add("enduser[invoiceAddress][countryCode]", Enduser.InvoiceAddress.CountryCode); - } + parameters.Add("enduser[invoiceAddress][countryCode]", Enduser.InvoiceAddress.CountryCode); } //Company info if (Enduser.Company != null) { if (!ParameterValidator.IsEmpty(Enduser.Company.CocNumber)) - { - nvc.Add("enduser[company][cocNumber]", Enduser.Company.CocNumber); - } + parameters.Add("enduser[company][cocNumber]", Enduser.Company.CocNumber); + if (!ParameterValidator.IsEmpty(Enduser.Company.CountryCode)) - { - nvc.Add("enduser[company][countryCode]", Enduser.Company.CountryCode); - } + parameters.Add("enduser[company][countryCode]", Enduser.Company.CountryCode); + if (!ParameterValidator.IsEmpty(Enduser.Company.Name)) - { - nvc.Add("enduser[company][name]", Enduser.Company.Name); - } + parameters.Add("enduser[company][name]", Enduser.Company.Name); + if (!ParameterValidator.IsEmpty(Enduser.Company.VatNumber)) - { - nvc.Add("enduser[company][vatNumber]", Enduser.Company.VatNumber); - } + parameters.Add("enduser[company][vatNumber]", Enduser.Company.VatNumber); } } @@ -327,40 +261,35 @@ public override NameValueCollection GetParameters() if (SalesData != null) { if (!ParameterValidator.IsNull(SalesData.DeliveryDate)) - { - nvc.Add("saleData[deliveryDate]", SalesData.DeliveryDate.ToString("dd-MM-yyyy")); - } + parameters.Add("saleData[deliveryDate]", SalesData.DeliveryDate.ToString("dd-MM-yyyy")); + if (!ParameterValidator.IsNull(SalesData.InvoiceDate)) - { - nvc.Add("saleData[invoiceDate]", SalesData.InvoiceDate.ToString("dd-MM-yyyy")); - } + parameters.Add("saleData[invoiceDate]", SalesData.InvoiceDate.ToString("dd-MM-yyyy")); + if (!ParameterValidator.IsNull(SalesData.OrderData)) { int i = 0; + foreach (OrderData data in SalesData.OrderData) { ParameterValidator.IsNotNull(data.ProductId, "SalesData.OrderData.ProductId"); - nvc.Add(string.Format("saleData[orderData][{0}][productId]", i), data.ProductId); + parameters.Add(string.Format("saleData[orderData][{0}][productId]", i), data.ProductId); if (!ParameterValidator.IsNull(data.Description)) - { - nvc.Add(string.Format("saleData[orderData][{0}][description]", i), data.Description); - } + parameters.Add(string.Format("saleData[orderData][{0}][description]", i), data.Description); ParameterValidator.IsNotNull(data.Price, "SalesData.OrderData.Price"); - nvc.Add(string.Format("saleData[orderData][{0}][price]", i), data.Price.ToString()); + parameters.Add(string.Format("saleData[orderData][{0}][price]", i), data.Price.ToString()); ParameterValidator.IsNotNull(data.Quantity, "SalesData.OrderData.Quantity"); - nvc.Add(string.Format("saleData[orderData][{0}][quantity]", i), data.Quantity.ToString()); + parameters.Add(string.Format("saleData[orderData][{0}][quantity]", i), data.Quantity.ToString()); if (!ParameterValidator.IsNull(data.VatCode)) - { - nvc.Add(string.Format("saleData[orderData][{0}][vatCode]", i), EnumUtil.ToEnumString((TaxClass)data.VatCode)); - } + parameters.Add(string.Format("saleData[orderData][{0}][vatCode]", i), EnumUtil.ToEnumString(data.VatCode)); + if (!ParameterValidator.IsNull(data.ProductType)) - { - nvc.Add(string.Format("saleData[orderData][{0}][productType]", i), EnumUtil.ToEnumString((ProductType)data.ProductType)); - } + parameters.Add(string.Format("saleData[orderData][{0}][productType]", i), EnumUtil.ToEnumString(data.ProductType)); + i++; } } @@ -368,11 +297,9 @@ public override NameValueCollection GetParameters() // TestMode if (!ParameterValidator.IsNull(TestMode)) - { - nvc.Add("testMode", ((bool)TestMode) ? "1" : "0"); - } + parameters.Add("testMode", ((bool)TestMode) ? "1" : "0"); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } @@ -380,15 +307,12 @@ public override NameValueCollection GetParameters() public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); + if (!Response.Request.Result) - { - // toss throw new ErrorException(Response.Request.Message); - } } } } diff --git a/PAYNLSDK/API/Validate/BankAccountNumber/Request.cs b/PAYNLSDK/API/Validate/BankAccountNumber/Request.cs index 9cf2710..ef63587 100644 --- a/PAYNLSDK/API/Validate/BankAccountNumber/Request.cs +++ b/PAYNLSDK/API/Validate/BankAccountNumber/Request.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using PAYNLSDK.Converters; +using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; using PAYNLSDK.Utilities; -using System; -using System.Collections.Specialized; namespace PAYNLSDK.API.Validate.BankAccountNumber { @@ -14,10 +14,7 @@ public class Request : RequestBase public override bool RequiresApiToken { - get - { - return false; - } + get { return false; } } public override int Version @@ -40,14 +37,14 @@ public override string Querystring get { return ""; } } - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotEmpty(BankAccountNumber, "bankAccountNumber"); - nvc.Add("bankAccountNumber", BankAccountNumber); + parameters.Add("bankAccountNumber", BankAccountNumber); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } @@ -55,9 +52,8 @@ public override System.Collections.Specialized.NameValueCollection GetParameters public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } } diff --git a/PAYNLSDK/API/Validate/BankAccountNumber/Response.cs b/PAYNLSDK/API/Validate/BankAccountNumber/Response.cs index 947a028..c263ef2 100644 --- a/PAYNLSDK/API/Validate/BankAccountNumber/Response.cs +++ b/PAYNLSDK/API/Validate/BankAccountNumber/Response.cs @@ -7,6 +7,6 @@ namespace PAYNLSDK.API.Validate.BankAccountNumber public class Response : ResponseBase { [JsonProperty("result"), JsonConverter(typeof(BooleanConverter))] - public bool result { get; protected set; } + public bool Result { get; protected set; } } } diff --git a/PAYNLSDK/API/Validate/BankAccountNumberInternational/Request.cs b/PAYNLSDK/API/Validate/BankAccountNumberInternational/Request.cs index fd4702e..77b7765 100644 --- a/PAYNLSDK/API/Validate/BankAccountNumberInternational/Request.cs +++ b/PAYNLSDK/API/Validate/BankAccountNumberInternational/Request.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using PAYNLSDK.Converters; +using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; using PAYNLSDK.Utilities; -using System; -using System.Collections.Specialized; namespace PAYNLSDK.API.Validate.BankAccountNumberInternational { @@ -14,10 +14,7 @@ public class Request : RequestBase public override bool RequiresApiToken { - get - { - return false;// base.RequiresApiToken; - } + get { return false; } } public override int Version @@ -40,14 +37,14 @@ public override string Querystring get { return ""; } } - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotEmpty(BankAccountNumber, "bankAccountNumber"); - nvc.Add("bankAccountNumber", BankAccountNumber); + parameters.Add("bankAccountNumber", BankAccountNumber); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } @@ -55,9 +52,8 @@ public override System.Collections.Specialized.NameValueCollection GetParameters public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } } diff --git a/PAYNLSDK/API/Validate/BankAccountNumberInternational/Response.cs b/PAYNLSDK/API/Validate/BankAccountNumberInternational/Response.cs index 0b3b094..65fc587 100644 --- a/PAYNLSDK/API/Validate/BankAccountNumberInternational/Response.cs +++ b/PAYNLSDK/API/Validate/BankAccountNumberInternational/Response.cs @@ -1,12 +1,12 @@ using Newtonsoft.Json; + using PAYNLSDK.Converters; -using System; namespace PAYNLSDK.API.Validate.BankAccountNumberInternational { public class Response : ResponseBase { [JsonProperty("result"), JsonConverter(typeof(BooleanConverter))] - public bool result { get; protected set; } + public bool Result { get; protected set; } } } diff --git a/PAYNLSDK/API/Validate/GetServerIps/Request.cs b/PAYNLSDK/API/Validate/GetServerIps/Request.cs index ced38eb..9c6e44e 100644 --- a/PAYNLSDK/API/Validate/GetServerIps/Request.cs +++ b/PAYNLSDK/API/Validate/GetServerIps/Request.cs @@ -34,13 +34,12 @@ public override string Querystring public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } - string[] ips = JsonConvert.DeserializeObject(RawResponse); - Response r = new Response(); - r.IPAddresses = ips; - response = r; + + response = new Response + { + IPAddresses = JsonConvert.DeserializeObject(RawResponse) + }; } } } diff --git a/PAYNLSDK/API/Validate/IBAN/Request.cs b/PAYNLSDK/API/Validate/IBAN/Request.cs index 6023a2e..95e2853 100644 --- a/PAYNLSDK/API/Validate/IBAN/Request.cs +++ b/PAYNLSDK/API/Validate/IBAN/Request.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using PAYNLSDK.Converters; +using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; using PAYNLSDK.Utilities; -using System; -using System.Collections.Specialized; namespace PAYNLSDK.API.Validate.IBAN { @@ -14,10 +14,7 @@ public class Request : RequestBase public override bool RequiresApiToken { - get - { - return false;// base.RequiresApiToken; - } + get { return false; } } public override int Version @@ -40,14 +37,14 @@ public override string Querystring get { return ""; } } - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotEmpty(IBAN, "iban"); - nvc.Add("iban", IBAN); + parameters.Add("iban", IBAN); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } @@ -55,9 +52,8 @@ public override System.Collections.Specialized.NameValueCollection GetParameters public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } } diff --git a/PAYNLSDK/API/Validate/IBAN/Response.cs b/PAYNLSDK/API/Validate/IBAN/Response.cs index 31c9bbd..1121f07 100644 --- a/PAYNLSDK/API/Validate/IBAN/Response.cs +++ b/PAYNLSDK/API/Validate/IBAN/Response.cs @@ -1,12 +1,12 @@ using Newtonsoft.Json; + using PAYNLSDK.Converters; -using System; namespace PAYNLSDK.API.Validate.IBAN { public class Response : ResponseBase { [JsonProperty("result"), JsonConverter(typeof(BooleanConverter))] - public bool result { get; protected set; } + public bool Result { get; protected set; } } } diff --git a/PAYNLSDK/API/Validate/IsPayServerIp/Request.cs b/PAYNLSDK/API/Validate/IsPayServerIp/Request.cs index 7a7afbb..8644fb2 100644 --- a/PAYNLSDK/API/Validate/IsPayServerIp/Request.cs +++ b/PAYNLSDK/API/Validate/IsPayServerIp/Request.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using PAYNLSDK.Converters; +using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; using PAYNLSDK.Utilities; -using System; -using System.Collections.Specialized; namespace PAYNLSDK.API.Validate.IsPayServerIp { @@ -14,10 +14,7 @@ public class Request : RequestBase public override bool RequiresApiToken { - get - { - return false;// base.RequiresApiToken; - } + get { return false; } } public override int Version @@ -40,14 +37,14 @@ public override string Querystring get { return ""; } } - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotEmpty(IpAddress, "IpAddress"); - nvc.Add("ipAddress", IpAddress); + parameters.Add("ipAddress", IpAddress); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } @@ -55,9 +52,8 @@ public override System.Collections.Specialized.NameValueCollection GetParameters public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } } diff --git a/PAYNLSDK/API/Validate/IsPayServerIp/Response.cs b/PAYNLSDK/API/Validate/IsPayServerIp/Response.cs index 205b842..35848c8 100644 --- a/PAYNLSDK/API/Validate/IsPayServerIp/Response.cs +++ b/PAYNLSDK/API/Validate/IsPayServerIp/Response.cs @@ -1,12 +1,12 @@ using Newtonsoft.Json; + using PAYNLSDK.Converters; -using System; namespace PAYNLSDK.API.Validate.IsPayServerIp { public class Response : ResponseBase { [JsonProperty("result"), JsonConverter(typeof(BooleanConverter))] - public bool result { get; protected set; } + public bool Result { get; protected set; } } } diff --git a/PAYNLSDK/API/Validate/KVK/Request.cs b/PAYNLSDK/API/Validate/KVK/Request.cs index b5bd3c6..07fd6c0 100644 --- a/PAYNLSDK/API/Validate/KVK/Request.cs +++ b/PAYNLSDK/API/Validate/KVK/Request.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using PAYNLSDK.Converters; +using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; using PAYNLSDK.Utilities; -using System; -using System.Collections.Specialized; namespace PAYNLSDK.API.Validate.KVK { @@ -14,10 +14,7 @@ public class Request : RequestBase public override bool RequiresApiToken { - get - { - return false;// base.RequiresApiToken; - } + get { return false; } } public override int Version @@ -40,14 +37,14 @@ public override string Querystring get { return ""; } } - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotEmpty(KVK, "kvk"); - nvc.Add("kvk", KVK); + parameters.Add("kvk", KVK); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } @@ -55,9 +52,8 @@ public override System.Collections.Specialized.NameValueCollection GetParameters public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } } diff --git a/PAYNLSDK/API/Validate/KVK/Response.cs b/PAYNLSDK/API/Validate/KVK/Response.cs index 1313fea..6f2c5e6 100644 --- a/PAYNLSDK/API/Validate/KVK/Response.cs +++ b/PAYNLSDK/API/Validate/KVK/Response.cs @@ -1,12 +1,12 @@ using Newtonsoft.Json; + using PAYNLSDK.Converters; -using System; namespace PAYNLSDK.API.Validate.KVK { public class Response : ResponseBase { [JsonProperty("result"), JsonConverter(typeof(BooleanConverter))] - public bool result { get; protected set; } + public bool Result { get; protected set; } } } diff --git a/PAYNLSDK/API/Validate/SOFI/Request.cs b/PAYNLSDK/API/Validate/SOFI/Request.cs index 552e39e..a76ca9c 100644 --- a/PAYNLSDK/API/Validate/SOFI/Request.cs +++ b/PAYNLSDK/API/Validate/SOFI/Request.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using PAYNLSDK.Converters; +using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; using PAYNLSDK.Utilities; -using System; -using System.Collections.Specialized; namespace PAYNLSDK.API.Validate.SOFI { @@ -14,10 +14,7 @@ public class Request : RequestBase public override bool RequiresApiToken { - get - { - return false;// base.RequiresApiToken; - } + get { return false; } } public override int Version @@ -40,14 +37,14 @@ public override string Querystring get { return ""; } } - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotEmpty(SOFI, "sofi"); - nvc.Add("sofi", SOFI); + parameters.Add("sofi", SOFI); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } @@ -55,9 +52,8 @@ public override System.Collections.Specialized.NameValueCollection GetParameters public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } } diff --git a/PAYNLSDK/API/Validate/SOFI/Response.cs b/PAYNLSDK/API/Validate/SOFI/Response.cs index c80d5c5..c2ec6bb 100644 --- a/PAYNLSDK/API/Validate/SOFI/Response.cs +++ b/PAYNLSDK/API/Validate/SOFI/Response.cs @@ -1,12 +1,12 @@ using Newtonsoft.Json; + using PAYNLSDK.Converters; -using System; namespace PAYNLSDK.API.Validate.SOFI { public class Response : ResponseBase { [JsonProperty("result"), JsonConverter(typeof(BooleanConverter))] - public bool result { get; protected set; } + public bool Result { get; protected set; } } } diff --git a/PAYNLSDK/API/Validate/SWIFT/Request.cs b/PAYNLSDK/API/Validate/SWIFT/Request.cs index fd63b1a..ec1da68 100644 --- a/PAYNLSDK/API/Validate/SWIFT/Request.cs +++ b/PAYNLSDK/API/Validate/SWIFT/Request.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using PAYNLSDK.Converters; +using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; using PAYNLSDK.Utilities; -using System; -using System.Collections.Specialized; namespace PAYNLSDK.API.Validate.SWIFT { @@ -14,10 +14,7 @@ public class Request : RequestBase public override bool RequiresApiToken { - get - { - return false;// base.RequiresApiToken; - } + get { return false; } } public override int Version @@ -40,14 +37,14 @@ public override string Querystring get { return ""; } } - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotEmpty(SWIFT, "swift"); - nvc.Add("swift", SWIFT); + parameters.Add("swift", SWIFT); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } @@ -55,9 +52,8 @@ public override System.Collections.Specialized.NameValueCollection GetParameters public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } } diff --git a/PAYNLSDK/API/Validate/SWIFT/Response.cs b/PAYNLSDK/API/Validate/SWIFT/Response.cs index 77b64df..a34ba15 100644 --- a/PAYNLSDK/API/Validate/SWIFT/Response.cs +++ b/PAYNLSDK/API/Validate/SWIFT/Response.cs @@ -1,12 +1,12 @@ using Newtonsoft.Json; + using PAYNLSDK.Converters; -using System; namespace PAYNLSDK.API.Validate.SWIFT { public class Response : ResponseBase { [JsonProperty("result"), JsonConverter(typeof(BooleanConverter))] - public bool result { get; protected set; } + public bool Result { get; protected set; } } } diff --git a/PAYNLSDK/API/Validate/Util.cs b/PAYNLSDK/API/Validate/Util.cs index bb5e3a1..8e3e5c9 100644 --- a/PAYNLSDK/API/Validate/Util.cs +++ b/PAYNLSDK/API/Validate/Util.cs @@ -1,6 +1,6 @@ using Newtonsoft.Json; + using PAYNLSDK.Net; -using System; namespace PAYNLSDK.API.Validate { @@ -9,19 +9,22 @@ public class Util public IClient Client { get; set; } private JsonSerializerSettings serializerSettings; - public JsonSerializerSettings SerializerSettings - { - get - { - if (serializerSettings == null) - { - serializerSettings = new JsonSerializerSettings(); - serializerSettings.NullValueHandling = NullValueHandling.Ignore; + public JsonSerializerSettings SerializerSettings + { + get + { + if (serializerSettings == null) + { + serializerSettings = new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }; } - return serializerSettings; + + return serializerSettings; } - set - { + set + { serializerSettings = value; } } @@ -38,69 +41,100 @@ public Util(IClient client, JsonSerializerSettings serializerSettings) public bool ValidatePayIP(string ipAddress) { - IsPayServerIp.Request request = new IsPayServerIp.Request(); - request.IpAddress = ipAddress; + var request = new IsPayServerIp.Request + { + IpAddress = ipAddress + }; + Client.PerformRequest(request); - return request.Response.result; + + return request.Response.Result; } public bool ValidateBankAccountNumber(string bankAccountNumber, bool international) { if (international) { - BankAccountNumberInternational.Request request = new BankAccountNumberInternational.Request(); - request.BankAccountNumber = bankAccountNumber; + var request = new BankAccountNumberInternational.Request + { + BankAccountNumber = bankAccountNumber + }; + Client.PerformRequest(request); - return request.Response.result; + + return request.Response.Result; } else { - BankAccountNumber.Request request = new BankAccountNumber.Request(); - request.BankAccountNumber = bankAccountNumber; + var request = new BankAccountNumber.Request + { + BankAccountNumber = bankAccountNumber + }; + Client.PerformRequest(request); - return request.Response.result; + + return request.Response.Result; } } public bool ValidateIBAN(string iban) { - IBAN.Request request = new IBAN.Request(); - request.IBAN = iban; + var request = new IBAN.Request + { + IBAN = iban + }; + Client.PerformRequest(request); - return request.Response.result; + + return request.Response.Result; } public bool ValidateSWIFT(string swift) { - SWIFT.Request request = new SWIFT.Request(); - request.SWIFT = swift; + var request = new SWIFT.Request + { + SWIFT = swift + }; + Client.PerformRequest(request); - return request.Response.result; + + return request.Response.Result; } public bool ValidateKVK(string kvk) { - KVK.Request request = new KVK.Request(); - request.KVK = kvk; + var request = new KVK.Request + { + KVK = kvk + }; + Client.PerformRequest(request); - return request.Response.result; + + return request.Response.Result; } public bool ValidateVAT(string vat) { - VAT.Request request = new VAT.Request(); - request.VAT = vat; + var request = new VAT.Request + { + VAT = vat + }; + Client.PerformRequest(request); - return request.Response.result; + + return request.Response.Result; } public bool ValidateSOFI(string sofi) { - SOFI.Request request = new SOFI.Request(); - request.SOFI = sofi; + var request = new SOFI.Request + { + SOFI = sofi + }; + Client.PerformRequest(request); - return request.Response.result; - } + return request.Response.Result; + } } } diff --git a/PAYNLSDK/API/Validate/VAT/Request.cs b/PAYNLSDK/API/Validate/VAT/Request.cs index ed222d2..a80dba2 100644 --- a/PAYNLSDK/API/Validate/VAT/Request.cs +++ b/PAYNLSDK/API/Validate/VAT/Request.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using PAYNLSDK.Converters; +using System.Collections.Specialized; + +using Newtonsoft.Json; + using PAYNLSDK.Exceptions; using PAYNLSDK.Utilities; -using System; -using System.Collections.Specialized; namespace PAYNLSDK.API.Validate.VAT { @@ -14,10 +14,7 @@ public class Request : RequestBase public override bool RequiresApiToken { - get - { - return false;// base.RequiresApiToken; - } + get { return false; } } public override int Version @@ -40,14 +37,14 @@ public override string Querystring get { return ""; } } - public override System.Collections.Specialized.NameValueCollection GetParameters() + public override NameValueCollection GetParameters(string apiToken, string serviceId) { - NameValueCollection nvc = base.GetParameters(); + var parameters = base.GetParameters(apiToken, serviceId); ParameterValidator.IsNotEmpty(VAT, "vat"); - nvc.Add("vat", VAT); + parameters.Add("vat", VAT); - return nvc; + return parameters; } public Response Response { get { return (Response)response; } } @@ -55,9 +52,8 @@ public override System.Collections.Specialized.NameValueCollection GetParameters public override void SetResponse() { if (ParameterValidator.IsEmpty(rawResponse)) - { throw new ErrorException("rawResponse is empty!"); - } + response = JsonConvert.DeserializeObject(RawResponse); } } diff --git a/PAYNLSDK/API/Validate/VAT/Response.cs b/PAYNLSDK/API/Validate/VAT/Response.cs index 81718d5..0a2e9ab 100644 --- a/PAYNLSDK/API/Validate/VAT/Response.cs +++ b/PAYNLSDK/API/Validate/VAT/Response.cs @@ -1,12 +1,12 @@ using Newtonsoft.Json; + using PAYNLSDK.Converters; -using System; namespace PAYNLSDK.API.Validate.VAT { public class Response : ResponseBase { [JsonProperty("result"), JsonConverter(typeof(BooleanConverter))] - public bool result { get; protected set; } + public bool Result { get; protected set; } } } diff --git a/PAYNLSDK/Banktransfer.cs b/PAYNLSDK/Banktransfer.cs index 0fc7d5c..685e206 100644 --- a/PAYNLSDK/Banktransfer.cs +++ b/PAYNLSDK/Banktransfer.cs @@ -1,27 +1,23 @@ using PAYNLSDK.Net; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace PAYNLSDK { public class Banktransfer - { - static public API.Banktransfer.Add.Response Add(PAYNLSDK.API.Banktransfer.Add.Request request) - { - Client c = new Client("", ""); - c.PerformRequest(request); - return request.Response; + { + static public API.Banktransfer.Add.Response Add(IClient client, API.Banktransfer.Add.Request request) + { + client.PerformRequest(request); + + return request.Response; } - static public API.Banktransfer.Add.Response Add(int amount, string bankAccountHolder, string bankAccountNumber, string bankAccountBic) - { - Client c = new Client("", ""); - var request = new API.Banktransfer.Add.Request(amount, bankAccountHolder, bankAccountNumber, bankAccountBic); - c.PerformRequest(request); - return request.Response; + static public API.Banktransfer.Add.Response Add(IClient client, int amount, string bankAccountHolder, string bankAccountNumber, string bankAccountBic) + { + var request = new API.Banktransfer.Add.Request(amount, bankAccountHolder, bankAccountNumber, bankAccountBic); + + client.PerformRequest(request); + + return request.Response; } } } diff --git a/PAYNLSDK/Class1.cs b/PAYNLSDK/Class1.cs index 69c706d..4c0d4c3 100644 --- a/PAYNLSDK/Class1.cs +++ b/PAYNLSDK/Class1.cs @@ -10,8 +10,8 @@ static void Main(string[] args) //RequestBase.ApiToken = "b3d9e04d265c26e839869728ce9310e6dfed2a83"; //RequestBase.ServiceId = "SL-4280-2030"; - RequestBase.ApiToken = "6f62fa2cbf03b38517401763e434c29cd8ece1f2"; - RequestBase.ServiceId = "SL-1094-0450"; + // RequestBase.ApiToken = "6f62fa2cbf03b38517401763e434c29cd8ece1f2"; + // RequestBase.ServiceId = "SL-1094-0450"; } } diff --git a/PAYNLSDK/Converters/CountryOptionConverter.cs b/PAYNLSDK/Converters/CountryOptionConverter.cs index 122f3b8..5f63450 100644 --- a/PAYNLSDK/Converters/CountryOptionConverter.cs +++ b/PAYNLSDK/Converters/CountryOptionConverter.cs @@ -17,7 +17,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist var dict = serializer.Deserialize>(reader); return dict; } - throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing country options.", reader.TokenType)); + throw new JsonSerializationException(string.Format("Unexpected token '{0}' when parsing country options.", reader.TokenType)); } diff --git a/PAYNLSDK/Converters/DMYConverter.cs b/PAYNLSDK/Converters/DMYConverter.cs index 133d5c0..60e0e46 100644 --- a/PAYNLSDK/Converters/DMYConverter.cs +++ b/PAYNLSDK/Converters/DMYConverter.cs @@ -1,84 +1,18 @@ -using System; -using Newtonsoft.Json; -using PAYNLSDK.Utilities; - -namespace PAYNLSDK.Converters +namespace PAYNLSDK.Converters { - public class DMYConverter : JsonConverter + public class DMYConverter : DateConverter { - private const string Format = "dd-MM-yyyy"; - private static string[] ParseFormats = { - // - argument. - "d-M-yyyy", "dd-MM-yyyy", - // Slash argument. - "d/M/yyyy", "dd/MM/yyyy" - }; - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - if (value is DateTime) - { - var dateTime = (DateTime)value; - if (dateTime.Kind == DateTimeKind.Unspecified) - { - throw new JsonSerializationException("Cannot convert date time with an unspecified kind"); - } - string convertedDateTime = dateTime.ToString(Format); - writer.WriteValue(convertedDateTime); - } - else - { - throw new JsonSerializationException("Expected value of type 'DateTime'."); - } - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - if (reader.TokenType == JsonToken.Null) - { - return null; - } - - if (reader.TokenType == JsonToken.Date) - { - var dateTime = (DateTime)reader.Value; - if (dateTime.Kind == DateTimeKind.Unspecified) - { - throw new JsonSerializationException("Parsed date time is not in the expected RFC3339 format"); - } - return dateTime; - } - - if (reader.TokenType == JsonToken.String) - { - DateTime dateTime; - /*string[] formats = { "d/M/yyyy", "dd/MM/yyyy", "d-M-yyyy", "dd-MM-yyyy" };*/ - string timeString = (string)reader.Value; - if (!ParameterValidator.IsEmpty(timeString)) - { - if (DateTime.TryParseExact(timeString, ParseFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateTime)) - { - // Gelukt we kunnen doorgaan - return dateTime; - } - else - { - // De opgegeven timeString is niet juist. - return null; - } - - } - return null; - } - throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing date.", reader.TokenType)); - } - - public override bool CanConvert(Type objectType) + private const string _format = "dd-MM-yyyy"; + private static readonly string[] _parseFormats = { - Type t = (Reflection.IsNullable(objectType)) - ? Nullable.GetUnderlyingType(objectType) - : objectType; + // - argument. + "d-M-yyyy", "dd-MM-yyyy", + // Slash argument. + "d/M/yyyy", "dd/MM/yyyy" + }; - return t == typeof(DateTime); - } + public DMYConverter() + : base(_format, _parseFormats) + { } } } diff --git a/PAYNLSDK/Converters/DateConverter.cs b/PAYNLSDK/Converters/DateConverter.cs new file mode 100644 index 0000000..1432e0e --- /dev/null +++ b/PAYNLSDK/Converters/DateConverter.cs @@ -0,0 +1,82 @@ +using System; +using System.Globalization; + +using Newtonsoft.Json; + +using PAYNLSDK.Utilities; + +namespace PAYNLSDK.Converters +{ + public abstract class DateConverter : JsonConverter + { + public string Format { get; protected set; } + public string[] ParseFormats { get; protected set; } + + protected DateConverter() { } + protected DateConverter(string format, string[] parseFormats) + { + Format = format; + ParseFormats = parseFormats; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + if (value is DateTime dateTime) + { + if (dateTime.Kind == DateTimeKind.Unspecified) + throw new JsonSerializationException("Cannot convert date time with an unspecified kind"); + + var convertedDateTime = dateTime.ToString(Format); + + writer.WriteValue(convertedDateTime); + } + else + { + throw new JsonSerializationException("Expected value of type 'DateTime'."); + } + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + return null; + + if (reader.TokenType == JsonToken.Date) + { + var dateTime = (DateTime)reader.Value; + + if (dateTime.Kind == DateTimeKind.Unspecified) + throw new JsonSerializationException("Parsed date time is not in the expected RFC3339 format"); + + return dateTime; + } + + if (reader.TokenType == JsonToken.String) + { + /*string[] formats = { "yyyy/M/d", "yyyy/MM/dd", "yyyy-M-d", "yyyy-MM-dd" };*/ + var timeString = (string)reader.Value; + + if (!ParameterValidator.IsEmpty(timeString) + && DateTime.TryParseExact(timeString, ParseFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateTime)) + { + // Gelukt we kunnen doorgaan + return dateTime; + } + + // De opgegeven timeString is niet juist. + return null; + } + + throw new JsonSerializationException(string.Format("Unexpected token '{0}' when parsing date.", reader.TokenType)); + } + + public override bool CanConvert(Type objectType) + { + Type t = Reflection.IsNullable(objectType) + ? Nullable.GetUnderlyingType(objectType) + : objectType; + + return t == typeof(DateTime); + } + } +} \ No newline at end of file diff --git a/PAYNLSDK/Converters/ErrorIdConverter.cs b/PAYNLSDK/Converters/ErrorIdConverter.cs index 0e9647a..98efa35 100644 --- a/PAYNLSDK/Converters/ErrorIdConverter.cs +++ b/PAYNLSDK/Converters/ErrorIdConverter.cs @@ -1,9 +1,6 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System; + +using Newtonsoft.Json; namespace PAYNLSDK.Converters { @@ -11,18 +8,18 @@ class ErrorIdConverter : JsonConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { - string result = serializer.Deserialize(reader); - if (result == String.Empty) - { + var result = serializer.Deserialize(reader); + + if (result == string.Empty) return 0; - } + try { - return Int32.Parse(result); + return int.Parse(result); } - catch (Exception e) + catch (Exception) { - throw new JsonSerializationException(String.Format("Unexpected conversion '{0}' when parsing errorId.", result)); + throw new JsonSerializationException(string.Format("Unexpected conversion '{0}' when parsing errorId.", result)); } } @@ -35,14 +32,12 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s } //if (CanConvert(value.GetType())) //{ - serializer.Serialize(writer, value); + serializer.Serialize(writer, value); //} - //throw new JsonSerializationException(String.Format("Can't serialize type {0} to Integer.", value.GetType())); + //throw new JsonSerializationException(string.Format("Can't serialize type {0} to Integer.", value.GetType())); } public override bool CanConvert(Type objectType) - { - return typeof(int).IsAssignableFrom(objectType); - } + => typeof(int).IsAssignableFrom(objectType); } } diff --git a/PAYNLSDK/Converters/YMDConverter.cs b/PAYNLSDK/Converters/YMDConverter.cs index 75d4f6a..b00d26e 100644 --- a/PAYNLSDK/Converters/YMDConverter.cs +++ b/PAYNLSDK/Converters/YMDConverter.cs @@ -1,84 +1,18 @@ -using System; -using Newtonsoft.Json; -using PAYNLSDK.Utilities; - -namespace PAYNLSDK.Converters +namespace PAYNLSDK.Converters { - public class YMDConverter : JsonConverter + public class YMDConverter : DateConverter { - private const string Format = "yyyy-MM-dd"; - private static string[] ParseFormats = { - // - argument. - "yyyy-M-d", "yyyy-MM-dd", - // Slash argument. - "yyyy/M/d", "yyyy/MM/dd" - }; - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - if (value is DateTime) - { - var dateTime = (DateTime)value; - if (dateTime.Kind == DateTimeKind.Unspecified) - { - throw new JsonSerializationException("Cannot convert date time with an unspecified kind"); - } - string convertedDateTime = dateTime.ToString(Format); - writer.WriteValue(convertedDateTime); - } - else - { - throw new JsonSerializationException("Expected value of type 'DateTime'."); - } - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - if (reader.TokenType == JsonToken.Null) - { - return null; - } - - if (reader.TokenType == JsonToken.Date) - { - var dateTime = (DateTime)reader.Value; - if (dateTime.Kind == DateTimeKind.Unspecified) - { - throw new JsonSerializationException("Parsed date time is not in the expected RFC3339 format"); - } - return dateTime; - } - - if (reader.TokenType == JsonToken.String) - { - DateTime dateTime; - /*string[] formats = { "yyyy/M/d", "yyyy/MM/dd", "yyyy-M-d", "yyyy-MM-dd" };*/ - string timeString = (string)reader.Value; - if (!ParameterValidator.IsEmpty(timeString)) - { - if (DateTime.TryParseExact(timeString, ParseFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateTime)) - { - // Gelukt we kunnen doorgaan - return dateTime; - } - else - { - // De opgegeven timeString is niet juist. - return null; - } - - } - return null; - } - throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing date.", reader.TokenType)); - } - - public override bool CanConvert(Type objectType) + private const string _format = "yyyy-MM-dd"; + private static readonly string[] _parseFormats = { - Type t = (Reflection.IsNullable(objectType)) - ? Nullable.GetUnderlyingType(objectType) - : objectType; + // - argument. + "yyyy-M-d", "yyyy-MM-dd", + // Slash argument. + "yyyy/M/d", "yyyy/MM/dd" + }; - return t == typeof(DateTime); - } + public YMDConverter() + : base(_format, _parseFormats) + { } } } diff --git a/PAYNLSDK/Converters/YMDHISConverter.cs b/PAYNLSDK/Converters/YMDHISConverter.cs index 1f98bb5..14a3b5b 100644 --- a/PAYNLSDK/Converters/YMDHISConverter.cs +++ b/PAYNLSDK/Converters/YMDHISConverter.cs @@ -1,108 +1,26 @@ -using System; -using Newtonsoft.Json; -using PAYNLSDK.Utilities; - -namespace PAYNLSDK.Converters +namespace PAYNLSDK.Converters { - public class YMDHISConverter : JsonConverter + public class YMDHISConverter : DateConverter { - private const string Format = "yyyy-MM-dd HH:ii:ss"; - private static string[] ParseFormats = { - // - argument. - "yyyy-M-d h:mm:ss tt", "yyyy-M-d h:mm tt", - "yyyy-MM-dd hh:mm:ss", "yyyy-M-d h:mm:ss", - "yyyy-M-d hh:mm tt", "yyyy-M-d hh tt", - "yyyy-M-d h:mm", "yyyy-M-d h:mm", - "yyyy-MM-dd hh:mm", "yyyy-M-dd hh:mm", - // Slash argument. - "yyyy/M/d h:mm:ss tt", "yyyy/M/d h:mm tt", - "yyyy/MM/dd hh:mm:ss", "yyyy/M/d h:mm:ss", - "yyyy/M/d hh:mm tt", "yyyy/M/d hh tt", - "yyyy/M/d h:mm", "yyyy/M/d h:mm", - "yyyy/MM/dd hh:mm", "yyyy/M/dd hh:mm" - }; - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - if (value is DateTime) - { - var dateTime = (DateTime)value; - if (dateTime.Kind == DateTimeKind.Unspecified) - { - throw new JsonSerializationException("Cannot convert date time with an unspecified kind"); - } - string convertedDateTime = dateTime.ToString(Format); - writer.WriteValue(convertedDateTime); - } - else - { - throw new JsonSerializationException("Expected value of type 'DateTime'."); - } - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - if (reader.TokenType == JsonToken.Null) - { - return null; - } - - if (reader.TokenType == JsonToken.Date) - { - var dateTime = (DateTime)reader.Value; - if (dateTime.Kind == DateTimeKind.Unspecified) - { - throw new JsonSerializationException("Parsed date time is not in the expected RFC3339 format"); - } - return dateTime; - } - - if (reader.TokenType == JsonToken.String) - { - DateTime dateTime; -/* - string[] formats = { - // - argument. - "yyyy-M-d h:mm:ss tt", "yyyy-M-d h:mm tt", - "yyyy-MM-dd hh:mm:ss", "yyyy-M-d h:mm:ss", - "yyyy-M-d hh:mm tt", "yyyy-M-d hh tt", - "yyyy-M-d h:mm", "yyyy-M-d h:mm", - "yyyy-MM-dd hh:mm", "yyyy-M-dd hh:mm", - // Slash argument. - "yyyy/M/d h:mm:ss tt", "yyyy/M/d h:mm tt", - "yyyy/MM/dd hh:mm:ss", "yyyy/M/d h:mm:ss", - "yyyy/M/d hh:mm tt", "yyyy/M/d hh tt", - "yyyy/M/d h:mm", "yyyy/M/d h:mm", - "yyyy/MM/dd hh:mm", "yyyy/M/dd hh:mm" - }; - */ - string timeString = (string)reader.Value; - if (!ParameterValidator.IsEmpty(timeString)) - { - if (DateTime.TryParseExact(timeString, ParseFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateTime)) - { - // Gelukt we kunnen doorgaan - return dateTime; - } - else - { - // De opgegeven timeString is niet juist. - return null; - } - - } - return null; - } - throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing date.", reader.TokenType)); - } - - public override bool CanConvert(Type objectType) + private const string _format = "yyyy-MM-dd HH:ii:ss"; + private static readonly string[] _parseFormats = { - Type t = (Reflection.IsNullable(objectType)) - ? Nullable.GetUnderlyingType(objectType) - : objectType; - - return t == typeof(DateTime); - } + // - argument. + "yyyy-M-d h:mm:ss tt", "yyyy-M-d h:mm tt", + "yyyy-MM-dd hh:mm:ss", "yyyy-M-d h:mm:ss", + "yyyy-M-d hh:mm tt", "yyyy-M-d hh tt", + "yyyy-M-d h:mm", "yyyy-M-d h:mm", + "yyyy-MM-dd hh:mm", "yyyy-M-dd hh:mm", + // Slash argument. + "yyyy/M/d h:mm:ss tt", "yyyy/M/d h:mm tt", + "yyyy/MM/dd hh:mm:ss", "yyyy/M/d h:mm:ss", + "yyyy/M/d hh:mm tt", "yyyy/M/d hh tt", + "yyyy/M/d h:mm", "yyyy/M/d h:mm", + "yyyy/MM/dd hh:mm", "yyyy/M/dd hh:mm" + }; + + public YMDHISConverter() + : base(_format, _parseFormats) + { } } } diff --git a/PAYNLSDK/Enums/enums.cs b/PAYNLSDK/Enums/enums.cs index 9bd9b0f..df09632 100644 --- a/PAYNLSDK/Enums/enums.cs +++ b/PAYNLSDK/Enums/enums.cs @@ -54,7 +54,7 @@ public static T ToEnum(string str) var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single(); if (enumMemberAttribute.Value == str) return (T)Enum.Parse(enumType, name); } - return default(T); + return default; } /// diff --git a/PAYNLSDK/Exceptions/ErrorException.cs b/PAYNLSDK/Exceptions/ErrorException.cs index 0aff6f1..a5e332f 100644 --- a/PAYNLSDK/Exceptions/ErrorException.cs +++ b/PAYNLSDK/Exceptions/ErrorException.cs @@ -1,5 +1,6 @@ -using PAYNLSDK.Objects; -using System; +using System; + +using PAYNLSDK.Objects; namespace PAYNLSDK.Exceptions { @@ -8,7 +9,7 @@ namespace PAYNLSDK.Exceptions /// public class ErrorException : Exception { - private Error error; + private readonly Error error; /// /// Error, if any /// @@ -18,14 +19,11 @@ public Error Error } /// - /// Retiurn whether or not there's an Error object associated with this Exception + /// Return whether or not there's an Error object associated with this Exception /// public bool HasError { - get - { - return (error != null); - } + get { return error != null; } } /// @@ -67,6 +65,5 @@ public ErrorException(string message) : base(message) { } - } } diff --git a/PAYNLSDK/Net/Client.cs b/PAYNLSDK/Net/Client.cs index f4699ad..09a8c88 100644 --- a/PAYNLSDK/Net/Client.cs +++ b/PAYNLSDK/Net/Client.cs @@ -1,16 +1,14 @@ -using PAYNLSDK.Net.ProxyConfigurationInjector; -using System; +using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Net; using System.Text; -using System.Threading.Tasks; + using PAYNLSDK.API; using PAYNLSDK.Exceptions; -using PAYNLSDK.Objects; +using PAYNLSDK.Net.ProxyConfigurationInjector; + using Newtonsoft.Json; -using System.Collections.Specialized; namespace PAYNLSDK.Net { @@ -24,19 +22,19 @@ public class Client : IClient /// /// PAYNL API TOKEN /// - public string ApiToken + private string ApiToken { get; - private set; + set; } /// /// PAYNL SERVICE ID /// - public string ServiceID + private string ServiceID { get; - private set; + set; } /// @@ -104,10 +102,10 @@ public Client(string apiToken) /// /// create new Client /// - public Client() - : this(null, null, null) - { - } + // public Client() + // : this(null, null, null) + // { + // } /// /// Performs an actual request @@ -116,18 +114,20 @@ public Client() /// raw response string public string PerformRequest(RequestBase request) { - HttpWebRequest httprequest = PrepareRequest(request.Url, "POST"); - string rawResponse = PerformRoundTrip2(httprequest, HttpStatusCode.OK, () => + var httprequest = PrepareRequest(request.Url, "POST"); + + var rawResponse = PerformRoundTrip2(httprequest, HttpStatusCode.OK, () => { - using (var requestWriter = new StreamWriter(httprequest.GetRequestStream())) - { - //string serializedResource = resource.Serialize(); - string serializedResource = request.ToQueryString(); - requestWriter.Write(serializedResource); - } - } - ); + using var requestWriter = new StreamWriter(httprequest.GetRequestStream()); + + //string serializedResource = resource.Serialize(); + var serializedResource = request.ToQueryString(ApiToken, ServiceID); + + requestWriter.Write(serializedResource); + }); + request.RawResponse = rawResponse; + return rawResponse; } @@ -139,21 +139,23 @@ public string PerformRequest(RequestBase request) /// private HttpWebRequest PrepareRequest(string requestUriString, string method) { - string uriString = String.Format("{0}/{1}", Endpoint, requestUriString); + var uriString = string.Format("{0}/{1}", Endpoint, requestUriString); var uri = new Uri(uriString); var request = WebRequest.Create(uri) as HttpWebRequest; + request.UserAgent = UserAgent; + const string ApplicationJsonContentType = "application/json"; // http://tools.ietf.org/html/rfc4627 const string WWWUrlContentType = "application/x-www-form-urlencoded"; // http://tools.ietf.org/html/rfc4627 + request.Accept = ApplicationJsonContentType; //request.ContentType = ApplicationJsonContentType; request.ContentType = WWWUrlContentType; request.Method = method; - if (null != ProxyConfigurationInjector) - { + if (ProxyConfigurationInjector != null) request.Proxy = ProxyConfigurationInjector.InjectProxyConfiguration(request.Proxy, uri); - } + return request; } @@ -170,21 +172,21 @@ private string PerformRoundTrip2(HttpWebRequest request, HttpStatusCode expected { requestAction(); - using (var response = request.GetResponse() as HttpWebResponse) + using var response = request.GetResponse() as HttpWebResponse; + + var statusCode = (HttpStatusCode)response.StatusCode; + + if (statusCode == expectedHttpStatusCode) { - var statusCode = (HttpStatusCode)response.StatusCode; - if (statusCode == expectedHttpStatusCode) - { - Stream responseStream = response.GetResponseStream(); - Encoding encoding = GetEncoding(response); + Stream responseStream = response.GetResponseStream(); + Encoding encoding = GetEncoding(response); - using (var responseReader = new StreamReader(responseStream, encoding)) - { - return responseReader.ReadToEnd(); - } - } - throw new ErrorException(String.Format("Unexpected status code {0}", statusCode)); + using var responseReader = new StreamReader(responseStream, encoding); + + return responseReader.ReadToEnd(); } + + throw new ErrorException(string.Format("Unexpected status code {0}", statusCode)); } catch (WebException e) { @@ -192,7 +194,7 @@ private string PerformRoundTrip2(HttpWebRequest request, HttpStatusCode expected } catch (Exception e) { - throw new ErrorException(String.Format("Unhandled exception {0}", e), e); + throw new ErrorException(string.Format("Unhandled exception {0}", e), e); } } @@ -215,14 +217,12 @@ private static Encoding GetEncoding(HttpWebResponse response) /// ErrorException private ErrorException ErrorExceptionFromWebException(WebException e) { - var httpWebResponse = e.Response as HttpWebResponse; - if (null == httpWebResponse) - { - // some kind of network error: didn't even make a connection + // some kind of network error: didn't even make a connection + if (!(e.Response is HttpWebResponse httpWebResponse)) return new ErrorException(e.Message, e); - } var statusCode = (HttpStatusCode)httpWebResponse.StatusCode; + switch (statusCode) { case HttpStatusCode.Unauthorized: @@ -230,34 +230,33 @@ private ErrorException ErrorExceptionFromWebException(WebException e) case HttpStatusCode.MethodNotAllowed: case HttpStatusCode.UnprocessableEntity: case HttpStatusCode.BadRequest: - using (var responseReader = new StreamReader(httpWebResponse.GetResponseStream())) { - string rawResponse = responseReader.ReadToEnd(); // Try JSON parsing. + using var responseReader = new StreamReader(httpWebResponse.GetResponseStream()); + + string rawResponse = responseReader.ReadToEnd(); + try { - Dictionary errors = JsonConvert.DeserializeObject>(rawResponse); - string errMessage = ""; + var errors = JsonConvert.DeserializeObject>(rawResponse); + var errMessage = ""; + if (errors.ContainsKey("error")) - { errMessage = errors["error"]; - } else if (errors.ContainsKey("message")) - { errMessage = errors["message"]; - } - ErrorException errorException = new ErrorException(errMessage, e); + var errorException = new ErrorException(errMessage, e); + if (errorException != null) - { return errorException; - } } - catch (Exception ex1) + catch (Exception) { - return new ErrorException(String.Format("Unknown error for {0}", statusCode), e); + return new ErrorException(string.Format("Unknown error for {0}", statusCode), e); } - return new ErrorException(String.Format("Unknown error for {0}", statusCode), e); + + return new ErrorException(string.Format("Unknown error for {0}", statusCode), e); } case HttpStatusCode.InternalServerError: case HttpStatusCode.NotImplemented: @@ -275,9 +274,9 @@ private ErrorException ErrorExceptionFromWebException(WebException e) case HttpStatusCode.NetworkConnectTimeoutError: return new ErrorException("Something went wrong on our end, please try again", e); default: - return new ErrorException(String.Format("Unhandled status code {0}", statusCode), e); + return new ErrorException(string.Format("Unhandled status code {0}", statusCode), e); } } - + } } diff --git a/PAYNLSDK/Net/IClient.cs b/PAYNLSDK/Net/IClient.cs index 951cab7..2d1a0d2 100644 --- a/PAYNLSDK/Net/IClient.cs +++ b/PAYNLSDK/Net/IClient.cs @@ -13,11 +13,11 @@ public interface IClient /// /// PAYNL API TOKEN /// - string ApiToken { get; } + // string ApiToken { get; } /// /// PAYNL SERVICE ID /// - string ServiceID { get; } + // string ServiceID { get; } /// /// Proxy injector diff --git a/PAYNLSDK/Objects/StornoDetails.cs b/PAYNLSDK/Objects/StornoDetails.cs index d08d2cb..466704c 100644 --- a/PAYNLSDK/Objects/StornoDetails.cs +++ b/PAYNLSDK/Objects/StornoDetails.cs @@ -1,5 +1,4 @@ -using System; -using Newtonsoft.Json; +using Newtonsoft.Json; namespace PAYNLSDK.Objects { @@ -36,7 +35,7 @@ public class StornoDetails /// BIC of the bankaccount the refund is deposited to /// [JsonProperty("bic")] - public string bic { get; protected set; } + public string BIC { get; protected set; } /// /// City of the bankaccount owner @@ -61,6 +60,5 @@ public class StornoDetails /// [JsonProperty("emailAdress")] public string EmailAddress { get; protected set; } - } } diff --git a/PAYNLSDK/PaymentMethod.cs b/PAYNLSDK/PaymentMethod.cs index d8ea946..b213079 100644 --- a/PAYNLSDK/PaymentMethod.cs +++ b/PAYNLSDK/PaymentMethod.cs @@ -15,12 +15,15 @@ public class PaymentMethod /// /// Payment Method ID /// Response containing the payment method data - static public PAYNLSDK.API.PaymentMethod.Get.Response Get(int paymentMethodId) + static public API.PaymentMethod.Get.Response Get(IClient client, int paymentMethodId) { - PaymentMethodGet request = new PaymentMethodGet(); - request.PaymentMethodId = paymentMethodId; - Client c = new Client("", ""); - c.PerformRequest(request); + var request = new PaymentMethodGet() + { + PaymentMethodId = paymentMethodId + }; + + client.PerformRequest(request); + return request.Response; } @@ -28,11 +31,12 @@ static public PAYNLSDK.API.PaymentMethod.Get.Response Get(int paymentMethodId) /// Get information for all payment methods. /// /// Response containing a list of information for all payment methods - static public PAYNLSDK.API.PaymentMethod.GetAll.Response GetAll() + static public API.PaymentMethod.GetAll.Response GetAll(IClient client) { - PaymentMethodGetAll request = new PaymentMethodGetAll(); - Client c = new Client("", ""); - c.PerformRequest(request); + var request = new PaymentMethodGetAll(); + + client.PerformRequest(request); + return request.Response; } } diff --git a/PAYNLSDK/PaymentProfile.cs b/PAYNLSDK/PaymentProfile.cs index 82521d9..0327c54 100644 --- a/PAYNLSDK/PaymentProfile.cs +++ b/PAYNLSDK/PaymentProfile.cs @@ -16,12 +16,15 @@ public class PaymentProfile /// /// Payment profile ID /// Payment profile response - static public PAYNLSDK.API.PaymentProfile.Get.Response Get(int paymentProfileId) + static public API.PaymentProfile.Get.Response Get(IClient client, int paymentProfileId) { - PaymentProfileGet request = new PaymentProfileGet(); - request.PaymentProfileId = paymentProfileId; - Client c = new Client("", ""); - c.PerformRequest(request); + var request = new PaymentProfileGet() + { + PaymentProfileId = paymentProfileId + }; + + client.PerformRequest(request); + return request.Response; } @@ -29,11 +32,12 @@ static public PAYNLSDK.API.PaymentProfile.Get.Response Get(int paymentProfileId) /// Get details for all payment profiles /// /// List of payment profile info - static public PAYNLSDK.API.PaymentProfile.GetAll.Response GetAll() + static public API.PaymentProfile.GetAll.Response GetAll(IClient client) { - PaymentProfileGetAll request = new PaymentProfileGetAll(); - Client c = new Client("", ""); - c.PerformRequest(request); + var request = new PaymentProfileGetAll(); + + client.PerformRequest(request); + return request.Response; } @@ -45,15 +49,18 @@ static public PAYNLSDK.API.PaymentProfile.GetAll.Response GetAll() /// Payment Method ID /// Indicator wether to show profiles that are initially not allowed on registration. /// Response containing the list of payment profile information - static public PAYNLSDK.API.PaymentProfile.GetAvailable.Response GetAvailable(int categoryId, int? programId, int? paymentMethodId, bool? showNotAllowedOnRegistration) + static public API.PaymentProfile.GetAvailable.Response GetAvailable(IClient client, int categoryId, int? programId, int? paymentMethodId, bool? showNotAllowedOnRegistration) { - PaymentProfileGetAvailable request = new PaymentProfileGetAvailable(); - request.CategoryId = categoryId; - request.ProgramId = programId; - request.PaymentMethodId = paymentMethodId; - request.ShowNotAllowedOnRegistration = showNotAllowedOnRegistration; - Client c = new Client("", ""); - c.PerformRequest(request); + var request = new PaymentProfileGetAvailable() + { + CategoryId = categoryId, + ProgramId = programId, + PaymentMethodId = paymentMethodId, + ShowNotAllowedOnRegistration = showNotAllowedOnRegistration + }; + + client.PerformRequest(request); + return request.Response; } @@ -64,10 +71,8 @@ static public PAYNLSDK.API.PaymentProfile.GetAvailable.Response GetAvailable(int /// ID of the program for which the payment options are used. (Only available if the program option is enabled!) /// Payment Method ID /// Response containing the list of payment profile information - static public PAYNLSDK.API.PaymentProfile.GetAvailable.Response GetAvailable(int categoryId, int? programId, int? paymentMethodId) - { - return GetAvailable(categoryId, programId, paymentMethodId, null); - } + static public API.PaymentProfile.GetAvailable.Response GetAvailable(IClient client, int categoryId, int? programId, int? paymentMethodId) + => GetAvailable(client, categoryId, programId, paymentMethodId, null); /// /// Get payment profile information for all your available profiles for the specified service category @@ -75,19 +80,15 @@ static public PAYNLSDK.API.PaymentProfile.GetAvailable.Response GetAvailable(int /// The ID of the category of the service the payment options are used for /// ID of the program for which the payment options are used. (Only available if the program option is enabled!) /// Response containing the list of payment profile information - static public PAYNLSDK.API.PaymentProfile.GetAvailable.Response GetAvailable(int categoryId, int? programId) - { - return GetAvailable(categoryId, programId, null, null); - } + static public API.PaymentProfile.GetAvailable.Response GetAvailable(IClient client, int categoryId, int? programId) + => GetAvailable(client, categoryId, programId, null, null); /// /// Get payment profile information for all your available profiles for the specified service category /// /// The ID of the category of the service the payment options are used for /// Response containing the list of payment profile information - static public PAYNLSDK.API.PaymentProfile.GetAvailable.Response GetAvailable(int categoryId) - { - return GetAvailable(categoryId, null, null, null); - } + static public API.PaymentProfile.GetAvailable.Response GetAvailable(IClient client, int categoryId) + => GetAvailable(client, categoryId, null, null, null); } } diff --git a/PAYNLSDK/Service.cs b/PAYNLSDK/Service.cs index 59fb8c2..ad30ccb 100644 --- a/PAYNLSDK/Service.cs +++ b/PAYNLSDK/Service.cs @@ -1,6 +1,4 @@ -using PAYNLSDK.Enums; -using PAYNLSDK.Net; -using System; +using PAYNLSDK.Net; using ServiceGetCategories = PAYNLSDK.API.Service.GetCategories.Request; namespace PAYNLSDK @@ -16,23 +14,16 @@ public class Service /// /// Payment Option ID /// Response object containing service categories - static public PAYNLSDK.API.Service.GetCategories.Response GetCategories(int? paymentOptionId) + static public API.Service.GetCategories.Response GetCategories(IClient client, int? paymentOptionId = null) { - ServiceGetCategories request = new ServiceGetCategories(); - request.PaymentOptionId = paymentOptionId; - Client c = new Client("", ""); - c.PerformRequest(request); - return request.Response; - } + var request = new ServiceGetCategories() + { + PaymentOptionId = paymentOptionId + }; - /// - /// Get Service Categories - /// - /// Response object containing service categories - static public PAYNLSDK.API.Service.GetCategories.Response GetCategories() - { - return GetCategories(null); + client.PerformRequest(request); + + return request.Response; } } - } diff --git a/PAYNLSDK/Transaction.cs b/PAYNLSDK/Transaction.cs index b6dbd6b..6f0e1a6 100644 --- a/PAYNLSDK/Transaction.cs +++ b/PAYNLSDK/Transaction.cs @@ -22,17 +22,20 @@ public class Transaction /// /// Transaction Id /// True if PAID, false otherwise - static public bool IsPaid(string transactionId) + static public bool IsPaid(IClient client, string transactionId) { try { - TransactionInfo request = new TransactionInfo(); - request.TransactionId = transactionId; - Client c = new Client(); - c.PerformRequest(request); - return (request.Response.PaymentDetails.State == Enums.PaymentStatus.PAID); + var request = new TransactionInfo() + { + TransactionId = transactionId + }; + + client.PerformRequest(request); + + return IsPaid(request?.Response?.PaymentDetails?.State); } - catch (ErrorException e) + catch (ErrorException) { return false; } @@ -43,13 +46,13 @@ static public bool IsPaid(string transactionId) /// /// Transaction status /// True if PAID, false otherwise - static public bool IsPaid(Enums.PaymentStatus status) + static public bool IsPaid(PaymentStatus? status) { try { - return (status == Enums.PaymentStatus.PAID); + return status == PaymentStatus.PAID; } - catch (ErrorException e) + catch (ErrorException) { return false; } @@ -60,17 +63,20 @@ static public bool IsPaid(Enums.PaymentStatus status) /// /// Transaction Id /// True if CANCELLED, false otherwise - static public bool IsCancelled(string transactionId) + static public bool IsCancelled(IClient client, string transactionId) { try { - TransactionInfo request = new TransactionInfo(); - request.TransactionId = transactionId; - Client c = new Client(); - c.PerformRequest(request); - return (request.Response.PaymentDetails.State == Enums.PaymentStatus.CANCEL); + var request = new TransactionInfo() + { + TransactionId = transactionId + }; + + client.PerformRequest(request); + + return IsCancelled(request?.Response?.PaymentDetails?.State); } - catch (ErrorException e) + catch (ErrorException) { return false; } @@ -81,13 +87,13 @@ static public bool IsCancelled(string transactionId) /// /// Transaction status /// True if CANCELLED, false otherwise - static public bool IsCancelled(Enums.PaymentStatus status) + static public bool IsCancelled(PaymentStatus? status) { try { - return (status == Enums.PaymentStatus.CANCEL); + return status == PaymentStatus.CANCEL; } - catch (ErrorException e) + catch (ErrorException) { return false; } @@ -98,21 +104,21 @@ static public bool IsCancelled(Enums.PaymentStatus status) /// /// Transaction Id /// True if PENDING, false otherwise - static public bool IsPending(string transactionId) + static public bool IsPending(IClient client, string transactionId) { try { - TransactionInfo request = new TransactionInfo(); - request.TransactionId = transactionId; - Client c = new Client(); - c.PerformRequest(request); - return ((request.Response.PaymentDetails.State == Enums.PaymentStatus.PENDING_1) || - (request.Response.PaymentDetails.State == Enums.PaymentStatus.PENDING_2) || - (request.Response.PaymentDetails.State == Enums.PaymentStatus.PENDING_3) || - (request.Response.PaymentDetails.State == Enums.PaymentStatus.VERIFY) || - (request.Response.PaymentDetails.StateName == "PENDING")); + var request = new TransactionInfo() + { + TransactionId = transactionId + }; + + client.PerformRequest(request); + + return IsPending(request?.Response?.PaymentDetails?.State) + || request?.Response?.PaymentDetails?.StateName == "PENDING"; } - catch (ErrorException e) + catch (ErrorException) { return false; } @@ -123,17 +129,16 @@ static public bool IsPending(string transactionId) /// /// Transaction status /// True if PENDING, false otherwise - static public bool IsPending(Enums.PaymentStatus status) + static public bool IsPending(PaymentStatus? status) { try { - return ((status == Enums.PaymentStatus.PENDING_1) || - (status == Enums.PaymentStatus.PENDING_2) || - (status == Enums.PaymentStatus.PENDING_3) || - (status == Enums.PaymentStatus.VERIFY) - ); + return status == PaymentStatus.PENDING_1 + || status == PaymentStatus.PENDING_2 + || status == PaymentStatus.PENDING_3 + || status == PaymentStatus.VERIFY; } - catch (ErrorException e) + catch (ErrorException) { return false; } @@ -144,18 +149,21 @@ static public bool IsPending(Enums.PaymentStatus status) /// /// Transaction Id /// True if VERIFY, false otherwise - static public bool IsVerify(string transactionId) + static public bool IsVerify(IClient client, string transactionId) { try { - TransactionInfo request = new TransactionInfo(); - request.TransactionId = transactionId; - Client c = new Client(); - c.PerformRequest(request); - return ((request.Response.PaymentDetails.State == Enums.PaymentStatus.VERIFY) || - (request.Response.PaymentDetails.StateName == "VERIFY")); + var request = new TransactionInfo() + { + TransactionId = transactionId + }; + + client.PerformRequest(request); + + return IsVerify(request?.Response?.PaymentDetails?.State) + || request.Response.PaymentDetails.StateName == "VERIFY"; } - catch (ErrorException e) + catch (ErrorException) { return false; } @@ -166,13 +174,13 @@ static public bool IsVerify(string transactionId) /// /// Transaction status /// True if VERIFY, false otherwise - static public bool IsVerify(Enums.PaymentStatus status) + static public bool IsVerify(PaymentStatus? status) { try { - return ((status == Enums.PaymentStatus.VERIFY)); + return status == PaymentStatus.VERIFY; } - catch (ErrorException e) + catch (ErrorException) { return false; } @@ -183,13 +191,14 @@ static public bool IsVerify(Enums.PaymentStatus status) /// /// Transaction status /// True if REFUND or REFUNDING, false otherwise - static public bool IsRefund(Enums.PaymentStatus status) + static public bool IsRefund(PaymentStatus? status) { try { - return ((status == Enums.PaymentStatus.REFUND) || (status == Enums.PaymentStatus.REFUNDING)); + return status == PaymentStatus.REFUND + || IsRefunding(status); } - catch (ErrorException e) + catch (ErrorException) { return false; } @@ -200,13 +209,13 @@ static public bool IsRefund(Enums.PaymentStatus status) /// /// Transaction status /// True if REFUNDING, false otherwise - static public bool IsRefunding(Enums.PaymentStatus status) + static public bool IsRefunding(PaymentStatus? status) { try { - return ((status == Enums.PaymentStatus.REFUNDING)); + return status == PaymentStatus.REFUNDING; } - catch (ErrorException e) + catch (ErrorException) { return false; } @@ -217,13 +226,16 @@ static public bool IsRefunding(Enums.PaymentStatus status) /// /// Transaction ID /// Full response object with all information available - static public PAYNLSDK.API.Transaction.Info.Response Info(string transactionId) + static public API.Transaction.Info.Response Info(IClient client, string transactionId) { - TransactionInfo request = new TransactionInfo(); - request.TransactionId = transactionId; - Client c = new Client(); - c.PerformRequest(request); - return request.Response; + var request = new TransactionInfo() + { + TransactionId = transactionId + }; + + client.PerformRequest(request); + + return request.Response; } /// @@ -233,13 +245,16 @@ static public PAYNLSDK.API.Transaction.Info.Response Info(string transactionId) /// /// Paymentmethod ID /// FUll response with all service information - static public PAYNLSDK.API.Transaction.GetService.Response GetService(PaymentMethodId? paymentMethodId) + static public API.Transaction.GetService.Response GetService(IClient client, PaymentMethodId? paymentMethodId) { - TransactionGetService request = new TransactionGetService(); - request.PaymentMethodId = paymentMethodId; - Client c = new Client(); - c.PerformRequest(request); - return request.Response; + var request = new TransactionGetService() + { + PaymentMethodId = paymentMethodId + }; + + client.PerformRequest(request); + + return request.Response; } /// @@ -248,10 +263,8 @@ static public PAYNLSDK.API.Transaction.GetService.Response GetService(PaymentMet /// This is an important API if you want to build your own payment screens. /// /// FUll response with all service information - static public PAYNLSDK.API.Transaction.GetService.Response GetService() - { - return GetService(null); - } + static public API.Transaction.GetService.Response GetService(IClient client) + => GetService(client, null); /// /// Performs a (partial) refund call on an existing transaction @@ -261,15 +274,18 @@ static public PAYNLSDK.API.Transaction.GetService.Response GetService() /// Amount of the refund. If null is given, it will be the full amount of the transaction. /// Date to process the refund. May be null. /// Full response including the Refund ID - static public PAYNLSDK.API.Transaction.Refund.Response Refund(string transactionId, string description, int? amount, DateTime? processDate) + static public API.Transaction.Refund.Response Refund(IClient client, string transactionId, string description, int? amount, DateTime? processDate) { - TransactionRefund request = new TransactionRefund(); - request.TransactionId = transactionId; - request.Description = description; - request.Amount = amount; - request.ProcessDate = processDate; - Client c = new Client(); - c.PerformRequest(request); + var request = new TransactionRefund() + { + TransactionId = transactionId, + Description = description, + Amount = amount, + ProcessDate = processDate + }; + + client.PerformRequest(request); + return request.Response; } @@ -280,10 +296,8 @@ static public PAYNLSDK.API.Transaction.Refund.Response Refund(string transaction /// Reason for the refund. May be null. /// Amount of the refund. If null is given, it will be the full amount of the transaction. /// Full response including the Refund ID - static public PAYNLSDK.API.Transaction.Refund.Response Refund(string transactionId, string description, int? amount) - { - return Refund(transactionId, description, amount, null); - } + static public API.Transaction.Refund.Response Refund(IClient client, string transactionId, string description, int? amount) + => Refund(client, transactionId, description, amount, null); /// /// Performs a (partial) refund call on an existing transaction @@ -291,20 +305,16 @@ static public PAYNLSDK.API.Transaction.Refund.Response Refund(string transaction /// Transaction ID /// Reason for the refund. May be null. /// Full response including the Refund ID - static public PAYNLSDK.API.Transaction.Refund.Response Refund(string transactionId, string description) - { - return Refund(transactionId, description, null, null); - } + static public API.Transaction.Refund.Response Refund(IClient client, string transactionId, string description) + => Refund(client, transactionId, description, null); /// /// Performs a (partial) refund call on an existing transaction. /// /// Transaction ID /// Full response including the Refund ID - static public PAYNLSDK.API.Transaction.Refund.Response Refund(string transactionId) - { - return Refund(transactionId, null, null, null); - } + static public API.Transaction.Refund.Response Refund(IClient client, string transactionId) + => Refund(client, transactionId, null); /// /// Performs a (partial) refund call on an existing transaction @@ -315,22 +325,24 @@ static public PAYNLSDK.API.Transaction.Refund.Response Refund(string transaction /// Date to process the refund. May be null. /// The url to send notifications to on changes in this refund. /// Full response including the Refund ID - static public PAYNLSDK.API.Transaction.Refund.Response Refund(string transactionId, string description, int? amount, DateTime? processDate, string exchangeUrl) + static public API.Transaction.Refund.Response Refund(IClient client, string transactionId, string description, int? amount, DateTime? processDate, string exchangeUrl) { // Unable to reuse existing method for refunding, since this specific case needs to be done with different Request // API.Transaction.Refund.Request vs. API.Refund.Transaction.Request (already existing in code, we simply use this here) + var request = new API.Refund.Transaction.Request(transactionId) + { + TransactionId = transactionId, + Description = description, + Amount = amount, + ProcessDate = processDate, + ExchangeUrl = exchangeUrl + }; + + client.PerformRequest(request); - var request = new API.Refund.Transaction.Request(transactionId); - request.TransactionId = transactionId; - request.Description = description; - request.Amount = amount; - request.ProcessDate = processDate; - request.ExchangeUrl = exchangeUrl; - Client c = new Client(); - c.PerformRequest(request); // We will convert the response to a PAYNLSDK.API.Transaction.Refund.Response so we stay in the same, original, namespace. // We manage to get away with this because the API responses have the same definition. - return JsonConvert.DeserializeObject(request.RawResponse); + return JsonConvert.DeserializeObject(request.RawResponse); } /// @@ -338,12 +350,15 @@ static public PAYNLSDK.API.Transaction.Refund.Response Refund(string transaction /// /// Transaction ID /// Full response including the message about the approvement - static public PAYNLSDK.API.Transaction.Approve.Response Approve(string transactionId) + static public API.Transaction.Approve.Response Approve(IClient client, string transactionId) { - TransactionApprove request = new TransactionApprove(); - request.TransactionId = transactionId; - Client c = new Client(); - c.PerformRequest(request); + var request = new TransactionApprove() + { + TransactionId = transactionId + }; + + client.PerformRequest(request); + return request.Response; } @@ -352,12 +367,15 @@ static public PAYNLSDK.API.Transaction.Approve.Response Approve(string transacti /// /// Transaction ID /// Full response including the message about the decline - static public PAYNLSDK.API.Transaction.Decline.Response Decline(string transactionId) + static public API.Transaction.Decline.Response Decline(IClient client, string transactionId) { - TransactionDecline request = new TransactionDecline(); - request.TransactionId = transactionId; - Client c = new Client(); - c.PerformRequest(request); + var request = new TransactionDecline() + { + TransactionId = transactionId + }; + + client.PerformRequest(request); + return request.Response; } @@ -373,19 +391,18 @@ static public PAYNLSDK.API.Transaction.Decline.Response Decline(string transacti /// TransferType for this transaction (merchant/transaction) /// TransferValue eg MerchantId (M-xxxx-xxxx) or orderId /// Transaction Start Request - static public PAYNLSDK.API.Transaction.Start.Request CreateTransactionRequest(string ipAddress, string returnUrl, int? paymentOptionId, string paymentSubOptionId, bool? testMode, string transferType, string transferValue) - { - API.Transaction.Start.Request request = new API.Transaction.Start.Request(); - request.Amount = 0; - request.IPAddress = ipAddress; - request.ReturnUrl = returnUrl; - request.PaymentOptionId = paymentOptionId; - request.PaymentOptionSubId = paymentSubOptionId; - request.TestMode = testMode; - request.TransferType = transferType; - request.TransferValue = transferValue; - return request; - } + static public API.Transaction.Start.Request CreateTransactionRequest(string ipAddress, string returnUrl, int? paymentOptionId, string paymentSubOptionId, bool? testMode, string transferType, string transferValue) + => new API.Transaction.Start.Request() + { + Amount = 0, + IPAddress = ipAddress, + ReturnUrl = returnUrl, + PaymentOptionId = paymentOptionId, + PaymentOptionSubId = paymentSubOptionId, + TestMode = testMode, + TransferType = transferType, + TransferValue = transferValue + }; /// /// Creates a transaction start request. @@ -398,19 +415,18 @@ static public PAYNLSDK.API.Transaction.Start.Request CreateTransactionRequest(st /// TransferType for this transaction (merchant/transaction) /// TransferValue eg MerchantId (M-xxxx-xxxx) or orderId /// Transaction Start Request - static public PAYNLSDK.API.Transaction.Start.Request CreateTransactionRequest(string ipAddress, string returnUrl, int? paymentOptionId, int? paymentSubOptionId, bool? testMode, string transferType, string transferValue) - { - API.Transaction.Start.Request request = new API.Transaction.Start.Request(); - request.Amount = 0; - request.IPAddress = ipAddress; - request.ReturnUrl = returnUrl; - request.PaymentOptionId = paymentOptionId; - request.PaymentOptionSubId = paymentSubOptionId.ToString(); - request.TestMode = testMode; - request.TransferType = transferType; - request.TransferValue = transferValue; - return request; - } + static public API.Transaction.Start.Request CreateTransactionRequest(string ipAddress, string returnUrl, int? paymentOptionId, int? paymentSubOptionId, bool? testMode, string transferType, string transferValue) + => new API.Transaction.Start.Request() + { + Amount = 0, + IPAddress = ipAddress, + ReturnUrl = returnUrl, + PaymentOptionId = paymentOptionId, + PaymentOptionSubId = paymentSubOptionId.ToString(), + TestMode = testMode, + TransferType = transferType, + TransferValue = transferValue + }; /// /// Creates a transaction start request. @@ -421,18 +437,16 @@ static public PAYNLSDK.API.Transaction.Start.Request CreateTransactionRequest(st /// In case of an iDEAL payment this is the ID of the bank (see the paymentOptionSubList in the getService function). /// Whether or not we perform this call in test mode. /// Transaction Start Request - static public PAYNLSDK.API.Transaction.Start.Request CreateTransactionRequest(string ipAddress, string returnUrl, int? paymentOptionId, string paymentSubOptionId, bool? testMode) - { - API.Transaction.Start.Request request = new API.Transaction.Start.Request(); - request.Amount = 0; - request.IPAddress = ipAddress; - request.ReturnUrl = returnUrl; - request.PaymentOptionId = paymentOptionId; - request.PaymentOptionSubId = paymentSubOptionId; - request.TestMode = testMode; - return request; - } - + static public API.Transaction.Start.Request CreateTransactionRequest(string ipAddress, string returnUrl, int? paymentOptionId, string paymentSubOptionId, bool? testMode) + => new API.Transaction.Start.Request() + { + Amount = 0, + IPAddress = ipAddress, + ReturnUrl = returnUrl, + PaymentOptionId = paymentOptionId, + PaymentOptionSubId = paymentSubOptionId, + TestMode = testMode + }; /// /// Creates a transaction start request. @@ -443,32 +457,16 @@ static public PAYNLSDK.API.Transaction.Start.Request CreateTransactionRequest(st /// In case of an iDEAL payment this is the ID of the bank (see the paymentOptionSubList in the getService function). /// Whether or not we perform this call in test mode. /// Transaction Start Request - static public PAYNLSDK.API.Transaction.Start.Request CreateTransactionRequest(string ipAddress, string returnUrl, int? paymentOptionId, int? paymentSubOptionId, bool? testMode) - { - API.Transaction.Start.Request request = new API.Transaction.Start.Request(); - request.Amount = 0; - request.IPAddress = ipAddress; - request.ReturnUrl = returnUrl; - request.PaymentOptionId = paymentOptionId; - request.PaymentOptionSubId = paymentSubOptionId.ToString(); - request.TestMode = testMode; - return request; - } - - /// - /// Creates a transaction start request. - /// - /// Test Mode will be defaulted to FALSE. - /// - /// The IP address of the customer - /// The URL where the customer has to be send to after the payment. - /// The ID of the payment option (for iDEAL use 10). - /// In case of an iDEAL payment this is the ID of the bank (see the paymentOptionSubList in the getService function). - /// Transaction Start Request - static public PAYNLSDK.API.Transaction.Start.Request CreateTransactionRequest(string ipAddress, string returnUrl, int? paymentOptionId, int? paymentSubOptionId) - { - return CreateTransactionRequest(ipAddress, returnUrl, paymentOptionId, "", false); - } + static public API.Transaction.Start.Request CreateTransactionRequest(string ipAddress, string returnUrl, int? paymentOptionId, int? paymentSubOptionId, bool? testMode = false) + => new API.Transaction.Start.Request() + { + Amount = 0, + IPAddress = ipAddress, + ReturnUrl = returnUrl, + PaymentOptionId = paymentOptionId, + PaymentOptionSubId = paymentSubOptionId.ToString(), + TestMode = testMode + }; /// /// Creates a transaction start request. @@ -479,10 +477,8 @@ static public PAYNLSDK.API.Transaction.Start.Request CreateTransactionRequest(st /// The URL where the customer has to be send to after the payment. /// The ID of the payment option (for iDEAL use 10). /// Transaction Start Request - static public PAYNLSDK.API.Transaction.Start.Request CreateTransactionRequest(string ipAddress, string returnUrl, int paymentOptionId) - { - return CreateTransactionRequest(ipAddress, returnUrl, paymentOptionId, "", false); - } + static public API.Transaction.Start.Request CreateTransactionRequest(string ipAddress, string returnUrl, int paymentOptionId, bool? testMode = false) + => CreateTransactionRequest(ipAddress, returnUrl, paymentOptionId, "", testMode); /// /// Creates a transaction start request. @@ -492,19 +488,17 @@ static public PAYNLSDK.API.Transaction.Start.Request CreateTransactionRequest(st /// The IP address of the customer /// The URL where the customer has to be send to after the payment. /// Transaction Start Request - static public PAYNLSDK.API.Transaction.Start.Request CreateTransactionRequest(string ipAddress, string returnUrl) - { - return CreateTransactionRequest(ipAddress, returnUrl, null, "", false); - } + static public API.Transaction.Start.Request CreateTransactionRequest(string ipAddress, string returnUrl, bool? testMode = false) + => CreateTransactionRequest(ipAddress, returnUrl, null, "", testMode); /// /// Performs a request to start a transaction. /// /// Full response object including Transaction ID - static public PAYNLSDK.API.Transaction.Start.Response Start(PAYNLSDK.API.Transaction.Start.Request request) + static public API.Transaction.Start.Response Start(IClient client, API.Transaction.Start.Request request) { - Client c = new Client(); - c.PerformRequest(request); + client.PerformRequest(request); + return request.Response; } } diff --git a/PAYNLSDK/Utilities/Validators.cs b/PAYNLSDK/Utilities/Validators.cs index 240e610..0771c51 100644 --- a/PAYNLSDK/Utilities/Validators.cs +++ b/PAYNLSDK/Utilities/Validators.cs @@ -10,10 +10,10 @@ public class ParameterValidator { public static void IsNotEmpty(string param, string paramName) { - if (String.IsNullOrWhiteSpace(param)) - { - throw new ArgumentException(string.Format("Invalid parameter {0}. Cannot be null, empty or consist of whitespace only", paramName),"paramName"); - + if (string.IsNullOrWhiteSpace(param)) + { + throw new ArgumentException(string.Format("Invalid parameter {0}. Cannot be null, empty or consist of whitespace only", paramName), "paramName"); + } } @@ -27,7 +27,7 @@ public static void IsNotNull(object param, string paramName) public static bool IsEmpty(string param) { - return String.IsNullOrWhiteSpace(param); + return string.IsNullOrWhiteSpace(param); } public static bool IsNull(object param)