Code Monkey home page Code Monkey logo

pagarme-js's Introduction

Pagar.me JavaScript

Quality Gate Status Code Smells Coverage Maintainability Rating Security Rating

A JavaScript library to interface with Pagar.me's API, it works in the browser and with Node.js.

The documentation can be found in our JSDocs

Description

This library covers all your needs for integrating with Pagar.me, providing:

  • A clean Promise-based interface for all endpoints in Pagarme's API
  • A fast way to generate card hashes
  • Postback signature validation
  • Documents validations (CPF, CNPJ, and others)

How to use

First, install it:

yarn add pagarme

Or using npm:

npm install pagarme

Pagar.me's JavaScript library can be used in three ways:

Node.js

Import like usual:

import pagarme from 'pagarme'

also works using require:

const pagarme = require('pagarme')

Browser (CommonJS)

Import the browser build:

import pagarme from 'pagarme/browser'

also works using require:

const pagarme = require('pagarme/browser')

Browser (Global Variable)

You can also use the latest release from our CDN and import the build directly in your HTML:

<script src="https://assets.pagar.me/pagarme-js/4.11/pagarme.min.js" />

The library will be available as the global variable pagarme.

API Docs

This library provides a promise based interface for all functions. Before you can use the library, you need to provide authentication details which will be used through API calls.

For a detailed documentation, see our JSDocs.

Client API

All of Pagar.me's REST API endpoints are covered in the client object. Every function call issued to client will return a Promise which represents and manages the result's lifecycle.

Using connect

When you call connect, a Promise which resolves to a client or an error will be returned. If an authentication error happens, you can catch the error with the Promise interface:

import pagarme from 'pagarme'

pagarme.client.connect({ email: '[email protected]', password: '123456' })
  .then(client => client.transactions.all())
  .then(transactions => console.log(transactions))
  .catch(error => console.error(error))

As the entire library is based on promises, you can also use ES6 generators with every call to make code more procedural:

import pagarme from 'pagarme'

let client

try {
  client = yield pagarme.client.connect({
    email: '[email protected]',
    password: '123456'
  })
} catch (err) {
  console.log('Authentication error')
}

try {
  const transactions = yield client.transactions.all()
  console.log(transactions)
} catch (err) {
  console.log('Error fetching transactions')
}

The downside of this approach is that you need to handle errors using try/catch.

Pagar.me authorizes clients in various fashions. This library handles all available authentication strategies:

Using API key:

import pagarme from 'pagarme'

pagarme.client.connect({ api_key: 'ak_test_y7jk294ynbzf93' })
  .then(client => client.transactions.all())
  .then(transactions => console.log(transactions))

⚠️ Never use API keys in the browser, you should use encryption keys instead.

Using encryption key:

import pagarme from 'pagarme'

const card = {
  card_number: '4111111111111111',
  card_holder_name: 'abc',
  card_expiration_date: '1225',
  card_cvv: '123',
}

pagarme.client.connect({ encryption_key: 'ek_test_y7jk294ynbzf93' })
  .then(client => client.security.encrypt(card))
  .then(card_hash => console.log(card_hash))

Using email and password:

import pagarme from 'pagarme'

pagarme.client.connect({ email: '[email protected]', password: '123456' })
  .then(client => client.transactions.all())
  .then(transactions => console.log(transactions))

Building

To build the library, use npm start.

  • Node.js build is produced inside the dist directory.
  • Browser build is produced inside the browser directory.

Testing

To run the library tests, use npm test.

To run tests, you need to export API_KEY environment variable with your API key. When submitting a PR, Travis will already have it exported.

Contributing

Community contributions are essential for keeping this library great. We simply can't access the huge number of platforms and myriad configurations for running it, so if you find any problems, feel free to open an issue.

Be sure to provide at least the following information on the issue:

  • Environment (e.g. Node 7, Chrome 57)
  • Operating System (e.g. iOS 10)
  • Library version (e.g. 3.0.0)

We provide source maps to ease debugging. Use them whenever possible when providing stack traces as it will make digging onto the issue easier.

License

The MIT License (MIT)
Copyright (c) 2017 Pagar.me Pagamentos S/A

pagarme-js's People

Contributors

alalbux avatar allangrds avatar andersouza avatar btfshadow avatar chuttam avatar deivis avatar dependabot[bot] avatar derekstavis avatar evaporei avatar felquis avatar flyingluscas avatar gabriel949 avatar grvcoelho avatar guarilha avatar haskellcamargo avatar hrfreire avatar joaolucasl avatar joaovjs avatar leonero avatar lhnakan avatar lucasrichter avatar marcoworms avatar michaelfidelis avatar miguelzinhe avatar moog avatar murilohns avatar rsmelo avatar vannessasoares avatar vcapretz avatar zignd avatar

