Single-page web applications
The use of a single-page-application or SPA presents the following advantages:
- Reduced loading time.
- Less resources consumed.
Integration steps
- Loading the payment form
- Initializing the payment form
- Displaying the payment form
- Analyzing the payment result
Frameworks
Loading the payment form
In the HEAD
, :
Chargez notre librairie JavaScript : src="https://static.lyra.com/static/js/krypton-client/V4.0/stable/kr-payment-form.min.js"
Intégrez obligatoirement la clé publique dans le paramètre
kr-public-key
(3 ème clé du tableau des clés API REST ).Apply a theme (link: Themes ).
In the BODY
, :
- Mask the payment form, in a
<div>
.
Code sample
<head> <!-- Javascript library. Should be loaded in head section --> <script type="text/javascript" src="https://static.lyra.com/static/js/krypton-client/V4.0/stable/kr-payment-form.min.js" kr-public-key="69876357:testpublickey_DEMOPUBLICKEY95me92597fd28tGD4r5:testpublickey_DEMOPUBLICKEY95me92597fd28tGD4r5"> </script> <!-- theme and plugins. should be loaded in the HEAD section --> <link rel="stylesheet" href="https://static.lyra.com/static/js/krypton-client/V4.0/ext/classic-reset.min.css"> <script type="text/javascript" src="https://static.lyra.com/static/js/krypton-client/V4.0/ext/classic.js"></script> </head> <body> ... <!--Hidden payment form --> <div id="paymentForm" class="kr-embedded" style="display:none"> <!-- payment form fields --> <div class="kr-pan"></div> <div class="kr-expiry"></div> <div class="kr-security-code"></div> <!-- payment form submit button --> <button class="kr-payment-button"></button> <!-- error zone --> <div class="kr-form-error"></div> </div> ... </body>
Initializing the payment form
When the buyer decides to pay:
- Create a formToken during the call to the Charge/CreatePayment Web Service.
For security reasons, the call is always made via your merchant server (never via the browser) to avoid CORS (Cross Origin Policy) errors.
Code sample
/**
* Called on 'checkout' click
*/
function onCheckout(){
// Create the order, based on your cart
var order = {
"amount": 990,
"currency": "EUR",
"orderId": "myOrderId-999999",
"customer": {
"email": "sample@example.com"
}
};
// Call merchant server to get form token and then display payment form
getFormToken(order, displayPaymentForm, alert);
}
/**
* Get form token from merchant server
* @param order
* @param resolve
* @param reject
*/
function getFormToken(order, resolve, reject){
var request = new XMLHttpRequest();
// Open a new connection, using the POST request on the URL endpoint
request.open('POST', 'YOUR_SERVER/payment/init', true);
request.setRequestHeader('Content-Type', 'application/json');
request.onload = function (){
if (request.status >= 200 && request.status < 400) {
resolve(this.response);
}
else
{
reject("Invalid server response. Code " + request.status);
}
};
request.onerror = function (error){
reject(error);
};
// Send request
request.send(JSON.stringify(order));
}
- Call your merchant server to validate the cart (stock control and management, cart amount, etc.).
Example of code on Node JS :
/* Init payment form */
router.post('/init', function(req, res, next){
var order = req.body;
// TO DO: check that order is valid
// Call CreatePayment web service to create the form token
request.post({
url: "https://api.lyra.com/api-payment/V4/Charge/CreatePayment",
headers: {
'Authorization': 'Basic Njk4NzYzNTc6dGVzdHBhc3N3b3JkX0RFTU9QUklWQVRFS0VZMjNHNDQ3NXpYWlEyVUE1eDdN',
'Content-Type': 'application/json'
},
json: order
}, function(error, response, body){
if (body.status === 'SUCCESS')
{
// Send back the form token to the client side
res.send(body.answer.formToken);
}
else
{
// Do your own error handling
console.error(body);
res.status(500).send('error');
}
});
});
Displaying the payment form
Once the formToken has been generated:
- Display the form, marked by default.
- Associate it with the form: KR.setFormToken.
- Intégrate the KR.onSubmit function to receive the notification during the return to the shop (browser side).
Code sample
/**
* Display the payment form with the argument form token
* @param formToken
*/
function displayPaymentForm(formToken){
// Show the payment form
document.getElementById('paymentForm').style.display = 'block';
// Set form token
KR.setFormToken(formToken);
// Add listener for submit event
KR.onSubmit(onPaid);
}
Analyzing the payment result
At the end of the payment, analyze the payment result:
Via the IPN (Instant Payment Notification), during a server-to-server call. More information: IPN (Instant Payment Notification URL) analysis.
Depuis le retour à la boutique, lors du retour dans le navigateur grâce à la méthode KR.onSubmit.
- Use a custom function
onPaid
to display a message depending on the transaction status.
- Use a custom function
Code sample
/**
* Called when payment is finished
* @param event
*/
function onPaid(event){
if (event.clientAnswer.orderStatus === "PAID") {
// Remove the payment form
KR.removeForms();
// Show success message
document.getElementById("paymentSuccessful").style.display = "block";
} else {
// Show error message to the user
alert("Payment failed !");
}
}
Integration with Vue / React / Angular
Integration with JavaScript compiled frameworks (such as Vue, React or Angular) requires the use of the embedded-form-glue library.
Advantages
- Preload the library to allow for a faster display on slow networks.
- Manage the configuration when the application is not yet loaded.
- Easily add, delete and display the form once again.
Working in asynchronous environment
In an asynchronous environment, all events and methods return promises. The then()
method contains two properties:
KR
: the JavaScript library reference is always returned, which allows to chain the promises.result
: the operation result can be undefined or absent from the object if any result is returned.
Code sample
KR.validateForm().then( ({KR, result}) => { /* there is no error */ /* result == null */ } ) .catch( ({KR, result}) => { /* Get the error message */ var code = result.errorCode; var message = result.errorMessage; var myMessage = code + ": " + message; console.log(myMessage); /* if you have defined a callback using */ /* result.onError(), you can trigger it calling: */ return result.doOnError(); } );
Examples
Framework | Description |
---|---|
Angular | example of integration for Angular |
ember | example of integration for Ember |
ionic | example of integration for Ionic |
next | integration example for Next |
React | example of integration for React |
server | integration example for Server |
svelte | integration example for Svelte |
vue | example of integration for Vue.js |
require.js | example of integration with RequireJS |