
Example Library Code
Quick Find
Go straight to the section you need.
1.0 Gateway Integration →
2.0 New Transactions →
3.0 Management Requests →
4.0 AVS/CV2 Checking →
5.0 3-D Secure Authentication →
11 Receipts and Notifications →
17 Advanced Data →
17.7 Device Information Fields
19 Gateway Wallet →
26 Digital Wallet Transactions →
Appendix
A-1 Response Codes
A-1.1 Authorisation Response Codes
A-2 AVS / CV2 Check Response Codes
A-3 Secure Authentication Data
A-4 3-D Secure Enrolment/Authentication Only
A-9 Duplicate Transaction Checking
A-10 Capture Delay
A-13 Sample Signature Calculation
A-14 Transaction Life cycle
A-14.1 Authorise, Capture and Settlement
A-15.2 Mail Order/Telephone Order (MOTO)
A-15.3 Continuous Authority (CA)
A-16 Payment Tokenisation
A-16.1 PREAUTH, SALE, REFUND, VERIFY requests
A-16.3 CANCEL or CAPTURE requests
A-16.5 SALE or REFUND Referred Authorisation requests
A-18 PSD2 SCA Compliance
A-18.1 Obtaining Strong Customer Authentication
A-18.3 Exemptions to Strong Customer Authentication
A-19 Hosted Payment Page Options
A-20 Integration Libraries
A-20.1 Gateway Integration Library
A-20.2 Hosted Payment Page Library
A-20.3 Hosted Payment Fields Library
A-21 Example HTTP Requests
A-22 Example Integration Code
A-23 Example Library Code
A-23.1 Gateway Integration Library
A-23 Example Library Code
The follow section provides samples of how to integrate with the Gateway using our integration libraries as documented in section A-20.1.
A-23.1 Gateway Integration Library
The following example PHP code shows how to send a SALE transaction using the Gateway library:
- <?PHP
- require(‘gateway.php’);
- use \P3\SDK\Gateway;
- // Signature key entered on MMS. The demo account is fixed to this value,
- Gateway::$merchantSecret = ‘Circle4Take40Idea’;
- // Gateway URL
- Gateway::$hostedUrl = ‘https://gateway.swipen.com/hosted/’;
- if (!isset($_POST[‘responseCode’])) {
- // Send request to gateway
- $req = array(
- ‘merchantID’ => 100001,
- ‘action’ => ‘SALE’,
- ‘type’ => 1,
- ‘currencyCode’ => 826,
- ‘countryCode’ => 826,
- ‘amount’ => 1001,
- ‘orderRef’ => ‘Test purchase’,
- ‘redirectURL’ => ($_SERVER[‘HTTPS’] == ‘on’ ? ‘https’ : ‘http’) . ‘://’ . $_SERVER[‘HTTP_HOST’] . $_SERVER[‘REQUEST_URI’],
- );
- try {
- echo Gateway::hostedRequest($req);
- } catch (\Exception $e) {
- // You should exit gracefully
- die(‘Sorry, the request could not be sent: ‘ . $e);
- }
- } else {
- // Received response from gateway
- try {
- Gateway::verifyResponse($_POST);
- } catch(\Exception $e) {
- // You should exit gracefully
- die(‘Sorry, the request could not be sent: ‘ . $e);
- }
- // Check the response code
- if ($_POST[‘responseCode’] === 0) {
- echo “<p>Thank you for your payment.</p>”;
- } else {
- echo “<p>Failed to take payment: ” . htmlentities($_POST[‘responseMessage’]) . “</p>”;
- }
- }
- ?>
A-23.1.2 Direct Sale Transaction (with 3-D Secure)
The following example PHP code shows how to send a SALE transaction with support for 3-D Secure using the Gateway library:
- 1.<?PHP
2.
3.require(‘gateway.php’);
4.
5.use \P3\SDK\Gateway;
6.
7.// Signature key entered on MMS. The demo account is fixed to this value,
8.Gateway::$merchantSecret = ‘Circle4Take40Idea’;
9.
10. // Gateway URL
11. Gateway::$directUrl = ‘https://gateway.example.com/direct/’;
12.
13. // Setup PHP session as use it to store data between 3DS steps
14. if (isset($_GET[‘sid’])) {
15. session_id($_GET[‘sid’]);
16. }
17.
18. session_start();
19.
20. // Compose current page URL (removing any sid and acs parameters)
21. $pageUrl = ((isset($_SERVER[‘HTTPS’]) && $_SERVER[‘HTTPS’] == ‘on’) ? ‘https://’ : ‘http://’)
22. . $_SERVER[‘SERVER_NAME’] . ($_SERVER[‘SERVER_PORT’] != ’80’ ? ‘:’ . $_SERVER[‘SERVER_PORT’] : ”)
23. . preg_replace(‘/(sid=[^&]+&?)|(acs=1&?)/’, ”, $_SERVER[‘REQUEST_URI’]);
24.
25. // Add back the correct sid parameter (used as session cookie may not be passed when the page is redirected fro
m an IFRAME)
26. $pageUrl .= (strpos($pageUrl, ‘?’) === false ? ‘?’ : ‘&’) . ‘sid=’ . urlencode(session_id());
27.
28.
29. // If ACS response into the IFRAME then redirect back to parent window
30. if (!empty($_GET[‘acs’])) {
31. echo silentPost($pageUrl, array(‘threeDSResponse’ => $_POST), ‘_parent’);
32. exit();
33. }
34.
35. if (!isset($_POST[‘threeDSResponse’])) {
36. // Initial request
37.
38. // Gather browser info – can be done at any time prior to the checkout
39. if (!isset($_POST[‘browserInfo’])) {
40. echo Gateway::collectBrowserInfo();
41. exit();
42. }
43.
44. // Direct Request
45. $req = array(
46. ‘merchantID’ => 100001,
47. ‘action’ => ‘SALE’,
48. ‘type’ => 1,
49. ‘currencyCode’ => 826,
50. ‘countryCode’ => 826,
51. ‘amount’ => 1001,
52. ‘cardNumber’ => ‘4012001037141112’,
53. ‘cardExpiryMonth’ => 12,
54. ‘cardExpiryYear’ => 15,
55. ‘cardCVV’ => ‘083’,
56. ‘customerName’ => ‘Test Customer’,
57. ‘customerEmail’ => ‘test@testcustomer.com’,
58. ‘customerAddress’ => ’16 Test Street’,
59. ‘customerPostCode’ => ‘TE15 5ST’,
60. ‘orderRef’ => ‘Test purchase’,
61.
62.
63. // The following fields are mandatory for 3DS v2
64. ‘remoteAddress’ => $_SERVER[‘REMOTE_ADDR’],
65. ‘threeDSRedirectURL’ => $pageUrl . ‘&acs=1’,
66.
67. // The following field allows options to be passed for 3DS v2
68. // and the values here are for demonstration purposes only
69. ‘threeDSOptions’ => array(
70. ‘paymentAccountAge’ => ‘20190601’,
71. ‘paymentAccountAgeIndicator’ => ’05’,
72. ),
73. );
74.
75. // Add the browser info as it is mandatory for 3DS v2
76. $req += $_POST[‘browserInfo’];
77.
78. } else {
79. // 3DS continuation request
80. $req = array(
81. // The following field are only required for tbe benefit of the SDK
82. ‘merchantID’ => 100001,
83. ‘action’ => ‘SALE’,
84.
85. // The following field must be passed to continue the 3DS request
86. ‘threeDSRef’ => $_SESSION[‘threeDSRef’],
87. ‘threeDSResponse’ => $_POST[‘threeDSResponse’],
88. );
89.
90. }
91.
92.
93. try {
94. $res = Gateway::directRequest($req);
95. } catch (\Exception $e) {
96. // You should exit gracefully
97. die(‘Sorry, the request could not be sent: ‘ . $e);
98. }
99.
100.// Check the response code
101.if ($res[‘responseCode’] === Gateway::RC_3DS_AUTHENTICATION_REQUIRED) {
102. // Send request to the ACS server displaying response in an IFRAME
103.
104. // Render an IFRAME to show the ACS challenge (hidden for fingerprint method)
105. $style = (isset($res[‘threeDSRequest’][‘threeDSMethodData’]) ? ‘display: none;’ : ”);
106. echo “<iframe name=\”threeds_acs\” style=\”height:420px; width:420px; {$style}\”></iframe>\n”;
107.
108. // Silently POST the 3DS request to the ACS in the IFRAME
109. echo silentPost($res[‘threeDSURL’], $res[‘threeDSRequest’], ‘threeds_acs’);
110.
111. // Remember the threeDSRef as need it when the ACS responds
112. $_SESSION[‘threeDSRef’] = $res[‘threeDSRef’];
113.
114.} else if ($res[‘responseCode’] === Gateway::RC_SUCCESS) {
115. echo “<p>Thank you for your payment.</p>”;
116.} else {
117. echo “<p>Failed to take payment: ” . htmlentities($res[‘responseMessage’]) . “</p>”;
118.}
119.
120.
121.
122.// Render HTML to silently POST data to URL in target brower window
123.function silentPost($url = ‘?’, array $post = null, $target = ‘_self’) {
124.
125. $url = htmlentities($url);
126. $target = htmlentities($target);
127. $fields = ”;
128.
129. if ($post) {
130. foreach ($post as $name => $value) {
131. $fields .= Gateway::fieldToHtml($name, $value);
132. }
133. }
134.
135. $ret = “
136. <form id=\”silentPost\” action=\”{$url}\” method=\”post\” target=\”{$target}\”>
137. {$fields}
138. <noscript><input type=\”submit\” value=\”Continue\”></noscript
139. </form>
140. <script>
141. window.setTimeout(‘document.forms.silentPost.submit()’, 0);
142. </script>
143. “;
144.
145. return $ret;
146.}
147.
148. ?>
A-23.2 Hosted Payment Page Library
A-23.2.1 Hosted Sale Transaction
The following example code shows how to prepare a payment form to open the Hosted Payment Page in a lightbox style overlay on your website using the Hosted Payment Page library:
- <html>
- <head>
- <!– Load the Hosted Payment Page library –>
- <script src=“https://gateway.swipen.com/sdk/web/v1/js/hostedforms.min.js”></script>
- </head>
- <body>
- <!–
- Hosted Payment <form> as created by the Gateway Integration Library hostedRequest() method
- with addition of ‘data-hostedforms-modal’ attribute to signify a modal form is required.
- –>
- <form name=“payment-form” method=“post” action=“https://gateway.swipen.com/hosted/” data-hostedforms-modal>
- <input type=“hidden” name=“merchantID” value=“100001” />
- <input type=“hidden” name=“action” value=“SALE” />
- <input type=“hidden” name=“type” value=“1” />
- <input type=“hidden” name=“currencyCode” value=“826” />
- <input type=“hidden” name=“countryCode” value=“826” />
- <input type=“hidden” name=“amount” value=“1001” />
- <input type=“hidden” name=“orderRef” value=“Test purchase” />
- <input type=“hidden” name=“redirectURL” value=“https://www.merchant.com/payment/” />
- <input type=“hidden” name=“signature” value=“07599ef4cdb2e26cb2bf34a9c65190a7ce82494bc1df144c3bb0d20ee2655d8278dc663b2b0421ef12b8f081e821151bb4c644277c5d65b5523a96539b53b5aa” />
- <input type=“submit” value=“Pay Now”>
- </form>
- <script>
- // Create a new Hosted Form object which will cause the above <form> to load into a modal
- // overlay over this page.
- var form = new window.hostedForms.classes.Form(document.forms[0]);
- </script>
- </body>
- </html>
A-23.2.2 Hosted Sale Transaction (jQuery)
The following example code shows how to prepare a payment form to open the Hosted Payment Page in a lightbox style overlay on your website using the Hosted Payment Page and jQuery libraries:
1.<html>
- <head>
- <!– Load the jQuery library –>
- <script src=“https://code.jquery.com/jquery-3.4.1.min.js” integrity=“sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=” crossorigin=“anonymous”></script>
- <!– Load the Hosted Payment Page library –>
- <script src=“https://gateway.swipen.com/sdk/web/v1/js/hostedforms.min.js”></script>
- </head>
- <body>
- <!–
- Hosted Payment <form> as created by the Gateway Integration Library hostedRequest() method
- with addition of ‘data-hostedforms-modal’ attribute to signify a modal form is required.
- –>
- <form name=“payment-form” method=“post” action=“https://gateway.swipen.com/hosted/” data-hostedforms-modal>
- <input type=“hidden” name=“merchantID” value=“100001” />
- <input type=“hidden” name=“action” value=“SALE” />
- <input type=“hidden” name=“type” value=“1” />
- <input type=“hidden” name=“currencyCode” value=“826” />
- <input type=“hidden” name=“countryCode” value=“826” />
- <input type=“hidden” name=“amount” value=“1001” />
- <input type=“hidden” name=“orderRef” value=“Test purchase” />
- <input type=“hidden” name=“redirectURL” value=“https://www.merchant.com/payment/” />
- <input type=“hidden” name=“signature” value=“07599ef4cdb2e26cb2bf34a9c65190a7ce82494bc1df144c3bb0d20ee2655d8278dc663b2b0421ef12b8f081e821151bb4c644277c5d65b5523a96539b53b5aa” />
- <input type=“submit” value=“Pay Now”>
- </form>
- <script>
- // Create a new Hosted Form object which will cause the above <form> to load into a modal
- // overlay over this page.
- var form = $(document.forms[0]).hostedForm();
- </script>
- </body>
- </html>
A-23.2.3 Hosted Sale Transaction #2
The following example code shows how to create a payment form to open the Hosted Payment Page in a lightbox style overlay on your website using the Hosted Payment Page library:
- <html>
- <head>
- <!– Load the Hosted Payment Page library –>
- <script src=“https://gateway.swipen.com/sdk/web/v1/js/hostedforms.min.js”></script>
- </head>
- <body>
- <!— Pay button placeholder –>
- <div id=“paynow”></div>
- <script>
- // Create a new Hosted Form object which will render a payment button which will load
- // the Hosted Payment Pageo load into a modal overlay over this page.
- // The request can be provided from your server.
- var req = {
- merchantID: ‘100001’,
- action: ‘SALE’,
- type: ‘1’,
- currencyCode: ‘826’,
- countryCode: ‘826’,
- amount: ‘1001’,
- orderRef: ‘Test purchase’,
- redirectURL: ‘https://www.merchant.com/payment/’,
- signature: ‘07599ef4cdb2e26cb2bf34a9c65190a7ce82494bc1df144c3bb0d20ee2655d8278dc663b2b0421ef12b8f081e821151bb4c644277c5d65b5523a96539b53b5aa’,
- };
- var data = {
- id: ‘my-payment-form’,
- url: ‘https://gateway.swipen.com/hosted/modal/’,
- modal: true,
- data: req,
- submit: {
- type: ‘button’,
- label: ‘Pay <i>Now</i>‘
- }
- };
- var form = new window.hostedForms.classes.Form(‘paynow’, data);
- </script>
- </body>
- </html>
A-23.2.4 Hosted Sale Transaction #2 (jQuery)
The following example code shows how to create a payment form to open the Hosted Payment Page in a lightbox style overlay on your website using the Hosted Payment Page and jQuery libraries:
- <html>
- <head>
- <!– Load the jQuery library –>
- <script src=“https://code.jquery.com/jquery-3.4.1.min.js” integrity=“sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=” crossorigin=“anonymous”></script>
- <!– Load the Hosted Payment Page library –>
- <script src=“https://gateway.swipen.com/sdk/web/v1/js/hostedforms.min.js”></script>
- </head>
- <body>
- <!— Pay button placeholder –>
- <div id=“paynow”></div>
- <script>
- // Create a new Hosted Form object which will render a payment button which will load
- // the Hosted Payment Pageo load into a modal overlay over this page.
- // The request can be provided from your server.
- var req = {
- merchantID: ‘100001’,
- action: ‘SALE’,
- type: ‘1’,
- currencyCode: ‘826’,
- countryCode: ‘826’,
- amount: ‘1001’,
- orderRef: ‘Test purchase’,
- redirectURL: ‘https://www.merchant.com/payment/’,
- signature: ‘07599ef4cdb2e26cb2bf34a9c65190a7ce82494bc1df144c3bb0d20ee2655d8278dc663b2b0421ef12b8f081e821151bb4c644277c5d65b5523a96539b53b5aa’,
- };
- var data = {
- id: ‘my-payment-form’,
- url: ‘https://gateway.swipen.com/hosted/modal/’,
- modal: true,
- data: req,
- submit: {
- type: ‘button’,
- label: ‘Pay <i>Now</i>‘
- }
- };
- var form = $(‘#paynow’).hostedForm(data);
- </script>
- </body>
43. </html>
A-23.3 Hosted Payment Fields Library
The following example code shows how to create and manage Hosted Payment Fields using the Hosted Payment Field library.
The example shows how to style fields using an inline stylesheet and how to listen and react to the field’s events.
The example also shows how to set up the payment form both automatically and manually and integrate with the jQuery validator plugin. You should choose the set-up method best suited for your needs and whatever validation plugin or functions you are familiar with.
Note: The example code demonstrates including the static transaction information, such as the merchantID and amount, in hidden form fields and POSTing the form directly to the Gateway’s Direct Integration using partial message signing. We would however recommend that you capture just the information you require and then POST this data to your own website where you can use it to build a new fully signed request to send to the Gateway’s Direct Integration as a server-to-server request.
- <html>
- <head>
- <!– Load the jQuery library –>
- <script src=“https://code.jquery.com/jquery-3.4.1.min.js” integrity=“sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=” crossorigin=“anonymous”></script>
- <!– Load the jQuery Validator plugin –>
- <script src=“https://cdn.jsdelivr.net/npm/jquery-validation@1.19.1/dist/jquery.validate.min.js”></script>
- <!– Load the Hosted Payment Field library –>
- <script src=“https://gateway.swipen.com/sdk/web/v1/js/hostedfields.min.js”></script>
- <!– General styles –>
- <style>
- body {
- font-size: 14px;
- }
- .form-group {
- margin: 4px 0 15px 0;
- }
- .form-group LABEL {
- display: inline-block;
- max-width: 100%;
- margin-bottom: 5px;
- font-weight: bold;
- }
- .form-control {
- display: block;
- box-sizing: border-box;
- height: 34px;
- width: 400px;
- padding: 6px 12px;
- font-size: 14px;
- color: #555;
- background-color: #fff;
- background-image: none;
- border: 1px solid #ccc;
- border-radius: 4px;
- -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
- box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
- -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
- -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
- transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
- }
- .form-control.hf-focus {
- border-color: #66afe9;
- outline: 0;
- -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102,175,233,.6);
- box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102,175,233,.6);
- }
- .has-error .form-control.hf-focus {
- border-color: #843534;
- -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 6px #ce8483;
- box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 6px #ce8483;
- }
- </style>
- <!– Hosted Field internal styles –>
- <style class=“hostedfield”>
- /* Grey out when disabled */
- .hostedfield:disabled {
- cursor: not-allowed;
- background-color: #eee;
- opacity: 1;
- }
- /* Change border and text to green when valid */
- .form-control:valid,
- .hostedfield:valid {
- border-color: #28a745 !important;
- color: #28a745 !important;
- }
- /* Change border and text to red when invalid */
- .form-control:invalid,
- .hostedfield:invalid {
- border-color: #a94442 !important;
- color: #a94442 !important;
- }
- /* Change text to light grey when readonly */
- .form-control:readonly,
- .hostedfield:readonly {
- color: lightgrey !important;
- }
- /* Emulate webkit auto fill style */
- .form-control.hf-autofill,
- .hostedfield.hf-autofill {
- background-color: rgb(250, 255, 189) !important;
- background-image: none !important;
- color: rgb(0, 0, 0) !important;
- }
- /* Add light blue placeholder */
- .form-control::placeholder,
- .hostedfield::placeholder {
- color: lightblue;
- }
- /* Show hovering over the control */
- .form-control:hover,
- .hostedfield:hover {
- font-style: italic;
- }
- /* Style by id (hosted field will have ‘-hostedfield’ appended to the id) */
- #form-card-number, #form-card-number-hostedfield {
- color: darkcyan;
- }
- </style>
- <!– Hosted Field card-number internal styles –>
- <style class=“card-number”>
- .hostedfield::placeholder {
- color: orange;
- }
- </style>
- </head>
- <body>
- <!– tokenise payment data and send directly to the Gateway –>
- <form id=“form” method=“POST” novalidate=“novalidate” lang=“en”
- action=“https://gateway.swipen.com/direct/”
- data-hostedform-tokenize=‘{“#form-customer-name”: “customerName”}’>
- <input type=“hidden” name=“merchantID” value=“100001”>
- <input type=“hidden” name=“action” value=“SALE”>
- <input type=“hidden” name=“type” value=“1”>
- <input type=“hidden” name=“countryCode” value=“826”>
- <input type=“hidden” name=“currencyCode” value=“826”>
- <input type=“hidden” name=“amount” value=“1001”>
- <input type=“hidden” name=“orderRef” value=“Test purchase”>
- <input type=“hidden” name=“transactionUnique” value=“1234”>
- <input type=“hidden” name=“redirectURL” value=“https://www.merchant.com/payment/”>
- <input type=“hidden” name=“signature” value=“5a0dd6fed71ef68bb3f20175b6a04bbd9d1c904d32ae3f160bd3b8f55740207e5d1e8de5e7e9960b136407e7454b82e428b8378003aa0146df3efa91a3e61b17|merchantID,action,type,countryCode,currencyCode,amount,orderRef,transactionUnique,redirectURL”>
- <input type=“hidden” name=“paymentToken” value=“”>
- <div class=“form-group”>
- <label for=“form-customer-name”>Name on card:</label>
- <input id=“form-customer-name” type=“text” name=“paymentToken[customerName]” autocomplete=“cc-name” class=“form-control form-control-native hostedfield-tokenise” placeholder=“Firstname Surname” required>
- </div>
- <div class=“form-group”>
- <label for=“form-card-number”>Card Number:</label>
- <input id=“form-card-number” type=“hostedfield:cardNumber” name=“card-number” autocomplete=“cc-number” class=“form-control form-control-hosted” style=“background: #f2f8fb;” placeholder=“**** **** **** ****” required>
- </div>
- <div class=“form-group”>
- <label for=“form-card-expiry-date”>Card Expiry Date:</label>
- <input id=“form-card-expiry-date” type=“hostedfield:cardExpiryDate” name=“card-expiry-date” autocomplete=“cc-exp” class=“form-control form-control-hosted” required>
- </div>
- <div class=“form-group”>
- <label for=“form-card-start-date”>Card Issue Date:</label>
- <input id=“form-card-start-date” type=“hostedfield:cardStartDate” name=“card-start-date” autocomplete=“cc-iss” class=“form-control form-control-hosted” data-hostedfield=‘{“dropdown”:true}’ data-hostedfield-format=“N – m | y” data-hostedfield-min-date=“-40” data-hostedfeld-max-date=“0”>
- </div>
- <div class=“form-group”>
- <label for=“form-card-cvv”>CVV:</label>
- <input id=“form-card-cvv” type=“hostedfield:cardCVV” name=“card-cvv” autocomplete=“cc-csc” class=“form-control form-control-hosted” required>
- </div>
- <button id=“form-submit” type=“submit”>Pay <span>▷</span></button>
- </form>
- <script>
- // This example demonstrates both automatic and manual form setup
- var automatic_setup = true;
- $(document).ready(function () {
- var $form = $(‘#form’);
- // Listen for events on the form to see those sent from the Hosted Payment Fields
- // (For demonstration purposes only)
- $form.on(events);
- if (automatic_setup) {
- ///////////////////////////////////////////////////////////////
- // FORM AUTOMATIC SETUP
- ///////////////////////////////////////////////////////////////
- var opts = {
- // Auto setup the form creating all hosted fields (default)
- autoSetup: true,
- // Auto validate, tokenise and submit the form (default)
- autoSubmit: true,
- // Optional field configuration (by type)
- fields: {
- any: {
- nativeEvents: true,
- },
- cardNumber: {
- selector: $(‘#form-card-number’),
- style: ‘text-decoration: green wavy underline;’,
- stylesheet: $(‘style.hostedfields, style.card-number’)
- }
- }
- };
- try {
- // Create form, automatically creating all child Hosted Payment Fields
- $form.hostedForm(opts);
- } catch(e) {
- showError(‘Failed to create hosted form: ‘ + e);
- throw e; // Can’t continue with this script
- }
- // Listen for some events from the form thrown by the auto methods
- $form.on({
- // Let jQuery Validator check the form on submission
- ‘hostedform:presubmit’: function (event) {
- console.log(‘Form submitting’);
- return $form.valid();
- },
- // Show form is valid
- ‘hostedform:valid’: function (event) {
- console.log(‘Form valid’);
- return true;
- },
- // Show any validation errors
- ‘hostedform:invalid’: function (event, details) {
- console.log(‘Form invalid’);
- showFieldErrors(details.invalid);
- return true;
- },
- // Show general error
- ‘hostedform:error’: function (event, details) {
- showError(details.message);
- return true;
- }
- });
- // Use jQuery validator to validate the form
- $form.validate();
- // End of form automatic setup
- } else {
- ///////////////////////////////////////////////////////////////
- // FORM MANUAL SETUP
- ///////////////////////////////////////////////////////////////
- try {
- // Create the card number field with custom options
- $(‘#form-card-number’).hostedField({
- nativeEvents: true,
- style: ‘text-decoration: green wavy underline;’,
- stylesheet: $(‘style.hostedfields, style.card-number’)
- });
- // Create the remaining hosted fields
- $(‘.form-control-hosted:input’, $form).hostedField({nativeEvents: true});
- } catch (e) {
- showError(‘Failed to create hosted fields: ‘ + e);
- throw e; // Can’t continue with this script
- }
- $form.validate({
- // Get the hosted form widget for the submitted form (Form1 only)
- submitHandler: function () {
- try {
- console.log(‘getPaymentToken’);
- // Check we have some enabled fields to submit
- if ($($form[0].elements).filter(‘:enabled:not([type=“hidden”])’).length === 0) {
- showError(‘You must enable some fields’);
- return false;
- }
- var hostedform = $form.hostedForm(‘instance’);
- var also = {
- customerName: $(‘#form-customer-name’).val()
- };
- hostedform.getPaymentDetails(also, true).then(
- // Success validating the form and requesting a payment token
- function (details) {
- if (details.success) {
- $form[0].elements[‘paymentToken’].value = details.paymentToken;
- $form[0].submit();
- } else if (details.invalid) {
- $form.valid();
- showFieldErrors(details.invalid);
- } else {
- showError(‘There was a problem fetching the payment token. Please seek assistance.’);
- }
- },
- // Failure either validating the form or requesting the payment details
- function (e) {
- showError(‘There was a problem fetching the payment token. Please seek assistance.’);
- }
- );
- } catch (e) {
- showError(‘There was a problem fetching the payment token. Please seek assistance.’);
- }
- }
- });
- // End of form manual setup
- }
- // Hide errors once all fields are valid
- $(‘#form :input’).on(‘valid’, function () {
- if ($(this.form).find(‘:invalid’).length === 0) {
- hideError($(this.form));
- }
- })
- // Listen for some events on the none Hosted Fields
- $(‘.form-control-native’).on(‘invalid’, bsMarkInvalid);
- $(‘.form-control-native’).on(‘valid’, bsMarkValid);
- // Check we can see the Hosted Fields via their new class
- // (For demonstration purposes only)
- console.log($(‘.form-control-hosted.hostedfield-element’));
- // Check we can see the Hosted Fields via the psuedo element
- // (For demonstration purposes only)
- console.log($(‘.form-control:hostedfield’));
- });
- ///////////////////////////////////////////////////////////////////
- // Supporting functions
- ///////////////////////////////////////////////////////////////////
- // Display events that are passed from hosted field
- var events = {
- ‘hostedfield:create.example’ : showEvent,
- ‘hostedfield:destroy.example’ : showEvent,
- ‘hostedfield:ready.example’ : showEvent,
- ‘hostedfield:style.example’ : showEvent,
- ‘hostedfield:placeholder.example’ : showEvent,
- ‘hostedfield:invalid.example invalid.example’ : showEvent,
- ‘hostedfield:userinvalid.example userinvalid.example’ : showEvent,
- ‘hostedfield:valid.example valid.example’ : showEvent,
- ‘hostedfield:uservalid.example uservalid.example’ : showEvent,
- ‘hostedfield:disabled.example disabled.example’ : showEvent,
- ‘hostedfield:enabled.example enabled.example’ : showEvent,
- ‘hostedfield:required.example required.example’ : showEvent,
- ‘hostedfield:optional.example optional.example’ : showEvent,
- ‘hostedfield:readonly.example readonly.example’ : showEvent,
- ‘hostedfield:readwrite.example readwrite.example’ : showEvent,
- ‘hostedfield:focus.example focus.example’ : showEvent,
- ‘hostedfield:blur.example blur.example’ : showEvent,
- ‘hostedfield:mouseenter.example mouseenter.example’ : showEvent,
- ‘hostedfield:mouseleave.example mouseleave.example’ : showEvent,
- ‘hostedfield:mouseover.example mouseover.example’ : showEvent,
- ‘hostedfield:mouseout.example mouseout.example’ : showEvent,
- ‘hostedfield:mousemove.example mousemove.example’ : showEvent,
- ‘hostedfield:keydown.example keydown.example’ : showEvent,
- ‘hostedfield:keypress.example keypress.example’ : showEvent,
- ‘hostedfield:keyup.example keyup.example’ : showEvent,
- ‘hostedfield:change.example change.example’ : showEvent,
- ‘hostedfield:input.example input.example’ : showEvent,
- ‘hostedfield:invalid.example invalid.example’ : bsMarkInvalid,
- ‘hostedfield:valid.example valid.example’ : bsMarkValid,
- ‘hostedfield:valid.example valid.example’ : hideError,
- };
- function isInvalid(element) {
- return !element[0].checkValidity();
- }
- function showError(msg) {
- $(‘#error-info’).html(msg).show();
- }
- function hideError($form, msg) {
- $(‘#error-info’, $form).hide();
- }
- function showFieldErrors(errors) {
- var msg = ‘<h5>Error</h5><p>The following fields are invalid:</p><ul>’;
- for (var p in errors) {
- msg += ‘<li><b>‘ + p + ‘:</b> ‘ + errors[p] + ‘</li>‘;
- }
- msg += ‘</ul>‘
- showError(msg);
- }
- function bsMarkInvalid(e) {
- var element = (e instanceof $.Event ? this : e);
- $(element).closest(‘.form-group’).addClass(‘has-error’);
- }
- function bsMarkValid(e) {
- var element = (e instanceof $.Event ? this : e);
- $(element).closest(‘.form-group’).removeClass(‘has-error’);
- }
- function showEvent(event) {
- console.log(event);
- console.log(‘Field ‘ + event.type + ‘ event: ‘, this, arguments);
- }
- jQuery.validator.setDefaults({
- ignore: [],
- rules: {
- ‘customer-name’: {
- checkValidity: true,
- required: false
- },
- ‘card-details’: {
- checkValidity: true,
- required: false
- },
- ‘card-number’: {
- checkValidity: true,
- required: false
- },
- ‘card-expiry-date’: {
- checkValidity: true,
- required: false
- },
- ‘card-start-date’: {
- checkValidity: true,
- required: false
- },
- ‘card-issue-number’: {
- checkValidity: true,
- required: false
- },
- ‘card-cvv’: {
- checkValidity: true,
- required: false
- }
- },
- keyup: null, // Don\’t validate on keyup
- showErrors: function (errorMap, errorList) {
- if (errorList && errorList.length) {
- var errors = {};
- for (var i = 0, max_i = errorList.length; i < max_i; i++ ) {
- var label = $(‘label[for=“‘ + errorList[i].element.id + ‘”]:not(“.error”)’).text();
- errors[label] = errorList[i].message;
- }
- showFieldErrors(errors);
- }
- this.defaultShowErrors(errorMap, errorList);
- },
- highlight: bsMarkInvalid,
- unhighlight: bsMarkValid,
- errorPlacement: function (error, element) {
- $(element).closest(‘.form-control:not(“.hostedfield-element”)’).after(error);
- }
- });
- $.validator.addMethod(‘checkValidity’,
- function (value, element, params, message) {
- element.checkValidity();
- var valid = (element.validationMessage === ”);
- $(element).attr(‘aria-invalid’, !valid);
- return valid;
- },
- function (params, element) {
- return element.validationMessage;
- }
- );
- </script>
- </body>
483.</html>