JavaScript client reference
The JavaScript client allows to create a payment form on your merchant website, using the following code:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <!-- Javascript library. Should be loaded in head section --> <script src="https://api.lyra.com/static/js/krypton-client/V4.0/stable/kr-payment-form.min.js" kr-public-key="69876357:testpublickey_DEMOPUBLICKEY95me92597fd28tGD4r5" kr-post-url-success="paid.html"> </script> <!-- theme and plugins. should be loaded after the javascript library --> <!-- not mandatory but helps to have a nice payment form out of the box --> <link rel="stylesheet" href="https://api.lyra.com/static/js/krypton-client/V4.0/ext/classic-reset.css"> <script src="https://api.lyra.com/static/js/krypton-client/V4.0/ext/classic.js"> </script> </head> <body> <!-- payment form --> <div class="kr-embedded" kr-form-token="DEMO-TOKEN-TO-BE-REPLACED"> <!-- 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> </html>
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <!-- Javascript library. Should be loaded in head section --> <script src="<?php echo $client->getClientEndpoint();?>/static/js/krypton-client/V4.0/stable/kr-payment-form.min.js" kr-public-key="<?php echo $client->getPublicKey();?>" kr-post-url-success="paid.php"> </script> <!-- theme and plugins. should be loaded after the javascript library --> <!-- not mandatory but helps to have a nice payment form out of the box --> <link rel="stylesheet" href="<?php echo $client->getClientEndpoint();?>/static/js/krypton-client/V4.0/ext/classic-reset.css"> <script src="<?php echo $client->getClientEndpoint();?>/static/js/krypton-client/V4.0/ext/classic.js"> </script> </head> <body style="padding-top:20px"> <!-- payment form --> <div class="kr-embedded" kr-form-token="<?php echo $formToken;?>"> <!-- 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> </html>
For more detailed documentation, go to Getting started: Single payment .
Supported platforms
We make every effort to support all recent versions of the major browsers available on the market.
For security reasons and to deliver the best user experience to the majority of our merchants, we do not support browsers and operating systems that no longer receive security patches.
These browsers represent a minor part of the traffic making payments on the Internet.
We support:
- Internet Explorer from version 10 onwards
- Edge starting from version 17 onwards
- Chrome from version 70 onwards
- Firefox starting from version 64 onwards
- Safari (Desktop and mobile) from version 11 onwards
- Android native browser from Android 4.4 onwards
- All the latest versions of IOS starting from iPhone 4S
TLS 1.2 must be supported by the browser.
We strive to test most browsers, both mobile and desktop. However, it is possible that a combination of mobile + browser eludes our attention. In this case, please contact our support team.
If you want to support a combination that is not taken into account by our JavaScript client, you can implement our form with redirect.
Also note that some antivirus or ad-blocker software may block our solution. Please contact support if you notice any improper detection.
Initialization parameters
Various parameters can be defined while loading the JavaScript client. For example, in order to define kr-public-key and kr-post-url-success :
<!-- Javascript library. Should be loaded in head section --> <script src="https://api.lyra.com/static/js/krypton-client/V4.0/stable/kr-payment-form.min.js" kr-public-key="69876357:testpublickey_DEMOPUBLICKEY95me92597fd28tGD4r5" kr-post-url-success="paid.html"> </script>
<!-- Javascript library. Should be loaded in head section --> <script src="<?php echo $client->getClientEndpoint();?>/static/js/krypton-client/V4.0/stable/kr-payment-form.min.js" kr-public-key="<?php echo $client->getPublicKey();?>" kr-post-url-success="paid.php"> </script>
The available parameters are:
General settings:
Parameter | Required | DESCRIPTION |
---|---|---|
kr-public-key | yes | Public key for making a payment. |
kr-language | Language used for displaying the form in Culture format (en-US). | |
kr-post-url-success | URL to which the form is submitted (POST method) if successful. | |
kr-get-url-success | URL to which the form is submitted (POST method) if successful. | |
kr-post-url-refused | URL called when all attempts have failed (POST method). | |
kr-get-url-refused | URL called when all attempts have failed (GET method). | |
kr-clear-on-error | Disables the removal of CVV in case of rejected transaction (true or false). | |
kr-hide-debug-toolbar | Hides the debug sidebar in test mode (true or false). | |
kr-spa-mode | If the value is true, the form is not automatically initialized (false is the default value). |
Placeholder customization:
Parameter | Required | DESCRIPTION |
---|---|---|
kr-placeholder-expiry | Placeholder of the kr-expiry field (expiry date) | |
kr-placeholder-pan | Placeholder of the kr-pan field (card number) | |
kr-placeholder-security-code | Placeholder of the kr-security-code field (CVV) | |
kr-placeholder-identity-document-type | Placeholder of the ID document type field, if required (LATAM case) | |
kr-placeholder-identity-document-number | Placeholder of the ID number field, if required (LATAM case) | |
kr-placeholder-installment-number | Placeholder of the Payment method field | |
kr-placeholder-card-holder-mail | Placeholder of the e-mail field, if required (Latin America case) | |
kr-placeholder-card-holder-name | Placeholder of the cardholder name field, if required (Latin America case) |
Personalization of animated labels (specific to the material theme):
Parameter | Required | DESCRIPTION |
---|---|---|
kr-label-expiry | Animated label of the kr-expiry field (expiry date) | |
kr-label-pan | Animated label of the kr-pan field (card number) | |
kr-label-security-code | Animated label of the kr-security-code (CVV) field | |
kr-label-identity-document-type | Animated label of the ID type field, if required (LATAM case) | |
kr-label-identity-document-number | Animated label of the ID number field, if required (LATAM case) | |
kr-label-installment-number | Animated label of the Payment method field | |
kr-label-card-holder-mail | Animated label of the e-mail field, if required (LATAM case) | |
kr-label-card-holder-name | Animated label of the cardholder name field, if required (LATAM case) |
These parameters can also be overridden with the KR.setFormConfig() method. For example, to override the kr-post-url-success parameter:
KR.setFormConfig({
'kr-post-url-success': 'https://my.site'
}).then(({
KR
}) => {
/* there is no error */
);
Warning, if the kr-post-url-success and kr-get-url-success parameters are defined simultaneously, the POST method will have priority. The same applies to kr-post-url-refused and kr-get-url-refused* .
Events
It is possible to attach custom JavaScript callbacks to different events. The JavaScript client supports the following events:
Parameter | DESCRIPTION |
---|---|
KR.onBlur() | Un des champs du formulaire perd le focus. voir KR.onFocus() |
KR.onBrandChanged() | Called when the card brand has been detected. |
KR.onError() | Allows to be notified when an error occurs. |
KR.onFocus() | One of the form fields gets focus. |
KR.onFormCreated() | The payment form is ready but the content of iframes has not loaded yet. |
KR.onFormReady() | The form is ready to be used. |
KR.onFormValid() | Called when the card brand has been detected. |
KR.onInstallmentChanged() | Called when the buyer selects the number of installments for the payment. |
KR.onLoaded() | First event called before the form is created. |
KR.onPopinClosed() | Emits an event when the form pop-in is closed (case Pop-In: rapid testing ) |
KR.onSubmit() | Called just before the form is posted. |
KR.wallet.onTabChange() | Detects caps lock in case of a wallet (see Buyer wallet management ) |
KR.onTransactionCreated() | Called when a transaction is created (accepted or rejected) |
KR.button.onClick() | Called when the buyer clicks on the form button. |
KR.on3dSecureAbort() | Called when 3DS authentication is abandoned by the user |
The following events are obsolete and are no longer supported They should not be used :
- KR.onFormReadyListener()
- KR.onFormCreateListener()
All events return promises, allowing you to integrate them into a chain. See Working in asynchronous environment for more information.
KR.onBrandChanged()
The callback defined in KR.onBrandChanged() is called each time a card brand is detected. Example of integration:
<script type="text/javascript"> $(document).ready(function() { KR.onBrandChanged( function({KR, cardInfo}) { var myMessage = "Selected brand: " + cardInfo.brand + ", and bin: " + cardInfo.bin; $("#custommessage").html(myMessage); }); }); </script>
The cardInfo object contains the brand property which can take the following values:
- amex
- cb
- mastercard
- maestro
- visa_electron
- visa
It also contains the BIN of the card, i.e. the first 6 characters of the PAN.
To view the complete list, see the reference documentation of the effectiveBrand parameter here: Payment .
KR.onFormValid()
The callback defined in KR.onFormValid() is called once all the required fields are filled in and the data is valid. Integration example
<script type="text/javascript"> $(document).ready(function() { KR.onFormValid( function({KR, cardInfo}) { var myMessage = "Selected brand: " + cardInfo.brand + ", and bin: " + cardInfo.bin; $("#custommessage").html(myMessage); }); }); </script>
The cardInfo object contains the brand property which can take the following values:
- amex
- cb
- mastercard
- maestro
- visa_electron
- visa
It also contains the BIN of the card, i.e. the first 6 characters of the PAN.
To view the complete list, see the reference documentation of the effectiveBrand parameter here: Payment .
KR.onError()
KR.onError() allows to intercept errors before they appear.
Example of interception of error messages:
<script type="text/javascript"> $(document).ready(function() { KR.onError( function(event) { var code = event.errorCode; var message = event.errorMessage; var myMessage = code + ": " + message; try { /* if client answer exists, a refused transaction has been created */ /* it's not always the case. For example, if the form is empty, */ /* error is raised before transaction creation */
After that, error messages will automatically appear in the following element, if it is present:
<div id="customerror"></div>
When several errors are generated, they are merged into one single error. The children property will contain the details of all errors:
{ "errorCode": "CLIENT_300", "errorMessage": "Invalid form data", "children": [{ "errorCode": "CLIENT_301", "errorMessage": "Invalid card number", "field": "pan", (...) }, { "errorCode": "CLIENT_302", "errorMessage": "Invalid expiry date", "field": "expiryDate", (...) }, { "errorCode": "CLIENT_303", "errorMessage": "Invalid security code", "field": "securityCode", (...) }], "detailedErrorCode": null, "detailedErrorMessage": null, (...) }
For more information on errors, go to: Managing errors (JS client)
KR.onFocus()
Kr.onFocus() allows to be notified when a form field is in focus:
Example of integration:
<script type="text/javascript"> $(document).ready(function() { KR.onFocus( function(event) { var myMessage = "focus on: " + event.field; $("#custommessage").html(myMessage); }); }); </script>
If the card number field is in focus, the event variable will take the following value:
{ "field":"pan", "formId":"F73867", "_type":"krypton/focus" }
You can also use KR.onBlur() to detect the loss of a field's focus It operates similarly to KR.onFocus()
KR.onInstallmentChanged()
KR.onInstallmentChanged() allows you to be notified when the buyer selects the number of installments.
<script type="text/javascript">
$(document).ready(function() {
KR.onInstallmentChanged( function({KR, installmentInfo}) {
console.log(installmentInfo)
});
});
</script>
The installmentInfo object has the following attributes:
- brand => Card brand. E.g.: “VISA”
- hasInterests => Boolean that indicates if an interest rate applies. E.g.: false
- installmentCount => Total number of installments. E.g.: 1
- totalAmount => Total amount, including interest Example: 20000
KR.onSubmit()
KR.onSubmit() allows to intercept information about the authorized transaction before the form makes a POST to the URL defined with kr-post-success-url .
Example of integration:
<script type="text/javascript"> $(document).ready(function() { KR.onSubmit( function(event) { /* Change the button label to the orderStatus */ $(".kr-payment-button > span:first").html(event.clientAnswer.orderStatus); $(".kr-spinner").hide(); $(".kr-payment-button > span:first").show(); /* return values: * true: kr-post-success-url is called using POST * false: kr-post-success-url is not called, execution stops. */ return false; }); }); </script>
The callback receives an object with 2 parameters:
- KR: Reference to the library
- event: Object that contains the newly created transaction.
The object contained in event is the same as the one posted by the form. For more details, go to: Browser return .
The behavior varies depending on the boolean returned by your function:
Return value | Behavior |
---|---|
true | The JavaScript client performs a POST on kr-post-success-url . |
false | The POST with kr-post-success-url is not made. You manage the post-payment action yourself. |
KR.button.onClick()
KR.button.onClick() allows for custom processing before the JavaScript client validates the form and makes the call to create a transaction. KR.button.onClick() accepts either a callback or a promise as a parameter.
You can stop the execution string by returning false at the end of processing:
Return value | Behavior |
---|---|
false | The execution is interrupted. Error handling does not take place. The transaction is not created. |
true | The execution continues normally when the callback is executed. |
KR.onTransactionCreated()
There are 2 callbacks that allow intercepting a newly created transaction:
- KR.onSubmit() : when an accepted transaction is created.
- KR.onError() : When a rejected transaction is created.
KR.onTransactionCreated() allows to intercept all newly created transactions, whether they are accepted or rejected KR.onTransactionCreated() accepts as parameter either a callback or a promise.
The callback receives an object with 2 parameters:
- KR: Reference to the library
- event: Object that contains the newly created transaction.
You can stop the execution string by returning false at the end of processing:
Return value | Behavior |
---|---|
false | The execution is interrupted Error handling or redirection does not occur. |
true | The execution continues normally when the callback is executed. |
KR.on3dSecureAbort()
During 3D Secure authentication, the user can choose to cancel This will close the 3DS-Secure pop-in and an abort error will appear This event allows to intercept when the user abandons the payment.
Note that in this case, the transaction is not created in real time A rejected transaction with a 149 error will be created asynchronously, and only if the user has not made a new payment attempt The creation will take place after 10 minutes maximum To intercept this transaction, you must use the IPNs See IPN Basics for more details.
Methods
Several methods are available for interacting with the JavaScript client:
Method | DESCRIPTION |
---|---|
KR.field.focus() | Gives focus to an embedded form field. |
KR.setFormConfig() | Allows to override the JavaScript client configuration, see the next section. |
KR.setFormToken() | Shortcut for changing the formToken of the current form. |
KR.setBrand() | Forces the detection of the payment method. |
KR.submit() | Submits the form() Equivalent to the user clicking the form button |
KR.validate() | Obsolete, use KR.validateForm() |
KR.validateForm() | Triggers local validation of the form. |
The following methods are obsolete and are no longer supported They should not be used :
- KR.validate(): use KR.validateForm()
- KR.registerPlugin()
Pop-in display management (see Pop-in: rapid testing )
Method | DESCRIPTION |
---|---|
KR.closePopin() | Closes the pop-in (if open). |
KR.openPopin() | Opens the pop-in (if closed). |
KR.setShopName() | Changes the name of the shop defined in the pop-in header. |
Dynamic form management (add, remove DOM):
Method | DESCRIPTION |
---|---|
KR.addForm(CSS class or id) | Adds a form to a DOM element Returns a formId |
KR.attachForm(CSS class or id) | Enable the form on an existing DOM Returns a formId |
KR.hideForm(formId) | Hide the form |
KR.removeEventCallbacks() | Deletes all previously attached callbacks using KR.on[*] functions. |
KR.removeForms() | Removes all forms from the DOM (automatically calls KR.removeEventCallbacks() ) |
KR.showForm(formId) | Displaying a form |
you can see the Embedded Form Glue GitHub repository for more information.
Managing the payment form submission button:
Parameter | DESCRIPTION |
---|---|
KR.button.setLabel('MON LABEL') | Defines a custom label |
KR.button.showSpinner() | Displays the waiting animation |
KR.button.hideSpinner() | Hides the waiting animation |
KR.button.disable() | Disables the button (not clickable) |
KR.button.enable() | Activate the button |
All events return promises, allowing you to integrate them into a chain. See Working in asynchronous environment for more information.
KR.field.focus()
To give focus to a form field, you can use the KR.field.focus(FIELD_CLASS) method. You must pass the class of the embedded form field as a parameter.
For example, to add a button that will set focus on the expiry date field:
<button type="button" onclick="KR.fields.focus('kr-expiry')">Focus expiry field</button>
KR.setFormConfig()
This method allows to override the initialization parameters , as well as the following elements:
Use | DESCRIPTION |
---|---|
KR.setFormConfig({formToken: "NEW_FORM_TOKEN"}); | Changes the current formToken. |
KR.setFormConfig({language: "fr-FR"}); | Changes the language of the payment form and error messages. |
KR.setFormConfig({'kr-label-do-register': 'custom'}) | Sets the label of the "Save my card" checkbox |
This method returns a promise.
KR.setBrand()
Forces the detection of the payment method. The method takes as parameter the name of the payment method. The supported values are (not exhaustive):
- VISA
- VISA_DEBIT
- VISA_ELECTRON
- MASTERCARD
- MASTERCARD_DEBIT
- MAESTRO
- AMEX
- CB
- (...)
Warning: if you set a different value, it will be submitted unchanged to the payment gateway If the value is not supported by your store configuration, no transaction will be created.
To re-enable automatic detection, call KR.setBrand() without any parameters.
KR.validateForm()
This method checks locally if the form is valid. It returns a promise:
- then() is called when the form is valid. result will be set to null.
- catch() is called when the form is invalid. result contains the details of the error.
Example of a call:
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(); } );
Once you have intercepted the errors, you can trigger the KR.onError() event manually by calling result.doOnError();
.
Button personalization
The payment button is automatically added to your form using the following code:
<!-- payment form submit button --> <button class="kr-payment-button"></button>
<!-- payment form submit button --> <button class="kr-payment-button"></button>
There are numerous benefits to using our payment button:
- The labels are translated automatically.
- The amount is automatically formatted and updated.
- We handle the pending transition animation for you.
- The button automatically changes to read-only mode if necessary.
If you want to manage the button label yourself, all you need to do is add it as follows:
<button class="kr-payment-button">Custom label</button>
You can also insert a variable that represents the amount and currency. The JavaScript client will automatically replace them:
<button class="kr-payment-button">this will cost %amount-and-currency% !!</button>
Frequently Asked Questions
Here you will find the frequently asked questions about the JavaScript client.
How to correct CORS or "Unable to post message" errors upon payment?
First, you have to be developing from a web server The test page must be accessed with http:// and not with file://
If you use the ionic or cordova framework, you must explicitly declare the domain names that can be called by the JavaScript client. To do this, add the folowing in config.xml :
<allow-navigation href="https://api.lyra.com/static/js/krypton-client/V4.0" />
More information here .
How to configure the CSP (Content Security Policy)
If your website uses CSP (Content Security Policy), you must allow the JavaScript client to create its IFrames. To do this, you must add the following 3 instructions:
CSP directive | Values |
---|---|
connect-src | https://api.lyra.com |
frame-src | https://api.lyra.com |
script-src | https://api.lyra.com |
Example of adding your page head to the meta section:
<meta
http-equiv="Content-Security-Policy"
content="
connect-src https://api.lyra.com;
frame-src https://api.lyra.com;
script-src https://api.lyra.com;"
/>
(More information on the CSP here.)[https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP]
If you use an external fraud detection engine (such as monitor+, clearsale, etc.), you should also add:
CSP directive | Values |
---|---|
connect-src | https://secure.lyra.com |
frame-src | https://secure.lyra.com |
script-src | https://secure.lyra.com |
Advanced use
To see all the advanced use cases, go to the following articles:
DESCRIPTION | Article |
---|---|
Transmit the fields based on your needs | Use cases |
Adding custom form fields | Additional fields |
Performing a single payment | Start: single payment |
Handling embedded form errors | Error handling |
Handling new payment attempts (retry) | Handling retries |
Event and method reference of the JS client | JavaScript Client Reference |
Pre-configured themes and personalization with CSS | Themes |
Switch from redirected form to embedded form | Migrating the form with redirect |
Examples of integration
Depending on the JavaScript framework that you use on your merchant website, several examples of integration are available here
Framework | DESCRIPTION |
---|---|
Vue.js | example of integration for Vue.js |
React | example of integration for React |
React + NextJS | example of integration with React and NextJS |
Angular | example of integration for Angular and TypeScript |
Ionic | example of integration for Ionic |
require.js | example of integration with RequireJS |
Javacript | Generic library to be used in JavaScript frameworks |
C# | example of integration for C\# (.NET) |
python/flask | example in Python using the Flask framework |
php/symfony | example in python in PHP with symfony |