private void InitiateTransaction() { // Limpa o log: this.uxLog.Items.Clear(); // Cria uma transação: // Tipo da transação inválido significa que o pinpad vai perguntar ao usuário o tipo da transação. AccountType AccountType; Installment installment = this.GetInstallment(out AccountType); // Pega o valor da transação decimal amount; decimal.TryParse(this.uxTbxTransactionAmount.Text, out amount); if (amount == 0) { this.Log("Valor da transaçào inválido."); return; } // Cria e configura a transação: TransactionEntry transaction = new TransactionEntry(AccountType, amount); transaction.Installment = installment; transaction.InitiatorTransactionKey = this.uxTbxItk.Text; transaction.CaptureTransaction = true; // Envia para o autorizador: IAuthorizationReport report = this.SendRequest(transaction); this.UpdateTransactions(); }
public TransactionTableEntry(IAuthorizationReport report, bool isCancelled) { // Mapping this way so I can mock it dumbly this.StoneId = report.AcquirerTransactionKey; this.Amount = report.Amount; this.Type = report.TransactionType; this.BrandName = report.Card.BrandName; this.CardholderName = report.Card.CardholderName; this.IsCaptured = !isCancelled; }
/// <summary> /// Authorizes a payment. /// </summary> /// <param name="transaction">Transaction to authorize.</param> /// <returns>The report returned from Stone Authorizer, or null if something /// went wrong.</returns> public IAuthorizationReport Authorize(TransactionOption transaction) { // Verify if the authorizer is eligible to do something: if (this.IsUsable == false) { return(null); } // Setup transaction data: ITransactionEntry transactionEntry = new TransactionEntry { Amount = transaction.Amount, CaptureTransaction = true, InitiatorTransactionKey = transaction.Itk, Type = transaction.AccountType }; IAuthorizationReport authReport = null; try { // Authorize the transaction setup and return it's value: ResponseStatus authorizationStatus; authReport = this.StoneAuthorizer.Authorize(transactionEntry, out authorizationStatus); // Show result on console: if (authReport.WasSuccessful == true) { authReport.ShowTransactionOnScreen(); this.Transactions.Add(new TransactionTableEntry(authReport, false)); } else { authReport.ShowErrorOnTransaction(); this.Transactions.Add(new TransactionTableEntry(authReport, true)); } } catch (CardHasChipException) { Console.WriteLine("O cartao possui chip. For favor, insira-o."); this.Transactions.Add(new TransactionTableEntry(transactionEntry, true)); } catch (ExpiredCardException) { Console.WriteLine("Cartão expirado."); this.Transactions.Add(new TransactionTableEntry(transactionEntry, true)); } catch (Exception) { Console.WriteLine("Ocorreu um erro na transacao."); this.Transactions.Add(new TransactionTableEntry(transactionEntry, true)); } return(authReport); }
/// <summary> /// Shows the error that occurred while processing a transaction. /// </summary> /// <param name="failedTransaction">Failed transaction to log on console.</param> public static void ShowErrorOnTransaction(this IAuthorizationReport failedTransaction) { List <string> lines = new List <string>(); lines.Add(string.Format("Codigo de erro: {0}", failedTransaction.ResponseCode)); lines.Add(string.Format("Razao do erro: {0}", failedTransaction.ResponseReason)); Console.WriteLine("TRANSACAO NAO APROVADA:"); Console.Write(lines.ToArray() .ToMarkdownBulletedList()); }
/// <summary> /// Envia a transação para a SDK da Stone. /// </summary> /// <param name="transaction">Transação a ser capturada.</param> /// <returns>Report da transação.</returns> private IAuthorizationReport SendRequest(ITransactionEntry transaction) { ICardPaymentAuthorizer currentAuthorizer = this.GetCurrentPinpad(); if (currentAuthorizer == null) { this.Log("Selecione um pinpad."); } IAuthorizationReport response = null; try { ResponseStatus authorizationStatus; response = currentAuthorizer.Authorize(transaction, out authorizationStatus); } catch (ExpiredCardException) { this.Log("Cartão expirado."); currentAuthorizer.PromptForCardRemoval("CARTAO EXPIRADO"); return(null); } catch (CardHasChipException) { this.Log("Cartão possui chip. Insira o cartão."); currentAuthorizer.PromptForCardRemoval("CARTAO POSSUI CHIP"); return(null); } catch (InvalidConnectionException) { this.Log("Computador não está conectado a internet!"); currentAuthorizer.PromptForCardRemoval("SEM CONEXAO"); return(null); } if (response == null) { this.Log("Um erro ocorreu durante a transação."); return(null); } // Handle poi response: this.VerifyPoiResponse(response); // Loga as mensagens de request e response enviadas e recebidas do autorizador da Stone: this.LogTransaction(response); currentAuthorizer.PinpadFacade.Display.ShowMessage(this.PinpadMessages.MainLabel, null, DisplayPaddingType.Center); return(response); }
/// <summary> /// Show a bulleted list with the information about the transaction. /// </summary> /// <param name="transaction">Transaction to log on console.</param> public static void ShowTransactionOnScreen(this IAuthorizationReport transaction) { List <string> lines = new List <string>(); lines.Add(string.Format("Stone ID: {0}", transaction.AcquirerTransactionKey)); lines.Add(string.Format("Valor: {0}", transaction.Amount)); lines.Add(string.Format("Tipo: {0}", transaction.TransactionType == AccountType.Credit ? "Credito" : "Debito")); lines.Add(string.Format("Bandeira: {0}", transaction.Card.BrandName)); lines.Add(string.Format("Nome do portador: {0}", transaction.Card.CardholderName)); Console.WriteLine("TRANSACAO APROVADA:"); Console.Write(lines.ToArray() .ToMarkdownBulletedList()); }
/// <summary> /// Mapeia os dados sobra a transação (retornados na resposta do autorizador) /// para criar um recibo virtual (para ser mandado por email). /// </summary> /// <param name="report">Resposta do autorizador.</param> /// <returns>Parametros para criar o recibo virtual.</returns> private FinancialOperationParameters GetReceipt(IAuthorizationReport report) { FinancialOperationParameters param = new FinancialOperationParameters(); param.CardBrand = report.Card.BrandName; param.ClientMaskedCardNumber = report.Card.MaskedPrimaryAccountNumber; param.ClientName = report.Card.CardholderName; param.DisplayAidArqc = true; param.DisplayCompanyInformation = false; param.TransactionAid = report.Card.ApplicationId; param.TransactionAmount = report.Amount; param.TransactionArqc = report.Card.ApplicationCryptogram; param.TransactionDateTime = report.DateTime.Value; param.TransactionStoneId = report.AcquirerTransactionKey; return(param); }
/// <summary> /// Reads the card password. /// Perfoms an authorization operation. /// </summary> /// <param name="card">Information about the card.</param> /// <param name="transaction">Information about the transaction.</param> /// <param name="authorizationMessage">Authorization message returned.</param> /// <returns></returns> public bool BuyGas(ICard card, ITransactionEntry transaction, out string authorizationMessage) { Pin pin; authorizationMessage = string.Empty; // Tries to read the card password: try { if (this.Authorizer.ReadPassword(out pin, card, transaction.Amount) != ResponseStatus.Ok) { return(false); } } catch (Exception) { return(false); } // Tries to authorize the transaction: IAuthorizationReport report = this.Authorizer.SendAuthorizationAndGetReport(card, transaction, pin); // Verifies if there were any return: if (report == null) { return(false); } // Verifies authorization response: if (report.WasSuccessful == true) { // The transaction was approved: authorizationMessage = "Transação aprovada"; Task.Run(() => { this.Authorizer.Cancel(report.AcquirerTransactionKey, report.Amount); }); return(true); } else { // The transaction was rejected or declined: authorizationMessage = string.Format("({0}) {1}", report.ResponseCode, report.ResponseReason); return(false); } }
/// <summary> /// Loga o XML da transação em um arquivo definido pelo app.config. /// </summary> /// <param name="report">Resposta do autorizador.</param> private void LogTransaction(IAuthorizationReport report) { if (string.IsNullOrEmpty(this.logFilePath) == true || Directory.Exists(this.logFilePath) == false) { return; } StreamWriter valor = new StreamWriter(this.logFilePath + "\\log.txt", true, Encoding.ASCII); valor.WriteLine(DateTime.Now + System.Environment.NewLine); valor.WriteLine("Request:" + System.Environment.NewLine); valor.Write(report.XmlRequest + System.Environment.NewLine + System.Environment.NewLine); valor.WriteLine("Response" + System.Environment.NewLine); valor.Write(report.XmlResponse + System.Environment.NewLine + System.Environment.NewLine); valor.WriteLine("=============================================" + System.Environment.NewLine); valor.Close(); }
/// <summary> /// Performs a cancellation operation. /// </summary> /// <param name="sender">Cancellation button.</param> /// <param name="e">Click event arguments.</param> private void OnCancelTransaction(object sender, RoutedEventArgs e) { // Limpa o log: this.uxLog.Items.Clear(); ICardPaymentAuthorizer currentAuthorizer = this.GetCurrentPinpad(); if (currentAuthorizer == null) { this.Log("Selecione um pinpad."); return; } string atk = this.uxCbbxTransactions.SelectedItem.ToString(); // Verifica se um ATK válido foi selecionado: if (string.IsNullOrEmpty(atk) == true) { this.Log("Não é possivel cancelar um ATK vazio."); return; } // Seleciona a transação a ser cancelada de acordo com o ATK: IAuthorizationReport transaction = this.approvedTransactions.Where(t => t.AcquirerTransactionKey == atk).First(); // Cancela a transação: ICancellationReport cancelResult = currentAuthorizer.Cancel(transaction.AcquirerTransactionKey, transaction.Amount); if (cancelResult.WasSuccessful == true) { // Cancelamento autorizado. // Retira a transação da coleção de transação aprovadas: this.approvedTransactions.Remove(transaction); this.uxCbbxTransactions.Items.Remove(transaction.AcquirerTransactionKey); } else { // Cancelamento não autorizado: this.Log(string.Format("{0} - {1}", cancelResult.ResponseCode, cancelResult.ResponseReason)); } this.UpdateTransactions(); }
/// <summary> /// Reads the card password. /// Perfoms an authorization operation. /// </summary> /// <param name="card">Information about the card.</param> /// <param name="transaction">Information about the transaction.</param> /// <param name="authorizationMessage">Authorization message returned.</param> /// <returns></returns> public bool BuyThePizza(ICard card, ITransactionEntry transaction, out string authorizationMessage) { Pin pin; authorizationMessage = string.Empty; // Tries to read the card password: try { if (this.authorizer.ReadPassword(out pin, card, transaction.Amount) != ResponseStatus.Ok) { return(false); } } catch (Exception e) { pin = null; Debug.WriteLine(e.Message); return(false); } // Tries to authorize the transaction: IAuthorizationReport report = this.authorizer.SendAuthorizationAndGetReport(card, transaction, pin); // Verifies if there were any return: if (report == null) { return(false); } // Verifies authorization response: if (report.WasSuccessful == true) { // The transaction was approved: this.BoughtPizzas.Add(report); authorizationMessage = "Transação aprovada"; return(true); } else { // Transaction was declined: authorizationMessage = string.Format("({0}) {1}", report.ResponseCode, report.ResponseReason); return(false); } }
/// <summary> /// Verifica a resposta do autorizador. Se a transação foi bem sucedida, /// grava a transação na lista da transações da classe. /// </summary> /// <param name="report">Resposta do autorizador.</param> private void VerifyPoiResponse(IAuthorizationReport report) { if (report == null) { return; } // Verifica o retorno do autorizador: if (report.WasSuccessful == true) { // Transaction approved: this.Log("Transação aprovada."); // Envia comprovante da transação por e-mail: if (string.IsNullOrEmpty(this.uxTbxCustomerEmail.Text) == false) { try { ReceiptFactory.Build(ReceiptType.Transaction, this.uxTbxCustomerEmail.Text) .AddBodyParameters(this.GetReceipt(report)) .Send(); } catch (Exception e) { this.Log(e.Message); } } // Salva em uma collection: this.approvedTransactions.Add(report); // Adiciona o ATK (identificador unico da transação) ao log: this.uxCbbxTransactions.Items.Add(report.AcquirerTransactionKey); } else { this.Log("Transação negada!"); this.Log(report.ResponseCode + " " + report.ResponseReason); } }