Stargazers

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

Watchers

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

pagarme-js's Issues

Missing reference links on docs

GitHub templates

It would be awesome to have in this project the basic templates for all interactions on GitHub, as:

  • Pull Requests
  • Issues

Error on Ionic 2

Utilizando o código de exemplo desta nova api, somente consigo fazer a geração de hash quando estou em um navegador ou simulando um navegador no celular.

Quando tento chamar da aplicação recebo a seguinte mensagem: "Error: You must suply a valid key",
E apesar de está mensagem vir da chamada de connect, pelo retorno do serviço é retornando as informações corretamente. Porém como gera erro ele não chama o meu código de geração de Hash.

Código tal qual estou usando, estou usando tanto a chave quanto a encryption por que se não colocar a chave ele dá erro.

Obs: parece ser um erro Cors.

pagarme.client.connect({ api_key : '<api_key>', encryption_key : 'e_key'})
.then(
client => { client.security.encrypt(card).then(card_hash => {
this.alertCtrl.create(
{
title: 'foi',
subTitle: card_hash,
buttons: ['OK']
}
).present();
console.log(card_hash)

  },error => {
    console.log('Error ao gerar hash');
    console.log(error);

    this.alertCtrl.create(
      {
        title: 'Erro',
        subTitle: error,
        buttons: ['OK']
      }
    ).present();
  });
},
error => {
  console.log('Error ao autenticar');
  console.log(error);
  this.alertCtrl.create(
    {
      title: 'Erro',
      subTitle: error,
      buttons: ['OK']
    }
  ).present();
}

);

Contributing guide

A contributing guide would be awesome!

It may include:

  • How to execute the proper environment
  • How to prepare the bundle with webpack
  • Etc etc etc

Syntax errors and xmlDoc isn't used.

Eslint errors:

/Users/felquis/Documents/github/pagarme/pagarme-js/src/body.js
   52:5   error    'xmlDoc' is defined but never used  
    
/Users/felquis/Documents/github/pagarme/pagarme-js/src/head.js
  4:1  error  Parsing error: Unexpected token

/Users/felquis/Documents/github/pagarme/pagarme-js/src/tail.js
  1:1  error  Parsing error: Unexpected token }

Add Rollup as the module bundler.

#I watched the talk on pagarme channel about your JS library, and one of the improvement points mentioned was the library size. So, I saw that you using webpack, and the webpack bundling generated is too big, thus I thought you might use the Rollup as the module bundler, because the Rollup generates a really clean and smaller bundle, and I think that will reduce a good part of the size.

Test faling "when a valid api key is given"

image

 FAIL  lib/resources/index.spec.js (5.921s)
  ● pagarme.client › when a valid api key is given

    You must supply a valid API key
      
      at pagarme.js:21774:7
          at <anonymous>

  pagarme.client
    ✓ should return an error if an invalid api key is given (909ms)
    ✓ should return an error when an invalid auth option is given
    ✓ should return an error if an invalid encryption_key is given (606ms)
    ✕ when a valid api key is given (575ms)
    ✓ when a valid encryption_key is given (654ms)
    ✓ when Pagarme is offline and API key is used (13ms)
    ✓ when Pagarme is offline and encryption key is used (12ms)

Ionic 2

*Estou usando chaves de teste no momento.

Quando tento fazer a geração do hash utilizando a api_key ou a secret. Ele informa que eu devo utilizar uma chave ou secret válida. Em ambos os carros eu recebo a mensagem de erro.

submodulo browser no npm não está funcionando

Boa tarde,

Durante alguns testes que venho realizando hoje, houve um problema no qual eu tentei utilizar o pacote npm em um projeto react, e quando fui importar o módulo deu erro...

o import foi feito de acordo com a documentação, import pagarme from 'pagarme/browser';
porém foi apontado que não existia arquivo pagarme.js no pacote pagarme/browser, e realmente não existe, este arquivo apenas existe no modulo pagarme.

add .all() shortcut on JSDocs

currently .all() shortcut for .find({}) is not well documented on JSDocs. This is true for almost all endpoints. We need to add JSDocs meta-comments on those endpoints to document this better.

Adicionar .babelrc para o .npmignore

Ao fazer upgrade para o babel 6, o babel começa a considerar os arquivos .babelrc dentro da pasta node_modules, fazendo com que aplicações tenham problemas, como por exemplo ao usar o pagarmejs no React Native.

Discussão sobre:
facebook/react-native#4062

Seria interessante adicionar o arquivo .babelrc ao .npmignore para manter a consistência em aplicações usando babel 6.

