Page History
...
Использование виджета Google Pay позволяет осуществлять оплату как обычными картами, привязанными к аккаунту Google, так и токенизированными картами Google Pay. При этом на устройствах без установленного приложения Google Pay покупателю будет предложено выбрать сохраненную карту из Google.
...
Code Block | ||
---|---|---|
| ||
const tokenizationSpecification = { type: 'PAYMENT_GATEWAY', parameters: { 'gateway': 'assistbelassist', 'gatewayMerchantId': '02510116604241796260' } } |
...
Для отображения кнопки скрипт вызывает функцию addGooglePayButton. При этом можно настроить вид кнопки Google Pay. Для этого необходимо внести изменения в метод createButton:
- buttonColor – задает цвет кнопки, возможные значения black (черный) и white (белый);
- buttonType - задает тип кнопки, возможные значения long (длинная) и short (короткая).
Подробная информация о добавлении кнопки приведена в документации Google Pay API https://developers.google.com/pay/api/web/reference/object?hl=ru#ButtonOptions.
Пример функции addGooglePayButton, которая добавляет большую кнопку черного цвета:
Code Block | ||
---|---|---|
| ||
function addGooglePayButton() {
const paymentsClient = getGooglePaymentsClient();
const button =
paymentsClient.createButton({onClick: onGooglePaymentButtonClicked, buttonColor:'black', buttonType:'long'}); //создание кнопки
document.getElementById('container').appendChild(button); //добавление кнопки на страницу
document.getElementById('container').style.display = 'block';
} |
Warning |
---|
При настройке кнопки необходимо учитывать требования по брендированию Google. |
Если устройство поддерживает оплату с помощью Google Pay, то будет отображена кнопка в соответствии с настройками.
Нажатие на кнопку инициирует передачу информации об операции в Google Pay с помощью функции getGoogleTransactionInfo. Для операции необходимо передать следующие параметры:
- currencyCode — валюта заказа;
- totalPrice — сумма заказа;
- totalPriceStatus — статус суммы заказа.
Параметр totalPriceStatus может принимать следующие значения:
- NOT_CURRENTLY_KNOWN — используется для проверки возможностей оплаты;
- ESTIMATED — сумма заказа может быть изменена позже, в зависимости от ответа;
- FINAL — сумма заказа окончательная, не изменится в процессе.
Пример функции getGoogleTransactionInfo:
Code Block | ||
---|---|---|
| ||
function getGoogleTransactionInfo() {
return {
currencyCode: $('#currency').val(), //валюта заказа
totalPriceStatus: 'FINAL', //статус суммы заказа
totalPrice: $('#amount').val() //сумма заказа
};
} |
После подтверждения оплаты покупателем результат будет возвращен в функцию processPayment.
Для проведения платежа в виджет следует передать данные заказа (функция processPayment).
Список параметров функции processPayment
Параметр | Описание |
merchant_id | Идентификатор интернет-магазина |
amount | Сумма заказа в единицах валюты |
currency | Валюта заказа |
ordernumber | Уникальный номер заказа на стороне интернет-магазина |
comment | Комментарий |
Email покупателя | |
firstname | Имя покупателя |
lastname | Фамилия покупателя |
middlename | Отчество покупателя |
В качестве значений могут быть указаны названия полей заполненной платежной формы. Пример функции processPayment:
Code Block | ||
---|---|---|
| ||
function processPayment(paymentData) {
var data = {
paymentData : paymentData,
merchant_id : $('#merchantId').val(), //идентификатор интернет-магазина
amount : $('#amount').val(), //сумма заказа
currency : $('#currency').val(), //валюта
ordernumber : $('#ordernumber').val(), //номер заказа
email : $('#email').val(), //email покупателя
firstname : $('#firstname').val(), //имя покупателя
middlename : $('#middlename').val(),
lastname : $('#lastname').val() //фамилия клиента
comment : $('#comment').val() //комментарий к заказу
}; |
После завершения оплаты с помощью Google Pay сервер возвращает в ответ номер заказа и статус. Для обработки ответа необходимо добавить соответствующий код в эту функцию processPayment:
Code Block | ||
---|---|---|
| ||
$.post("/pay/tokenpay_widget_gp.cfm", JSON.stringify(data)).then(function (result) {
// здесь должна быть обработка ответа от сервиса оплаты
// это пример ответа {"order":{"ordernumber":"2019.03.11-664","orderstate":"Approved"}}
}); |
Если по каким-то причинам оплата заказа прошла неуспешно, то сервис вернет сообщения об ошибках (ненулевые значения параметров firstcode, secondcode).
Скрипт использует Google Pay API, который поддерживается:
- на всех мобильных устройствах, независимо от операционной системы;
- в браузерах Google Chrome, Mozilla Firefox, Apple Safari, Microsoft Edge, Opera или UCWeb UC Browser.
Warning |
---|
В Google Pay отсутствует возможность привязать специальную тестовую карту, поэтому при тестировании будет отображаться реальная карта. Однако, в тестовой среде Google эта карта будет подменяться на тестовую и в скрипт будут возвращаться данные тестовой карты. Это позволяет использовать привязанную реальную карту без опасений, что с нее будут списаны средства. |
Пример скрипта
Ниже приведен пример скрипта виджета, который может быть размещен на платежной странице интернет-магазина.
Code Block | ||
---|---|---|
| ||
<script type="text/javascript">
const baseRequest = {
apiVersion: 2,
apiVersionMinor: 0
};
const allowedCardNetworks = ["MASTERCARD", "VISA"];
const allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];
const tokenizationSpecification = {
type: 'PAYMENT_GATEWAY',
parameters: {
'gateway': 'belassist',
'gatewayMerchantId': '02510116604241796260'
}
}
const baseCardPaymentMethod = {
type: 'CARD',
parameters: {
allowedAuthMethods: allowedCardAuthMethods,
allowedCardNetworks: allowedCardNetworks,
billingAddressRequired: true,
billingAddressParameters: {"format": "MIN"}
}
}
const cardPaymentMethod = Object.assign(
{},
baseCardPaymentMethod,
{
tokenizationSpecification: tokenizationSpecification
}
);
let paymentsClient = null;
function getGoogleIsReadyToPayRequest() {
return Object.assign(
{},
baseRequest,
{
allowedPaymentMethods: [baseCardPaymentMethod]
}
);
}
/**
* Configure support for the Google Pay API
*
* @see {@link https://developers.google.com/pay/api/web/reference/object#PaymentDataRequest|PaymentDataRequest}
* @returns {object} PaymentDataRequest fields
*/
function getGooglePaymentDataRequest() {
const paymentDataRequest = Object.assign({}, baseRequest);
paymentDataRequest.allowedPaymentMethods = [cardPaymentMethod];
paymentDataRequest.transactionInfo = getGoogleTransactionInfo();
paymentDataRequest.merchantInfo = {
// @todo a merchant ID is available for a production environment after approval by Google
// See {@link https://developers.google.com/pay/api/web/guides/test-and-deploy/integration-checklist|Integration checklist}
merchantId: '16590966430175452581',
merchantOrigin: 'www.assist.ru',
merchantName: 'ASSIST Merchant'
};
return paymentDataRequest;
}
/**
* Return an active PaymentsClient or initialize
*
* @see {@link https://developers.google.com/pay/api/web/reference/client#PaymentsClient|PaymentsClient constructor}
* @returns {google.payments.api.PaymentsClient} Google Pay API client
*/
function getGooglePaymentsClient() {
if ( paymentsClient === null ) {
paymentsClient = new google.payments.api.PaymentsClient({environment: 'TEST'});
}
return paymentsClient;
}
/**
* Initialize Google PaymentsClient after Google-hosted JavaScript has loaded
*
* Display a Google Pay payment button after confirmation of the viewer's
* ability to pay.
*/
function onGooglePayLoaded() {
const paymentsClient = getGooglePaymentsClient();
paymentsClient.isReadyToPay(getGoogleIsReadyToPayRequest())
.then(function(response) {
if (response.result) {
addGooglePayButton();
// @todo prefetch payment data to improve performance after confirming site functionality
prefetchGooglePaymentData();
}
})
.catch(function(err) {
// show error in developer console for debugging
console.error(err);
});
}
/**
* Add a Google Pay purchase button alongside an existing checkout button
*
* @see {@link https://developers.google.com/pay/api/web/reference/object#ButtonOptions|Button options}
* @see {@link https://developers.google.com/pay/api/web/guides/brand-guidelines|Google Pay brand guidelines}
*/
function addGooglePayButton() {
const paymentsClient = getGooglePaymentsClient();
const button =
paymentsClient.createButton({onClick: onGooglePaymentButtonClicked, buttonColor:'black', buttonType:'long'});
document.getElementById('container').appendChild(button);
document.getElementById('container').style.display = 'block';
}
/**
* Provide Google Pay API with a payment amount, currency, and amount status
*
* @see {@link https://developers.google.com/pay/api/web/reference/object#TransactionInfo|TransactionInfo}
* @returns {object} transaction info, suitable for use as transactionInfo property of PaymentDataRequest
*/
function getGoogleTransactionInfo() {
return {
currencyCode: $('#currency').val(),
totalPriceStatus: 'FINAL',
// set to cart total
totalPrice: $('#amount').val()
};
}
/**
* g payment data to improve performance
*
* @see {@link https://developers.google.com/pay/api/web/reference/client#prefetchPaymentData|prefetchPaymentData()}
*/
function prefetchGooglePaymentData() {
const paymentDataRequest = getGooglePaymentDataRequest();
// transactionInfo must be set but does not affect cache
paymentDataRequest.transactionInfo = {
totalPriceStatus: 'NOT_CURRENTLY_KNOWN',
currencyCode: $('#currency').val()
};
const paymentsClient = getGooglePaymentsClient();
paymentsClient.prefetchPaymentData(paymentDataRequest);
}
/**
* Show Google Pay payment sheet when Google Pay payment button is clicked
*/
function onGooglePaymentButtonClicked() {
const paymentDataRequest = getGooglePaymentDataRequest();
paymentDataRequest.transactionInfo = getGoogleTransactionInfo();
const paymentsClient = getGooglePaymentsClient();
paymentsClient.loadPaymentData(paymentDataRequest)
.then(function(paymentData) {
// handle the response
processPayment(paymentData);
})
.catch(function(err) {
// show error in developer console for debugging
console.error(err);
});
}
/**
* Process payment data returned by the Google Pay API
*
* @param {object} paymentData response from Google Pay API after user approves payment
* @see {@link https://developers.google.com/pay/api/web/reference/object#PaymentData|PaymentData object reference}
*/
function processPayment(paymentData) {
var data = {
paymentData : paymentData,
merchant_id : $('#merchantId').val(),
amount : $('#amount').val(),
currency : $('#currency').val(),
ordernumber : $('#ordernumber').val(),
email : $('#email').val(),
firstname : $('#firstname').val(),
middlename : $('#middlename').val(),
lastname : $('#lastname').val(),
comment : $('#comment').val()
};
// For debug
console.log(data);
$.post("/pay/tokenpay_widget_gp.cfm", JSON.stringify(data)).then(function (result) {
// For debug
console.log(result);
// Example result:
// {"order":{"ordernumber":"2019.03.11-664","orderstate":"Approved"}}
});
}
</script>
<script async src="https://pay.google.com/gp/p/js/pay.js" onload="onGooglePayLoaded()"></script> |