Sample Code | Google Pay™
Sample code of Google Pay™ Direct Integration
This sample code is a complete example of a payment page that uses the MyFatoorah with Google Pay™.
//1: load google pay js file
<script src="https://pay.google.com/gp/p/js/pay.js">
</script>
//2: add google pay container div
<div id="gp-container"></div>
//3: prepare google pay model
<script>
$(document).ready(function () {
googlePayModel = {
sessionId: "", // Here you add the "SessionId" you receive from InitiateSession Endpoint.
amount: "10", // Add the invoice amount.
currencyCode: "KWD", // Here, add your Currency Code.
countryCode: "KWT", // Here, add your Country Code.
language: 'en', // Here, add your prefered language values[ar|en].
cardViewId: 'gpcontainer', // Here, add your google pay div id.
isProduction: false, // Here, add your the environment 'true' mean production.
merchantId: '12345678901234567890', // Here add the merchantId, for production get value from google pay api console
gatewayMerchantId: '<gatewayMerchantId>', // Here add the recieved from MyFatoorah
merchantName: 'YOUR COMAPNY NAME',
};
startGooglePay(googlePayModel);
function startGooglePay(invModel) {
var gpDiv = invModel.cardViewId;
const buttonLocale = invModel.language == 'ar' ? 'ar' : 'en';
const environment = invModel.isProduction == true ? 'PRODUCTION' : 'TEST';
const allowedCardNetworks = ["AMEX", "MASTERCARD", "VISA"];
const allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];
const gatewayMerchantId = invModel.gatewayMerchantId;
const merchantId = invModel.merchantId;
const merchantName = invModel.merchantName;
const mainItem = "Pay Invoice ";
const sessionId = invModel.sessionId;
const invoiceValue = Number(parseFloat(invModel.amount.replace(",", "")).toFixed(2)).toString();
let countryCode = invModel.countryCode;
let currencyCode = invModel.currencyCode;
const callbackIntents = ["PAYMENT_AUTHORIZATION"];
const baseRequest = {
apiVersion: 2,
apiVersionMinor: 0,
};
const tokenizationSpecification = {
type: 'PAYMENT_GATEWAY',
parameters: {
'gateway': 'myfatoorah',
'gatewayMerchantId': invModel.gatewayMerchantId
},
};
const merchantInfo = {
merchantId: merchantId,
merchantName: merchantName,
};
const baseCardPaymentMethod = {
type: 'CARD',
parameters: {
allowedAuthMethods: allowedCardAuthMethods,
allowedCardNetworks: allowedCardNetworks
}
};
const cardPaymentMethod = Object.assign(
{},
baseCardPaymentMethod,
{
tokenizationSpecification: tokenizationSpecification
}
);
let paymentsClient = null;
function onGooglePayLoaded() {
const paymentsClient = getGooglePaymentsClient();
const googleIsReadyToPayRequest = Object.assign({}, baseRequest);
googleIsReadyToPayRequest.allowedPaymentMethods = [baseCardPaymentMethod];
paymentsClient.isReadyToPay(googleIsReadyToPayRequest)
.then(function (response) {
if (response.result) {
addGooglePayButton();
prefetchGooglePaymentData();
}
})
.catch(function (err) {
// show error in developer console for debugging
console.error(err);
});
}
function addGooglePayButton() {
const paymentsClient = getGooglePaymentsClient();
const button =
paymentsClient.createButton({
buttonType: "pay",
buttonColor: "black",
buttonLocale: buttonLocale,
buttonSizeMode: 'fill',
onClick: onGooglePaymentButtonClicked,
allowedPaymentMethods: [baseCardPaymentMethod]
});
document.getElementById(gpDiv).appendChild(button);
}
function onGooglePaymentButtonClicked() {
const paymentDataRequest = getGooglePaymentDataRequest();
paymentDataRequest.transactionInfo = getGoogleTransactionInfo();
const paymentsClient = getGooglePaymentsClient();
paymentsClient.loadPaymentData(paymentDataRequest);
}
function getGoogleTransactionInfo() {
return {
displayItems: [
{
label: mainItem,
type: "SUBTOTAL",
price: invoiceValue,
},
],
countryCode: countryCode,
currencyCode: currencyCode,
totalPriceStatus: "FINAL",
totalPrice: invoiceValue,
totalPriceLabel: "Total"
};
}
function prefetchGooglePaymentData() {
const paymentDataRequest = getGooglePaymentDataRequest();
// transactionInfo must be set but does not affect cache
paymentDataRequest.transactionInfo = {
totalPriceStatus: 'NOT_CURRENTLY_KNOWN',
totalPrice: invoiceValue,
currencyCode: currencyCode
};
const paymentsClient = getGooglePaymentsClient();
paymentsClient.prefetchPaymentData(paymentDataRequest);
}
function getGooglePaymentDataRequest() {
const paymentDataRequest = Object.assign({}, baseRequest);
paymentDataRequest.allowedPaymentMethods = [cardPaymentMethod];
paymentDataRequest.transactionInfo = getGoogleTransactionInfo(mainItem, invoiceValue);
paymentDataRequest.merchantInfo = merchantInfo;
paymentDataRequest.callbackIntents = callbackIntents;
return paymentDataRequest;
}
function getGooglePaymentsClient() {
if (paymentsClient === null) {
paymentsClient = new google.payments.api.PaymentsClient({
environment: environment,
paymentDataCallbacks: {
onPaymentAuthorized: onPaymentAuthorized,
}
});
}
return paymentsClient;
}
function processPayment(paymentData) {
var reqData = {
type: 2,
sessionId: sessionId, // Here you add the "SessionId" you receive from InitiateSession Endpoint.
token: paymentData, // Here you add the google pay token
};
//Ajax call to your backend (ProcessPayment or any method name)
//In your backend method you need to do the followings:
//1: Call UpdateSession endpoint
//2: If success then call ExecutePayment endpoint
//3: Return the ExecutePayment result
return $.ajax({
url: YourHostUrl + "/ProcessPayment", //Here you add UpdateSession endpoint
method: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(reqData)
});
}
function onPaymentAuthorized(paymentData) {
return new Promise(function (resolve, reject) {
// handle the response
processPayment(paymentData)
.then(function (result) {
if (result.IsSuccess) {
resolve({ transactionState: 'SUCCESS' });
//success url
window.location = result.PaymentURL;
} else {
throw {
transactionState: 'FAILED',
error: {
intent: 'PAYMENT_AUTHORIZATION',
message: result.Message,
reason: 'PAYMENT_PROCCESS_FAILED',
url: result.PaymentURL
}
};
}
})
.catch(function (e) {
resolve({
transactionState: e.transactionState,
error: {
intent: e.error.intent,
message: e.error.message,
reason: e.error.reason
}
});
//failur url
window.location = e.url;
});
});
}
onGooglePayLoaded();
}
});
</script>
Updated 12 months ago