Giter Site home page Giter Site logo

cielo3.0's Introduction

Características

  • Funções Assincronas.
  • HttpClient.
  • Sem dependência a bibliotecas JSON (NewtonSoft, Jil, MessagePack...)
  • Testes Unitários
  • .Net Standard 2

Principais recursos

  • Pagamentos por cartão de crédito.
  • Pagamentos por cartão de débito.
  • Pagamentos recorrentes (de acordo com a Cielo funciona somente para crédito)
    • Com autorização na primeira recorrência ou a partir de uma data.
  • Boleto
  • Transferência Eletrônica
  • Cancelamento de autorização.
  • Consulta de pagamentos.
  • Tokenização do Cartão
    • GetRecurrentPayment - Busca informações sobre a recorrência
    • CreateToken - Tokeniza o cartão válido (ou inválido).
    • CreateTokenValid - Gera um pagamento de 1 real (cancela logo em seguida) para garantir que o cartão é válido e retorna a Token.

Como utilizar

Como não tem uma documentação formal utilize o projeto de Teste (CieloTestsCore) para ver os exemplos criados (e verificar se ainda estão funcionando).

Implemente seu provider JSON

Você pode utilizar qualquer provider JSON. Para isso implemente a interface ISerializerJSON. Exemplo utilizando Newtonsoft:

public class SerializerJSON : ISerializerJSON
{
    public string Serialize<T>(T value)
    {
        // return System.Text.Json.JsonSerializer.Serialize<T>(value);

        return Newtonsoft.Json.JsonConvert.SerializeObject(value);
    }

    public T Deserialize<T>(string jsonText)
    {
        //var json = MessagePackSerializer.Serialize(p);
        //return MessagePackSerializer.Deserialize<Transaction>(jsonText);

        // return Jil.JSON.Deserialize<T>(jsonText);

        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonText);
    }

    public async Task<T> DeserializeAsync<T>(HttpContent content)
    {
        // return await System.Text.Json.JsonSerializer.DeserializeAsync<T>(await content.ReadAsStreamAsync(), _jsonOptions).ConfigureAwait(false);

        var serializer = new JsonSerializer();
        using (var textReader = new StreamReader(await content.ReadAsStreamAsync().ConfigureAwait(false)))
        using (var jsonReader = new JsonTextReader(textReader))
        {
            return serializer.Deserialize<T>(jsonReader);
        }
    }
}

Métodos Async e Sync

Método com o Sufixo Async será executado de forma assincrona.

   await api.CreateTransactionAsync(Guid.NewGuid(), transaction);

Quando não tiver o sufixo Async será executado de forma sincrona.

   api.CreateTransaction(Guid.NewGuid(), transaction));

Chave do Sandbox

Caso queira executar o teste unitário pode deixar a minha chave do Sandbox, se deseja utilizar a sua altere a classe:

  public class Merchant
  {
          public static readonly Merchant SANDBOX = 
                 new Merchant(Guid.Parse("00000000-0000-0000-0000-000000000000"), "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");

  }

Nuget

Install-Package CieloRest -Version 1.0.19

Documentação da Cielo

Exemplo de utilização (utilize os casos de Teste para ver mais exemplos)

        var customer = new Customer(name: _nome);

        var creditCard = new Card(
            cardNumber: SandboxCreditCard.NotAuthorizedCardExpired,
            holder: _nomeCartao,
            expirationDate: _invalidDate,
            securityCode: "123",
            brand: CardBrand.Visa);

        var payment = new Payment(
            amount: 150.04M,
            currency: Currency.BRL,
            installments: 1,
            capture: true,
            softDescriptor: _descricao,
            card: creditCard);

        var transaction = new Transaction(
            merchantOrderId: Random().Next().ToString(),
            customer: customer,
            payment: payment);

        try
        {
            var returnTransaction = _api.CreateTransaction(Guid.NewGuid(), transaction);

            Assert.IsTrue(returnTransaction.Payment.GetStatus() == Status.Denied, "Transação não foi negada");
        }
        catch (CieloException ex)
        {
            Assert.IsTrue(ex.GetCieloErrors().Any(i => i.Code == 126));
        }