Callback de erro no checkout transparente

Não estou conseguindo fazer a captura de falha de pagamento utilizando o checkout transparente.

Entendo que não existe uma transactionId mas gostaria de capturar uma falha no pagamento ou alguma coisa do tipo para eu registrar que houve uma tentativa de pagamento. Olhando a api não me parece que foi implementado um callback de error.

Vocês poderiam adicionar um callback de falha de pagamento para que seja possível capturar um erro?

Api: https://assets.pagar.me/checkout/checkout.js

Wrong postback examples on docs

At https://docs.pagar.me/reference#validando-um-postback, we found that the JS sample lacks a basic detail for the operation.

const pagarme = require('pagarme')

// Calculate signature:
pagarme.postback.calculateSignature('X-Hub-Signature', 'postbackBody')
// returns a hash

// Verify signature:
pagarme.postback.verifySignature('X-Hub-Signature', 'postbackBody', 'expectedHash')
// returns true or false

This example is kinda wrong, due to the fact that it leads the developer to believe that he doesn't need Pagar.me's API Key. The right approach would be to make explicit and clear that the developer need the client to perform such actions, which contains the API Key.

Register package on NPM

Is it already registered on NPM? I could not find it.
For a better controlling dependencies, register this package on NPM. Doing so, that dependency becomes clear and together all other ones in package.json.

(bug) invalid card number validation

Description

When I tried to validate an invalid card_number, the following error was dispatched:

Uncaught TypeError: Cannot read property '0' of undefined

I used the 1231231231231231 dummy card_number like

import pagarme from 'pagarme'

pagarme.validate({ 
  card: { 
    card_number: '1231231231231231',
    card_expiration_date: ''
  } 
})

Package version

pagarme@^3.0.2:
  version "3.0.2"
  resolved "https://registry.yarnpkg.com/pagarme/-/pagarme-3.0.2.tgz#4ff05cd9234abbadb95d71cfa6c935650e9a8a90"

Wrong card number validations

The first case is when passing an empty string, the resulting object asserts true. It was supposed to return false, right?

import pagarme from 'pagarme'
...
console.log(pagarme.validate({card: {card_number: ""}})))

screenshot 2017-08-14 15 45 07

Another cases are bad errors handling for miscellaneous inputs:

This works and returns true, as it should be:
console.log(pagarme.validate({ card: { card_number: "4242424242424242" } }))

But sending the same input as integer:
console.log(pagarme.validate({ card: { card_number: 4242424242424242 } }))
screenshot 2017-08-14 15 48 28

Also, this returns true either:
console.log(pagarme.validate({ card: { card_number: "424242424242____" } }))

It took me a while to actually realize what wrong with my code, as the documentation here says nothing about this validate method, and the documentation at https://docs.pagar.me/docs/obtendo-os-dados-do-cartao is too simple.

Typo

