Angular e mercado pago

3 respostas
guilhermebhte

Para o pagamento de boleto, pelo que entendi não precisa de fazer nada no frontend. Mas para cartão é preciso, conforme este link:

https://www.mercadopago.com.br/developers/pt/guides/online-payments/checkout-api/receiving-payment-by-card/

No código fiz assim:

salvar(): void {
    if(this.cartao) {
      this.window['Mercadopago'].getPaymentMethod({
        'bin': this.quartoFormGroup.controls.numeroCartao.value.substring(0, 7).replace('\\.', '')
      }, this.setPaymentMethod);
    }
    const registro = this.criarFormulario();
    this.publicoService.create(registro).subscribe(
      () => {
        //this.stateStorageService.clearPlanoVenda();
        //this.router.navigate(['/autenticacao']);
      },
      (error: any) => {
        super.mostrarError(error);
      }
    );
  }

  setPaymentMethod(status: any, response: any): void {
    if (status === 200) {
      const paymentMethod = response[0];
      this.quartoFormGroup.controls.paymentMethodId.setValue(paymentMethod.id);
      if(paymentMethod.additional_info_needed.includes('issuer_id')) {
        this.getIssuers(paymentMethod.id);
      } else {
        this.installments(
          paymentMethod.id,
          this.quartoFormGroup.controls.transactionAmount.value,
          null
        );
      }
    } else {
      alert(`Informação do método de pagamento: ${response}`);
    }
  }

  getIssuers(paymentMethodId: any): void {
    this.window['Mercadopago'].getIssuers(
      paymentMethodId,
      this.setIssuers
    );
  }

  setIssuers(status: any, response: any): void {
    if (status === 200) {
      let issuerSelect: any;// = document.getElementById('issuer');
      response.forEach((issuer: any) => {
        const opt = document.createElement('option');
        opt.text = issuer.name;
        opt.value = issuer.id;
        //issuerSelect.appendChild(opt);
      });
      this.installments(
        this.quartoFormGroup.controls.paymentMethodId.value,
        this.quartoFormGroup.controls.transactionAmount.value,
        issuerSelect.value
      );
    } else {
      alert(`issuers method info error: ${response}`);
    }
  }

  installments(paymentMethodId: any, transactionAmount: any, issuerId: any): void {
    this.window['Mercadopago'].getInstallments({
      'payment_method_id': paymentMethodId,
      'amount': transactionAmount,
      'issuer_id': issuerId ? issuerId : undefined
    },
    this.setInstallments);
  }

  setInstallments(status: any, response: any): void {
    if (status === 200) {
      this.quartoFormGroup.controls.parcelaCartao.value;
      response[0].payer_costs.forEach((payerCost: any) => {
        const opt = document.createElement('option');
        opt.text = payerCost.recommended_message;
        opt.value = payerCost.installments;
        this.quartoFormGroup.controls.parcelaCartao.setValue(opt);
      });
    } else {
      alert(`installments method info error: ${response}`);
    }
  }

Fiquei na dúvida como fazer isso no angular ?

doSubmit = false;
document.getElementById('paymentForm').addEventListener('submit', getCardToken);
function getCardToken(event){
   event.preventDefault();
   if(!doSubmit){
       let $form = document.getElementById('paymentForm');
       window.Mercadopago.createToken($form, setCardTokenAndPay);
       return false;
   }
};

function setCardTokenAndPay(status, response) {
   if (status == 200 || status == 201) {
       let form = document.getElementById('paymentForm');
       let card = document.createElement('input');
       card.setAttribute('name', 'token');
       card.setAttribute('type', 'hidden');
       card.setAttribute('value', response.id);
       form.appendChild(card);
       doSubmit=true;
       form.submit();
   } else {
       alert("Verify filled data!\n"+JSON.stringify(response, null, 4));
   }
};

Coloco o breakpoint aqui ‘bin’: this.quartoFormGroup.controls.numeroCartao.value.substring(0, 7).replace(’\.’, ‘’) , ai ele para.

Mas não para nesta parte:

<strong>setPaymentMethod(status: any, response: any): void {

if (status === 200) {</strong>

Como fazer funcionar esta parte e o que está faltando ??

3 Respostas

javaflex

Te aconselho fazer tudo em javascript puro, que é muito mais simples, sem as burocracias do TyprScript, além de tudo já tem exemplos prontos. No TypeScript com Angular só faz as chamadas pra atender os componentes.

guilhermebhte

Certo. Imaginei isso.

Mas fiquei na dúvida de como incorporar no angular, esta parte em javascript com html.

javaflex

Da mesma forma que voce acessa a propriedade “Mercadopago” do js puro do Mercado Pago, voce acessaria uma propriedade criada por voce em um js puro seu.

Existem outras formas também, mas é o que veio em mente no momento. No geral pesquise por algo assim: acessar função em um js externo pelo Angular.

Criado 23 de outubro de 2020
Ultima resposta 23 de out. de 2020
Respostas 3
Participantes 2