Handle payment response
Stay organized with collections
Save and categorize content based on your preferences.
When you call show()
method on a PaymentRequest
object, it returns the
payment request response. After the response is received, it must be sent back
to the retailer server. There, the transaction ID is verified against
PSP to ensure the transaction was successful. The UI is then updated for the
user based on the verification status.
To aid in verification, the response from Google Pay contains the fields required by
NPCI. For more information, see the NPCI UPI Linking Specification.
Additionally, Google Pay provides the flexibility of a customized response.
Refer to Google Pay response
section for detailed response fields.
The following example shows how the browser response is converted to a JSON
string and sent back to the retailer server, then further processed. After
receiving the server response, it will complete the payment by logging a message
in the console.
/**
* Process the response from browser.
*
* @private
* @param {PaymentResponse} instrument The payment instrument that was authed.
*/
function processResponse(instrument) {
var instrumentString = instrumentToJsonString(instrument);
console.log(instrumentString);
fetch('/buy', {
method: 'POST',
headers: new Headers({'Content-Type': 'application/json'}),
body: instrumentString,
})
.then(function(buyResult) {
if (buyResult.ok) {
return buyResult.json();
}
console.log('Error sending instrument to server.');
})
.then(function(buyResultJson) {
completePayment(instrument, buyResultJson.status, buyResultJson.message);
})
.catch(function(err) {
console.log('Unable to process payment. ' + err);
});
}
/**
* Notify browser that the instrument authorization has completed.
*
* @private
* @param {PaymentResponse} instrument The payment instrument that was authed.
* @param {string} result Whether the auth was successful. Should be either
* 'success' or 'fail'.
* @param {string} msg The message to log in console.
*/
function completePayment(instrument, result, msg) {
instrument.complete(result)
.then(function() {
console.log('Payment succeeds.');
console.log(msg);
})
.catch(function(err) {
console.log(err);
});
}
Utility methods
This section will cover all of the utility methods used in the provided sample
codes.
A utility method to show the alert dialog when the user cannot make payment with
the Google Pay.
/** Handle Google Pay not ready to pay case. */
function handleNotReadyToPay() {
alert('Google Pay is not ready to pay.');
}
Utility
method to convert paymentResponse
to JSON string.
* Converts the payment response into a JSON string.
*
* @private
* @param {PaymentResponse} paymentResponse The payment response to convert.
* @return {string} The string representation of the payment response.
*/
function paymentResponseToJsonString(paymentResponse) {
// PaymentResponse is an interface, JSON.stringify works only on dictionaries.
var paymentResponseDictionary = {
methodName:paymentResponse.methodName,
details:paymentResponse.details,
shippingAddress: addressToJsonString(paymentResponse.shippingAddress),
shippingOption: paymentResponse.shippingOption,
payerName: paymentResponse.payerName,
payerPhone: paymentResponse.payerPhone,
payerEmail: paymentResponse.payerEmail,
};
return JSON.stringify(paymentResponseDictionary, undefined, 2);
}
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2024-10-16 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-10-16 UTC."],[[["\u003cp\u003eCalling \u003ccode\u003eshow()\u003c/code\u003e on a \u003ccode\u003ePaymentRequest\u003c/code\u003e object initiates a payment request and returns a response that needs to be sent to the retailer's server for verification.\u003c/p\u003e\n"],["\u003cp\u003eThe server verifies the transaction ID against the Payment Service Provider (PSP) to ensure successful payment before updating the user interface.\u003c/p\u003e\n"],["\u003cp\u003eGoogle Pay's response includes necessary fields for verification as per NPCI guidelines and can be further customized as needed.\u003c/p\u003e\n"],["\u003cp\u003eUtility methods are provided for tasks such as handling payment failures, converting the payment response to JSON format for server communication, and completing the payment process.\u003c/p\u003e\n"]]],["The `show()` method on a `PaymentRequest` object returns a payment response, which must be sent to the retailer's server. The server verifies the transaction ID with the payment service provider (PSP). Google Pay's response includes fields required by NPCI and allows for customization. The provided code demonstrates converting the browser response to a JSON string and sending it to the server. After the server response, `completePayment` function logs a message in the console. `paymentResponseToJsonString` is used to convert response to JSON. `handleNotReadyToPay` display a alert.\n"],null,["# Handle payment response\n\nWhen you call `show()` method on a `PaymentRequest` object, it returns the\npayment request response. After the response is received, it must be sent back\nto the retailer server. There, the transaction ID is verified against\nPSP to ensure the transaction was successful. The UI is then updated for the\nuser based on the verification status.\n\nTo aid in verification, the response from Google Pay contains the fields required by\nNPCI. For more information, see the [NPCI UPI Linking Specification](https://www.npci.org.in/sites/all/themes/npcl/images/PDF/UPI_Linking_Specs_ver_1.5.1.pdf).\nAdditionally, Google Pay provides the flexibility of a customized response.\nRefer to [Google Pay response](/pay/india/api/web/googlepay-response)\nsection for detailed response fields.\n\nThe following example shows how the browser response is converted to a JSON\nstring and sent back to the retailer server, then further processed. After\nreceiving the server response, it will complete the payment by logging a message\nin the console. \n\n\n /**\n * Process the response from browser.\n *\n * @private\n * @param {PaymentResponse} instrument The payment instrument that was authed.\n */\n function processResponse(instrument) {\n var instrumentString = instrumentToJsonString(instrument);\n console.log(instrumentString);\n\n fetch('/buy', {\n method: 'POST',\n headers: new Headers({'Content-Type': 'application/json'}),\n body: instrumentString,\n })\n .then(function(buyResult) {\n if (buyResult.ok) {\n return buyResult.json();\n }\n console.log('Error sending instrument to server.');\n })\n .then(function(buyResultJson) {\n completePayment(instrument, buyResultJson.status, buyResultJson.message);\n\n })\n .catch(function(err) {\n console.log('Unable to process payment. ' + err);\n });\n }\n\n /**\n * Notify browser that the instrument authorization has completed.\n *\n * @private\n * @param {PaymentResponse} instrument The payment instrument that was authed.\n * @param {string} result Whether the auth was successful. Should be either\n * 'success' or 'fail'.\n * @param {string} msg The message to log in console.\n */\n function completePayment(instrument, result, msg) {\n instrument.complete(result)\n .then(function() {\n console.log('Payment succeeds.');\n console.log(msg);\n })\n .catch(function(err) {\n console.log(err);\n });\n }\n\nUtility methods\n---------------\n\nThis section will cover all of the utility methods used in the provided sample\ncodes.\n\nA utility method to show the alert dialog when the user cannot make payment with\nthe Google Pay. \n\n /** Handle Google Pay not ready to pay case. */\n function handleNotReadyToPay() {\n alert('Google Pay is not ready to pay.');\n }\n\n`Utility` method to convert `paymentResponse` to JSON string. \n\n * Converts the payment response into a JSON string.\n *\n * @private\n * @param {PaymentResponse} paymentResponse The payment response to convert.\n * @return {string} The string representation of the payment response.\n */\n function paymentResponseToJsonString(paymentResponse) {\n // PaymentResponse is an interface, JSON.stringify works only on dictionaries.\n var paymentResponseDictionary = {\n methodName:paymentResponse.methodName,\n details:paymentResponse.details,\n shippingAddress: addressToJsonString(paymentResponse.shippingAddress),\n shippingOption: paymentResponse.shippingOption,\n payerName: paymentResponse.payerName,\n payerPhone: paymentResponse.payerPhone,\n payerEmail: paymentResponse.payerEmail,\n };\n return JSON.stringify(paymentResponseDictionary, undefined, 2);\n }"]]