public async Task <ChargeResponse> CreateChargeAsync(ChargeData chargeData) { var jsonSettings = new JsonSerializerSettings(); jsonSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; jsonSettings.NullValueHandling = NullValueHandling.Ignore; logger.Debug("CreateChargeAsync [REQ]:" + chargeData.Description); try { string bodyJson = JsonConvert.SerializeObject(chargeData, jsonSettings); StringContent httpContent = new StringContent(bodyJson, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(zebedeeUrl + "charges", httpContent); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); //Deserialize ChargeResponse deserializedCharge = JsonConvert.DeserializeObject <ChargeResponse>(responseBody, jsonSettings); logger.Debug("createInvoiceAsync[RES]:" + deserializedCharge.Data.Id); return(deserializedCharge); } catch (Exception e) { logger.Error(string.Format("Error :{0} ", e.Message)); throw e; } }
public async Task CreateChargeAsync(ChargeData chargeData, Action <ChargeResponse> chargeAction) { ChargeResponse deserializedCharge = await CreateChargeAsync(chargeData); logger.Debug("CreateChargeAsync[RES]:" + deserializedCharge.Data.Id); chargeAction(deserializedCharge); }
public async virtual Task <ChargeResponse> Get(string identifier) { string requestUri = string.Format("{0}/api/charges/{1}", server, identifier); HttpResponseMessage result = null; try { result = await client.GetAsync(requestUri); if (result.StatusCode == HttpStatusCode.OK) { ChargeResponse response = JsonConvert.DeserializeObject <ChargeResponse>(result.Content.ReadAsStringAsync().GetAwaiter().GetResult()); if (response.alreadyExist) { return(new ChargeResponseOK()); } } throw new Exception("TODO"); } catch (Exception ex) { return(new ChargeResponseException() { Message = ex.Message }); } }
private async void handleInvoice(ChargeResponse invoice) { //3.Lightning BOLT invoice string string boltInvoice = invoice.Data.Invoice.Request; string chargeId = invoice.Data.Id; if (string.IsNullOrEmpty(boltInvoice)) { Debug.Log("bolt Invoice is not set in Invoice in reponse.Check the BTCpay server's lightning setup"); return; } Texture2D texs = GenerateQR(boltInvoice);//Generate QR code image //4.Set the QR code Image to image Gameobject QRcodeBOLT11.GetComponent <Image>().sprite = Sprite.Create(texs, new Rect(0.0f, 0.0f, texs.width, texs.height), new Vector2(0.5f, 0.5f), 100.0f); //5.Subscribe the get notified about payment status string status = await zbdClient.SubscribeChargeAsync(chargeId); if ("completed".Equals(status)) { //Change the image from QR to Paid QRcodeBOLT11.GetComponent <Image>().sprite = Resources.Load <Sprite>("image/paid"); logger.Debug("payment is complete"); } else { //for example, if the amount paid is not full, do something.the line below just print the status. logger.Error("payment is not completed:" + status); } }
public void ChargeSerialize_Test() { /* * { * "name": "Purchased game item #MASA001", * "description": "Description of the Charge by Masa", * "amount": "1000", * "callbackUrl": "http://localhost/callback", * "internalId": "MASA001" * } */ //test text string testMessage = "TEST MESSAGE"; string testPaymentName = "Purchased game item #MASA001"; ChargeResponse charge = new ChargeResponse(); charge.Message = testMessage; ChargeData data = new ChargeData(); data.Name = testPaymentName; charge.Data = data; //Serialize string output = JsonConvert.SerializeObject(charge); Assert.Contains(testMessage, output); //Deserialize ChargeResponse deserializedCharge = JsonConvert.DeserializeObject <ChargeResponse>(output); Assert.NotNull(deserializedCharge.Data); Assert.Equal(deserializedCharge.Data.Name, testPaymentName); }
void IssueCharge() { Payer payer = new Payer(); payer.Name = "Pagador teste - SDK .NET"; payer.CpfCnpj = "18415256930"; Charge charge = new Charge(); charge.Description = "Cobrança teste gerada pelo SDK .NET"; charge.Amount = 176.45m; charge.Payer = payer; charge.PaymentTypes = new PaymentType[] { PaymentType.BOLETO, PaymentType.CREDIT_CARD }; try { ChargeResponse response = boletoFacil.IssueCharge(charge); ShowObjectResponseHeader(); foreach (Charge c in response.Data.Charges) { Console.WriteLine(""); Console.WriteLine(c); } ShowResponseSerialized(response); } catch (BoletoFacilException e) { HandleException(e); } finally { DoneMessage(); } }
public async Task <string> SubscribeChargeAsync(string chargeId, int timeoutSec = 60) { ChargeResponse chargeDetail = await zbdService.SubscribeInvoiceAsync(chargeId, timeoutSec); logger.Debug("SubscribeChargeAsync with amount:" + chargeDetail.Data.Amount); return(chargeDetail.Data.Status); }
private async Task <ChargeResponse> getChargeDetailAsync(String chargeUuid) { if (String.IsNullOrEmpty(chargeUuid)) { throw new ZedebeeException("GET Charge Detail Missing chargeUuid :" + chargeUuid); } ChargeResponse deserializedCharge = null; string responseBody = null; string url = this.zebedeeUrl + "charges/" + chargeUuid; try { HttpResponseMessage response = await client.GetAsync(url); responseBody = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); //Deserialize deserializedCharge = JsonConvert.DeserializeObject <ChargeResponse>(responseBody, jsonSettings); } catch (Exception e) { logger.Error(string.Format("Get Charge with Exception :" + e)); throw new ZedebeeException("Get Charge Detail ends with Exception :" + url + "-" + responseBody, e); } return(deserializedCharge); }
public void IssueChargeCarnet() { BoletoFacil boletoFacil = GetBoletoFacil(); Charge charge = Charge; charge.Installments = 3; ChargeResponse response = boletoFacil.IssueCharge(charge); Assert.IsNotNull(response); Assert.IsTrue(response.Success); Assert.AreEqual(3, response.Data.Charges.Length); Assert.IsInstanceOfType(response.Data.Charges[0], typeof(Charge)); Assert.IsInstanceOfType(response.Data.Charges[1], typeof(Charge)); Assert.IsInstanceOfType(response.Data.Charges[2], typeof(Charge)); Assert.AreEqual("101", response.Data.Charges[0].Code); Assert.AreEqual("102", response.Data.Charges[1].Code); Assert.AreEqual("103", response.Data.Charges[2].Code); Assert.AreEqual(StartDate.Date, response.Data.Charges[0].DueDate.Date); Assert.AreEqual(StartDate.Date.AddMonths(1), response.Data.Charges[1].DueDate.Date); Assert.AreEqual(StartDate.Date.AddMonths(2), response.Data.Charges[2].DueDate.Date); Assert.AreEqual(BaseUrl, response.Data.Charges[0].Link.Substring(0, BaseUrl.Length)); Assert.AreEqual(BaseUrl, response.Data.Charges[1].Link.Substring(0, BaseUrl.Length)); Assert.AreEqual(BaseUrl, response.Data.Charges[2].Link.Substring(0, BaseUrl.Length)); Assert.AreEqual("03399.63290 64000.001014 00236.601027 8 67150000004115", response.Data.Charges[0].PayNumber); Assert.AreEqual("03399.63290 64000.001014 00236.601027 8 67250000004115", response.Data.Charges[1].PayNumber); Assert.AreEqual("03399.63290 64000.001014 00236.601027 8 67350000004115", response.Data.Charges[2].PayNumber); }
public Dictionary <string, string> Get3DSPaymentParams(ChargeResponse chargeResponse, string redirectUrl) { return(new Dictionary <string, string> { ["MD"] = chargeResponse.TransactionId, ["TermUrl"] = redirectUrl, ["PaReq"] = chargeResponse.PaReq }); }
public ChargeResponse GetCharge(BaseRequestParams parameters) { ChargeResponse response = new ChargeResponse() { Xm = parameters.Xm, Sfzh = parameters.Sfzh }; return(response); }
public ActionResult Donate(Charge charge, string cardToken) { Card c = (Card)Session["cardInfo"]; charge.Amount *= 100; this.charge = new PostCharge() { Amount = charge.Amount, CardToken = cardToken, Currency = "AUD", Description = charge.Description, Email = charge.Email, IPAddress = Request.ServerVariables["REMOTE_ADDR"] }; ChargeResponse response = ps.Charge(this.charge); if (response.Error == null) { if (response.Charge.Success) { receipt = new DonateReceipt() { Amount = response.Charge.Amount.ToString(), Card_Token = response.Charge.Card_Token, Created = response.Charge.Created, Currency = response.Charge.Currency, Description = response.Charge.Description, Email = response.Charge.Email, IP_address = response.Charge.IP_address, Token = response.Charge.Token }; drs.AddReceipt(receipt); Session.Remove("cardInfo"); return(RedirectToAction("Receipt", new { token = receipt.Token })); } else { TempData["PurchaceFailed"] = response.Messages[0].Message; return(RedirectToAction("Donate", new { ct = cardToken })); } } else { if (response.Messages != null) { TempData["PurchaceFailed"] = response.Messages[0].Message; } else { TempData["PurchaceFailed"] = response.Description; } return(RedirectToAction("Donate", new { ct = cardToken })); } }
private void HandleResponse(ChargeResponse response) { // You may want to perform different actions based on the // response code. This example shows an message dialog with // the response data when the charge is approved. if (response.ResponseCode == ChargeResponse.Code.APPROVED) { // Any extra params we included with the return URL can be // queried from the ExtraParams dictionary. string recordId; response.ExtraParams.TryGetValue("record_id", out recordId); // The URL is a public attack vector for the app, so it's // important to validate any parameters. if (!this.IsValidRecordId(recordId)) { ShowMessage("Invalid Record ID"); return; } string message = String.Format( CultureInfo.CurrentCulture, "Charged!\n" + "Record: {0}\n" + "Transaction ID: {1}\n" + "Amount: {2} {3}\n" + "Card Type: {4}\n" + "Redacted Number: {5}", recordId, response.TransactionId, response.Amount, response.Currency, response.CardType, response.RedactedCardNumber); // Generally you would do something app-specific here, // like load the record specified by recordId, record the // success or failure, etc. Since this sample doesn't // actually do much, we'll just pop a message dialog. ShowMessage(message); } else // other response code values are documented in ChargeResponse.cs { string recordId; response.ExtraParams.TryGetValue("record_id", out recordId); string message = String.Format( CultureInfo.CurrentCulture, "Not Charged!\n" + "Record: {0}", recordId); ShowMessage(message); } }
public void CancelChargeCanBeMocked() { var chargeResponse = new ChargeResponse(); this.mockWebStoreClient.Setup(mwsc => mwsc.CancelCharge(It.IsAny <string>(), It.IsAny <CancelChargeRequest>(), It.IsAny <Dictionary <string, string> >())).Returns(chargeResponse); var result = this.mockWebStoreClient.Object.CancelCharge("chargeId", new CancelChargeRequest("Testing"), new Dictionary <string, string>()); Assert.That(result, Is.EqualTo(chargeResponse)); this.mockWebStoreClient.Verify(mwsc => mwsc.CancelCharge(It.IsAny <string>(), It.IsAny <CancelChargeRequest>(), It.IsAny <Dictionary <string, string> >()), Times.Once); }
public void ChargeCanBeMocked() { var chargeResponse = new ChargeResponse(); this.mockInStoreClient.Setup(misc => misc.Charge(It.IsAny <CreateChargeRequest>(), It.IsAny <Dictionary <string, string> >())).Returns(chargeResponse); var result = this.mockInStoreClient.Object.Charge(new CreateChargeRequest("ChargePermissionId", 100, Types.Currency.USD, "chargeRefernceId"), new Dictionary <string, string>()); Assert.That(result, Is.EqualTo(chargeResponse)); this.mockInStoreClient.Verify(misc => misc.Charge(It.IsAny <CreateChargeRequest>(), It.IsAny <Dictionary <string, string> >()), Times.Once); }
public void ChargeDeserialize_Test() { //test text string testJson = @" { ""message"": ""Successfully retrieved Charge."", ""data"": { ""id"": ""773cc63c-8e4a-437d-87f1-c89049e4d076"", ""name"": ""Purchased game item #MASA001"", ""description"": ""Description of the Charge by Masa"", ""createdAt"": ""2019-12-28T20:45:39.575Z"", ""successUrl"": ""http://localhost/success"", ""callbackUrl"": ""http://localhost/callback"", ""internalId"": ""MASA001"", ""amount"": ""1000"", ""status"": ""expired"", ""invoice"": { ""expiresAt"": ""2019-12-28T20:55:39.594Z"", ""request"": ""lnbc10n1p0q00hnpp5ce8yksx5455eh7rtmmx7f6jm0gs4wy3n3794mywm78sm06kwr7tqdp4g3jhxcmjd9c8g6t0dcsx7e3qw35x2gzrdpshyem9yp38jgzdv9ekzcqzpgxqzjcfppj7j3tfup9ph0g0g6hkf5ykh0scw87ffnz9qy9qsqsp5zqeu32n0khtpejtcep2wkavwqxvnvp09wh8fx5k28cdfs4hv8mqs7x426zqdg0wmhy2ta6hz4kdej7hh9rx2alkn7qsdfn3vgq7g2x4n09amt0d6duxpk9znurlwxrz676zyrceghla7yux0p7vpn6ymekcpn5ypxj"" } } }"; var jsonSettings = new JsonSerializerSettings(); jsonSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //Deserialize ChargeResponse deserializedCharge = JsonConvert.DeserializeObject <ChargeResponse>(testJson, jsonSettings); //1st level Assert.Equal("Successfully retrieved Charge.", deserializedCharge.Message); Assert.NotNull(deserializedCharge.Data); ChargeData data = deserializedCharge.Data; //2nd level Assert.Equal("773cc63c-8e4a-437d-87f1-c89049e4d076", data.Id); Assert.Equal("Purchased game item #MASA001", data.Name); Assert.Equal("Description of the Charge by Masa", data.Description); // Assert.Equal(DateTime.Parse("2019-12-28T20:45:39.575Z"), data.CreatedAt); Assert.Equal("http://localhost/callback", data.CallbackUrl); Assert.Equal("MASA001", data.InternalId); Assert.Equal(1000, data.Amount); Assert.Equal("expired", data.Status); Assert.NotNull(data.Invoice); Invoice invoice = data.Invoice; //3rd level Assert.Equal(DateTime.Parse("2019-12-28T20:55:39.594Z"), invoice.ExpiresAt, TimeSpan.FromSeconds(1)); Assert.Equal("lnbc10n1p0q00hnpp5ce8yksx5455eh7rtmmx7f6jm0gs4wy3n3794mywm78sm06kwr7tqdp4g3jhxcmjd9c8g6t0dcsx7e3qw35x2gzrdpshyem9yp38jgzdv9ekzcqzpgxqzjcfppj7j3tfup9ph0g0g6hkf5ykh0scw87ffnz9qy9qsqsp5zqeu32n0khtpejtcep2wkavwqxvnvp09wh8fx5k28cdfs4hv8mqs7x426zqdg0wmhy2ta6hz4kdej7hh9rx2alkn7qsdfn3vgq7g2x4n09amt0d6duxpk9znurlwxrz676zyrceghla7yux0p7vpn6ymekcpn5ypxj", invoice.Request); }
/// <summary> ///Create Invoice asynchronously , returning ChargeDetail Reponse /// </summary> public async Task <ChargeResponse> CreateInvoiceAsync(Charge charge) { ChargeData chargeData = new ChargeData(); chargeData.Amount = charge.AmountInSatoshi * 1000; chargeData.Description = charge.Description; chargeData.Name = charge.Description; logger.Debug("CreateInvoice with amount:" + chargeData.Amount); ChargeResponse chargeDetail = await zbdService.CreateChargeAsync(chargeData); return(chargeDetail); }
public async Task given_data_for_add_new_charge_we_obtein_a_ok_response_with_true_result() { ReturnValueForPostAsync(false); string requestUri = "http://localhost:10001/api/charges/add"; Charge newCharge = GivenACharge(); var content = GivenAHttpContent(newCharge, requestUri); var chargeRepositoryServiceClient = new ChargeRepositoryServiceApiClient(client); ChargeResponse result = await chargeRepositoryServiceClient.AddCharge(newCharge); result.Should().BeOfType <Charges.Business.Dtos.ChargeResponseOK>(); result.alreadyExist.Should().Be(false); result.Message.Should().BeNull(); await client.Received(1).PostAsync(Arg.Any <string>(), Arg.Any <HttpContent>()); }
public void ConstructorAndFields() { ChargeResponse obj = new ChargeResponse(); Assert.IsNotNull(obj); Assert.IsNull(obj.Data); obj.Data = new ChargeList(); Assert.IsNotNull(obj.Data); obj.Data.Charges = new Charge[1]; obj.Data.Charges[0] = new Charge(); Assert.IsNotNull(obj.ToJson()); }
public void IssueChargeUniqueMandatoryFields() { BoletoFacil boletoFacil = GetBoletoFacil(); Charge charge = Charge; ChargeResponse response = boletoFacil.IssueCharge(charge); Assert.IsNotNull(response); Assert.IsTrue(response.Success); Assert.AreEqual(1, response.Data.Charges.Length); Assert.IsInstanceOfType(response.Data.Charges[0], typeof(Charge)); Assert.AreEqual("101", response.Data.Charges[0].Code); Assert.AreEqual(StartDate.Date, response.Data.Charges[0].DueDate.Date); Assert.AreEqual(BaseUrl, response.Data.Charges[0].Link.Substring(0, BaseUrl.Length)); Assert.AreEqual("03399.63290 64000.001014 00236.601027 8 67150000025000", response.Data.Charges[0].PayNumber); }
protected override void OnActivated(IActivatedEventArgs args) { base.OnActivated(args); // When the transaction is complete, we'll launch the returnUrl // if you provided one to us. var protocolArgs = args as ProtocolActivatedEventArgs; if (args.Kind != ActivationKind.Protocol || protocolArgs == null) { // There are several ways your app can be activated. // We are only concern with the case where we're activated. // In your app, this might mean you should handle this // differently. return; } Uri uri = protocolArgs.Uri; // This sample always uses com-innerfence-chargedemo://chargeresponse // as the base return URL. if (!uri.Host.Equals("chargeresponse")) { // In your app, this might mean that you should handle this as // a normal URL request instead of a charge response. return; } ChargeResponse response; try { // Creating the ChargeResponse object will throw an exception // if there's a problem with the response URL parameters response = new ChargeResponse(uri); } catch (ChargeException ex) { // In the event the parsing fails, we will throw an exception // and you should handle the error. ShowMessage(ex.Message); return; } this.HandleResponse(response); }
public virtual async Task <ChargeResponse> AddCharge(Charge newCharge) { string requestUri = string.Format("{0}/api/charges/add", server); var content = GivenAHttpContent(newCharge, requestUri); var result = await client.PostAsync(requestUri, content); ChargeResponse response = JsonConvert.DeserializeObject <ChargeResponse>(result.Content.ReadAsStringAsync().GetAwaiter().GetResult()); if (result.StatusCode == HttpStatusCode.OK && response.alreadyExist) { return(new ChargeAlreadyExist()); } if (result.StatusCode == HttpStatusCode.OK && !response.alreadyExist) { return(new ChargeResponseOK()); } throw new Exception("TODO"); }
public void IssueChargeWithProxy() { BoletoFacil boletoFacil = GetBoletoFacil(); boletoFacil.SetProxy("http://localhost", "username", "password"); Assert.IsTrue(boletoFacil.UseProxy); Charge charge = Charge; ChargeResponse response = boletoFacil.IssueCharge(charge); Assert.IsNotNull(response); Assert.IsTrue(response.Success); Assert.AreEqual(1, response.Data.Charges.Length); Assert.IsInstanceOfType(response.Data.Charges[0], typeof(Charge)); Assert.AreEqual("101", response.Data.Charges[0].Code); Assert.AreEqual(StartDate.Date, response.Data.Charges[0].DueDate.Date); Assert.AreEqual(BaseUrl, response.Data.Charges[0].Link.Substring(0, BaseUrl.Length)); Assert.AreEqual("03399.63290 64000.001014 00236.601027 8 67150000025000", response.Data.Charges[0].PayNumber); }
protected override string OnNotify(System.Web.HttpContext context) { context.Request.ContentEncoding = encode; var c = context.Request.Form; var fields = typeof(ChargeResponse).GetFields(); var obj = new ChargeResponse(); foreach (var item in fields) { item.SetValue(obj, c[item.Name]); } if (obj.CheckSign(obj.ChkValue)) { return "签名不正确"; } if (obj.RespCode == "000000") { IPayHistory order = OnlinePayBusiness.Instance.GetOrder(obj.OrdId, ThisCompanyType); Confirm(order, GetType(), Convert.ToDecimal(obj.OrdAmt)); return string.Format("RECV_ORD_ID_{0}", obj.OrdId); } return string.Format("失败 {0}", obj.RespCode); }
private async void handleInvoice(ChargeResponse invoice) { //3.Lightning BOLT invoice string string boltInvoice = invoice.Data.Invoice.Request; string chargeId = invoice.Data.Id; if (string.IsNullOrEmpty(boltInvoice)) { Debug.Log("bolt Invoice is not set in Invoice in reponse.Check the BTCpay server's lightning setup"); return; } Texture2D texs = GenerateQR(boltInvoice);//Generate QR code image //4.Set the QR code iamge to image Gameobject //4.取得したBOLTからQRコードを作成し、ウオレットでスキャンするために表示する。 QRcodeBOLT11.GetComponent <Image>().sprite = Sprite.Create(texs, new Rect(0.0f, 0.0f, texs.width, texs.height), new Vector2(0.5f, 0.5f), 100.0f); //5.Subscribe the an callback method with invoice ID to be monitored //5.支払がされたら実行されるコールバックを引き渡して、コールーチンで実行する // StartCoroutine(btcPayClient.SubscribeInvoiceCoroutine(invoice.Id, printInvoice)); //StartCoroutine(btcPayClient.listenInvoice(invoice.Id, printInvoice)); string status = await zbdClient.SubscribeChargeAsync(chargeId); if ("completed".Equals(status)) { //インボイスのステータスがcompleteであれば、全額が支払われた状態なので、支払完了のイメージに変更する //Change the image from QR to Paid QRcodeBOLT11.GetComponent <Image>().sprite = Resources.Load <Sprite>("image/paid"); logger.Debug("payment is complete"); } else { //for example, if the amount paid is not full, do something.the line below just print the status. //全額支払いでない場合には、なにか処理をおこなう。以下は、ただ ステータスを表示して終了。 logger.Error("payment is not completed:" + status); } }
public async Task <ActionResult <ChargeResponse> > Post(Charges.Business.Dtos.Charge charge) { try { ChargeResponse result = await actionFactory .CreateAddChargeAction() .Execute(charge); if (result is ChargeAlreadyExist) { return(BadRequest(new ChargeResponseKO() { Message = "Identifier already exist" }));; } return(Ok(result)); } catch (Exception e) { return(BadRequest(new ChargeResponseKO() { Message = e.Message })); } }
static async System.Threading.Tasks.Task Main(string[] args) { Payment payment = new Payment(); var key = payment.GetEncryptionKey(Secretkey); var json = JsonConvert.SerializeObject(GetData()); var encryptedData = payment.EncryptData(key, json); PayLoad postData = GetPayLoad(encryptedData); var jsondata = JsonConvert.SerializeObject(postData); ChargeResponse chargeReponse = await payment.SuggestCardType(chargeEndpoint, jsondata); if (chargeReponse != null && chargeReponse.status == "success" && chargeReponse.data.suggested_auth == "PIN") { var rawJsonDataInit = JsonConvert.SerializeObject(GetData(chargeReponse.data.suggested_auth, "3310")); var encryptedDataInit = payment.EncryptData(key, rawJsonDataInit); PayLoad payloadInit = GetPayLoad(encryptedDataInit); var encrptedjsondataInit = JsonConvert.SerializeObject(payloadInit); CardResponse cardReponse = await payment.InitializePayment(chargeEndpoint, encrptedjsondataInit); if (cardReponse != null && cardReponse.data.chargeResponseCode == "02" && cardReponse.data.authModelUsed == "PIN") { var dataRf = new { PBFPubKey = PublicKey, transaction_reference = cardReponse.data.txRef, otp = "12345" }; var jsondf = JsonConvert.SerializeObject(dataRf); ValidateResponse valReps = await payment.ValidatePayment(validationEndpoint, jsondf); } } else if (chargeReponse.status == "error") { } }
/// <summary> /// This method does polling to Zebedee GetCharge Details API with a charge ID in a loop /// 1. It will time out after a certain delay /// 2. It will keep hitting the API until get the Target status in certain frequency (e.g. Settled or Failed) /// </summary> /// <param name="invoiceUUid"></param> /// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns> public async Task <ChargeResponse> SubscribeInvoiceAsync(string invoiceUUid, int timeoutSec = 60) { logger.Debug("SubscribeInvoice[REQ]:" + invoiceUUid); TimeSpan delay = TimeSpan.FromSeconds(1); TimeSpan timeout = TimeSpan.FromSeconds(Math.Min(timeoutSec, 60));//Max 60 sec Task timeoutTask = Task.Delay(timeout); ChargeResponse chargeDetail = null; // Keep retry when satus is pending or timeoutTask is not completed while ((chargeDetail == null || chargeDetail.Data.Status == "pending") && !timeoutTask.IsCompleted) { chargeDetail = await getChargeDetailAsync(invoiceUUid); await Task.Delay(delay); } if (timeoutTask.IsCompleted) { throw new ZedebeeException("Get Charge Detail Timed-out in " + timeout); } return(chargeDetail); }
public void ChargeResponse() { var obj = new ChargeResponse { Amount = 16, ChargeId = "Lorum_913", CreatedAt = DateTime.Now, Currency = "Lorum_883", Payments = new List <PaymentResponse> { new AfterPayPaymentResponse { Amount = 89, ChargeId = "Lorum_594", CreatedAt = DateTime.Now, Currency = "Lorum_369", Details = new AfterPayDetailsResponse { AuthenticationUrl = "Lorum_504", BankAccountNumber = "Lorum_483", BillToAddress = new AfterPayDetailsRequest.OrderAddress { City = "Lorum_527", HouseNumber = 54, HouseNumberAddition = "Lorum_149", IsoCountryCode = "Lorum_854", PostalCode = "Lorum_531", Reference = new AfterPayDetailsRequest.OrderAddress.ReferencePerson { DateOfBirth = DateTime.Now, EmailAddress = "Lorum_828", Gender = "Lorum_87", Initials = "Lorum_959", IsoLanguage = "Lorum_836", LastName = "Lorum_542", PhoneNumber1 = "Lorum_948", PhoneNumber2 = "Lorum_594" }, Region = "Lorum_436", StreetName = "Lorum_648" }, CallbackUrl = "Lorum_261", CancelledUrl = "Lorum_925", ExpiredUrl = "Lorum_418", FailedUrl = "Lorum_569", InvoiceNumber = "Lorum_490", IpAddress = "Lorum_244", Orderline = new List <AfterPayDetailsRequest.OrderLine> { new AfterPayDetailsRequest.OrderLine { ArticleDescription = "Lorum_881", ArticleId = "Lorum_993", NetUnitPrice = 94, Quantity = 55, UnitPrice = 95, VatCategory = AfterPayVatCategory.Low }, new AfterPayDetailsRequest.OrderLine { ArticleDescription = "Lorum_257", ArticleId = "Lorum_65", NetUnitPrice = 31, Quantity = 17, UnitPrice = 6, VatCategory = AfterPayVatCategory.Zero } }, OrderNumber = "Lorum_878", Password = "******", PortfolioId = 88, PurchaseId = "Lorum_815", Result = new AfterPayDetailsResponse.ResultResponse { Checksum = "Lorum_577", OrderReference = "Lorum_857", ResultId = 69, StatusCode = "Lorum_655", TimestampIn = "Lorum_114", TimestampOut = "Lorum_53", TotalInvoicedAmount = 81, TotalReservedAmount = 70, TransactionId = "Lorum_259" }, ShipToAddress = new AfterPayDetailsRequest.OrderAddress { City = "Lorum_567", HouseNumber = 8, HouseNumberAddition = "Lorum_264", IsoCountryCode = "Lorum_622", PostalCode = "Lorum_969", Reference = new AfterPayDetailsRequest.OrderAddress.ReferencePerson { DateOfBirth = DateTime.Now, EmailAddress = "Lorum_555", Gender = "Lorum_25", Initials = "Lorum_879", IsoLanguage = "Lorum_260", LastName = "Lorum_601", PhoneNumber1 = "Lorum_534", PhoneNumber2 = "Lorum_599" }, Region = "Lorum_599", StreetName = "Lorum_896" }, SuccessUrl = "Lorum_237", TotalOrderAmount = 57 }, DueDate = DateTime.Now, ExpiresAt = DateTime.Now, PaymentId = "Lorum_21", Recurring = false, RecurringId = "Lorum_673", ShortPaymentId = "Lorum_481", Status = "Lorum_273", Test = false, UpdatedAt = DateTime.Now }, new AfterPayPaymentResponse { Amount = 14, ChargeId = "Lorum_445", CreatedAt = DateTime.Now, Currency = "Lorum_347", Details = new AfterPayDetailsResponse { AuthenticationUrl = "Lorum_560", BankAccountNumber = "Lorum_881", BillToAddress = new AfterPayDetailsRequest.OrderAddress { City = "Lorum_834", HouseNumber = 13, HouseNumberAddition = "Lorum_827", IsoCountryCode = "Lorum_179", PostalCode = "Lorum_239", Reference = new AfterPayDetailsRequest.OrderAddress.ReferencePerson { DateOfBirth = DateTime.Now, EmailAddress = "Lorum_290", Gender = "Lorum_389", Initials = "Lorum_219", IsoLanguage = "Lorum_992", LastName = "Lorum_443", PhoneNumber1 = "Lorum_341", PhoneNumber2 = "Lorum_606" }, Region = "Lorum_35", StreetName = "Lorum_795" }, CallbackUrl = "Lorum_618", CancelledUrl = "Lorum_696", ExpiredUrl = "Lorum_349", FailedUrl = "Lorum_216", InvoiceNumber = "Lorum_978", IpAddress = "Lorum_961", Orderline = new List <AfterPayDetailsRequest.OrderLine> { new AfterPayDetailsRequest.OrderLine { ArticleDescription = "Lorum_449", ArticleId = "Lorum_84", NetUnitPrice = 10, Quantity = 41, UnitPrice = 14, VatCategory = AfterPayVatCategory.High }, new AfterPayDetailsRequest.OrderLine { ArticleDescription = "Lorum_985", ArticleId = "Lorum_851", NetUnitPrice = 93, Quantity = 50, UnitPrice = 18, VatCategory = AfterPayVatCategory.Zero } }, OrderNumber = "Lorum_995", Password = "******", PortfolioId = 5, PurchaseId = "Lorum_130", Result = new AfterPayDetailsResponse.ResultResponse { Checksum = "Lorum_774", OrderReference = "Lorum_354", ResultId = 36, StatusCode = "Lorum_308", TimestampIn = "Lorum_506", TimestampOut = "Lorum_18", TotalInvoicedAmount = 58, TotalReservedAmount = 58, TransactionId = "Lorum_305" }, ShipToAddress = new AfterPayDetailsRequest.OrderAddress { City = "Lorum_66", HouseNumber = 45, HouseNumberAddition = "Lorum_478", IsoCountryCode = "Lorum_97", PostalCode = "Lorum_441", Reference = new AfterPayDetailsRequest.OrderAddress.ReferencePerson { DateOfBirth = DateTime.Now, EmailAddress = "Lorum_414", Gender = "Lorum_229", Initials = "Lorum_368", IsoLanguage = "Lorum_599", LastName = "Lorum_431", PhoneNumber1 = "Lorum_750", PhoneNumber2 = "Lorum_37" }, Region = "Lorum_421", StreetName = "Lorum_40" }, SuccessUrl = "Lorum_16", TotalOrderAmount = 31 }, DueDate = DateTime.Now, ExpiresAt = DateTime.Now, PaymentId = "Lorum_538", Recurring = false, RecurringId = "Lorum_492", ShortPaymentId = "Lorum_267", Status = "Lorum_719", Test = false, UpdatedAt = DateTime.Now } }, Status = "Lorum_891", UpdatedAt = DateTime.Now }; var deserialized = ConversionTest(obj); Assert.IsNotNull(deserialized); Assert.AreEqual(obj.ChargeId, deserialized.ChargeId); // Check only date and time up to seconds.. Json.NET does not save milliseconds. Assert.AreEqual( new DateTime(obj.CreatedAt.Year, obj.CreatedAt.Month, obj.CreatedAt.Day, obj.CreatedAt.Hour, obj.CreatedAt.Minute, obj.CreatedAt.Second), new DateTime(deserialized.CreatedAt.Year, deserialized.CreatedAt.Month, deserialized.CreatedAt.Day, deserialized.CreatedAt.Hour, deserialized.CreatedAt.Minute, deserialized.CreatedAt.Second)); Assert.AreEqual(obj.Currency, deserialized.Currency); Assert.AreEqual(obj.Payments?.Count(), deserialized.Payments?.Count()); for (var paymentsIndex = 0; paymentsIndex < obj.Payments.Count(); paymentsIndex++) { var expectedAfterPayPaymentResponseInPayments = obj.Payments.ElementAt(paymentsIndex) as AfterPayPaymentResponse; var actualAfterPayPaymentResponseInPayments = deserialized.Payments.ElementAt(paymentsIndex) as AfterPayPaymentResponse; Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.ChargeId, actualAfterPayPaymentResponseInPayments.ChargeId); // Check only date and time up to seconds.. Json.NET does not save milliseconds. Assert.AreEqual( new DateTime(expectedAfterPayPaymentResponseInPayments.CreatedAt.Year, expectedAfterPayPaymentResponseInPayments.CreatedAt.Month, expectedAfterPayPaymentResponseInPayments.CreatedAt.Day, expectedAfterPayPaymentResponseInPayments.CreatedAt.Hour, expectedAfterPayPaymentResponseInPayments.CreatedAt.Minute, expectedAfterPayPaymentResponseInPayments.CreatedAt.Second), new DateTime(actualAfterPayPaymentResponseInPayments.CreatedAt.Year, actualAfterPayPaymentResponseInPayments.CreatedAt.Month, actualAfterPayPaymentResponseInPayments.CreatedAt.Day, actualAfterPayPaymentResponseInPayments.CreatedAt.Hour, actualAfterPayPaymentResponseInPayments.CreatedAt.Minute, actualAfterPayPaymentResponseInPayments.CreatedAt.Second)); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Currency, actualAfterPayPaymentResponseInPayments.Currency); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.AuthenticationUrl, actualAfterPayPaymentResponseInPayments.Details.AuthenticationUrl); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BankAccountNumber, actualAfterPayPaymentResponseInPayments.Details.BankAccountNumber); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.City, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.City); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.HouseNumber, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.HouseNumber); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.HouseNumberAddition, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.HouseNumberAddition); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.IsoCountryCode, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.IsoCountryCode); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.PostalCode, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.PostalCode); // Check only date and time up to seconds.. Json.NET does not save milliseconds. Assert.AreEqual( new DateTime(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.DateOfBirth.Year, expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.DateOfBirth.Month, expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.DateOfBirth.Day, expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.DateOfBirth.Hour, expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.DateOfBirth.Minute, expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.DateOfBirth.Second), new DateTime(actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.DateOfBirth.Year, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.DateOfBirth.Month, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.DateOfBirth.Day, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.DateOfBirth.Hour, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.DateOfBirth.Minute, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.DateOfBirth.Second)); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.EmailAddress, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.EmailAddress); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.Gender, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.Gender); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.Initials, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.Initials); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.IsoLanguage, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.IsoLanguage); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.LastName, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.LastName); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.PhoneNumber1, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.PhoneNumber1); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.PhoneNumber2, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Reference.PhoneNumber2); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.Region, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.Region); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.BillToAddress.StreetName, actualAfterPayPaymentResponseInPayments.Details.BillToAddress.StreetName); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.CallbackUrl, actualAfterPayPaymentResponseInPayments.Details.CallbackUrl); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.CancelledUrl, actualAfterPayPaymentResponseInPayments.Details.CancelledUrl); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ExpiredUrl, actualAfterPayPaymentResponseInPayments.Details.ExpiredUrl); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.FailedUrl, actualAfterPayPaymentResponseInPayments.Details.FailedUrl); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.InvoiceNumber, actualAfterPayPaymentResponseInPayments.Details.InvoiceNumber); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.IpAddress, actualAfterPayPaymentResponseInPayments.Details.IpAddress); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.Orderline?.Count(), actualAfterPayPaymentResponseInPayments.Details.Orderline?.Count()); for (var orderlineIndex = 0; orderlineIndex < expectedAfterPayPaymentResponseInPayments.Details.Orderline.Count(); orderlineIndex++) { var expectedOrderLineInOrderline = expectedAfterPayPaymentResponseInPayments.Details.Orderline.ElementAt(orderlineIndex) as AfterPayDetailsRequest.OrderLine; var actualOrderLineInOrderline = actualAfterPayPaymentResponseInPayments.Details.Orderline.ElementAt(orderlineIndex) as AfterPayDetailsRequest.OrderLine; Assert.AreEqual(expectedOrderLineInOrderline.ArticleDescription, actualOrderLineInOrderline.ArticleDescription); Assert.AreEqual(expectedOrderLineInOrderline.ArticleId, actualOrderLineInOrderline.ArticleId); Assert.AreEqual(expectedOrderLineInOrderline.NetUnitPrice, actualOrderLineInOrderline.NetUnitPrice); Assert.AreEqual(expectedOrderLineInOrderline.Quantity, actualOrderLineInOrderline.Quantity); Assert.AreEqual(expectedOrderLineInOrderline.UnitPrice, actualOrderLineInOrderline.UnitPrice); Assert.AreEqual(expectedOrderLineInOrderline.VatCategory, actualOrderLineInOrderline.VatCategory); } Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.OrderNumber, actualAfterPayPaymentResponseInPayments.Details.OrderNumber); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.Password, actualAfterPayPaymentResponseInPayments.Details.Password); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.PortfolioId, actualAfterPayPaymentResponseInPayments.Details.PortfolioId); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.PurchaseId, actualAfterPayPaymentResponseInPayments.Details.PurchaseId); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.Result.Checksum, actualAfterPayPaymentResponseInPayments.Details.Result.Checksum); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.Result.OrderReference, actualAfterPayPaymentResponseInPayments.Details.Result.OrderReference); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.Result.ResultId, actualAfterPayPaymentResponseInPayments.Details.Result.ResultId); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.Result.StatusCode, actualAfterPayPaymentResponseInPayments.Details.Result.StatusCode); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.Result.TimestampIn, actualAfterPayPaymentResponseInPayments.Details.Result.TimestampIn); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.Result.TimestampOut, actualAfterPayPaymentResponseInPayments.Details.Result.TimestampOut); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.Result.TotalInvoicedAmount, actualAfterPayPaymentResponseInPayments.Details.Result.TotalInvoicedAmount); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.Result.TotalReservedAmount, actualAfterPayPaymentResponseInPayments.Details.Result.TotalReservedAmount); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.Result.TransactionId, actualAfterPayPaymentResponseInPayments.Details.Result.TransactionId); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.City, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.City); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.HouseNumber, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.HouseNumber); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.HouseNumberAddition, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.HouseNumberAddition); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.IsoCountryCode, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.IsoCountryCode); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.PostalCode, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.PostalCode); // Check only date and time up to seconds.. Json.NET does not save milliseconds. Assert.AreEqual( new DateTime(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.DateOfBirth.Year, expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.DateOfBirth.Month, expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.DateOfBirth.Day, expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.DateOfBirth.Hour, expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.DateOfBirth.Minute, expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.DateOfBirth.Second), new DateTime(actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.DateOfBirth.Year, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.DateOfBirth.Month, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.DateOfBirth.Day, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.DateOfBirth.Hour, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.DateOfBirth.Minute, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.DateOfBirth.Second)); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.EmailAddress, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.EmailAddress); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.Gender, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.Gender); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.Initials, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.Initials); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.IsoLanguage, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.IsoLanguage); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.LastName, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.LastName); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.PhoneNumber1, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.PhoneNumber1); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.PhoneNumber2, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Reference.PhoneNumber2); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.Region, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.Region); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.ShipToAddress.StreetName, actualAfterPayPaymentResponseInPayments.Details.ShipToAddress.StreetName); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.SuccessUrl, actualAfterPayPaymentResponseInPayments.Details.SuccessUrl); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Details.TotalOrderAmount, actualAfterPayPaymentResponseInPayments.Details.TotalOrderAmount); if (expectedAfterPayPaymentResponseInPayments.DueDate.HasValue && actualAfterPayPaymentResponseInPayments.DueDate.HasValue) { // Check only date and time up to seconds.. Json.NET does not save milliseconds. Assert.AreEqual( new DateTime(expectedAfterPayPaymentResponseInPayments.DueDate.Value.Year, expectedAfterPayPaymentResponseInPayments.DueDate.Value.Month, expectedAfterPayPaymentResponseInPayments.DueDate.Value.Day, expectedAfterPayPaymentResponseInPayments.DueDate.Value.Hour, expectedAfterPayPaymentResponseInPayments.DueDate.Value.Minute, expectedAfterPayPaymentResponseInPayments.DueDate.Value.Second), new DateTime(actualAfterPayPaymentResponseInPayments.DueDate.Value.Year, actualAfterPayPaymentResponseInPayments.DueDate.Value.Month, actualAfterPayPaymentResponseInPayments.DueDate.Value.Day, actualAfterPayPaymentResponseInPayments.DueDate.Value.Hour, actualAfterPayPaymentResponseInPayments.DueDate.Value.Minute, actualAfterPayPaymentResponseInPayments.DueDate.Value.Second)); } if (expectedAfterPayPaymentResponseInPayments.ExpiresAt.HasValue && actualAfterPayPaymentResponseInPayments.ExpiresAt.HasValue) { // Check only date and time up to seconds.. Json.NET does not save milliseconds. Assert.AreEqual( new DateTime(expectedAfterPayPaymentResponseInPayments.ExpiresAt.Value.Year, expectedAfterPayPaymentResponseInPayments.ExpiresAt.Value.Month, expectedAfterPayPaymentResponseInPayments.ExpiresAt.Value.Day, expectedAfterPayPaymentResponseInPayments.ExpiresAt.Value.Hour, expectedAfterPayPaymentResponseInPayments.ExpiresAt.Value.Minute, expectedAfterPayPaymentResponseInPayments.ExpiresAt.Value.Second), new DateTime(actualAfterPayPaymentResponseInPayments.ExpiresAt.Value.Year, actualAfterPayPaymentResponseInPayments.ExpiresAt.Value.Month, actualAfterPayPaymentResponseInPayments.ExpiresAt.Value.Day, actualAfterPayPaymentResponseInPayments.ExpiresAt.Value.Hour, actualAfterPayPaymentResponseInPayments.ExpiresAt.Value.Minute, actualAfterPayPaymentResponseInPayments.ExpiresAt.Value.Second)); } Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.PaymentId, actualAfterPayPaymentResponseInPayments.PaymentId); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Recurring, actualAfterPayPaymentResponseInPayments.Recurring); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.RecurringId, actualAfterPayPaymentResponseInPayments.RecurringId); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.ShortPaymentId, actualAfterPayPaymentResponseInPayments.ShortPaymentId); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Status, actualAfterPayPaymentResponseInPayments.Status); Assert.AreEqual(expectedAfterPayPaymentResponseInPayments.Test, actualAfterPayPaymentResponseInPayments.Test); if (expectedAfterPayPaymentResponseInPayments.UpdatedAt.HasValue && actualAfterPayPaymentResponseInPayments.UpdatedAt.HasValue) { // Check only date and time up to seconds.. Json.NET does not save milliseconds. Assert.AreEqual( new DateTime(expectedAfterPayPaymentResponseInPayments.UpdatedAt.Value.Year, expectedAfterPayPaymentResponseInPayments.UpdatedAt.Value.Month, expectedAfterPayPaymentResponseInPayments.UpdatedAt.Value.Day, expectedAfterPayPaymentResponseInPayments.UpdatedAt.Value.Hour, expectedAfterPayPaymentResponseInPayments.UpdatedAt.Value.Minute, expectedAfterPayPaymentResponseInPayments.UpdatedAt.Value.Second), new DateTime(actualAfterPayPaymentResponseInPayments.UpdatedAt.Value.Year, actualAfterPayPaymentResponseInPayments.UpdatedAt.Value.Month, actualAfterPayPaymentResponseInPayments.UpdatedAt.Value.Day, actualAfterPayPaymentResponseInPayments.UpdatedAt.Value.Hour, actualAfterPayPaymentResponseInPayments.UpdatedAt.Value.Minute, actualAfterPayPaymentResponseInPayments.UpdatedAt.Value.Second)); } } Assert.AreEqual(obj.Status, deserialized.Status); if (obj.UpdatedAt.HasValue && deserialized.UpdatedAt.HasValue) { // Check only date and time up to seconds.. Json.NET does not save milliseconds. Assert.AreEqual( new DateTime(obj.UpdatedAt.Value.Year, obj.UpdatedAt.Value.Month, obj.UpdatedAt.Value.Day, obj.UpdatedAt.Value.Hour, obj.UpdatedAt.Value.Minute, obj.UpdatedAt.Value.Second), new DateTime(deserialized.UpdatedAt.Value.Year, deserialized.UpdatedAt.Value.Month, deserialized.UpdatedAt.Value.Day, deserialized.UpdatedAt.Value.Hour, deserialized.UpdatedAt.Value.Minute, deserialized.UpdatedAt.Value.Second)); } }
private async Task VerifyResult(Business.Dtos.Charge newCharge, ActivityDto activityDto, ChargeActivityServiceApiClient clientActivityService, ChargeResponse result) { result.Should().BeOfType <ChargeResponseOK>(); await clientActivityService.Received(1).NotifyNewCharge(Arg.Is <ActivityDto>(item => item.identifier == activityDto.identifier)); await clientChargeRepository.Received(1).AddCharge(newCharge); await clientActivityService.Received(1).UpdateNotifyCharge(Arg.Is <ActivityDto>(item => item.identifier == activityDto.identifier && item.AddResult == activityDto.AddResult)); }
public async Task <Transaction> Charge(ChargeOptions options, UserWallet wallet) { HttpResponseMessage response = null; string requestContentBase64String = string.Empty; string requestUri = HttpUtility.UrlEncode(""); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri); string requestHttpMethod = request.Method.Method; //Calculate UNIX time DateTime epochStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); TimeSpan timeSpan = DateTime.UtcNow - epochStart; string requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString(); //create random nonce for each request string nonce = Guid.NewGuid().ToString("N"); string merchantRef = $"BST-{Guid.NewGuid().ToString("N")}"; ChargeInfo cInfo = new ChargeInfo() { Amount = options.Amount, TxnMode = 1, TxnType = "DR", MerchantTxnRef = merchantRef, OrderTxnRef = options.RefLocal, PhoneNumber = FormatPhoneNumber(wallet.Value), TxnWallet = ResolveOperator(wallet) }; string rawContent = JsonConvert.SerializeObject(cInfo); request.Content = new StringContent(rawContent, Encoding.UTF8, "application/json"); //Checking if the request contains body, usually will be null with HTTP GET and DELETE if (request.Content != null) { var stringToHash = await request.Content.ReadAsStringAsync(); System.Diagnostics.Debug.WriteLine($"Request Content: {stringToHash}"); var hasher = MD5.Create(); var HashValue = hasher.ComputeHash(Encoding.ASCII.GetBytes(stringToHash)); requestContentBase64String = string.Join("", HashValue.Select(b => b.ToString("x2"))); } //Creating the raw signature string string signatureRawData = String.Format("{0}{1}{2}{3}{4}{5}", appId, requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String); string requestSignatureBase64String = CreateToken(signatureRawData, apiKey); string authHeader = string.Format("{0}:{1}:{2}:{3}", appId, requestSignatureBase64String, nonce, requestTimeStamp); request.Headers.Authorization = new AuthenticationHeaderValue("amx", authHeader); try { using (var client = new HttpClient()) { response = await client.SendAsync(request); // get charge response from server response ChargeResponse chargeResponse = JsonConvert.DeserializeObject <ChargeResponse>(await response.Content.ReadAsStringAsync()); return(new Transaction() { Type = TransactionType.Charge, ChargedAmount = 0, Status = (response.IsSuccessStatusCode && chargeResponse?.StatusCode == "010") ? TransactionStatus.Successful : TransactionStatus.Failed, RefLocal = options.RefLocal, Wallet = wallet, IdealAmount = options.Amount, FinalAmount = options.Amount, DateCompleted = DateTime.UtcNow, Message = chargeResponse.Message, RefExternal = merchantRef, }); } } catch (HttpRequestException) { return(new Transaction() { Status = TransactionStatus.Failed, Message = "An exception occured while processing transaction", Wallet = wallet }); } }