Problem when trying to receive flag with transparent checkout in Pagseguro API

Asked

Viewed 186 times

1

The problem is this, I am trying to implement the transparent checkout sandbox of the Pagseguro API, but when arriving at the step where the flag of the card is obtained, it always accuses error and never proceeds from there. The project is being done in angular 9.1 and Ionic 5.4.16. API in ruby on Rails 5.2.4.4. Another addendum, the documentation of Pagseguro warns to get the senderHash before finalizing the request, I have tried to implement this way and now I am trying to implement in the same closure, but the problem remains the same.

Follow the app code:

GET of session id, implemented just before the card screen:

  async createPaymentSessionId(): Promise<void> {
    this.loading = await this.loadingCtrl.create({
      message: "Gerando token de pagamento...",
    });
    this.loading.present();
    this.http
      .get(`${environment.estacionamentoApi}/create_session_id.json`, {
        headers: new HttpHeaders({
          EstacionamentoKeyAccess: environment.accessToken,
        }),
      })
      .subscribe(
        (res: { session_id: string }) => {
          this.paymentSessionId = res.session_id;
          this.order
            .subscribe(
              (currentOrder) =>
                (this.currentOrder = {
                  ...currentOrder,
                  paymentSessionId: this.paymentSessionId,
                })
            )
            .unsubscribe();
          this.orderSource.next(this.currentOrder);
          this.loading.dismiss();
        },
        () => {
          this.loading.dismiss();
        }
      );

Route required by the above method in Ruby On Rails:

  def create_session_id
    response = HTTParty.post("https://ws.sandbox.pagseguro.uol.com.br/v2/sessions?email=#{PAGSEGURO_CREDENTIALS_EMAIL}&token=#{PAGSEGURO_TOKEN_SANDBOX}")
    if (200..299).to_a.include?(response.code)
      debugger
      @session_id = response.parsed_response["session"]["id"]
      render json: {session_id: @session_id}, status: :ok
      return
    end
    render json: {errors: [{message: "Erro ao buscação Id de sessão Pagseguro"}]}, status: :unauthorized
  end

Method of finalizing the order:

async finalizaPedido(order: Order): Promise<void> {
    PagSeguroDirectPayment.onSenderHashReady(async (response) => {
      if (response.status == "error") {
        console.log(response.message);
        return false;
      }
      this.finalOrder.senderHash = response.senderHash;
      this.paymentLoading();
      this.finalOrder.order = order;
      if (order.cartao) {
        const bin = parseInt(order.dados_cartao.cardNumber.substring(0, 6));
        PagSeguroDirectPayment.getBrand({
          cardBin: bin,
          success: (response) => {
            this.finalOrder.brand = response.brand.name;
            const params = {
              cardNumber: order.dados_cartao.cardNumber,
              brand: response.brand.name,
              cvv: order.dados_cartao.ccv,
              expirationMonth: order.dados_cartao.expirationMonth,
              expirationYear: order.dados_cartao.expirationYear,
              success: (response) => {
                this.finalOrder.cardToken = response.card.token;

                PagSeguroDirectPayment.getInstallments({
                  amount: order.plano.valor,
                  maxInstallmentNoInterest: 13,
                  brand: this.finalOrder.brand,
                  success: (response) => {
                    this.http
                      .post(
                        `${environment.estacionamentoApi}/pedidos/comprar.json`,
                        this.finalOrder,
                        {
                          headers: new HttpHeaders({
                            EstacionamentoKeyAccess: environment.accessToken,
                          }),
                        }
                      )
                      .subscribe((resp: PaymentResponse) => {
                        if (resp.errors) {
                          this.onPaymentErrors(response.errors);
                        } else {
                          this.onPaymentSuccess(resp.pago);
                        }
                        this.loading.dismiss();
                      });
                  },
                  error: (response) => {
                    this.loading.dismiss();
                    this.onPaymentErrors([
                      {
                        message:
                          "Erro ao tentar gerar opções de parcelamento, por favor tente novamente!",
                      },
                    ]);
                    // callback para chamadas que falharam.
                  },
                  complete: (response) => {
                    // Callback para todas chamadas.
                  },
                });
              },
              error: (response) => {
                this.loading.dismiss();
                this.onPaymentErrors([
                  {
                    message:
                      "Erro ao gerar token de cartão de crédito, por favor tente novamente!",
                  },
                ]);
                //tratamento do erro
              },
            };
            PagSeguroDirectPayment.createCardToken(params);
          },
          error: (response) => {
            // SEMPRE CAI AQUI QUANDO O TENTO OBTER A BANDEIRA DO CARTÃO
            this.onPaymentErrors([
              {
                message:
                  "Erro checar bandeira do cartão, por favor tente novamente!",
              },
            ]);
            this.loading.dismiss();
          },
        });
      } else {
        try {
          this.paymentLoading();
          const response = await this.http
            .post<PaymentResponse>(
              `${environment.estacionamentoApi}/pedidos/comprar.json`,
              this.finalOrder,
              {
                headers: new HttpHeaders({
                  EstacionamentoKeyAccess: environment.accessToken,
                }),
              }
            )
            .toPromise();
          this.orderService.atualizaOrder({
            ...order,
            paymentSessionId: "",
          });
          this.loading.dismiss();
          this.onPaymentSuccess(response.pago);
        } catch (err) {
          this.loading.dismiss();
          this.onPaymentErrors(err.errors);
        }
      }
    });
  }

It’s highlighted in the code to make it clearer: inserir a descrição da imagem aqui

Thanks in advance people!!

1 answer

2

I managed to solve, the problem was that the Pagsegurodirectpayment.getBrand method needed to be implemented in Pagsegurodirectpayment.getPaymentMethods callback

 PagSeguroDirectPayment.getPaymentMethods({
        success: async (dados) => {
          if (order.cartao) {
            const bin = parseInt(order.dados_cartao.cardNumber.substring(0, 6));
            PagSeguroDirectPayment.getBrand({
              cardBin: bin,
              success: (response) => {

Browser other questions tagged

You are not signed in. Login or sign up in order to post.