Ir para conteúdo
willianlq

Integração API google pay

Recommended Posts

Boa tarde a todos,

Estou realizando uma integração da API do google pay, basicamente trabalho com duas classes(MainActivity e GooglePay.java) e estou com alguns problemas na classe principal, mais especificamente no método "possiblyShowGooglePayButton" e "onActivityResult", no qual enfrento problema de NullPointer e erros na conversão de Objetos JSON.

package com.example.testeapi;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.wallet.AutoResolveHelper;
import com.google.android.gms.wallet.IsReadyToPayRequest;
import com.google.android.gms.wallet.PaymentData;
import com.google.android.gms.wallet.PaymentDataRequest;
import com.google.android.gms.wallet.PaymentsClient;
import com.google.android.gms.wallet.Wallet;
import com.google.android.gms.wallet.WalletConstants;

import org.json.JSONObject;

import java.util.Optional;

public class MainActivity extends AppCompatActivity {
    public PaymentsClient mPaymentsClient;
    private View mGooglePayButton;
    private static final int LOAD_PAYMENT_DATA_REQUEST_CODE = 42;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mPaymentsClient =
                Wallet.getPaymentsClient(
                        this,
                        new Wallet.WalletOptions.Builder()
                                .setEnvironment(WalletConstants.ENVIRONMENT_TEST)
                                .build());
        possiblyShowGooglePayButton();
    }

    private void possiblyShowGooglePayButton() {
        final Optional<JSONObject> isReadyToPayJson = GooglePay.getIsReadyToPayRequest();
        if (!isReadyToPayJson.isPresent()) {
            return;
        }
        IsReadyToPayRequest request = IsReadyToPayRequest.fromJson(isReadyToPayJson.get().toString());
        if (request == null) {
            return;
        }
        Task<Boolean> task = mPaymentsClient.isReadyToPay(request);
        task.addOnCompleteListener(
                new OnCompleteListener<Boolean>() {
                    @Override
                    public void onComplete(@NonNull Task<Boolean> task) {
                        try {
                            boolean result = task.getResult(ApiException.class);
                            if (result) {
                                // show Google as a payment option
                                mGooglePayButton = findViewById(R.id.googlepay);
                                mGooglePayButton.setOnClickListener(
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                requestPayment(view);
                                            }
                                        });
                                mGooglePayButton.setVisibility(View.VISIBLE);
                            }
                        } catch (ApiException exception) {
                            // Erro
                        }
                    }
                });
    }

    public void requestPayment(View view) {
        Optional<JSONObject> paymentDataRequestJson = GooglePay.getPaymentDataRequest();
        if (!paymentDataRequestJson.isPresent()) {
            return;
        }
        PaymentDataRequest request =
                PaymentDataRequest.fromJson(paymentDataRequestJson.get().toString());
        if (request != null) {
            AutoResolveHelper.resolveTask(
                    mPaymentsClient.loadPaymentData(request), this, LOAD_PAYMENT_DATA_REQUEST_CODE);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // valor passado ao AutoResolveHelper
        if (requestCode == LOAD_PAYMENT_DATA_REQUEST_CODE) {
            switch (resultCode) {
                case Activity.RESULT_OK:
                    PaymentData paymentData = PaymentData.getFromIntent(data);
                    String json = paymentData.toJson();

                    String paymentMethodData = new JSONObject(json)
                            .getJSONObject(paymentMethodData);
                    String paymentToken = ((JSONObject) paymentMethodData)
                            .getJSONObject("tokenizationData")
                            .getString("token");
                    break;
                case Activity.RESULT_CANCELED:
                    break;
                case AutoResolveHelper.RESULT_ERROR:
                    Status status = AutoResolveHelper.getStatusFromIntent(data);
                    Log.i("Status", "Erro na requisição");
                    // Generally, there is no need to show an error to the user.
                    // The Google Pay payment sheet will present any account errors.
                    break;
                default:
            }
        }
    }
}

Se alguém puder me ajudar agradeço, já estou tentando resolver a um bom tempo.

classe.PNG

nullpointer.png

Compartilhar este post