Acredito ter um typo na linha 1932 no método PagarMe.creditCard.prototype.fillFromFrom = function(form) {

Esse método deveria se chamar fillFromForm, não?

(bug) only card number validation

Description

When I tried to validate only the card_number, the following error was dispatched:

Uncaught TypeError: Cannot read property 'replace' of undefined

I use the code below:

import pagarme from 'pagarme'

pagarme.validate({ card: { card_number: '5545497548400992' } })

If I pass the card_expiration_date even if it is an empty string, the error has gone.

Package version

pagarme@^3.0.2:
  version "3.0.2"
  resolved "https://registry.yarnpkg.com/pagarme/-/pagarme-3.0.2.tgz#4ff05cd9234abbadb95d71cfa6c935650e9a8a90"

Variavel KJUR dando erro ao importar pagarme.js como módulo

Estou usando Vue.js e a API da pagarme mas não estava conseguindo utilizar o arquivo "pagarme.js". Incluir por HTML não era uma opção então tentei baixar ele e utilizar o "import" do ES2015

import PagarMe from '../assets/pagarme-min'

mas mas isso disparava um erro:

pagarme.js?0203:2012Uncaught ReferenceError: KJUR is not defined

depois de um tempinho mexendo consegui arrumar, foi só declarar o KJUR na linha acima que deu erro:

Antes:
2012: if (typeof KJUR == "undefined" || !KJUR) KJUR = {};

Depois:
2012: var KJUR;
2013: if (typeof KJUR == "undefined" || !KJUR) KJUR = {};

Agora deu tudo certo 👍 mas fica a dica ai pra compatibilizar com os módulos do ES2015

Unreliable e2e tests

The e2e are passing without any api_kay or encryption key. This is unexpected and they must fail when process.env doesn't have any keys.

Problems creating subscriptions with card_hash generated by Bifrost

Description

I had problems creating subscriptions using a card_hash generated using Bifrost.

My Setup

  • Operating System: Windows 10
  • [X ] I have tested with the latest version
  • [X ] I can simulate the issue easily

Current Behavior

I tried to use Bifrost to generate a card_hash and then create a subscription. But when I did the POST request in the endpoint /subscriptions I got the error:

19 Sep 2017 17:00:51.894[33m{"id":"cj7s0ye4h0106hr6ebhcrsm8l","method":"POST","url":"/subscriptions","company":{"_id":"58f689b23debfb313ec86530","name":"Solutions Pagar.me"},"body":{"errors":[{"parameter_name":"amount","type":"invalid_parameter","message":"valor está faltando"}],"url":"/subscriptions","method":"post"},"httpVersion":"1.1","referer":"http://localhost/Apple/carrinho.html","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36","statusCode":400,"level":"warn","from":"response","service":"api","startTime":1505851251749,"hostname":"test","pid":16191,"latency":35}[39mpagarme-api.log

I used this POST:

19 Sep 2017 17:00:51.814[32m{"id":"cj7s0ye4h0106hr6ebhcrsm8l","method":"POST","url":"/subscriptions","body":{"customer":{"email":"[email protected]","document_number":"*","address":{"street_number":"111","neighborhood":"Itaim Bibi","street":"Rua Joaquim Floriano","zipcode":"04534003"},"name":"Caio Innocenti Teixeira"},"card_track_2":"4984235047519909=20052061737132390770","plan_id":"210394","split_rules":[{"charge_processing_fee":"true","liable":"true","recipient_id":"re_cj7rr79o300aior6dnmlsxiuz","percentage":"10"},{"charge_processing_fee":"false","recipient_id":"re_cj7rrckge00anor6dj1ucvls7","percentage":"90","liable":"false"}],"metadata":"{\"Sistema Ensino\": \"UNO\",\"Id Escola\": \"640672\",\"Id Distribuidor\": \"5996371\",\"Id Pedido\": \"6064250\"}","card_holder_name":"CAIO I TEIXEIRA","card_number_first_digits":"498423","payment_method":"credit_card","card_number_is_valid":"true","card_number_last_digits":"9909","card_sequence_number":"0","api_key":"*","card_expiration_date":"*","card_emv_data":"5F2A02098682025C00950500800000009A031709199C01009F02060000000264009F100706050A03A4A8009F1A0200769F260894A83223C21B31089F3303E0F0E89F360201369F3704B2E09A2F9F2701809F3403410302","card_number_token":"cj5cqnh6w00l80k68qw8sxg16","card_pin_mode":"offline","capture_method":"emv","card_number_fingerprint":"cj5cqnh6w00l80k68qw8sxg16"},"httpVersion":"1.1","referer":"http://localhost/Apple/carrinho.html","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36","level":"info","from":"request","service":"api","startTime":1505851251714,"hostname":"test","pid":16191}[39mpagarme-api.log

Expected Behavior

The response that I got says the parameter amount is missing. However, in order to create a subscription I have to pass the plan_id and the parameter amount is not required (actually the parameter amount is included inside the plan that I have created previously).

Clarify how to send 'opts' when not using client.connect

Since you don't need to use client.connect to be able to use the client's methods, we need to add better documentation to that part so people can make simple calls without using connect if they want to. Even though client.connect will always be better for anything that needs more than 1 request, I think we can give a much better dev experience by documenting and pointing out how to easily use the methods without the partial application of the authentication strategy.

Address missing endpoints in new API docs

Currently the lib only links to the new docs (pagarme.readme.io). Since pagar.me docs is currently (but not necessarily) a different project from pagarme-js docs we need to either update the new docs with all missing endpoints or link all missing endpoints to the old one

Pagamento com cartão de crédito no ambiente de testes respondendo 'api_key está faltando'

Ao tentar gerar o card_hash usando o form de checkout, estou tomando este erro:

{
  "errors": [
    {
      "type":"invalid_parameter",
      "parameter_name":"api_key",
      "message":"api_key está faltando"}
  ],
  "url":"/transactions/card_hash_key?encryption_key=<ENC_KEY>","method":"get"
}

Pode estar relacionado com #17.

Já tinha conseguido criar transações mais cedo - parou de funcionar há pouco.

Add some error handling for common mistakes inside the lib

Currently all errors comes from the API. When not sending args to a field that expects and object for instance, the lib blows up in weird ways, we need to cover unexpected behaviors and common developers mistakes (like we did with API key verification) so we give developers a better experience.

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.