### 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 ### Throws Rejects if URL validation fails or request fails (unless skipLogging: true) ### Example ```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); } ``` ``` -------------------------------- ### Using HttpService and Utilities in a Custom Component Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/utilities-and-services.md Example of integrating HttpService and utility functions like logDebug and roundToNumber within a custom React component for payment processing. Ensure HttpService is initialized and logging is enabled if desired. ```javascript import React from 'react'; import HttpService from '@cardknox/react-ifields/src/services/httpService'; import { logDebug, logError, roundToNumber } from '@cardknox/react-ifields/src/lib'; class CustomPaymentProcessor extends React.Component { constructor(props) { super(props); this.httpService = new HttpService({ enableLogging: true }); } processPayment = async (token) => { try { logDebug(true, 'Processing payment with token:', token); const amount = this.props.amount; const roundedAmount = roundToNumber(amount, 2); const response = await this.httpService.post( 'https://api.cardknox.com/charge', { xToken: token, xAmount: roundedAmount.toString() }, { isJson: true } ); logDebug(true, 'Payment response:', response); return response; } catch (err) { logError(true, 'Payment processing failed', err); throw err; } }; render() { return
Payment Processor
; } } export default CustomPaymentProcessor; ``` -------------------------------- ### Advanced Card Payment Form with 3DS Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/configuration.md This example configures an advanced Cardknox iField for card payments, enabling features like auto-formatting, input blocking, and placeholder text. It also includes 3D Secure (3DS) integration with environment and callback handling. ```javascript ``` -------------------------------- ### React iField onUpdate Callback Example Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/events-and-callbacks.md Handles updates from user interaction with the iField. Use this to manage validation state, detect card issuer, and react to specific events like input or blur. ```javascript handleUpdate = (data) => { // Update validation state this.setState({ isValid: data.isValid, cardIssuer: data.issuer }); // React to specific events switch (data.event) { case 'input': // User is typing console.log(`Card length: ${data.cardNumberLength}`); break; case 'issuerupdated': // Card issuer detected console.log(`Card type: ${data.issuer}`); // Update card logo/icon break; case 'blur': // Field lost focus - can validate if (!data.isValid && !data.isEmpty) { this.setState({ errorMessage: 'Invalid card number' }); } break; } } ``` ```javascript class PaymentForm extends React.Component { state = { isValid: false, cardIssuer: 'unknown', errorMessage: '' } handleUpdate = (data) => { // Update validation state this.setState({ isValid: data.isValid, cardIssuer: data.issuer }); // React to specific events switch (data.event) { case 'input': // User is typing console.log(`Card length: ${data.cardNumberLength}`); break; case 'issuerupdated': // Card issuer detected console.log(`Card type: ${data.issuer}`); // Update card logo/icon break; case 'blur': // Field lost focus - can validate if (!data.isValid && !data.isEmpty) { this.setState({ errorMessage: 'Invalid card number' }); } break; } } render() { return ( <>

Valid: {this.state.isValid ? 'Yes' : 'No'}

Card Type: {this.state.cardIssuer}

{this.state.errorMessage &&

{this.state.errorMessage}

} ); } } ``` -------------------------------- ### Get Transaction Information Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/apple-pay-component.md Implement this callback to return transaction details or null. It must return an object containing total and optional line items, or an error object. ```javascript async onGetTransactionInfo() { return { total: { label: string, amount: string, type?: 'final' | 'pending' }, lineItems?: [ { label: string, amount: string, type?: 'final' | 'pending', paymentTiming?: string, recurringPaymentStartDate?: string, recurringPaymentIntervalUnit?: string, recurringPaymentIntervalCount?: number, deferredPaymentDate?: string, automaticReloadPaymentThresholdAmount?: string } ], error?: object } } ``` ```javascript const handleGetTransactionInfo = async () => { return { total: { label: 'Total', amount: '99.99' }, lineItems: [ { label: 'Product', amount: '79.99' }, { label: 'Shipping', amount: '20.00' } ] }; }; ``` -------------------------------- ### Full React Cardknox Apple Pay Integration Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/apple-pay-component.md This snippet shows a complete implementation of the CardknoxApplePay component in React. It includes handlers for transaction details, shipping, payment authorization, and completion. Ensure React and necessary Cardknox libraries are installed. ```javascript import React from 'react'; import { CardknoxApplePay } from '@cardknox/react-ifields'; const iStatus = { success: 100 }; export default class ApplePayCheckout extends React.Component { state = { cart: [ { name: 'Product A', amount: '79.99' } ] }; handleGetTransactionInfo = async () => { return { total: { label: 'Cardknox Store', amount: '79.99' }, lineItems: this.state.cart.map(item => ({ label: item.name, amount: item.amount })) }; }; handleGetShippingMethods = async () => { return [ { identifier: 'standard', label: 'Standard (5-7 days)', amount: '0.00' }, { identifier: 'express', label: 'Express (2-3 days)', amount: '15.00' } ]; }; handleShippingContactSelected = async (contact) => { // Calculate shipping based on address const shippingAmount = '10.00'; const total = parseFloat('79.99') + parseFloat(shippingAmount); return { total: { label: 'Total', amount: total.toFixed(2) }, lineItems: [ { label: 'Product', amount: '79.99' }, { label: 'Shipping', amount: shippingAmount } ], shippingMethods: await this.handleGetShippingMethods() }; }; handleShippingMethodSelected = async (method) => { const shippingAmount = method.amount; const total = parseFloat('79.99') + parseFloat(shippingAmount); return { total: { label: 'Total', amount: total.toFixed(2) }, lineItems: [ { label: 'Product', amount: '79.99' }, { label: 'Shipping', amount: shippingAmount } ] }; }; handlePaymentMethodSelected = async (method) => { return { total: { label: 'Total', amount: '89.99' }, lineItems: [ { label: 'Product', amount: '79.99' }, { label: 'Shipping', amount: '10.00' } ] }; }; handleBeforeProcessPayment = async () => { // Validate inventory, etc. return iStatus.success; }; handlePaymentAuthorize = async (payment) => { const response = await fetch('/api/process-apple-pay', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payment) }); if (!response.ok) { throw new Error('Payment failed'); } return response.json(); }; handlePaymentComplete = (result) => { if (result.error) { console.error('Payment error:', result.error); } else { console.log('Payment successful:', result.response); } }; handleCancel = (event) => { console.log('Payment cancelled'); }; render() { const properties = { merchantIdentifier: 'merchant.com.example.store', buttonOptions: { buttonType: 'buy', buttonColor: 'black' }, countryCode: 'US', currencyCode: 'USD', supportedNetworks: ['visa', 'masterCard', 'amex'], supportedCountries: ['US', 'CA'], merchantCapabilities: ['supports3DS'] }; return ( ); } } ``` -------------------------------- ### Build for Production Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/test/README.md Compiles and minifies the project for production deployment. ```bash npm run build ``` -------------------------------- ### Initialize HttpService Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/utilities-and-services.md Creates an instance of HttpService, optionally enabling debug logging. ```javascript const httpService = new HttpService({ enableLogging: true }); ``` -------------------------------- ### Configuring Account Props for IField Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/react-cardknox-ifields/README.md Sets up the 'account' prop with iFields key and software details. This is required for component initialization. ```javascript export default class App extends React.Component { state = { account = { xKey: "{Your iFields key}", xSoftwareName: "{The name of your app}", xSoftwareVersion: "{Your app's version}" } } render() { return } } ``` -------------------------------- ### HttpService Constructor Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/utilities-and-services.md Initializes a new instance of the HttpService class, optionally enabling debug logging. ```APIDOC ## HttpService Constructor ### Description Initializes a new instance of the HttpService class, optionally enabling debug logging. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Constructor Signature ```javascript constructor(props) ``` ### Parameters - **props** (object) - Required - Configuration object - **props.enableLogging** (boolean) - Optional - Enable debug logging ### Returns HttpService instance ### Example ```javascript const httpService = new HttpService({ enableLogging: true }); ``` ``` -------------------------------- ### Run Proxy Server for Test Page Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/test/README.md Handles server-side requests for the test page during development. ```bash npm run proxy ``` -------------------------------- ### Project Directory Structure Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/README.md This snippet shows the directory structure of the react-cardknox-ifields project, outlining the different documentation files and their purposes. ```text output/ ├── README.md (this file) ├── ifield-component.md ├── apple-pay-component.md ├── types.md ├── configuration.md ├── events-and-callbacks.md ├── utilities-and-services.md └── exports-reference.md ``` -------------------------------- ### onGetTransactionInfo Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/events-and-callbacks.md Provides the initial transaction amount and line items during component initialization. It must return an object containing the total amount and optionally line items and an error object. ```APIDOC ## onGetTransactionInfo ### Description Provides the initial transaction amount and line items during component initialization. ### Callback Signature ```javascript async onGetTransactionInfo() ``` ### Must Return ```json { "total": { "label": "string", "amount": "string", "type": "final" | "pending" (optional) }, "lineItems": [ { "label": "string", "amount": "string", "type": "final" | "pending" (optional), "paymentTiming": "string" (optional), "recurringPaymentStartDate": "string" (optional), "recurringPaymentIntervalUnit": "string" (optional), "recurringPaymentIntervalCount": number (optional), "deferredPaymentDate": "string" (optional), "automaticReloadPaymentThresholdAmount": "string" (optional) } ] (optional), "error": object (optional) } ``` ### When Called During component initialization to determine initial payment amount. ### Example ```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) } ] }; }; ``` ``` -------------------------------- ### IField Minimal Configuration Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/README.md Sets up a basic IField component for card input. Requires a type and account details including API keys. ```javascript ``` -------------------------------- ### Get Token from IField Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/ifield-component.md Use a ref to retrieve a secure token for the data entered in the IField. The token is returned asynchronously via the onToken callback. A 60-second timeout is included. ```javascript const iFieldRef = React.createRef(); const handleGetToken = () => { iFieldRef.current.getToken(); }; const handleToken = (data) => { console.log('Token received:', data.xToken); }; ``` -------------------------------- ### Handle Payment Method Selection Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/events-and-callbacks.md Implement this callback to apply payment method-specific discounts or adjustments before proceeding. It must return a structured object including the total amount and optional line items. ```javascript const handlePaymentMethodSelected = async (method) => { // Could apply payment method-specific discounts const discount = method.network === 'amex' ? 0 : 0; const newTotal = (subtotal + tax + shipping - discount).toFixed(2); return { total: { label: 'Total', amount: newTotal }, lineItems: currentLineItems }; }; ``` -------------------------------- ### React iField onSubmit Callback Example Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/events-and-callbacks.md Handles form submission triggered by the Enter key in the iField when autoSubmit is enabled. Use this for quick payment forms or single-field payment collection. ```javascript handleSubmit = (e) => { e.preventDefault(); // Form was submitted (either by user or by iField) // Token should be processed in onToken callback console.log('Form submitted'); } ``` ```javascript handleSubmitClick = () => { console.log('User pressed Enter in iField'); } ``` ```javascript class QuickPayForm extends React.Component { formRef = React.createRef(); handleSubmit = (e) => { e.preventDefault(); // Form was submitted (either by user or by iField) // Token should be processed in onToken callback console.log('Form submitted'); } handleSubmitClick = () => { console.log('User pressed Enter in iField'); } render() { return (
{/* Form auto-submits when user presses Enter in iField */} ); } } ``` -------------------------------- ### render Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/apple-pay-component.md Renders the Apple Pay button, which, when clicked, initiates the Apple Pay payment flow. ```APIDOC ## render ### Description Returns a styled div element that functions as the Apple Pay button. Clicking this button initiates the Apple Pay payment session. ### Method Signature ```javascript render() ``` ### Returns - JSX.Element (styled div) ### CSS Class - `'apple-pay-button visible'` ``` -------------------------------- ### onGetShippingMethods Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/apple-pay-component.md Retrieves and returns an array of available shipping method objects. This is used to present shipping options to the user. ```APIDOC ## onGetShippingMethods ### Description Returns an array of available shipping method objects that will be presented to the user. ### Method ```javascript async onGetShippingMethods() ``` ### Returns An array of shipping method objects. ### Example ```javascript const handleGetShippingMethods = async () => { 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' } ]; }; ``` ``` -------------------------------- ### onBeforeProcessPayment Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/events-and-callbacks.md Called before the Apple Pay sheet is displayed. It must return `iStatus.success` (100) to proceed or throw an error to cancel the process. ```APIDOC ## onBeforeProcessPayment ### Description Called before the Apple Pay sheet is displayed. Allows for pre-payment validation. ### Callback Signature ```javascript async onBeforeProcessPayment() ``` ### Must Return `iStatus.success` (100) to proceed, or throw error to cancel. ### Example ```javascript const handleBeforeProcessPayment = async () => { // Validate inventory const isInStock = await checkInventory(); if (!isInStock) { throw new Error('Item out of stock'); } // Return success to proceed return 100; // iStatus.success }; ``` ``` -------------------------------- ### Handle Update Data Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/types.md Demonstrates how to react to user input and field state changes. Useful for real-time validation feedback or logging events. ```javascript const handleUpdate = (updateData) => { if (updateData.isValid) { console.log('Data is valid'); } switch (updateData.event) { case 'input': console.log('User typed'); break; case 'focus': console.log('Field focused'); break; case 'issuerupdated': console.log('Card issuer:', updateData.issuer); break; } }; ``` -------------------------------- ### Build React Cardknox iFields Component Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/test/README.md Builds the main react-cardknox-ifields component before running tests. ```bash cd ../react-cardknox-ifields npm install npm run build ``` -------------------------------- ### post() Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/utilities-and-services.md Sends an HTTP POST request to a specified URL with a given body and optional fetch API options. It is designed to handle requests to allowed domains and can serialize the request body as JSON. ```APIDOC ## POST /post ### Description Sends an HTTP POST request to a specified URL with a given body and optional fetch API options. It is designed to handle requests to allowed domains and can serialize the request body as JSON. ### Method POST ### Endpoint `post(url, body, options)` ### Parameters #### Path Parameters - **url** (string) - Required - URL to request (must be to allowed domain) - **body** (object) - Required - Request body to send - **options** (object) - Optional - Fetch API options - **isJson** (boolean) - Optional - Serialize body as JSON (vs form-urlencoded). Defaults to `false`. ### Returns Promise - A promise that resolves with the response from the request. ### Throws Rejects if URL validation fails or request fails. ### Request Example ```javascript const httpService = new HttpService({ enableLogging: true }); try { const response = await httpService.post( 'https://api.cardknox.com/applepay/validate', { merchantIdentifier: 'merchant.com.example' }, { isJson: true } ); console.log(response); } catch (err) { console.error('Request failed:', err); } ``` ``` -------------------------------- ### IField Full Configuration with Options Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/README.md Provides comprehensive configuration for the IField component, including input formatting, logging, styling, and 3D Secure settings. ```javascript ``` -------------------------------- ### Mixed Usage with Different Payment Methods Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/exports-reference.md Demonstrates how to conditionally render different payment input fields (Credit Card, Apple Pay, Bank Account) based on user selection. Requires importing various types and components. ```javascript import React from 'react'; import IField, { CARD_TYPE, CVV_TYPE, ACH_TYPE, THREEDS_ENVIRONMENT, CardknoxApplePay } from '@cardknox/react-ifields'; export default function CompleteCheckout() { const [paymentMethod, setPaymentMethod] = React.useState('card'); return (
{paymentMethod === 'card' && ( )} {paymentMethod === 'apple-pay' && ( )} {paymentMethod === 'ach' && ( )}
); } ``` -------------------------------- ### Render Method Source: https://github.com/cardknox/react-cardknox-ifields/blob/master/_autodocs/ifield-component.md Renders the Cardknox iField component as a single iframe element, loading the iField interface from the Cardknox CDN. ```APIDOC ## Render ### Description Returns a single `