{"templateId":"markdown","sharedDataIds":{"sidebar":"sidebar-guides/sidebars.yaml"},"props":{"metadata":{"markdoc":{"tagList":["sub-heading"]},"type":"markdown"},"seo":{"title":"Data validation","description":"Transform your commerce with PXP's unified platform—seamless payments, real-time insights, and global growth in one powerful integration.","lang":"en-UK","siteUrl":"https://developer.pxp.io","llmstxt":{"hide":false,"sections":[{"title":"Table of contents","includeFiles":["**/*"],"excludeFiles":[]}],"excludeFiles":[]}},"dynamicMarkdocComponents":[],"compilationErrors":[],"ast":{"$$mdtype":"Tag","name":"article","attributes":{},"children":[{"$$mdtype":"Tag","name":"Heading","attributes":{"level":1,"id":"data-validation","__idx":0},"children":["Data validation"]},{"$$mdtype":"Tag","name":"SubHeading","attributes":{},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Learn about built-in validation and implement additional scenarios for Apple Pay web."]}]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"overview","__idx":1},"children":["Overview"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The Apple Pay component includes comprehensive validation to ensure data integrity and compliance with Apple's requirements. All built-in validation is performed before creating payment requests and during the Apple Pay flow. If it fails, the SDK will throw an ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["ApplePayValidationException"]}," with detailed error information."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["You can also easily build custom validation, depending on your business needs."]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"built-in-validation","__idx":2},"children":["Built-in validation"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["By default, the Apple Pay component validates that:"]},{"$$mdtype":"Tag","name":"ul","attributes":{},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Fields marked as required are provided."]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Payment request data meets Apple Pay specifications."]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Currency codes, country codes, and amounts are formatted properly."]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Merchant capabilities and supported networks are valid."]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Contact fields and shipping methods are properly configured."]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Browser and device compatibility requirements are met."]}]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"error-codes","__idx":3},"children":["Error codes"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The Apple Pay component returns structured error codes for different validation failures:"]},{"$$mdtype":"Tag","name":"div","attributes":{"className":"md-table-wrapper"},"children":[{"$$mdtype":"Tag","name":"table","attributes":{"className":"md"},"children":[{"$$mdtype":"Tag","name":"thead","attributes":{},"children":[{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"th","attributes":{"data-label":"Error code"},"children":["Error code"]},{"$$mdtype":"Tag","name":"th","attributes":{"data-label":"Description"},"children":["Description"]},{"$$mdtype":"Tag","name":"th","attributes":{"data-label":"Common causes"},"children":["Common causes"]}]}]},{"$$mdtype":"Tag","name":"tbody","attributes":{},"children":[{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"td","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["REQUIRED_FIELD"]}]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["A required field is missing."]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Missing mandatory configuration."]}]},{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"td","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["INVALID_AMOUNT_FORMAT"]}]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["The amount format is invalid."]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Non-decimal string amount."]}]},{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"td","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["INVALID_CURRENCY_CODE"]}]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["The currency code is invalid."]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Non-ISO 4217 currency format."]}]},{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"td","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["INVALID_COUNTRY_CODE"]}]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["The country code is invalid."]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Non-ISO 3166-1 alpha-2 format."]}]},{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"td","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["INVALID_MERCHANT_CAPABILITIES"]}]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Merchant capabilities invalid."]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Unsupported capability values."]}]},{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"td","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["INVALID_PAYMENT_NETWORKS"]}]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Payment networks invalid."]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Unsupported network values."]}]},{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"td","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["MISSING_MERCHANT_ID"]}]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["The merchant identifier is missing."]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Apple Pay merchant ID not configured."]}]},{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"td","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["INVALID_CONTACT_FIELDS"]}]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Contact fields invalid."]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Unsupported contact field values."]}]},{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"td","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["INVALID_SHIPPING_METHODS"]}]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Shipping methods invalid."]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Malformed shipping method data."]}]},{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"td","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["INVALID_LINE_ITEMS"]}]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Line items invalid."]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Malformed display items."]}]},{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"td","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["APPLE_PAY_NOT_AVAILABLE"]}]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Apple Pay not available."]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Unsupported browser/device."]}]},{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"td","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["HTTPS_REQUIRED"]}]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["HTTPS connection required."]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Non-secure context."]}]},{"$$mdtype":"Tag","name":"tr","attributes":{},"children":[{"$$mdtype":"Tag","name":"td","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["DOMAIN_NOT_REGISTERED"]}]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Domain not registered with Apple."]},{"$$mdtype":"Tag","name":"td","attributes":{},"children":["Domain validation failure."]}]}]}]}]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"validation-example","__idx":4},"children":["Validation example"]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"typescript","header":{"controls":{"copy":{}}},"source":"// Example of handling validation errors\nconst applePayConfig = {\n  // ... configuration\n  onError: (error) => {\n    if (error.name === 'ApplePayValidationException') {\n      const { validationResult } = error;\n      \n      // Handle specific validation errors\n      if (validationResult.errors['paymentRequest.merchantCapabilities']) {\n        console.error('Invalid merchant capabilities');\n      }\n      \n      if (validationResult.errors['paymentRequest.total.amount']) {\n        console.error('Invalid total amount format');\n      }\n      \n      if (validationResult.errors['merchantId']) {\n        console.error('Apple Pay merchant ID missing or invalid');\n      }\n      \n      // Display user-friendly error messages\n      Object.entries(validationResult.errors).forEach(([field, errorInfo]) => {\n        console.error(`${field}: ${errorInfo.message}`);\n      });\n    }\n  }\n};\n","lang":"typescript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"custom-validation","__idx":5},"children":["Custom validation"]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"pre-authorisation-validation","__idx":6},"children":["Pre-authorisation validation"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Run validation before the Apple Pay authorisation to catch issues early and prevent failed payments."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"typescript","header":{"controls":{"copy":{}}},"source":"const applePayComponent = pxpSdk.create('apple-pay-button', {\n  onPreAuthorisation: async () => {\n    try {\n      // 1. Business logic validation\n      const orderValidation = await validateOrder({\n        cartItems: getCartItems(),\n        customerLocation: getCustomerLocation(),\n        paymentAmount: getOrderTotal()\n      });\n      \n      if (!orderValidation.valid) {\n        throw new Error(orderValidation.reason);\n      }\n      \n      // 2. Apple Pay specific validation\n      const applePayValidation = await validateApplePayRequirements({\n        merchantId: getMerchantId(),\n        domain: window.location.hostname,\n        totalAmount: getOrderTotal()\n      });\n      \n      if (!applePayValidation.valid) {\n        throw new Error('Apple Pay requirements not met');\n      }\n      \n      // 3. Security validation\n      const securityCheck = await performSecurityValidation({\n        customerIP: getClientIP(),\n        deviceFingerprint: getDeviceFingerprint(),\n        paymentHistory: getCustomerPaymentHistory()\n      });\n      \n      if (securityCheck.riskLevel === 'HIGH') {\n        // Return additional security data for transaction\n        return {\n          riskScreeningData: {\n            performRiskScreening: true,\n            deviceSessionId: await getDeviceSessionId(),\n            userIp: \"192.168.1.100\",\n            account: {\n              id: \"user_12345678\",\n              creationDateTime: \"2024-01-15T10:30:00.000Z\"\n            },\n            items: [{\n              price: 140.00,\n              quantity: 1,\n              category: \"Electronics\"\n            }],\n            fulfillments: [{\n              type: \"Shipped\",\n              shipping: {\n                shippingMethod: \"Express\"\n              },\n              recipientPerson: {\n                phoneNumber: \"+1234567890\",\n                email: \"customer@example.com\"\n              }\n            }]\n          },\n          threeDSecureData: {\n            requestThreeDS: true\n          }\n        };\n      }\n      \n      // 4. Inventory validation\n      const inventoryCheck = await validateInventory(getCartItems());\n      if (!inventoryCheck.allAvailable) {\n        throw new Error('Some items are no longer available');\n      }\n      \n      // 5. Regulatory compliance\n      const complianceCheck = await validateCompliance({\n        customerCountry: getCustomerCountry(),\n        orderAmount: getOrderTotal(),\n        productTypes: getProductTypes()\n      });\n      \n      if (!complianceCheck.compliant) {\n        throw new Error('Order does not meet regulatory requirements');\n      }\n      \n      // Return transaction initialisation data\n      return {\n        addressVerification: true,\n        riskScreeningData: {\n          performRiskScreening: true,\n          deviceSessionId: await getDeviceSessionId(),\n          userIp: \"192.168.1.100\",\n          account: {\n            id: \"user_12345678\",\n            creationDateTime: \"2024-01-15T10:30:00.000Z\"\n          },\n          fulfillments: [{\n            type: \"Shipped\",\n            recipientPerson: {\n              phoneNumber: \"+1234567890\"\n            }\n          }]\n        }\n      };\n      \n    } catch (error) {\n      console.error('Pre-authorisation validation failed:', error);\n      // Returning null will cancel the Apple Pay flow\n      return null;\n    }\n  }\n});\n","lang":"typescript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"post-authorisation-validation","__idx":7},"children":["Post-authorisation validation"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Run validation after Apple Pay authorisation to ensure payment integrity before completing the transaction."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"typescript","header":{"controls":{"copy":{}}},"source":"const applePayConfig = {\n  onPostAuthorisation: async (result, applePayResult) => {\n    try {\n      if (result instanceof AuthorisedSubmitResult) {\n        // 1. Validate Apple Pay payment data\n        const paymentValidation = await validateApplePayData({\n          paymentToken: applePayResult.token,\n          billingContact: applePayResult.billingContact,\n          shippingContact: applePayResult.shippingContact\n        });\n        \n        if (!paymentValidation.valid) {\n          throw new Error('Apple Pay payment data validation failed');\n        }\n        \n        // 2. Final inventory check\n        const finalInventoryCheck = await reserveInventory(getOrderId());\n        if (!finalInventoryCheck.success) {\n          throw new Error('Inventory no longer available');\n        }\n        \n        // 3. Validate billing address\n        if (applePayResult.billingContact) {\n          const billingValidation = await validateBillingAddress({\n            address: applePayResult.billingContact.postalAddress,\n            name: applePayResult.billingContact.name\n          });\n          \n          if (!billingValidation.valid) {\n            throw new Error('Billing address validation failed');\n          }\n        }\n        \n        // 4. Validate shipping address\n        if (applePayResult.shippingContact) {\n          const shippingValidation = await validateShippingAddress({\n            address: applePayResult.shippingContact.postalAddress,\n            restrictions: getShippingRestrictions()\n          });\n          \n          if (!shippingValidation.valid) {\n            throw new Error('Shipping address validation failed');\n          }\n        }\n        \n        // 5. Process successful payment\n        await completeOrder({\n          transactionId: result.provider.code,\n          applePayData: applePayResult\n        });\n        \n        // Redirect to success page\n        window.location.href = '/payment-success';\n        \n      } else if (result instanceof FailedSubmitResult) {\n        // Handle payment failure\n        console.error('Payment failed:', result.errorReason);\n        showError('Payment processing failed. Please try again.');\n      }\n      \n    } catch (error) {\n      console.error('Post-authorisation validation failed:', error);\n      showError(error.message);\n    }\n  }\n};\n","lang":"typescript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"shipping-contact-validation","__idx":8},"children":["Shipping contact validation"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Validate shipping addresses in real-time as customers select them in the Apple Pay sheet."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"typescript","header":{"controls":{"copy":{}}},"source":"const applePayConfig = {\n  onShippingContactSelected: async (contact) => {\n    try {\n      // 1. Validate address format\n      const addressValidation = validateAddressFormat(contact.postalAddress);\n      if (!addressValidation.valid) {\n        return {\n          errors: [{\n            code: 'shippingContactInvalid',\n            contactField: 'postalAddress',\n            message: 'Please enter a complete address'\n          }]\n        };\n      }\n      \n      // 2. Check shipping restrictions\n      const shippingValidation = await validateShippingAvailability({\n        countryCode: contact.postalAddress.countryCode,\n        postalCode: contact.postalAddress.postalCode,\n        cartItems: getCartItems()\n      });\n      \n      if (!shippingValidation.available) {\n        return {\n          errors: [{\n            code: 'shippingContactInvalid',\n            contactField: 'postalAddress',\n            message: 'Shipping not available to this location'\n          }]\n        };\n      }\n      \n      // 3. Calculate shipping costs\n      const shippingCost = await calculateShippingCost({\n        address: contact.postalAddress,\n        items: getCartItems(),\n        expedited: false\n      });\n      \n      // 4. Calculate taxes\n      const tax = await calculateTax({\n        address: contact.postalAddress,\n        subtotal: getSubtotal()\n      });\n      \n      // Return updated payment details\n      const newTotal = getSubtotal() + shippingCost + tax;\n      \n      return {\n        newTotal: {\n          label: 'Total',\n          amount: newTotal.toFixed(2)\n        },\n        newLineItems: [\n          { label: 'Subtotal', amount: getSubtotal().toFixed(2) },\n          { label: 'Shipping', amount: shippingCost.toFixed(2) },\n          { label: 'Tax', amount: tax.toFixed(2) }\n        ],\n        newShippingMethods: await getAvailableShippingMethods(contact.postalAddress)\n      };\n      \n    } catch (error) {\n      console.error('Shipping contact validation failed:', error);\n      return {\n        errors: [{\n          code: 'shippingContactInvalid',\n          message: 'Unable to validate shipping address. Please try again.'\n        }]\n      };\n    }\n  }\n};\n","lang":"typescript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"browser-compatibility-validation","__idx":9},"children":["Browser compatibility validation"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Ensure Apple Pay requirements are met before showing the component."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"typescript","header":{"controls":{"copy":{}}},"source":"function validateApplePayCompatibility() {\n  const validation = {\n    valid: true,\n    errors: []\n  };\n  \n  // Check if running on HTTPS\n  if (window.location.protocol !== 'https:') {\n    validation.valid = false;\n    validation.errors.push({\n      code: 'HTTPS_REQUIRED',\n      message: 'Apple Pay requires HTTPS connection'\n    });\n  }\n  \n  // Check if Apple Pay is available\n  if (!window.ApplePaySession) {\n    validation.valid = false;\n    validation.errors.push({\n      code: 'APPLE_PAY_NOT_AVAILABLE',\n      message: 'Apple Pay not supported in this browser'\n    });\n  }\n  \n  // Check if device can make payments\n  if (window.ApplePaySession && !ApplePaySession.canMakePayments()) {\n    validation.valid = false;\n    validation.errors.push({\n      code: 'APPLE_PAY_NOT_AVAILABLE',\n      message: 'Apple Pay not available on this device'\n    });\n  }\n  \n  // Check Safari version for CSS method\n  if (shouldUseCssMethod()) {\n    const safariVersion = getSafariVersion();\n    if (safariVersion && safariVersion < 11.1) {\n      validation.valid = false;\n      validation.errors.push({\n        code: 'SAFARI_VERSION_INCOMPATIBLE',\n        message: 'Safari 11.1+ required for CSS method'\n      });\n    }\n  }\n  \n  return validation;\n}\n\n// Use validation before initialising\nconst compatibilityCheck = validateApplePayCompatibility();\nif (compatibilityCheck.valid) {\n  // Initialise Apple Pay component\n  initializeApplePay();\n} else {\n  // Show alternative payment methods\n  showAlternativePaymentMethods();\n  console.warn('Apple Pay not available:', compatibilityCheck.errors);\n}\n","lang":"typescript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"validate-geographic-restrictions","__idx":10},"children":["Validate geographic restrictions"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Check in real-time if any cart items are restricted in the customer's country to prevent compliance violations."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"typescript","header":{"controls":{"copy":{}}},"source":"function validateGeographicRestrictions(customerCountry, cartItems) {\n  const restrictedItems = cartItems.filter(item => \n    item.restrictions?.countries?.includes(customerCountry) ||\n    item.restrictions?.applePayRestricted?.includes(customerCountry)\n  );\n  \n  // Check Apple Pay specific restrictions\n  const applePayRestrictions = getApplePayCountryRestrictions();\n  const applePayBlocked = !applePayRestrictions.allowedCountries.includes(customerCountry);\n  \n  return {\n    valid: restrictedItems.length === 0 && !applePayBlocked,\n    restrictedItems: restrictedItems,\n    applePayBlocked: applePayBlocked,\n    message: applePayBlocked ? \n      'Apple Pay not available in your country' : \n      `Some items cannot be shipped to ${customerCountry}`\n  };\n}\n","lang":"typescript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"calculate-a-risk-score","__idx":11},"children":["Calculate a risk score"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Calculate a comprehensive fraud risk score based on multiple behavioural and historical factors, with Apple Pay specific considerations."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"typescript","header":{"controls":{"copy":{}}},"source":"async function calculateFraudScore(transactionData, applePayData) {\n  const factors = {\n    velocityScore: await checkPaymentVelocity(transactionData.customerEmail),\n    locationScore: await validateLocation(transactionData.ipAddress),\n    deviceScore: await analyzeDeviceFingerprint(transactionData.deviceData),\n    historyScore: await analyzePaymentHistory(transactionData.customerId),\n    applePayScore: await analyzeApplePayData(applePayData)\n  };\n  \n  // Apple Pay specific risk factors\n  const applePayFactors = {\n    deviceAccountScore: applePayData.paymentMethod?.deviceAccountIdentifier ? 0.1 : 0.3,\n    biometricScore: applePayData.biometricAuthentication ? 0.1 : 0.4,\n    walletScore: await analyzeWalletHistory(applePayData.paymentMethod?.primaryAccountIdentifier)\n  };\n  \n  // Weight Apple Pay factors (generally lower risk)\n  const baseScore = Object.values(factors).reduce((sum, score) => sum + score, 0) / Object.keys(factors).length;\n  const applePayAdjustment = Object.values(applePayFactors).reduce((sum, score) => sum + score, 0) / Object.keys(applePayFactors).length;\n  \n  const totalScore = (baseScore * 0.7) + (applePayAdjustment * 0.3); // Apple Pay generally reduces risk\n  \n  return {\n    score: totalScore,\n    riskLevel: totalScore > 0.8 ? 'HIGH' : totalScore > 0.5 ? 'MEDIUM' : 'LOW',\n    factors: { ...factors, ...applePayFactors },\n    applePayAdvantage: baseScore - totalScore // How much Apple Pay reduced the risk\n  };\n}\n","lang":"typescript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"validate-payment-amounts","__idx":12},"children":["Validate payment amounts"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Ensure payment amounts meet Apple Pay requirements and business rules."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"typescript","header":{"controls":{"copy":{}}},"source":"function validatePaymentAmounts(paymentRequest) {\n  const validation = {\n    valid: true,\n    errors: []\n  };\n  \n  // Validate total amount format\n  const totalAmount = parseFloat(paymentRequest.total.amount);\n  if (isNaN(totalAmount) || totalAmount <= 0) {\n    validation.valid = false;\n    validation.errors.push({\n      field: 'total.amount',\n      code: 'INVALID_AMOUNT',\n      message: 'Total amount must be a positive number'\n    });\n  }\n  \n  // Validate line items sum up to total\n  if (paymentRequest.lineItems && paymentRequest.lineItems.length > 0) {\n    const lineItemsSum = paymentRequest.lineItems.reduce((sum, item) => {\n      return sum + parseFloat(item.amount);\n    }, 0);\n    \n    const difference = Math.abs(lineItemsSum - totalAmount);\n    if (difference > 0.01) { // Allow for small rounding differences\n      validation.valid = false;\n      validation.errors.push({\n        field: 'lineItems',\n        code: 'AMOUNT_MISMATCH',\n        message: 'Line items do not sum to total amount'\n      });\n    }\n  }\n  \n  // Check minimum/maximum amounts\n  const minAmount = 0.50; // Apple Pay minimum\n  const maxAmount = 10000.00; // Business rule maximum\n  \n  if (totalAmount < minAmount) {\n    validation.valid = false;\n    validation.errors.push({\n      field: 'total.amount',\n      code: 'AMOUNT_TOO_LOW',\n      message: `Minimum amount is ${minAmount}`\n    });\n  }\n  \n  if (totalAmount > maxAmount) {\n    validation.valid = false;\n    validation.errors.push({\n      field: 'total.amount',\n      code: 'AMOUNT_TOO_HIGH',\n      message: `Maximum amount is ${maxAmount}`\n    });\n  }\n  \n  return validation;\n}\n","lang":"typescript"},"children":[]}]},"headings":[{"value":"Data validation","id":"data-validation","depth":1},{"value":"Overview","id":"overview","depth":2},{"value":"Built-in validation","id":"built-in-validation","depth":2},{"value":"Error codes","id":"error-codes","depth":3},{"value":"Validation example","id":"validation-example","depth":3},{"value":"Custom validation","id":"custom-validation","depth":2},{"value":"Pre-authorisation validation","id":"pre-authorisation-validation","depth":3},{"value":"Post-authorisation validation","id":"post-authorisation-validation","depth":3},{"value":"Shipping contact validation","id":"shipping-contact-validation","depth":3},{"value":"Browser compatibility validation","id":"browser-compatibility-validation","depth":3},{"value":"Validate geographic restrictions","id":"validate-geographic-restrictions","depth":3},{"value":"Calculate a risk score","id":"calculate-a-risk-score","depth":3},{"value":"Validate payment amounts","id":"validate-payment-amounts","depth":3}],"frontmatter":{"seo":{"title":"Data validation"}},"lastModified":"2026-04-22T11:40:18.000Z","pagePropGetterError":{"message":"","name":""}},"slug":"/guides/checkout/components/web/apple-pay/data-validation","userData":{"isAuthenticated":false,"teams":["anonymous"]},"isPublic":true}