LanderMalta / maxipago-gateway-sdk

Javascript library for MaxiPago API.
https://www.npmjs.com/package/maxipago-gateway-sdk
MIT License
4 stars 5 forks source link

feat: add xml error attribute #13

Closed Sup3r-Us3r closed 2 years ago

Sup3r-Us3r commented 2 years ago

Some errors I had when using this SDK were not returned in a way that was easy to identify, very generic errors for example: errorCode 1 and no message.

With the addition of this attribute, it became much easier to identify which error was returned, for example:

<?xml version="1.0" encoding="UTF-8"?>
<response>
  <errorCode>1</errorCode>
  <errorMessage><![CDATA[Parser Error: URI=null Line=1: cvc-complex-type.2.4.a: Invalid content was found starting with element 'firstName'. One of '{customerIdExt}' is expected.]]></errorMessage>
  <time>1648837447555</time>
</response>

I also had a need to translate these error messages that are in English into Portuguese, to return in a friendly way to the end user, a deal like this:

const messageErrors = {
  dateInvalid: 'The transaction has an expired credit card'.toLowerCase(),
  inputLength: 'Input length must be multiple of 8 when decrypting with padded cipher'.toLowerCase(),
  consumerError: 'Customer id validation error'.toLowerCase(),
  unableCostumer: 'unable to find consumer',
  schemaValidation: 'Schema validation for the vertical SA for the incoming transaction xml failed'.toLowerCase(),
  invalidCardNumber: 'Credit Card Number is not a valid credit card number'.toLowerCase(),
  transactionAmountIsInvalid: 'Transaction Amount is not a valid number in the range of'.toLowerCase(),
  processorIdIsInvalid: 'Request is invalid and can not be processed'.toLowerCase(),
  customerIdExtInvalid: "One of '{customerIdExt}' is expected".toLowerCase(),
  firstNameInvalid: "One of '{firstName}' is expected".toLowerCase(),
  lastNameInvalid: "One of '{middleName, lastName}' is expected".toLowerCase(),
  formatDobInvalid: "facet-valid with respect to pattern '\\d{1,2}\\/\\d{1,2}\\/\\d{4}".toLowerCase(),
  dobInvalid: 'date of birth is not a valid date format.'.toLowerCase(),
  cardExpired: 'card has expired',
  requiredCreditCardNumber: 'creditCardNumber is a required field',
  customerOrTokenInvalid: 'Invalid customer id and/or token',
  requiredCustomer: 'customerId is a required field',
  requiredToken: 'token is a required field'
};
import { messageErrors } from './maxiPagoErrorHandlingMessageEnglish';

type Action =
  | 'autorizar o pagamento'
  | 'adicionar o cliente'
  | 'adicionar o cartão'
  | 'deletar o cartão';

export function maxiPagoErrorHandling(messageError: string, action: Action) {
  messageError = messageError.toLowerCase();

  if (messageError.includes(messageErrors.dateInvalid)) {
    return 'Data de vencimento do cartão não é valida';
  }

  if (messageError.includes(messageErrors.inputLength)) {
    return 'Quantidade inválida de dígitos';
  }

  ...

  return `Não foi possível ${action}, por favor tente novamente!`;
}

And to use and treat the value that comes from this attribute I would do:

import { maxiPagoErrorHandling } from '../../shared/utils/maxiPagoErrorHandling';

const maxiPagoResponse = await this.mpGateway.addCustomer(customerData);

if (maxiPagoResponse && maxiPagoResponse?.errorXML && maxiPagoResponse.errorCode !== 0 ) {
  throw new AppError({
    title: 'Cliente não cadastrado',
    description: maxiPagoErrorHandling(maxiPagoResponse?.errorXML, 'adicionar o cliente'),
    statusCode: 400,
  });
}

It would be very interesting if you can accept the pull request, I'm currently using this lib to perform this integration, but I needed to add this errorXML attribute to satisfy the error handling, and to get around this problem temporarily I used the patch-package.

LanderMalta commented 2 years ago

Hey @Sup3r-Us3r thanks a lot for your contribution. Many thanks also to everyone who is watching this discussion. @andreeluis, @joaovdl, @marcelocruzsilverio, @lucasfelype, @cinthia-tondinelli @anderson101251 and @isaoliveira003

Sorry for the delay in reviewing and approving your PR, I recently had some personal issues that prevented me from reviewing this library. For a payment library this time is an eternity, it won't happen again!

I've already approved your PR and updated some deprecated dependencies, also released version v1.0.13 here on github and published on npm.

I'm also Brazilian :brazil: :brazil: :brazil: and I really liked your idea of ​​translating the error messages into Brazilian Portuguese, what do you think about including this and other language translations into the library? We can receive the language as a parameter when creating the gateway and return the translated friendly message, the call to instantiate the gateway would look something like:

var mpGateway = maxipago.buildGateway(maxiPagoID, maxiPagoKEY, maxiPagoEnv, "pt-br"); - for Brazilian Portuguese or var mpGateway = maxipago.buildGateway(maxiPagoID, maxiPagoKEY, maxiPagoEnv, "fr"); - for French or var mpGateway = maxipago.buildGateway(maxiPagoID, maxiPagoKEY, maxiPagoEnv, "de"); - for German etc...

Remembering that this parameter would be optional to prevent not to break for those who already use this library. What do you all think? Shall we open an issue to work on this?

Thank you very much and see you later!