Giter Club home page Giter Club logo

cielo's Introduction

cielo

Client para a API 3.0 da Cielo em Typescript/Nodejs

MIT license Build Status Known Vulnerabilities codebeat badge JavaScript Style Guide Open Source Love svg2

Índice

Installation

npm install --save cielo

Como utilizar?

Iniciando

import { CieloConstructor, Cielo } from 'cielo';

const cieloParams: CieloConstructor = {
    merchantId: 'xxxxxxxxxxxxxxxxxxxxxxx',
    merchantKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
    requestId: 'xxxxxxx', // Opcional - Identificação do Servidor na Cielo
    sandbox: true, // Opcional - Ambiente de Testes
    debug: true // Opcional - Exibe os dados enviados na requisição para a Cielo
}

const cielo = new Cielo(cieloParams);

Paramêtros de criação

Campo Descrição Obrigatório? Default
merchantId Identificador da loja na Cielo. Sim null
merchantKey Chave publica para autenticação dupla na Cielo. Sim null
requestId Identificador do Request, utilizado quando o lojista usa diferentes servidores para cada GET/POST/PUT. Não null
sandbox Ambiente de testes da Cielo Não false
debug Exibe requisição da transação no console Não false

Cartão de Crédito

Criando uma transação

Usando Promise

const vendaParams: TransactionCreditCardRequestModel = {
    customer: {
        name: "Comprador crédito",
    },
    merchantOrderId: "2014111703",
    payment: {
        amount: 10000, // R$100,00
        creditCard: {
            brand: EnumBrands.VISA,
            cardNumber: "4532117080573700",
            holder: "Comprador T Cielo",
            expirationDate: "12/2021",
        },
        installments: 1,
        softDescriptor: "Banzeh",
        type: EnumCardType.CREDIT,
        capture: false,
    },
};

cielo.creditCard.transaction(dadosSale)
    .then((data) => {
        return console.log(data);
    })
    .catch((err) => {
        return console.error('ERRO', err);
    })

Ou usando Async / Await

const transaction = await cielo.creditCard.transaction(dadosSale);
console.log(transaction);

Capturando uma venda

const capturaVendaParams: CaptureRequestModel = {
    paymentId: '24bc8366-fc31-4d6c-8555-17049a836a07',
    amount: 2000, // Caso o valor não seja definido, captura a venda no valor total
};

cielo.creditCard.captureSaleTransaction(capturaVendaParams)
    .then((data) => {
        return console.log(data);
    })
    .catch((err) => {
        return console.error('ERRO', err);
    })

Cancelando uma venda

const cancelamentoVendaParams: CancelTransactionRequestModel = {
    paymentId: '24bc8366-fc31-4d6c-8555-17049a836a07',
    amount: 100, // Caso o valor não seja definido, cancela a venda no valor total
};

cielo.creditCard.cancelTransaction(cancelamentoVendaParams)
    .then((data) => {
        return console.log(data);
    })
    .catch((err) => {
        return console.error('ERRO', err);
    })

Ou usando Async / Await

const cancel = await cielo.creditCard.cancelSale(dadosSale);
console.log(cancel);

Cartão de Débito

Criando uma venda simplificada

const debitCardTransactionParams: DebitCardSimpleTransactionRequestModel = {  
    merchantOrderId: "2014121201",
    customer:{  
      name: "Paulo Henrique"     
    },
    payment: {  
      type: EnumCardType.DEBIT,
      amount: 15700,
      provider: "Simulado",
      returnUrl: "http://www.google.com.br",
      debitCard:{  
          cardNumber: "4532117080573703",
          holder: "Teste Holder",
          expirationDate: "12/2022",
          securityCode: "023",
          brand: EnumBrands.VISA
      }
    }
 }

  cielo.debitCard.createSimpleTransaction(debitCardTransactionParams)
    .then((data) => {
        return console.log(data);
    })
    .catch((err) => {
        return console.error('ERRO', err);
    })

Pagamentos com Transferência Eletronica

Criando uma venda simplificada

const transferenciaEletronicaParams: EletronicTransferCreateRequestModel = {
    merchantOrderId: '2017051109',
    customer: {
      name: 'Nome do Comprador',
      identity: '12345678909',
      identityType: 'CPF',
      email: '[email protected]',
      address: {
        street: 'Alameda Xingu',
        number: '512',
        complement: '27 andar',
        zipCode: '12345987',
        city: 'São Paulo',
        state: 'SP',
        country: 'BRA',
        district: 'Alphaville',
      },
    },
    payment: {
      provider: 'Bradesco',
      type: 'EletronicTransfer',
      amount: 10000,
      returnUrl: 'http://www.cielo.com.br',
    },
  };

  cielo.eletronicTransfer.create(transferenciaEletronicaParams)(dadosSale)
  .then((data) => {
      return console.log(data);
  })
  .catch((err) => {
      return console.error('ERRO', err);
  })

