cancel
Showing results for 
Search instead for 
Did you mean: 

Regarding the usage of Authorize.net API for Payments in SAPUI5 CAPM application

I have used below API'S by Authorize.net. One is https://apitest.authorize.net/xml/v1/request.api and other one is https://test.authorize.net/payment/payment. 
First API will generate a token for the rendering of Form for Payments page and using that token I will render the form. So, coming to my application development I have a CAP (Cloud Application Programming Model) service which will fetch the token from the API and returns it. And I have a SAPUI5 Fiori application which will call this service and gets the token and placed inside the form rendering for the second API. This works fine and am able to make payments there. But when payment is completed, I am unable to get the transaction Id and authentication code from the payments completed page. Because it was embedded inside an iframe. So, I can't access this using iframe communication response. Till the I can't get the back the messages after payment through iframe communicator. Can you please help me in this. Iam attaching the required files of my code can you please guide me in how to achieve this.

This is my server code to generate token 

const cds = require('@sap/cds');
const axios = require('axios');

module.exports = cds.service.impl(async function () {
this.on('POST', 'TransactionDetails', async (req) => {
const requestData = req.data;
if (!requestData.merchantName || !requestData.transactionKey || !requestData.customerProfileId) {
req.error(400, 'Required fields are missing.');
return;
}
const requestPayload = {
getHostedPaymentPageRequest: {
merchantAuthentication: {
name: requestData.merchantName,
transactionKey: requestData.transactionKey,
},
transactionRequest: {
transactionType: requestData.transactionType,
amount: requestData.amount.toFixed(2),
profile: {
customerProfileId: requestData.customerProfileId,
},
customer: {
email: requestData.customerEmail,
},
billTo: {
firstName: requestData.firstName,
lastName: requestData.lastName,
company: requestData.company,
address: requestData.address,
city: requestData.city,
state: requestData.state,
zip: requestData.zip,
country: requestData.country,
},
},
hostedPaymentSettings: {
setting: JSON.parse(requestData.paymentSettings),
},
},
};
try {
const response = await axios.post(
'https://apitest.authorize.net/xml/v1/request.api',
requestPayload,
{
headers: {
'Content-Type': 'application/json',
},
}
);
if (response.data.token) {
return { token: response.data.token };
} else {
req.error(500, 'Token not received in response.');
return;
}
} catch (error) {
req.error(500, `Failed to generate payment token: ${error.message}`);
return;
}
});
});

 

This is the view code of the app is below

<mvc:View
xmlns:mvc="sap.ui.core.mvc"
xmlns:core="sap.ui.core"
xmlns:m="sap.m"
controllerName="sap.com.payment.controller.View2"
displayBlock="true">

<m:Page id="pageid" title="Payment Page">
<m:content>
<core:HTML id="htmlID" />
<m:Button id="Success" text="Back" press="onBack" />
</m:content>
</m:Page>
</mvc:View>

This is the controller of js code

sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/m/MessageToast"
], function (Controller, MessageToast) {
"use strict";
return Controller.extend("sap.com.payment.controller.View2", {
onInit: function () {
this.oRouter = sap.ui.core.UIComponent.getRouterFor(this);
this.oRouter.getRoute("View2").attachPatternMatched(this._onObjectMatched, this);
window.addEventListener("message", this.onMessage.bind(this), false);
console.log("Message listener added and waiting for iframe messages");
},
_onObjectMatched: function (oEvent) {
var oDetails = JSON.parse(oEvent.getParameter("arguments").Details);
const requestData = {
merchantName: oDetails.merchantName,
transactionKey: oDetails.transactionKey,
transactionType: oDetails.transactionType,
amount: parseFloat(oDetails.amount),
customerProfileId: oDetails.customerProfileId,
customerEmail: oDetails.customerEmail,
firstName: oDetails.firstname,
lastName: oDetails.lastname,
company: oDetails.company,
address: oDetails.address,
city: oDetails.city,
state: oDetails.state,
zip: oDetails.zip,
country: oDetails.country,
paymentSettings: JSON.stringify([{
settingName: "hostedPaymentReturnOptions",
settingValue: "{\"showReceipt\": true, \"url\": \"https://mysite.com/receipt\", \"cancelUrl\": \"https://mysite.com/cancel\"}"
}])
};
fetch("/catalog/TransactionDetails", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(requestData)
})
.then(response => response.json())
.then(data => {
if (data.token) {
this._setFormInIframe(data.token);
} else {
MessageToast.show("Token not found in response");
}
})
.catch(error => {
MessageToast.show("Error: " + error.message);
});
},
_setFormInIframe: function (sToken) {
var oIframe = this.byId("htmlID");
var sFormHtml = `
<form method="post" action="https://test.authorize.net/payment/payment" id="formAuthorizeNetTestPage">
<input type="hidden" name="token" value="${sToken}" />
<button type="submit" style="display:none;">Submit</button>
</form>
<script>
document.getElementById('formAuthorizeNetTestPage').submit();
</script>
<script>
window.addEventListener('DOMContentLoaded', function(event) {
const transactionId = document.getElementById("receiptTransactionId")?.innerText;
const authCode = document.getElementById("receiptAuth")?.innerText;
console.log(transactionId);
console.log(authCode);
if (transactionId && authCode) {
const message = \`action=transactResponse&transactionId=\${transactionId}&authCode=\${authCode}\`;
parent.postMessage(message, '*');
console.log(message)
}
});
</script>
`;
oIframe.setContent(`
<iframe
referrerpolicy="no-referrer-when-downgrade"
frameborder="0"
width="100%"
height="95%"
srcdoc="${sFormHtml.replace(/"/g, '&quot;')}">
</iframe>
`);
},
onMessage: function (event) {
console.log("Message received: ", event.data);
const params = this._parseQueryString(event.data);
if (params.action === "transactResponse") {
const transactionId = params.transactionId;
const authCode = params.authCode;
console.log(`Transaction ID: ${transactionId}, Auth Code: ${authCode}`);
MessageToast.show(`Transaction ID: ${transactionId}, Auth Code: ${authCode}`);
} else {
console.log("Unknown action received from iframe");
}
},
_parseQueryString: function (str) {
var params = {};
var arr = str.split('&');
arr.forEach(function (pair) {
var [key, value] = pair.split('=');
params[key] = decodeURIComponent(value);
});
return params;
},
onBack: function () {
history.go(-1);
}
});
});

 

 

Thanks,

Sunil.

Sunil
Member
0 REPLIES 0