Link para o post
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisar ser um membro para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar Agora

  • Conteúdo Similar

    • Por Anderson Modolon
      Estou com uma dúvida mas não sei exatamente aonde seria o melhor local, pois é sobre o Google Calendar e também sobre PHP.
       
      Estou tentando fazer o convite de uma pessoa para um evento no Google Calendar onde é feito a criação do evento sem problemas, porém na parte do convite é retornado o seguinte erro: Fatal error: Uncaught Google\Service\Exception: { "error": { "errors": [ { "domain": "calendar", "reason": "forbiddenForServiceAccounts", "message": "Service accounts cannot invite attendees without Domain-Wide Delegation of Authority." } ], "code": 403, "message": "Service accounts cannot invite attendees without Domain-Wide Delegation of Authority." } } in D:\amwebagencia\testes-\agendamento-google\vendor\google\apiclient\src\Http\REST.php on line 134. Já fiz pesquisas a respeito desse erro mas até então sem resultados relevantes.
      require_once 'vendor/autoload.php';
      // Autorização - Está funcionando corretamente $client = new Google_Client(); $client->setAuthConfig('json-google-calendar/arquivo.json'); $client->addScope(Google_Service_Calendar::CALENDAR); $service = new Google_Service_Calendar($client); // Criação de evento - Está funcionando corretamente $calendarId = 'bbb@gmail.com'; // ID da agenda (por padrão, usa a agenda primária) $evento = new Google_Service_Calendar_Event(array(     'summary' => 'Título do Evento 22',     'description' => 'Descrição do Evento',     'start' => array(         'dateTime' => '2023-06-11T16:02:00',         'timeZone' => 'America/Sao_Paulo',     ),     'end' => array(         'dateTime' => '2023-06-11T17:02:00',         'timeZone' => 'America/Sao_Paulo',     ), )); $eventoInserido = $service->events->insert($calendarId, $evento); echo 'Evento inserido com sucesso. ID do Evento: ' . $eventoInserido->getId(); // Convidar pessoa para evento - Está retornando o erro: Fatal error: Uncaught Google\Service\Exception: { "error": { "errors": [ { "domain": "calendar", "reason": "forbiddenForServiceAccounts", "message": "Service accounts cannot invite attendees without Domain-Wide Delegation of Authority." } ], "code": 403, "message": "Service accounts cannot invite attendees without Domain-Wide Delegation of Authority." } } in D:\amwebagencia\testes-\agendamento-google\vendor\google\apiclient\src\Http\REST.php on line 134 $eventId = $eventoInserido->getId(); // ID do evento específico $email = 'xxx@gmail.com'; // E-mail da pessoa que você deseja convidar $attendee = new Google_Service_Calendar_EventAttendee(array(     'email' => $email, )); $event = $service->events->get('bbb@gmail.com', $eventId); $attendees = $event->getAttendees(); $attendees[] = $attendee; $event->setAttendees($attendees); $updatedEvent = $service->events->update('bbb@gmail.com', $eventId, $event, array('sendUpdates' => 'all')); echo 'Pessoa convidada com sucesso para o evento.';  
    • Por Caio Vargas
      Olá pessoa estou criando um sistema de agendamento porém agora quero fazer a implementação do Google calendar porém meu sistema não usa o composer teria alguma forma de usar a api sem precisar do composer
    • Por Giovanird
      Olá a todos!
      Tenho uma api  Sala de Aula e dentro dela o id de cada aluno. Em outra api, API ALUNO,  tenho os dados de cada aluno:  nome, foto, endereço.
      Estou fazendo o foreach da api Sala de Aula e preciso também retornar os dados de cada aluno.
      Segue o código que não estou conseguindo desenvolver
      $sala = file_get_contents("https://api/sala?id=987"); $sala = json_decode($sala, true); $sala = $sala['data']; foreach ($sala as $resulsala){ $codigoaluno = $resulsala['idaluno']; $alunos = file_get_contents("https://api/alunos?id=$codigoaluno"); $alunos = json_decode($alunos, true); $alunos = $alunos['data']; foreach ($alunos as $resulalunos){ echo $resulalunos['nome']; echo $resulalunos['foto']; echo $resulalunos['rua']; } }  
    • Por Orico Chain
      Oi pessoal,
       
      Preciso de ajuda, estou tentando gerar um TXT com dados de uma API mas não estou conseguindo:
       
      <?php $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.bololex.com/api/prices/TRX-USDT", CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => array( "cache-control: no-cache" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); $response = json_decode($response, true); $value1 = $response['result'] [0] ['ask'] ['priceChange']; if (empty($value1)) { $value1 = is_file('/var/www/html/24tstar.txt') ? file_get_c> } else { $value1 = round($value1, 6); file_put_contents('/var/www/html/24tstar.txt', $value1); Preciso que o TXT grave duas informações: ASK e PRICECHANGE uma em baixo da outra
       
      estou errando alguem lugar, alguém poderia me ajudar?
    • Por Kelven
      Bom dia pessoal tudo bem?
      Então, estou trabalhando em um site em php e preciso usar a api do facebook para obter o feed do instagram, porém a chave token é um conteúdo muito sensível, então decidi fazer em php para ela não ficar disponível do lado do cliente. Alguém sabe me dizer se é possível fazer isso? Porque eu pesquisando no google só achei maneiras de fazer em javascript.
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.