Boleto

Criando uma venda de Boleto

const boletoParams: BankSlipCreateRequestModel = {
    merchantOrderId: '20180531',
    customer: {
      name: 'Comprádor Boleto Cíéló Áá',
      identity: '1234567890',
      address: {
        street: 'Avenida Marechal Câmara',
        number: '160',
        complement: 'Sala 934',
        zipCode: '22750012',
        district: 'Centro',
        city: 'Rio de Janeiro',
        state: 'RJ',
        country: 'BRA'
      }
    },
    payment: {
      type: 'Boleto',
      amount: 15700,
      provider: 'Bradesco2',
      address: 'Rua Teste',
      boletoNumber: '123',
      assignor: 'Empresa Teste',
      demonstrative: 'Desmonstrative Teste',
      expirationDate: '5/1/2020',
      identification: '11884926754',
      instructions: 'Aceitar somente até a data de vencimento, após essa data juros de 1% dia.'
    }
  }

  cielo.bankSlip.create(boletoParams)
    .then((data) => {
      return console.log(data);
    })
    .catch((err) => {
      return console.error('ERRO', err);
    })

Recorrência

Criando Recorrências

const createRecurrencyParams: RecurrentCreateModel = {
    merchantOrderId: '2014113245231706',
    customer: {
      name: 'Comprador rec programada'
    },
    payment: {
      type: EnumCardType.CREDIT,
      amount: 1500,
      installments: 1,
      softDescriptor: '123456789ABCD',
      currency: 'BRL',
      country: 'BRA',
      recurrentPayment: {
        authorizeNow: true,
        endDate: '2022-12-01',
        interval: EnumRecurrentPaymentInterval.SEMIANNUAL
      },
      creditCard: {
        cardNumber: '4024007197692931',
        holder: 'Teste Holder',
        expirationDate: '12/2030',
        securityCode: '262',
        saveCard: false,
        brand: 'Visa' as EnumBrands
      }
    }
  }

  cielo.recurrent.create(createRecurrencyParams)
    .then((data) => {
      return console.log(data);
    })
    .catch((err) => {
      return console.error('ERRO', err);
    })

Modificando Recorrências

Modificando dados do comprador

const updateCustomer: RecurrentModifyCustomerModel = {
    paymentId: firstRecurrency.payment.recurrentPayment.recurrentPaymentId,
    customer: {
      name: 'Customer',
      email: '[email protected]',
      birthdate: '1999-12-12',
      identity: '22658954236',
      identityType: 'CPF',
      address: {
        street: 'Rua Teste',
        number: '174',
        complement: 'AP 201',
        zipCode: '21241140',
        city: 'Rio de Janeiro',
        state: 'RJ',
        country: 'BRA'
      },
      deliveryAddress: {
        street: 'Outra Rua Teste',
        number: '123',
        complement: 'AP 111',
        zipCode: '21241111',
        city: 'Qualquer Lugar',
        state: 'QL',
        country: 'BRA',
      }
    }
  }

cielo.recurrent.modifyCustomer(updateCustomer)
  .then((data) => {
    return console.log(data);
  })
  .catch((err) => {
    return console.error('ERRO', err);
  })

Modificando data final da Recorrência

const updateEndDate: RecurrentModifyEndDateModel = {
  paymentId: firstRecurrency.payment.recurrentPayment.recurrentPaymentId,
  endDate: '2021-01-09'
}

cielo.recurrent.modifyEndDate(updateEndDate)
  .then((data) => {
    return console.log(data);
  })
  .catch((err) => {
    return console.error('ERRO', err);
  })

Modificando intevalo da Recorrência

const modifyRecurrencyParams: RecurrentModifyIntervalModel = {
  paymentId: firstRecurrency.payment.recurrentPayment.recurrentPaymentId,
  interval: EnumRecurrentPaymentUpdateInterval.MONTHLY
}

cielo.recurrent.modifyInterval(modifyRecurrencyParams)
  .then((data) => {
    return console.log(data);
  })
  .catch((err) => {
    return console.error('ERRO', err);
  })

Modificando dia da Recorrência

const updateRecurrencyDay: RecurrentModifyDayModel = {
    paymentId: firstRecurrency.payment.recurrentPayment.recurrentPaymentId,
    recurrencyDay: 10
  }

cielo.recurrent.modifyRecurrencyDay(updateRecurrencyDay)
  .then((data) => {
    return console.log(data);
  })
  .catch((err) => {
    return console.error('ERRO', err);
  })

Modificando o valor da Recorrência

const updateAmount: RecurrentModifyAmountModel = {
  paymentId: firstRecurrency.payment.recurrentPayment.recurrentPaymentId,
  amount: 156 // Valor do Pedido em centavos: 156 equivale a R$ 1,56
}

