Before calling the payment request API, you must check whether the user can make a payment using the current device.
Use the canMakePayment()
method to query whether the user is allowed to make
payments with the current device.
- If the result returned is
True
, then Google Pay is installed on the device and the user can make a payment. - If the result returned is
False
, it indicates that Google Pay isn't installed on the device, or payment method is not added in Google Pay.
If a query is made using canMakePayment()
method with different payment
methods in supportedInstruments
, the following error will be returned:
DOMException: Query quota exceeded, not allowed to check whether can make
payment.
When this error occurs, Chrome will reset the quota after 30 minutes or on restart.
Each order made through Google Pay contains different data fields
(for example, transactionID
). To avoid the DOMException error, you must cache
the result of the first call, then check for the cache result before making more calls.
Checking user readiness
The sample function below checks to see whether a payment can be made using a session storage cache.
// Global key for canMakepayment cache.
const canMakePaymentCache = 'canMakePaymentCache';
/**
* Check whether can make payment with Google Pay or not. It will check session storage
* cache first and use the cache directly if it exists. Otherwise, it will call
* canMakePayment method from PaymentRequest object and return the result, the
* result will also be stored in the session storage cache for future usage.
*
* @private
* @param {PaymentRequest} request The payment request object.
* @return {Promise} a promise containing the result of whether can make payment.
*/
function checkCanMakePayment(request) {
// Check canMakePayment cache, use cache result directly if it exists.
if (sessionStorage.hasOwnProperty(canMakePaymentCache)) {
return Promise.resolve(JSON.parse(sessionStorage[canMakePaymentCache]));
}
// If canMakePayment() isn't available, default to assume the method is
// supported.
var canMakePaymentPromise = Promise.resolve(true);
// Feature detect canMakePayment().
if (request.canMakePayment) {
canMakePaymentPromise = request.canMakePayment();
}
return canMakePaymentPromise
.then((result) => {
// Store the result in cache for future usage.
sessionStorage[canMakePaymentCache] = result;
return result;
})
.catch((err) => {
console.log('Error calling canMakePayment: ' + err);
});
}