MIT License

Copyright (c) 2019 Hugo de Brito V. R. Alves

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

cielo3.0's People

Contributors

hugobritoalves avatar hugobritobh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

cielo3.0's Issues

Internal Server Error - Pagamento com recorrência

Estou tendo um erro ao tentar criar um pagamento usando recorrência.

Usando o GetCieloErrors():

[
   {
      "Code":0,
      "Message":"Error code InternalServerError."
   }
]

Estou montando a transação dessa maneira:

            var customer = new Customer(user.FullName);
            var card = new Card(input.CartaoNumero, input.CartaoNomeImpresso, input.CartaoExpiracao, input.CartaoCodigo, input.CartaoBandeira);
            var recurrent = new RecurrentPayment(plano.Intervalo, DateTime.Today.AddYears(5));
            var payment = new Payment(plano.Valor, Currency.BRL, 1, true, null, card, recurrentPayment: recurrent);
            var transaction = new Transaction(orderId, customer, payment);

E o objeto gerado que é enviado no CreateTransactionAsync() fica assim:

{
   "MerchantOrderId":"e4e5be04-db53-454c-b39b-c9e3faeb97ec",
   "Customer":{
      "Name":"admin admin",
      "Identity":null,
      "IdentityType":null,
      "Email":null,
      "Birthdate":null,
      "Address":null,
      "DeliveryAddress":null
   },
   "Payment":{
      "Installments":1,
      "Interest":null,
      "Capture":true,
      "Authenticate":null,
      "Recurrent":null,
      "RecurrentPayment":{
         "RecurrentPaymentId":null,
         "AuthorizeNow":true,
         "StartDate":null,
         "EndDate":"2025-07-09",
         "NextRecurrency":null,
         "Interval":"Monthly",
         "Links":null,
         "ReasonCode":null,
         "ReasonMessage":null,
         "SuccessfulRecurrences":0,
         "RecurrentTransactions":null,
         "Status":null
      },
      "CreditCard":{
         "CardNumber":"0000000000000001",
         "CardToken":null,
         "Holder":"TESTE",
         "CustomerName":null,
         "ExpirationDate":"08/2020",
         "SecurityCode":"123",
         "SaveCard":false,
         "Brand":"Visa"
      },
      "Tid":null,
      "ProofOfSale":null,
      "AuthorizationCode":null,
      "AuthenticationUrl":null,
      "BoletoNumber":null,
      "Instructions":null,
      "Country":"BRA",
      "ExtraDataCollection":null,
      "ExpirationDate":null,
      "Url":null,
      "Number":null,
      "BarCodeNumber":null,
      "DigitableLine":null,
      "Address":null,
      "SoftDescriptor":null,
      "ReturnUrl":"",
      "Wallet":null,
      "Provider":null,
      "PaymentId":null,
      "Type":"CreditCard",
      "ServiceTaxAmount":null,
      "Amount":"544",
      "CapturedAmount":null,
      "ReceivedDate":null,
      "CapturedDate":null,
      "FraudAnalysis":null,
      "Currency":"BRL",
      "DebitCard":null,
      "CardToken":null,
      "ReturnCode":null,
      "ReturnMessage":null,
      "ReasonCode":null,
      "ReasonMessage":null,
      "ProviderReturnCode":null,
      "ProviderReturnMessage":null,
      "Status":null,
      "Links":null
   }
}

Recorrência sem data fim

Olá,

Pela documentação da Cielo seria possível criar uma transação recorrente sem informar uma data fim.

Seria possível alterar o contrutor de RecurrentPayment para permitir isso?

Será que só assim eu consigo o mesmo efeito?

            var recurrent = new RecurrentPayment();
            recurrent.SetInterval(meuintervalo);

Obrigado

Address.District

Olá Hugo, tudo bem ?

Estive configurando em um cliente a api 3.0 para asp.net 4.5

E estou tendo uma situação com a class Address.

Dentro do código que eu puxei e também na consulta aqui no Git, me parece estar faltando um campo ou não consegui chamar esse campo que é obrigatório: Address.District.

Aparentemente é obrigatório mas não possui dentro do código, como posso proceder?

Obrigado desde já!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.