cielo.recurrent.modifyAmount(updateAmount)
  .then((data) => {
    return console.log(data);
  })
  .catch((err) => {
    return console.error('ERRO', err);
  })

Modificando data do próximo Pagamento

const updateNextPaymentDate: RecurrentModifyNextPaymentDateModel = {
  paymentId: firstRecurrency.payment.recurrentPayment.recurrentPaymentId,
  nextPaymentDate: '2020-05-20'
}

cielo.recurrent.modifyNextPaymentDate
  .then((data) => {
    return console.log(data);
  })
  .catch((err) => {
    return console.error('ERRO', err);
  })

Modificando dados do Pagamento da Recorrência (@todo)

const updatePayment: RecurrentModifyPaymentModel = {
  recurrentPaymentId: RecurrentPaymentId,
  payment: {  
    type: EnumCardType.CREDIT,
    amount: "123",
    installments: 3,
    country: "USA",
    currency: "BRL",
    softDescriptor: "123456789ABCD",
    creditCard: {  
        brand: EnumBrands.VISA,
        holder: "Teset card",
        cardNumber: "1234123412341232",
        expirationDate: "12/2030"
    }
  }
}

cielo.recurrent.modifyPayment(updatePayment)
  .then((data) => {
    return console.log(data);
  })
  .catch((err) => {
    return console.error('ERRO', err);
  })

Desabilitando um Pedido Recorrente

const deactivateRecurrencyParams: RecurrentModifyModel = {
  paymentId: firstRecurrency.payment.recurrentPayment.recurrentPaymentId
}

cielo.recurrent.deactivate(deactivateRecurrencyParams)
  .then((data) => {
    return console.log(data);
  })
  .catch((err) => {
    return console.error('ERRO', err);
  })

Reabilitando um Pedido Recorrente

const reactivateRecurrencyParams: RecurrentModifyModel = {
  paymentId: firstRecurrency.payment.recurrentPayment.recurrentPaymentId
}

cielo.recurrent.reactivate(updateReactivate)
  .then((data) => {
    return console.log(data);
  })
  .catch((err) => {
    return console.error('ERRO', err);
  })

Cartões

Gerando o token de cartão

const tokenParams: TokenizeRequestModel = {
  customerName: 'Comprádor Teste Cíéló Áá',
  cardNumber: '5555666677778884',
  holder: 'Comprador T Cielo',
  expirationDate: '12/2021',
  brand: brand as EnumBrands
};

cielo.card.createTokenizedCard(tokenParams)
    .then((data) => {
        console.log(data)
    })
    .catch((err) => {
        console.log(err);
    })

Consultas

Consulta Transação usando PaymentId

const consultaParams: ConsultTransactionPaymentIdRequestModel = {
    paymentId: "24bc8366-fc31-4d6c-8555-17049a836a07"
};

cielo.consult.paymentId(consultaParams)
    .then((data) => {
        console.log(data)
    })
    .catch((err) => {
        console.log(err);
    })

Consultando as transações usando MerchandOrderID

const consultaParamsMerchantOrderId: ConsultTransactionMerchantOrderIdRequestModel = {
    merchantOrderId: "2014111706"
};

cielo.consult.merchantOrderId(consultaParamsMerchantOrderId)
    .then((data) => {
        console.log(data)
    })
    .catch((err) => {
        console.log(err);
    })

Consulta de Cardbin

const consultaBinNacionalParams: ConsultBinRequestModel = {
  cardBin: '453211'
};

cielo.consult.bin(consultaBinNacionalParams)
.then((data) => {
    console.log(data)
})
.catch((err) => {
    console.log(err);
})

Consulta de cartão Tokenizado

const consultaCartaoTokenizadoParams: ConsultTokenRequestModel= {
    cardToken: '66b2c162-efbf-4692-aee5-e536c0f81037'
}

cielo.consult.cardtoken(consultaCartaoTokenizadoParams)
.then((data) => {
    console.log(data)
})
.catch((err) => {
    console.log(err);
})

Consulta de Recorrência

const recurrencyConsultingParams: ConsultTransactionRecurrentPaymentIdRequestModel = {
  recurrentPaymentId: firstRecurrency.payment.recurrentPayment.recurrentPaymentId
}

cielo.consult.recurrent(recurrencyConsultingParams)
.then((data) => {
    console.log(data)
})
.catch((err) => {
    console.log(err);
})

API Reference

Consulte os campos necessários na documentação da Cielo

PT-Br

En

Testes

Para rodar os testes automatizados, apenas execute o seguinte comando

npm test

Também é possível verificar o histórico de builds através do Travis CI

Autor

Flavio Takeuchi <[email protected]>

Github

Twitter

License

MIT License

Copyright (c) 2017 banzeh

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.

cielo's People

Contributors

banzeh avatar depfu[bot] avatar rzorzal avatar

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.