### Install Project Dependencies
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/test/README.md
Installs all necessary packages for the test project.
```bash
npm install
```
--------------------------------
### Install React Cardknox iFields
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/README.md
Install the library using npm. This command fetches and installs the necessary package for your React project.
```bash
npm install @cardknox/react-ifields
```
--------------------------------
### CommonJS Import Example
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/exports-reference.md
Provides an example of how to import components and constants using CommonJS syntax, assuming it's supported by the build environment.
```javascript
const IField = require('@cardknox/react-ifields');
const { CardknoxApplePay, CARD_TYPE } = require('@cardknox/react-ifields');
```
--------------------------------
### Start Development Server
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/test/README.md
Serves the test page on localhost for development.
```bash
npm start
```
--------------------------------
### Basic Apple Pay Checkout
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/configuration.md
This example shows a minimal Cardknox Apple Pay component setup. It focuses on essential properties like merchant identifier, button options, supported networks, country code, and currency code, along with callbacks for transaction info and payment processing.
```javascript
```
--------------------------------
### Full Apple Pay Checkout Example
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/configuration.md
This example demonstrates a complete Cardknox Apple Pay component with various properties for merchant identification, button styling, supported networks, country, and currency. It also includes callbacks for transaction info, payment authorization, and shipping details.
```javascript
```
--------------------------------
### Minimal Card Payment Form Setup
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/configuration.md
This snippet shows the basic setup for a Cardknox iField component for card payments. It requires the card type and account credentials, including the API key (xKey) and software identification.
```javascript
import IField, { CARD_TYPE } from '@cardknox/react-ifields';
```
--------------------------------
### Initialize IField with Account Data
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/types.md
Example of how to configure the IField component with merchant account details. Ensure all required fields are provided.
```javascript
const account = {
xKey: 'YOUR_IFIELDS_KEY',
xSoftwareName: 'MyPaymentApp',
xSoftwareVersion: '1.0.0'
};
```
--------------------------------
### Complete Import Example: With 3D Secure
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/exports-reference.md
Illustrates integrating 3D Secure functionality with the IField component, including enabling it, setting the environment, and handling results.
```javascript
import React from 'react';
import IField, { CARD_TYPE, THREEDS_ENVIRONMENT } from '@cardknox/react-ifields';
export default function SecurePaymentForm() {
const handleThreeDSResults = (
actionCode, xCavv, xEciFlag, xRefNum, xAuthenticateStatus, xSignatureVerification, xError
) => {
// Handle 3DS results
};
return (
);
}
```
--------------------------------
### Full IField Options Configuration
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/configuration.md
This example demonstrates a comprehensive set of options for the IField component, including formatting, input control, auto-submission, and styling.
```javascript
```
--------------------------------
### Full React iField Component Usage
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/ifield-component.md
This example demonstrates the complete integration of the IField component in a React application. It covers initialization, event handling for load, update, token, and error states, as well as methods for getting a token and clearing the field. Ensure you replace 'your-ifields-key' with your actual iField key.
```javascript
import React from 'react';
import IField, { CARD_TYPE } from '@cardknox/react-ifields';
export default class PaymentForm extends React.Component {
iFieldRef = React.createRef();
state = {
account: {
xKey: 'your-ifields-key',
xSoftwareName: 'MyApp',
xSoftwareVersion: '1.0.0'
},
isTokenValid: false,
loading: false
};
handleLoad = () => {
console.log('IField loaded');
};
handleUpdate = (data) => {
this.setState({ isTokenValid: data.isValid });
};
handleToken = (data) => {
if (data.result === 'error') {
console.error('Token error:', data.errorMessage);
} else {
console.log('Token received:', data.xToken);
// Send token to your server
}
};
handleError = (data) => {
console.error('IField error:', data.errorMessage);
};
handleGetToken = () => {
this.setState({ loading: true });
this.iFieldRef.current.getToken();
};
handleClear = () => {
this.iFieldRef.current.clearIfield();
};
render() {
return (
);
}
}
```
--------------------------------
### Get Initial Transaction Info
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/events-and-callbacks.md
Implement `onGetTransactionInfo` to provide the initial transaction amount and line items when the component initializes. This callback is required.
```javascript
const handleGetTransactionInfo = async () => {
const items = await fetchCartItems();
const subtotal = items.reduce((sum, item) => sum + item.price, 0);
const tax = subtotal * 0.08;
const total = subtotal + tax;
return {
total: {
label: 'Total Due',
amount: total.toFixed(2)
},
lineItems: [
...items.map(item => ({
label: item.name,
amount: item.price.toFixed(2)
})),
{
label: 'Tax',
amount: tax.toFixed(2)
}
]
};
};
```
--------------------------------
### Auto-submitting Token Request
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/configuration.md
This example shows how to enable automatic token requests upon valid data entry and handle the response via the onToken callback.
```javascript
{
if (data.result !== 'error') {
console.log('Token:', data.xToken);
}
}}
/>
```
--------------------------------
### Handle Token Data
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/types.md
Example of how to process the token data received from the iField. Useful for logging or sending to a backend.
```javascript
const handleToken = (tokenData) => {
console.log('Token:', tokenData.xToken);
console.log('Type:', tokenData.xTokenType);
console.log('Created:', tokenData.xTokenCreationTime);
};
```
--------------------------------
### IField onLoad Usage Pattern
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/events-and-callbacks.md
Example of how to use the onLoad callback to determine when the IField is ready for input. This is useful for enabling form submission or setting focus.
```javascript
import IField, { CARD_TYPE } from '@cardknox/react-ifields';
class CheckoutForm extends React.Component {
iFieldRef = React.createRef();
handleLoad = () => {
console.log('IField is ready for input');
// Can now safely call other methods like focusIfield()
}
render() {
return (
);
}
}
```
--------------------------------
### Complete Import Example: Single Component
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/exports-reference.md
Demonstrates importing and using the IField component with the CARD_TYPE constant in a React application.
```javascript
import React from 'react';
import IField, { CARD_TYPE } from '@cardknox/react-ifields';
export default function PaymentForm() {
return (
);
}
```
--------------------------------
### Configure ACH iField
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/configuration.md
Configure an ACH iField for bank account information. This example shows setting a placeholder and enabling logging.
```javascript
```
--------------------------------
### Complete Import Example: Multiple Types
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/exports-reference.md
Shows how to import and use IField with different payment types (CARD, CVV, ACH) dynamically based on user selection in a React component.
```javascript
import React from 'react';
import IField, { CARD_TYPE, CVV_TYPE, ACH_TYPE } from '@cardknox/react-ifields';
export default function PaymentOptions() {
const [type, setType] = React.useState(CARD_TYPE);
return (
<>
>
);
}
```
--------------------------------
### Get Shipping Methods
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/apple-pay-component.md
Implement this callback to return an array of available shipping method objects. Each object should include an identifier, label, detail, and amount.
```javascript
async onGetShippingMethods()
{
return [
{
identifier: 'standard',
label: 'Standard Shipping',
detail: 'Arrives in 5-7 business days',
amount: '10.00'
},
{
identifier: 'express',
label: 'Express Shipping',
detail: 'Arrives in 1-2 business days',
amount: '25.00'
}
];
}
```
--------------------------------
### Handle IField Token Response
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/events-and-callbacks.md
This example demonstrates how to handle the response from an iField tokenization process. It includes logic for both successful token retrieval and specific error conditions like timeouts.
```javascript
const handleToken = (data) => {
if (data.result === 'error') {
switch (data.errorMessage) {
case 'Transaction timed out.':
// Handle timeout
showError('Payment request timed out. Please try again.');
break;
default:
// Handle other errors
showError(`Payment error: ${data.errorMessage}`);
}
} else {
// Success
submitPayment(data.xToken, data.xTokenType);
}
};
```
--------------------------------
### Perform HTTP GET Request
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/utilities-and-services.md
Sends an HTTP GET request to an allowed domain, with options for fetch API and JSON parsing. Rejects if URL validation fails or the request fails.
```javascript
const httpService = new HttpService({ enableLogging: true });
try {
const data = await httpService.get('https://api.cardknox.com/status', {}, true);
console.log(data);
} catch (err) {
console.error('Request failed:', err);
}
```
--------------------------------
### HttpService Security Validations
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/utilities-and-services.md
Demonstrates various blocked requests due to invalid domains, path traversal, or unsupported protocols. These examples will throw errors when executed.
```javascript
const httpService = new HttpService();
// All of these will throw errors:
httpService.post('https://evil.com/steal'); // Invalid domain
httpService.post('https://api.cardknox.com/../../../etc/passwd'); // Path traversal
httpService.post('file:///etc/passwd'); // Invalid protocol
httpService.post('data:text/html,'); // Invalid protocol
```
--------------------------------
### IField onError and onToken Usage Pattern
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/events-and-callbacks.md
Example demonstrating how to use both onError and onToken callbacks for comprehensive error handling. onError can catch specific errors, while onToken handles both success and general errors.
```javascript
class PaymentForm extends React.Component {
handleError = (error) => {
// Display error to user
this.setState({
error: error.errorMessage,
loading: false
});
}
handleToken = (data) => {
if (data.result === 'error') {
// Already handled by onError, but can also handle here
} else {
this.submitPayment(data.xToken);
}
}
render() {
return (
);
}
}
```
--------------------------------
### IField onToken Usage Pattern
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/events-and-callbacks.md
Example of using the onToken callback to handle both successful token retrieval and errors. This pattern is common for processing payments or storing tokens.
```javascript
class PaymentProcessor extends React.Component {
iFieldRef = React.createRef();
handleToken = (data) => {
if (data.result === 'error') {
// Handle error
this.showError(`Token Error: ${data.errorMessage}`);
} else {
// Handle success
console.log('Token received:', data.xToken);
// Send token to your server
this.submitPayment(data.xToken);
}
}
handleGetToken = () => {
this.iFieldRef.current.getToken();
}
render() {
return (
<>
>
);
}
}
```
--------------------------------
### HttpService.get()
Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/utilities-and-services.md
Sends an HTTP GET request to a specified URL. It supports optional fetch API options and JSON response parsing, with built-in URL validation against allowed domains.
```APIDOC
## HttpService.get()
### Description
Sends an HTTP GET request to a specified URL. It supports optional fetch API options and JSON response parsing, with built-in URL validation against allowed domains.
### Method
GET
### Endpoint
[URL provided in the `url` parameter]
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
#### Request Body
- None
### Function Signature
```javascript
async get(url, options = {}, isJson = false)
```
### Parameters
- **url** (string) - Required - URL to request (must be to allowed domain: `api.cardknox.com`, `cdn.cardknox.com`)
- **options** (object) - Optional, defaults to `{}` - Fetch API options
- **isJson** (boolean) - Optional, defaults to `false` - Parse response as JSON
### Returns
Promise