Skip to content

Instantly share code, notes, and snippets.

@carneirocorp
Created October 2, 2020 15:33
Show Gist options
  • Save carneirocorp/a49413f1ea0edef7d4553fc41e79f355 to your computer and use it in GitHub Desktop.
Save carneirocorp/a49413f1ea0edef7d4553fc41e79f355 to your computer and use it in GitHub Desktop.
Controller comunicação com PDV
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using MongoDB.Bson.IO;
using Oba.Services.API.Config;
using Oba.Services.API.Data;
using Oba.Services.API.Models;
using Oba.Services.API.Models.Request;
using Oba.Services.API.Models.Response;
using Oba.Services.API.Mongo;
using Oba.Services.API.Providers.Cielo.Models;
using Oba.Services.API.Providers.Cielo.Services;
using static Oba.Services.API.Data.ObaCosmosDB;
namespace Oba.Services.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PdvController : ApiController
{
private readonly ObaCosmosDBConfiguration _cosmosConfiguration;
private readonly CieloService _cieloService;
private readonly TelemetryClient _telemetry;
public PdvController([FromServices] ObaCosmosDBConfiguration cosmosConfiguration, [FromServices] CieloConfiguration cieloConfiguration, TelemetryClient telemetry)
{
_cosmosConfiguration = cosmosConfiguration;
_cieloService = new CieloService(cieloConfiguration);
_telemetry = telemetry;
}
[HttpPost]
[Route("payment-method")]
public ActionResult PostPaymentMethod([FromBody] PdvRequest obj)
{
_telemetry.TrackTrace(Newtonsoft.Json.JsonConvert.SerializeObject(obj));
if (obj.Response != null && obj.Response.Length == 0 && obj.Operation == "cotSalePayment")
{
var objResponse = new PdvResponse
{
Execution = "cetContinue",
Interpret = new Interpret
{
CommandType = "cctGetValue",
MessageCommand = null,
Value = new Value
{
Title = "Pedido",
Subtitle = "Informe o número do pedido",
DataType = "cvtNumber",
Size = 7,
}
}
};
_telemetry.TrackTrace(Newtonsoft.Json.JsonConvert.SerializeObject(objResponse));
return Ok(objResponse);
} else {
if (obj.Response.Length > 0)
{
if (obj.Response == "PGTO_ERRO")
{
var objResponse = new PdvResponse
{
Execution = "cetFailed",
Return = new Return
{
Code = -1,
MessageText = "Erro ao processar pagamento"
},
};
_telemetry.TrackTrace(Newtonsoft.Json.JsonConvert.SerializeObject(objResponse));
return Ok(objResponse);
}
else if (obj.Response == "PGTO_SUCESSO")
{
var objResponse = new PdvResponse
{
Execution = "cetCompleted",
Return = new Return
{
Code = 0,
MessageText = "0"
},
Pay = new Models.Request.Payment
{
AuthorizationCode = obj.Pay.AuthorizationCode,
Total = Convert.ToDouble(obj.Pay.Total),
},
Interpret = null,
VouchersPrint = new List<string> { "Pagamento feito via aplicativo" },
};
_telemetry.TrackTrace(Newtonsoft.Json.JsonConvert.SerializeObject(objResponse));
return Ok(objResponse);
}
else
{
ObaCosmosService<Purchase> purchaseService = new ObaCosmosService<Purchase>(_cosmosConfiguration, ObaCosmosDB.purchaseCollection);
Purchase purchase = purchaseService.FirstOrDefault(p => p.Id == obj.Response);
if (purchase == null)
{
var objResponse = new PdvResponse
{
Execution = "cetContinue",
Pay = new Models.Request.Payment
{
AuthorizationCode = purchase.Payment.PaymentId,
Total = Convert.ToDouble(obj.Pay.Total),
},
Interpret = new Interpret
{
CommandType = "cctMessage",
MessageCommand = new MessageCommand
{
Title = "Falha",
Text = "Erro ao processar pagamento [VENDA NAO ENCONTRADA]",
DefaultButton = "OK",
MessageType = "cmtError",
Buttons = new List<Button>
{
new Button
{
Caption = "OK",
Response = "PGTO_ERRO"
}
}
}
},
Return = new Return
{
Code = 0,
MessageText = "0",
}
};
_telemetry.TrackTrace(Newtonsoft.Json.JsonConvert.SerializeObject(objResponse));
return Ok(objResponse);
}
else
{
var pgto = this.Post(new PdvPayload
{
Comments = "",
FinalPrice = Convert.ToDouble(obj.Pay.Total),
OrderId = Int32.Parse(obj.Response)
});
if (pgto is ObjectResult)
{
if (((ObjectResult)pgto).StatusCode == 500)
{
var objResponse = new PdvResponse
{
Execution = "cetContinue",
Interpret = new Interpret
{
CommandType = "cctMessage",
MessageCommand = new MessageCommand
{
Title = "Falha",
Text = $"Erro ao processar pagamento [{((ObjectResult)pgto).Value.ToString()}]",
DefaultButton = "OK",
MessageType = "cmtError",
Buttons = new List<Button>
{
new Button
{
Caption = "OK",
Response = "PGTO_ERRO"
}
}
}
},
Return = new Return
{
Code = 0,
MessageText = "0",
}
};
_telemetry.TrackTrace(Newtonsoft.Json.JsonConvert.SerializeObject(objResponse));
return Ok(objResponse);
}
}
if (pgto is NotFoundObjectResult)
{
var objResponse = new PdvResponse
{
Execution = "cetContinue",
Interpret = new Interpret
{
CommandType = "cctMessage",
MessageCommand = new MessageCommand
{
Title = "Falha",
Text = $"Erro ao processar pagamento [{((NotFoundObjectResult)pgto).Value.ToString()}]",
DefaultButton = "OK",
MessageType = "cmtError",
Buttons = new List<Button>
{
new Button
{
Caption = "OK",
Response = "PGTO_ERRO"
}
}
}
},
Return = new Return
{
Code = 0,
MessageText = "0",
}
};
_telemetry.TrackTrace(Newtonsoft.Json.JsonConvert.SerializeObject(objResponse));
return Ok(objResponse);
}
else
{
var objResponse = new PdvResponse
{
Execution = "cetContinue",
Interpret = new Interpret
{
CommandType = "cctMessage",
MessageCommand = new MessageCommand
{
Title = "Sucesso",
Text = "Pagamento processado com sucesso",
DefaultButton = "OK",
MessageType = "cmtInformation",
Buttons = new List<Button>
{
new Button
{
Caption = "OK",
Response = "PGTO_SUCESSO"
}
}
}
},
Return = new Return
{
Code = 0,
MessageText = "Pagamento processado com sucesso",
}
};
_telemetry.TrackTrace(Newtonsoft.Json.JsonConvert.SerializeObject(objResponse));
return Ok(objResponse);
}
}
}
}
else
{
var objResponse = new PdvResponse
{
Execution = "cetContinue",
Interpret = new Interpret
{
CommandType = "cctGetValue",
MessageCommand = null,
Value = new Value
{
Title = "Pedido",
Subtitle = "Informe o número do pedido",
DataType = "cvtNumber",
Size = 7,
}
}
};
_telemetry.TrackTrace(Convert.ToString(objResponse));
return Ok(objResponse);
}
}
}
[HttpPost]
public IActionResult Post([FromBody] PdvRequest payload)
{
return Ok(new PdvResponse { Interpret = new Interpret { }, Return = new Return { }, Sale = new Models.Response.Sale { } });
}
[HttpPost("payment")]
public ActionResult Post([FromBody] PdvPayload payload)
{
try
{
ObaCosmosService<Purchase> purchaseService = new ObaCosmosService<Purchase>(_cosmosConfiguration, ObaCosmosDB.purchaseCollection);
Purchase purchase = purchaseService.FirstOrDefault(p => p.Id == payload.OrderId.ToString());
if (purchase == null)
{
Envelope.Message = "Pedido não encontrado";
return NotFound(Envelope);
}
if (purchase.Payment == null || string.IsNullOrEmpty(purchase.Payment.PaymentId))
{
Envelope.Message = "Pagamento não encontrado";
return NotFound(Envelope);
}
if (purchase.Payment.CapturedAt.HasValue && purchase.Payment.CapturedAmount > 0)
{
Envelope.Message = "Pagamento já processado";
return Ok(Envelope);
}
var query = _cieloService.QueryPayment(purchase.Payment.PaymentId);
if (query != null)
{
if (!String.IsNullOrEmpty(query.AuthorizationCode) && !String.IsNullOrEmpty(query.ProofOfSale))
{
Envelope.Message = "Pagamento já processado";
return Ok(Envelope);
}
}
if (payload.FinalPrice > purchase.Payment.AuthorizedAmount)
{
Providers.Cielo.Models.Transaction cancellation = _cieloService.CancelByPayment(purchase.Payment.PaymentId);
Providers.Cielo.Models.AuthorizeResponse transaction = _cieloService.Capture(new Providers.Cielo.Models.Authorize
{
MerchantOrderId = purchase.Id,
Customer = purchase.Customer.ToType<Providers.Cielo.Models.Customer>(),
Payment = new Providers.Cielo.Models.Payment
{
Amount = payload.FinalPrice * 100,
Capture = true,
CreditCard = new Providers.Cielo.Models.CreditCard
{
CardToken = purchase.Payment.CardToken,
SecurityCode = purchase.Payment.Code
}
}
});
purchase.Payment.CanceledPayment = new PurchasePayment
{
PaymentId = purchase.Payment.PaymentId,
AuthorizedAt = purchase.Payment.AuthorizedAt,
CanceledAt = purchase.Payment.CanceledAt,
CardToken = purchase.Payment.CardToken,
Code = purchase.Payment.Code,
AuthorizedAmount = purchase.Payment.AuthorizedAmount,
CapturedAmount = 0
};
purchase.Payment.PaymentId = transaction.Payment.PaymentId;
purchase.Payment.CardToken = transaction.Payment?.CreditCard?.CardToken;
purchase.Payment.AuthorizedAt = transaction.Payment.ReceivedDate;
purchase.Payment.CapturedAt = transaction.Payment.ReceivedDate;
purchase.Payment.CanceledAt = null;
purchase.Payment.AuthorizedAmount = payload.FinalPrice;
purchase.Payment.CapturedAmount = payload.FinalPrice;
}
else if (payload.FinalPrice <= purchase.Payment.AuthorizedAmount)
{
Providers.Cielo.Models.Transaction transaction = _cieloService.PartialCapture(new Providers.Cielo.Models.PartialAuthorize
{
PaymentId = purchase.Payment.PaymentId,
Amount = payload.FinalPrice * 100
});
purchase.Payment.CapturedAt = DateTime.Now;
purchase.Payment.CapturedAmount = payload.FinalPrice;
}
purchaseService.Update(purchase.Id, purchase);
Envelope.Message = "Trasação efetuada com sucesso";
return Ok(Envelope);
}
catch (CieloException ex)
{
Envelope.Message = $"Falha no processo de pagamento [{ex.Message}]";
Envelope.Data = ex;
return StatusCode(500, Envelope);
}
catch (Exception ex)
{
Envelope.Message = "Falha no processo de pagamento";
Envelope.Data = ex;
return StatusCode(500, Envelope);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment