Ready client module Google Pay
Comrades, I present a ready-made JavaScript module for making payments using Google Pay. The module assumes use in the modern development environment of npm with export-import, however, those who want pure ES5, I think, will be able to redo it easily.
Link to module . The code has the necessary documentation and comments. Here I will give some explanations.
I must say that the Google documentation for the payment button was not the easiest, the list of errors returned by the Google Pay API is also not the most comprehensive. Therefore, unlike working with ApplePay, with Google Pay, I had to look a little before the module really worked.
The work consists of two stages: first we have to decide whether or not to show the button (not all browsers support Google Pay), and then do the payment processing itself.
1. Button display
There is nothing difficult. In options, we pass two parameters - googleBaseCardPaymentMethod and environment.
googleBaseCardPaymentMethod is an object that lists payment types and parameters (more details here on the allowed search ). If it is not specified, we call the standard setter in the code, which returns a typical object to us:
environment is an environment, PRODUCTION or TEST
On the call to the success callback, we actually draw (or show the already drawn) button. This is your choice. Just remember that Google requires compliance with its guides .
2. Processing
To display the Google button, the Pay API of your browser created a paymentClient object , which now along with other parameters must be passed to the processing function. Look at the other parameters:
googleBaseCardPaymentMethod - see above
googlePayPublicKey, merc_id, merc_name - for successful work with Google Pay you must have a registered merchant. Its parameters, we get the back.
In addition, we pass the success and fail callbacks, as well as the data for making a payment (see below).
So, to make a payment, we need to take a previously created object paymentsClient and call the method loadPaymentData with the object paymentDataRequest : const = paymentDataRequest getGooglePaymentDataRequest () :
For the test environment, Google offers its merchantInfo object. It should be used exactly with the merchantId , which is written in the example, merchantName is not essential.
In addition, we need a token object :
→ Read more about the parameters here
. When the object is formed, a request is sent to the Google server using the loadPaymentData method , a frame with saved maps is opened, and the frame is closed after the operation is completed:
After successful execution of the method (that is, calling the saved cards and passing verification), we can make an AJAX-request to our own back-up with the goal of making a payment using Google Pay. In this request, we will need to pass the googleToken that came from Google , as well as the public key.
Everything, our payment Google Pay after processing on a bek took place!
Link to module . The code has the necessary documentation and comments. Here I will give some explanations.
I must say that the Google documentation for the payment button was not the easiest, the list of errors returned by the Google Pay API is also not the most comprehensive. Therefore, unlike working with ApplePay, with Google Pay, I had to look a little before the module really worked.
The work consists of two stages: first we have to decide whether or not to show the button (not all browsers support Google Pay), and then do the payment processing itself.
1. Button display
exportfunctionshowGooglePayButton(options, callbacks) {
// проверка параметровconst check = checkParams("showGooglePayButton", options, callbacks);
if (!check) {
returnfalse;
} else {
options = check.options;
}
const paymentsClient = new google.payments.api.PaymentsClient({environment: options.environment});
// в приложении запоминаем экземпляр платёжного клиента, который создало API
callbacks.setPaymentClient(paymentsClient);
const request = {
apiVersion: 2,
apiVersionMinor: 0,
allowedPaymentMethods: [options.googleBaseCardPaymentMethod]
};
paymentsClient.isReadyToPay(request)
.then(function(response) {
if (response.result) {
callbacks.success();
returntrue;
} else {
console.log("Запрос на показ кнопки Google Pay закончился неудачно");
callbacks.fail();
}
})
.catch(function(err) {
console.log("showGooglePayButton ERROR");
callbacks.fail();
});
}
There is nothing difficult. In options, we pass two parameters - googleBaseCardPaymentMethod and environment.
googleBaseCardPaymentMethod is an object that lists payment types and parameters (more details here on the allowed search ). If it is not specified, we call the standard setter in the code, which returns a typical object to us:
const setGoogleBaseCardPaymentMethod = () => {
return {
type: "CARD",
parameters: {
allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
allowedCardNetworks: ["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"]
}
}
};
environment is an environment, PRODUCTION or TEST
On the call to the success callback, we actually draw (or show the already drawn) button. This is your choice. Just remember that Google requires compliance with its guides .
2. Processing
To display the Google button, the Pay API of your browser created a paymentClient object , which now along with other parameters must be passed to the processing function. Look at the other parameters:
googleBaseCardPaymentMethod - see above
googlePayPublicKey, merc_id, merc_name - for successful work with Google Pay you must have a registered merchant. Its parameters, we get the back.
In addition, we pass the success and fail callbacks, as well as the data for making a payment (see below).
So, to make a payment, we need to take a previously created object paymentsClient and call the method loadPaymentData with the object paymentDataRequest : const = paymentDataRequest getGooglePaymentDataRequest () :
const getGooglePaymentDataRequest = () => {
const cardPaymentMethod = Object.assign(
{},
baseMethod,
{
tokenizationSpecification: token
}
);
const paymentDataRequest = {
apiVersion: 2,
apiVersionMinor: 0,
allowedPaymentMethods : [cardPaymentMethod],
/* for demo (enviroment TEST):
merchantInfo : {
merchantId: '12345678901234567890',
merchantName: 'JOHN SMITH'
},
*//* for prod (enviroment PRODUCTION):
merchantInfo : {
merchantId: options.merc_id,
merchantName: options.merc_name
},
*/
merchantInfo : {
merchantId: options.merc_id,
merchantName: options.merc_name
},
transactionInfo : {
currencyCode: options.currency,
totalPriceStatus: 'FINAL',
totalPrice: "" + options.sum
}
};
return paymentDataRequest;
};
For the test environment, Google offers its merchantInfo object. It should be used exactly with the merchantId , which is written in the example, merchantName is not essential.
In addition, we need a token object :
const token = {
/* for demo (enviroment TEST):
parameters: {
"protocolVersion": "ECv1",
"publicKey": yourTestPublicKey
}
*//* for prod (enviroment PRODUCTION):
parameters: {
"protocolVersion": "ECv1",
"publicKey": params.googlePayPublicKey
}
*/
type: 'DIRECT',
parameters: {
"protocolVersion": "ECv1",
"publicKey": options.googlePayPublicKey
}
};
→ Read more about the parameters here
. When the object is formed, a request is sent to the Google server using the loadPaymentData method , a frame with saved maps is opened, and the frame is closed after the operation is completed:
paymentsClient.loadPaymentData(paymentDataRequest)
.then(function(paymentData) {
const googleToken = JSON.parse(paymentData.paymentMethodData.tokenizationData.token);
// your own client-back ajax request here
}
After successful execution of the method (that is, calling the saved cards and passing verification), we can make an AJAX-request to our own back-up with the goal of making a payment using Google Pay. In this request, we will need to pass the googleToken that came from Google , as well as the public key.
Everything, our payment Google Pay after processing on a bek took place!