У этого продавца нет доступных карт - Google Pay

Я пытаюсь интегрировать Google Pay в свой веб-сайт, но когда я нажимаю «оплатить с помощью googlepay», появляется следующая ошибка:

У этого продавца нет доступных карт.

Когда я читаю документацию, в ней говорится, что вы можете добавить пример в качестве продавца для тестирования, я просто хотел использовать тестовую среду, но все еще не работает.

Вот код, который я использую:

const allowedAuthMethods = ['PAN_ONLY','CRYPTOGRAM_3DS'] ;

const baseCardPaymentMethod = {
  type: 'CARD',
  parameters: {
    allowedCardNetworks: allowedNetworks,
    allowedAuthMethods: allowedAuthMethods 
  }
};

const googlePayBaseConfiguration = {
  apiVersion: 2,
  apiVersionMinor: 0,
  allowedPaymentMethods: [baseCardPaymentMethod]
};

/**
 * Holds the Google Pay client used to call the different methods available
 * through the API.
 * @type {PaymentsClient}
 * @private
 */
let googlePayClient;

/**
 * Defines and handles the main operations related to the integration of
 * Google Pay. This function is executed when the Google Pay library script has
 * finished loading.
 */
function onGooglePayLoaded() {
  googlePayClient = new google.payments.api.PaymentsClient({
        environment: 'TEST'
    });

  googlePayClient.isReadyToPay(googlePayBaseConfiguration)
  .then(function(response) {
    if(response.result) {
      createAndAddButton();
    } else {
      alert("Unable to pay using Google Pay");
    }
  }).catch(function(err) {
    console.error("Error determining readiness to use Google Pay: ", err);
  });

}

/**
 * Handles the creation of the button to pay with Google Pay.
 * Once created, this button is appended to the DOM, under the element 
 * 'buy-now'.
 */
function createAndAddButton() {

  const googlePayButton = googlePayClient.createButton({

    // currently defaults to black if default or omitted
    buttonColor: 'default',

    // defaults to long if omitted
    buttonType: 'long',

    onClick: onGooglePaymentsButtonClicked
  });

  document.getElementById('buy-now').appendChild(googlePayButton);
}

/**
 * Handles the click of the button to pay with Google Pay. Takes
 * care of defining the payment data request to be used in order to load
 * the payments methods available to the user.
 */
function onGooglePaymentsButtonClicked() {

  const tokenizationSpecification = {
  type: 'PAYMENT_GATEWAY',
  parameters: {
    gateway: 'example',
    gatewayMerchantId: 'exampleGatewayMerchantId'
  }
 };

  const cardPaymentMethod = {
  type: 'CARD',
  tokenizationSpecification: tokenizationSpecification,
  parameters: {
    allowedCardNetworks: ['VISA','MASTERCARD'],
    allowedAuthMethods: ['PAN_ONLY','CRYPTOGRAM_3DS'],
    billingAddressRequired: true,
    billingAddressParameters: {
      format: 'FULL',
      phoneNumberRequired: true
      }
    }
  };

  const transactionInfo = {
  totalPriceStatus: 'FINAL',
  totalPrice: '123.45',
  currencyCode: 'USD',
  countryCode: 'US'
  };

  const merchantInfo = {
   merchantId: '01234567890123456789', //Only in PRODUCTION
  merchantName: 'Example Merchant Name'
  };

  const paymentDataRequest = Object.assign({}, googlePayBaseConfiguration, {
  allowedPaymentMethods: [cardPaymentMethod],
  transactionInfo: transactionInfo,
  merchantInfo: merchantInfo   
  });

  googlePayClient
  .loadPaymentData(paymentDataRequest)
  .then(function(paymentData) {
    processPayment(paymentData);
  }).catch(function(err) {
    // Log error: { statusCode: CANCELED || DEVELOPER_ERROR }
  });
}

function processPayment(paymentData) {
  // TODO: Send a POST request to your processor with the payload
  // https://us-central1-devrel-payments.cloudfunctions.net/google-pay-server 
  // Sorry, this is out-of-scope for this codelab.
  return new Promise(function(resolve, reject) {
    // @todo pass payment token to your gateway to process payment
    const paymentToken = paymentData.paymentMethodData.tokenizationData.token;
    console.log('mock send token ' + paymentToken + ' to payment processor');
    setTimeout(function() {
      console.log('mock response from processor');
      alert('done');
      resolve({});
    }, 800);
  });
} ```

person Mayank    schedule 13.11.2019    source источник


Ответы (2)


У этого продавца нет доступных карт для использования.

Это сообщение означает, что у текущего пользователя Google нет карт, совместимых с вариантами оплаты, предоставленными продавцом. В частности, allowedCardNetworks и allowedAuthMethods.

Вот JSFiddle, который я создал на основе вашего фрагмента: https://jsfiddle.net/aumg6ncb/

Вот что я получаю после нажатия на кнопку:

введите здесь описание изображения

person Soc    schedule 13.11.2019

Если вы используете тестовый режим: - Я думаю, вы использовали тестовую карту в своем браузере Chrome или Google Кошельке.

При тестировании Google Pay у вас должна быть настоящая карта, сохраненная в браузере Chrome или Google Wallet, а также активны тестовые ключи API / тестовая среда Google Pay. С реальной карты не взимается плата, и Google передает тестовую карту во время оформления заказа вместо реальной карты. Наши обычные тестовые карты не работают с Google Pay, когда пользователь пытается сохранить их в Chrome.

person najib patel    schedule 07.02.2020